Initial commit: Vue3 + Python Notepad with Docker support

This commit is contained in:
yuany3721 2025-12-19 18:20:27 +08:00
commit 1fc6a19787
65 changed files with 12686 additions and 0 deletions

View File

@ -0,0 +1,15 @@
# <!-- Powered by BMAD™ Core -->
bundle:
name: Team All
icon: 👥
description: Includes every core system agent.
agents:
- bmad-orchestrator
- "*"
workflows:
- brownfield-fullstack.yaml
- brownfield-service.yaml
- brownfield-ui.yaml
- greenfield-fullstack.yaml
- greenfield-service.yaml
- greenfield-ui.yaml

View File

@ -0,0 +1,19 @@
# <!-- Powered by BMAD™ Core -->
bundle:
name: Team Fullstack
icon: 🚀
description: Team capable of full stack, front end only, or service development.
agents:
- bmad-orchestrator
- analyst
- pm
- ux-expert
- architect
- po
workflows:
- brownfield-fullstack.yaml
- brownfield-service.yaml
- brownfield-ui.yaml
- greenfield-fullstack.yaml
- greenfield-service.yaml
- greenfield-ui.yaml

View File

@ -0,0 +1,11 @@
# <!-- Powered by BMAD™ Core -->
bundle:
name: Team IDE Minimal
icon:
description: Only the bare minimum for the IDE PO SM dev qa cycle.
agents:
- po
- sm
- dev
- qa
workflows: null

View File

@ -0,0 +1,14 @@
# <!-- Powered by BMAD™ Core -->
bundle:
name: Team No UI
icon: 🔧
description: Team with no UX or UI Planning.
agents:
- bmad-orchestrator
- analyst
- pm
- architect
- po
workflows:
- greenfield-service.yaml
- brownfield-service.yaml

View File

@ -0,0 +1,22 @@
markdownExploder: true
qa:
qaLocation: docs/qa
prd:
prdFile: docs/prd.md
prdVersion: v4
prdSharded: true
prdShardedLocation: docs/prd
epicFilePattern: epic-{n}*.md
architecture:
architectureFile: docs/architecture.md
architectureVersion: v4
architectureSharded: true
architectureShardedLocation: docs/architecture
customTechnicalDocuments: null
devLoadAlwaysFiles:
- docs/architecture/coding-standards.md
- docs/architecture/tech-stack.md
- docs/architecture/source-tree.md
devDebugLog: .ai/debug-log.md
devStoryLocation: docs/stories
slashPrefix: BMad

View File

@ -0,0 +1,230 @@
version: 4.44.3
installed_at: '2025-12-18T08:06:52.610Z'
install_type: full
agent: null
ides_setup:
- iflow-cli
expansion_packs: []
files:
- path: .bmad-core\working-in-the-brownfield.md
hash: 07cc8eb6fc664bb8
modified: false
- path: .bmad-core\user-guide.md
hash: f83fb2a5bc8bfe4b
modified: false
- path: .bmad-core\enhanced-ide-development-workflow.md
hash: 39beb3516c070e2b
modified: false
- path: .bmad-core\core-config.yaml
hash: 073cf6d2527c545d
modified: false
- path: .bmad-core\utils\workflow-management.md
hash: c2196880f2281f84
modified: false
- path: .bmad-core\utils\bmad-doc-template.md
hash: 34df6ead8b91abfc
modified: false
- path: .bmad-core\templates\story-tmpl.yaml
hash: 11e79b87ff700c8f
modified: false
- path: .bmad-core\templates\qa-gate-tmpl.yaml
hash: 80bd060708208984
modified: false
- path: .bmad-core\templates\project-brief-tmpl.yaml
hash: 31ba176a6ea087ab
modified: false
- path: .bmad-core\templates\prd-tmpl.yaml
hash: 963116f9ab9f4b70
modified: false
- path: .bmad-core\templates\market-research-tmpl.yaml
hash: ad46d980371caeed
modified: false
- path: .bmad-core\templates\fullstack-architecture-tmpl.yaml
hash: cb00c49c284dc7cb
modified: false
- path: .bmad-core\templates\front-end-spec-tmpl.yaml
hash: b1513524db76eeda
modified: false
- path: .bmad-core\templates\front-end-architecture-tmpl.yaml
hash: 413a2d9541cb0645
modified: false
- path: .bmad-core\templates\competitor-analysis-tmpl.yaml
hash: d0b263b0f9de8221
modified: false
- path: .bmad-core\templates\brownfield-prd-tmpl.yaml
hash: 5b89b783cd2cacdb
modified: false
- path: .bmad-core\templates\brownfield-architecture-tmpl.yaml
hash: 24af1ba7d17e68da
modified: false
- path: .bmad-core\templates\brainstorming-output-tmpl.yaml
hash: ba806c97165c8178
modified: false
- path: .bmad-core\templates\architecture-tmpl.yaml
hash: e66f63be1af30585
modified: false
- path: .bmad-core\workflows\greenfield-ui.yaml
hash: 2b595f235c095790
modified: false
- path: .bmad-core\workflows\greenfield-service.yaml
hash: 1ea8b8d218f8caef
modified: false
- path: .bmad-core\workflows\greenfield-fullstack.yaml
hash: df34e60ccfac2624
modified: false
- path: .bmad-core\workflows\brownfield-ui.yaml
hash: 8a8068093272d00f
modified: false
- path: .bmad-core\workflows\brownfield-service.yaml
hash: a3cd68897852876e
modified: false
- path: .bmad-core\workflows\brownfield-fullstack.yaml
hash: 9716ad5956a37037
modified: false
- path: .bmad-core\tasks\validate-next-story.md
hash: 75e84133d364d973
modified: false
- path: .bmad-core\tasks\trace-requirements.md
hash: cb3e06cc0b957948
modified: false
- path: .bmad-core\tasks\test-design.md
hash: bcd13a95d296ce22
modified: false
- path: .bmad-core\tasks\shard-doc.md
hash: a83c900f64ea3d4f
modified: false
- path: .bmad-core\tasks\risk-profile.md
hash: addf5d143cfe6f12
modified: false
- path: .bmad-core\tasks\review-story.md
hash: dc366f2bd2211e11
modified: false
- path: .bmad-core\tasks\qa-gate.md
hash: b0a768f56f425d9f
modified: false
- path: .bmad-core\tasks\nfr-assess.md
hash: b9011d038b81a69b
modified: false
- path: .bmad-core\tasks\kb-mode-interaction.md
hash: 4d6b921c24ba4999
modified: false
- path: .bmad-core\tasks\index-docs.md
hash: 70b1d526b19d015e
modified: false
- path: .bmad-core\tasks\generate-ai-frontend-prompt.md
hash: ca4cabd824ea1b60
modified: false
- path: .bmad-core\tasks\facilitate-brainstorming-session.md
hash: 38594d876614e077
modified: false
- path: .bmad-core\tasks\execute-checklist.md
hash: 8a704b6f2bc52e12
modified: false
- path: .bmad-core\tasks\document-project.md
hash: 98f8790d20e83cf3
modified: false
- path: .bmad-core\tasks\create-next-story.md
hash: 99e5cc3237a9cffd
modified: false
- path: .bmad-core\tasks\create-doc.md
hash: 0a6aeba58cd7a3e4
modified: false
- path: .bmad-core\tasks\create-deep-research-prompt.md
hash: 6d05224a13df6047
modified: false
- path: .bmad-core\tasks\create-brownfield-story.md
hash: a70e435c8aafbf23
modified: false
- path: .bmad-core\tasks\correct-course.md
hash: 0e6d3227b1aac200
modified: false
- path: .bmad-core\tasks\brownfield-create-story.md
hash: 873dbf0760039028
modified: false
- path: .bmad-core\tasks\brownfield-create-epic.md
hash: 7b95c09793f16e1a
modified: false
- path: .bmad-core\tasks\apply-qa-fixes.md
hash: 70e6143a80f7296b
modified: false
- path: .bmad-core\tasks\advanced-elicitation.md
hash: d39118bf32237a21
modified: false
- path: .bmad-core\data\test-priorities-matrix.md
hash: 1dd5698a46ab054e
modified: false
- path: .bmad-core\data\test-levels-framework.md
hash: f814f8efed0e96e1
modified: false
- path: .bmad-core\data\technical-preferences.md
hash: a829f3172a10b396
modified: false
- path: .bmad-core\data\elicitation-methods.md
hash: 8c3ca9b84c8784c9
modified: false
- path: .bmad-core\data\brainstorming-techniques.md
hash: 62b0bf50648906b0
modified: false
- path: .bmad-core\data\bmad-kb.md
hash: c23a5fc5c6508c5c
modified: false
- path: .bmad-core\checklists\story-draft-checklist.md
hash: 0bc8a90678dba318
modified: false
- path: .bmad-core\checklists\story-dod-checklist.md
hash: df403478049b6958
modified: false
- path: .bmad-core\checklists\po-master-checklist.md
hash: 8354985e56053c48
modified: false
- path: .bmad-core\checklists\pm-checklist.md
hash: b53f0270312713d2
modified: false
- path: .bmad-core\checklists\change-checklist.md
hash: fb2d071796c8f8b6
modified: false
- path: .bmad-core\checklists\architect-checklist.md
hash: 15ef7d01b0e31c3f
modified: false
- path: .bmad-core\agents\ux-expert.md
hash: 5de34d36ca9a747c
modified: false
- path: .bmad-core\agents\sm.md
hash: bd6543412a550438
modified: false
- path: .bmad-core\agents\qa.md
hash: 4ad40f692ee9c9fe
modified: false
- path: .bmad-core\agents\po.md
hash: 02a321a754de36e3
modified: false
- path: .bmad-core\agents\pm.md
hash: eef91ef67b74c2cf
modified: false
- path: .bmad-core\agents\dev.md
hash: 944c6b2750c3f0a7
modified: false
- path: .bmad-core\agents\bmad-orchestrator.md
hash: 1adabdf959dddf55
modified: false
- path: .bmad-core\agents\bmad-master.md
hash: 7e7928ef673b5f79
modified: false
- path: .bmad-core\agents\architect.md
hash: f5d211e80b8e160d
modified: false
- path: .bmad-core\agents\analyst.md
hash: 220103a5b3af7eb1
modified: false
- path: .bmad-core\agent-teams\team-no-ui.yaml
hash: 00cbffc4106cbe1e
modified: false
- path: .bmad-core\agent-teams\team-ide-minimal.yaml
hash: 424972103dfde87d
modified: false
- path: .bmad-core\agent-teams\team-fullstack.yaml
hash: 14c7a2d8bc7ceb6f
modified: false
- path: .bmad-core\agent-teams\team-all.yaml
hash: db5b0ff0a9c9c2e8
modified: false

View File

@ -0,0 +1,651 @@
# <!-- Powered by BMAD™ Core -->
template:
id: architecture-template-v2
name: Architecture Document
version: 2.0
output:
format: markdown
filename: docs/architecture.md
title: "{{project_name}} Architecture Document"
workflow:
mode: interactive
elicitation: advanced-elicitation
sections:
- id: introduction
title: Introduction
instruction: |
If available, review any provided relevant documents to gather all relevant context before beginning. If at a minimum you cannot locate docs/prd.md ask the user what docs will provide the basis for the architecture.
sections:
- id: intro-content
content: |
This document outlines the overall project architecture for {{project_name}}, including backend systems, shared services, and non-UI specific concerns. Its primary goal is to serve as the guiding architectural blueprint for AI-driven development, ensuring consistency and adherence to chosen patterns and technologies.
**Relationship to Frontend Architecture:**
If the project includes a significant user interface, a separate Frontend Architecture Document will detail the frontend-specific design and MUST be used in conjunction with this document. Core technology stack choices documented herein (see "Tech Stack") are definitive for the entire project, including any frontend components.
- id: starter-template
title: Starter Template or Existing Project
instruction: |
Before proceeding further with architecture design, check if the project is based on a starter template or existing codebase:
1. Review the PRD and brainstorming brief for any mentions of:
- Starter templates (e.g., Create React App, Next.js, Vue CLI, Angular CLI, etc.)
- Existing projects or codebases being used as a foundation
- Boilerplate projects or scaffolding tools
- Previous projects to be cloned or adapted
2. If a starter template or existing project is mentioned:
- Ask the user to provide access via one of these methods:
- Link to the starter template documentation
- Upload/attach the project files (for small projects)
- Share a link to the project repository (GitHub, GitLab, etc.)
- Analyze the starter/existing project to understand:
- Pre-configured technology stack and versions
- Project structure and organization patterns
- Built-in scripts and tooling
- Existing architectural patterns and conventions
- Any limitations or constraints imposed by the starter
- Use this analysis to inform and align your architecture decisions
3. If no starter template is mentioned but this is a greenfield project:
- Suggest appropriate starter templates based on the tech stack preferences
- Explain the benefits (faster setup, best practices, community support)
- Let the user decide whether to use one
4. If the user confirms no starter template will be used:
- Proceed with architecture design from scratch
- Note that manual setup will be required for all tooling and configuration
Document the decision here before proceeding with the architecture design. If none, just say N/A
elicit: true
- id: changelog
title: Change Log
type: table
columns: [Date, Version, Description, Author]
instruction: Track document versions and changes
- id: high-level-architecture
title: High Level Architecture
instruction: |
This section contains multiple subsections that establish the foundation of the architecture. Present all subsections together at once.
elicit: true
sections:
- id: technical-summary
title: Technical Summary
instruction: |
Provide a brief paragraph (3-5 sentences) overview of:
- The system's overall architecture style
- Key components and their relationships
- Primary technology choices
- Core architectural patterns being used
- Reference back to the PRD goals and how this architecture supports them
- id: high-level-overview
title: High Level Overview
instruction: |
Based on the PRD's Technical Assumptions section, describe:
1. The main architectural style (e.g., Monolith, Microservices, Serverless, Event-Driven)
2. Repository structure decision from PRD (Monorepo/Polyrepo)
3. Service architecture decision from PRD
4. Primary user interaction flow or data flow at a conceptual level
5. Key architectural decisions and their rationale
- id: project-diagram
title: High Level Project Diagram
type: mermaid
mermaid_type: graph
instruction: |
Create a Mermaid diagram that visualizes the high-level architecture. Consider:
- System boundaries
- Major components/services
- Data flow directions
- External integrations
- User entry points
- id: architectural-patterns
title: Architectural and Design Patterns
instruction: |
List the key high-level patterns that will guide the architecture. For each pattern:
1. Present 2-3 viable options if multiple exist
2. Provide your recommendation with clear rationale
3. Get user confirmation before finalizing
4. These patterns should align with the PRD's technical assumptions and project goals
Common patterns to consider:
- Architectural style patterns (Serverless, Event-Driven, Microservices, CQRS, Hexagonal)
- Code organization patterns (Dependency Injection, Repository, Module, Factory)
- Data patterns (Event Sourcing, Saga, Database per Service)
- Communication patterns (REST, GraphQL, Message Queue, Pub/Sub)
template: "- **{{pattern_name}}:** {{pattern_description}} - _Rationale:_ {{rationale}}"
examples:
- "**Serverless Architecture:** Using AWS Lambda for compute - _Rationale:_ Aligns with PRD requirement for cost optimization and automatic scaling"
- "**Repository Pattern:** Abstract data access logic - _Rationale:_ Enables testing and future database migration flexibility"
- "**Event-Driven Communication:** Using SNS/SQS for service decoupling - _Rationale:_ Supports async processing and system resilience"
- id: tech-stack
title: Tech Stack
instruction: |
This is the DEFINITIVE technology selection section. Work with the user to make specific choices:
1. Review PRD technical assumptions and any preferences from .bmad-core/data/technical-preferences.yaml or an attached technical-preferences
2. For each category, present 2-3 viable options with pros/cons
3. Make a clear recommendation based on project needs
4. Get explicit user approval for each selection
5. Document exact versions (avoid "latest" - pin specific versions)
6. This table is the single source of truth - all other docs must reference these choices
Key decisions to finalize - before displaying the table, ensure you are aware of or ask the user about - let the user know if they are not sure on any that you can also provide suggestions with rationale:
- Starter templates (if any)
- Languages and runtimes with exact versions
- Frameworks and libraries / packages
- Cloud provider and key services choices
- Database and storage solutions - if unclear suggest sql or nosql or other types depending on the project and depending on cloud provider offer a suggestion
- Development tools
Upon render of the table, ensure the user is aware of the importance of this sections choices, should also look for gaps or disagreements with anything, ask for any clarifications if something is unclear why its in the list, and also right away elicit feedback - this statement and the options should be rendered and then prompt right all before allowing user input.
elicit: true
sections:
- id: cloud-infrastructure
title: Cloud Infrastructure
template: |
- **Provider:** {{cloud_provider}}
- **Key Services:** {{core_services_list}}
- **Deployment Regions:** {{regions}}
- id: technology-stack-table
title: Technology Stack Table
type: table
columns: [Category, Technology, Version, Purpose, Rationale]
instruction: Populate the technology stack table with all relevant technologies
examples:
- "| **Language** | TypeScript | 5.3.3 | Primary development language | Strong typing, excellent tooling, team expertise |"
- "| **Runtime** | Node.js | 20.11.0 | JavaScript runtime | LTS version, stable performance, wide ecosystem |"
- "| **Framework** | NestJS | 10.3.2 | Backend framework | Enterprise-ready, good DI, matches team patterns |"
- id: data-models
title: Data Models
instruction: |
Define the core data models/entities:
1. Review PRD requirements and identify key business entities
2. For each model, explain its purpose and relationships
3. Include key attributes and data types
4. Show relationships between models
5. Discuss design decisions with user
Create a clear conceptual model before moving to database schema.
elicit: true
repeatable: true
sections:
- id: model
title: "{{model_name}}"
template: |
**Purpose:** {{model_purpose}}
**Key Attributes:**
- {{attribute_1}}: {{type_1}} - {{description_1}}
- {{attribute_2}}: {{type_2}} - {{description_2}}
**Relationships:**
- {{relationship_1}}
- {{relationship_2}}
- id: components
title: Components
instruction: |
Based on the architectural patterns, tech stack, and data models from above:
1. Identify major logical components/services and their responsibilities
2. Consider the repository structure (monorepo/polyrepo) from PRD
3. Define clear boundaries and interfaces between components
4. For each component, specify:
- Primary responsibility
- Key interfaces/APIs exposed
- Dependencies on other components
- Technology specifics based on tech stack choices
5. Create component diagrams where helpful
elicit: true
sections:
- id: component-list
repeatable: true
title: "{{component_name}}"
template: |
**Responsibility:** {{component_description}}
**Key Interfaces:**
- {{interface_1}}
- {{interface_2}}
**Dependencies:** {{dependencies}}
**Technology Stack:** {{component_tech_details}}
- id: component-diagrams
title: Component Diagrams
type: mermaid
instruction: |
Create Mermaid diagrams to visualize component relationships. Options:
- C4 Container diagram for high-level view
- Component diagram for detailed internal structure
- Sequence diagrams for complex interactions
Choose the most appropriate for clarity
- id: external-apis
title: External APIs
condition: Project requires external API integrations
instruction: |
For each external service integration:
1. Identify APIs needed based on PRD requirements and component design
2. If documentation URLs are unknown, ask user for specifics
3. Document authentication methods and security considerations
4. List specific endpoints that will be used
5. Note any rate limits or usage constraints
If no external APIs are needed, state this explicitly and skip to next section.
elicit: true
repeatable: true
sections:
- id: api
title: "{{api_name}} API"
template: |
- **Purpose:** {{api_purpose}}
- **Documentation:** {{api_docs_url}}
- **Base URL(s):** {{api_base_url}}
- **Authentication:** {{auth_method}}
- **Rate Limits:** {{rate_limits}}
**Key Endpoints Used:**
- `{{method}} {{endpoint_path}}` - {{endpoint_purpose}}
**Integration Notes:** {{integration_considerations}}
- id: core-workflows
title: Core Workflows
type: mermaid
mermaid_type: sequence
instruction: |
Illustrate key system workflows using sequence diagrams:
1. Identify critical user journeys from PRD
2. Show component interactions including external APIs
3. Include error handling paths
4. Document async operations
5. Create both high-level and detailed diagrams as needed
Focus on workflows that clarify architecture decisions or complex interactions.
elicit: true
- id: rest-api-spec
title: REST API Spec
condition: Project includes REST API
type: code
language: yaml
instruction: |
If the project includes a REST API:
1. Create an OpenAPI 3.0 specification
2. Include all endpoints from epics/stories
3. Define request/response schemas based on data models
4. Document authentication requirements
5. Include example requests/responses
Use YAML format for better readability. If no REST API, skip this section.
elicit: true
template: |
openapi: 3.0.0
info:
title: {{api_title}}
version: {{api_version}}
description: {{api_description}}
servers:
- url: {{server_url}}
description: {{server_description}}
- id: database-schema
title: Database Schema
instruction: |
Transform the conceptual data models into concrete database schemas:
1. Use the database type(s) selected in Tech Stack
2. Create schema definitions using appropriate notation
3. Include indexes, constraints, and relationships
4. Consider performance and scalability
5. For NoSQL, show document structures
Present schema in format appropriate to database type (SQL DDL, JSON schema, etc.)
elicit: true
- id: source-tree
title: Source Tree
type: code
language: plaintext
instruction: |
Create a project folder structure that reflects:
1. The chosen repository structure (monorepo/polyrepo)
2. The service architecture (monolith/microservices/serverless)
3. The selected tech stack and languages
4. Component organization from above
5. Best practices for the chosen frameworks
6. Clear separation of concerns
Adapt the structure based on project needs. For monorepos, show service separation. For serverless, show function organization. Include language-specific conventions.
elicit: true
examples:
- |
project-root/
├── packages/
│ ├── api/ # Backend API service
│ ├── web/ # Frontend application
│ ├── shared/ # Shared utilities/types
│ └── infrastructure/ # IaC definitions
├── scripts/ # Monorepo management scripts
└── package.json # Root package.json with workspaces
- id: infrastructure-deployment
title: Infrastructure and Deployment
instruction: |
Define the deployment architecture and practices:
1. Use IaC tool selected in Tech Stack
2. Choose deployment strategy appropriate for the architecture
3. Define environments and promotion flow
4. Establish rollback procedures
5. Consider security, monitoring, and cost optimization
Get user input on deployment preferences and CI/CD tool choices.
elicit: true
sections:
- id: infrastructure-as-code
title: Infrastructure as Code
template: |
- **Tool:** {{iac_tool}} {{version}}
- **Location:** `{{iac_directory}}`
- **Approach:** {{iac_approach}}
- id: deployment-strategy
title: Deployment Strategy
template: |
- **Strategy:** {{deployment_strategy}}
- **CI/CD Platform:** {{cicd_platform}}
- **Pipeline Configuration:** `{{pipeline_config_location}}`
- id: environments
title: Environments
repeatable: true
template: "- **{{env_name}}:** {{env_purpose}} - {{env_details}}"
- id: promotion-flow
title: Environment Promotion Flow
type: code
language: text
template: "{{promotion_flow_diagram}}"
- id: rollback-strategy
title: Rollback Strategy
template: |
- **Primary Method:** {{rollback_method}}
- **Trigger Conditions:** {{rollback_triggers}}
- **Recovery Time Objective:** {{rto}}
- id: error-handling-strategy
title: Error Handling Strategy
instruction: |
Define comprehensive error handling approach:
1. Choose appropriate patterns for the language/framework from Tech Stack
2. Define logging standards and tools
3. Establish error categories and handling rules
4. Consider observability and debugging needs
5. Ensure security (no sensitive data in logs)
This section guides both AI and human developers in consistent error handling.
elicit: true
sections:
- id: general-approach
title: General Approach
template: |
- **Error Model:** {{error_model}}
- **Exception Hierarchy:** {{exception_structure}}
- **Error Propagation:** {{propagation_rules}}
- id: logging-standards
title: Logging Standards
template: |
- **Library:** {{logging_library}} {{version}}
- **Format:** {{log_format}}
- **Levels:** {{log_levels_definition}}
- **Required Context:**
- Correlation ID: {{correlation_id_format}}
- Service Context: {{service_context}}
- User Context: {{user_context_rules}}
- id: error-patterns
title: Error Handling Patterns
sections:
- id: external-api-errors
title: External API Errors
template: |
- **Retry Policy:** {{retry_strategy}}
- **Circuit Breaker:** {{circuit_breaker_config}}
- **Timeout Configuration:** {{timeout_settings}}
- **Error Translation:** {{error_mapping_rules}}
- id: business-logic-errors
title: Business Logic Errors
template: |
- **Custom Exceptions:** {{business_exception_types}}
- **User-Facing Errors:** {{user_error_format}}
- **Error Codes:** {{error_code_system}}
- id: data-consistency
title: Data Consistency
template: |
- **Transaction Strategy:** {{transaction_approach}}
- **Compensation Logic:** {{compensation_patterns}}
- **Idempotency:** {{idempotency_approach}}
- id: coding-standards
title: Coding Standards
instruction: |
These standards are MANDATORY for AI agents. Work with user to define ONLY the critical rules needed to prevent bad code. Explain that:
1. This section directly controls AI developer behavior
2. Keep it minimal - assume AI knows general best practices
3. Focus on project-specific conventions and gotchas
4. Overly detailed standards bloat context and slow development
5. Standards will be extracted to separate file for dev agent use
For each standard, get explicit user confirmation it's necessary.
elicit: true
sections:
- id: core-standards
title: Core Standards
template: |
- **Languages & Runtimes:** {{languages_and_versions}}
- **Style & Linting:** {{linter_config}}
- **Test Organization:** {{test_file_convention}}
- id: naming-conventions
title: Naming Conventions
type: table
columns: [Element, Convention, Example]
instruction: Only include if deviating from language defaults
- id: critical-rules
title: Critical Rules
instruction: |
List ONLY rules that AI might violate or project-specific requirements. Examples:
- "Never use console.log in production code - use logger"
- "All API responses must use ApiResponse wrapper type"
- "Database queries must use repository pattern, never direct ORM"
Avoid obvious rules like "use SOLID principles" or "write clean code"
repeatable: true
template: "- **{{rule_name}}:** {{rule_description}}"
- id: language-specifics
title: Language-Specific Guidelines
condition: Critical language-specific rules needed
instruction: Add ONLY if critical for preventing AI mistakes. Most teams don't need this section.
sections:
- id: language-rules
title: "{{language_name}} Specifics"
repeatable: true
template: "- **{{rule_topic}}:** {{rule_detail}}"
- id: test-strategy
title: Test Strategy and Standards
instruction: |
Work with user to define comprehensive test strategy:
1. Use test frameworks from Tech Stack
2. Decide on TDD vs test-after approach
3. Define test organization and naming
4. Establish coverage goals
5. Determine integration test infrastructure
6. Plan for test data and external dependencies
Note: Basic info goes in Coding Standards for dev agent. This detailed section is for QA agent and team reference.
elicit: true
sections:
- id: testing-philosophy
title: Testing Philosophy
template: |
- **Approach:** {{test_approach}}
- **Coverage Goals:** {{coverage_targets}}
- **Test Pyramid:** {{test_distribution}}
- id: test-types
title: Test Types and Organization
sections:
- id: unit-tests
title: Unit Tests
template: |
- **Framework:** {{unit_test_framework}} {{version}}
- **File Convention:** {{unit_test_naming}}
- **Location:** {{unit_test_location}}
- **Mocking Library:** {{mocking_library}}
- **Coverage Requirement:** {{unit_coverage}}
**AI Agent Requirements:**
- Generate tests for all public methods
- Cover edge cases and error conditions
- Follow AAA pattern (Arrange, Act, Assert)
- Mock all external dependencies
- id: integration-tests
title: Integration Tests
template: |
- **Scope:** {{integration_scope}}
- **Location:** {{integration_test_location}}
- **Test Infrastructure:**
- **{{dependency_name}}:** {{test_approach}} ({{test_tool}})
examples:
- "**Database:** In-memory H2 for unit tests, Testcontainers PostgreSQL for integration"
- "**Message Queue:** Embedded Kafka for tests"
- "**External APIs:** WireMock for stubbing"
- id: e2e-tests
title: End-to-End Tests
template: |
- **Framework:** {{e2e_framework}} {{version}}
- **Scope:** {{e2e_scope}}
- **Environment:** {{e2e_environment}}
- **Test Data:** {{e2e_data_strategy}}
- id: test-data-management
title: Test Data Management
template: |
- **Strategy:** {{test_data_approach}}
- **Fixtures:** {{fixture_location}}
- **Factories:** {{factory_pattern}}
- **Cleanup:** {{cleanup_strategy}}
- id: continuous-testing
title: Continuous Testing
template: |
- **CI Integration:** {{ci_test_stages}}
- **Performance Tests:** {{perf_test_approach}}
- **Security Tests:** {{security_test_approach}}
- id: security
title: Security
instruction: |
Define MANDATORY security requirements for AI and human developers:
1. Focus on implementation-specific rules
2. Reference security tools from Tech Stack
3. Define clear patterns for common scenarios
4. These rules directly impact code generation
5. Work with user to ensure completeness without redundancy
elicit: true
sections:
- id: input-validation
title: Input Validation
template: |
- **Validation Library:** {{validation_library}}
- **Validation Location:** {{where_to_validate}}
- **Required Rules:**
- All external inputs MUST be validated
- Validation at API boundary before processing
- Whitelist approach preferred over blacklist
- id: auth-authorization
title: Authentication & Authorization
template: |
- **Auth Method:** {{auth_implementation}}
- **Session Management:** {{session_approach}}
- **Required Patterns:**
- {{auth_pattern_1}}
- {{auth_pattern_2}}
- id: secrets-management
title: Secrets Management
template: |
- **Development:** {{dev_secrets_approach}}
- **Production:** {{prod_secrets_service}}
- **Code Requirements:**
- NEVER hardcode secrets
- Access via configuration service only
- No secrets in logs or error messages
- id: api-security
title: API Security
template: |
- **Rate Limiting:** {{rate_limit_implementation}}
- **CORS Policy:** {{cors_configuration}}
- **Security Headers:** {{required_headers}}
- **HTTPS Enforcement:** {{https_approach}}
- id: data-protection
title: Data Protection
template: |
- **Encryption at Rest:** {{encryption_at_rest}}
- **Encryption in Transit:** {{encryption_in_transit}}
- **PII Handling:** {{pii_rules}}
- **Logging Restrictions:** {{what_not_to_log}}
- id: dependency-security
title: Dependency Security
template: |
- **Scanning Tool:** {{dependency_scanner}}
- **Update Policy:** {{update_frequency}}
- **Approval Process:** {{new_dep_process}}
- id: security-testing
title: Security Testing
template: |
- **SAST Tool:** {{static_analysis}}
- **DAST Tool:** {{dynamic_analysis}}
- **Penetration Testing:** {{pentest_schedule}}
- id: checklist-results
title: Checklist Results Report
instruction: Before running the checklist, offer to output the full architecture document. Once user confirms, execute the architect-checklist and populate results here.
- id: next-steps
title: Next Steps
instruction: |
After completing the architecture:
1. If project has UI components:
- Use "Frontend Architecture Mode"
- Provide this document as input
2. For all projects:
- Review with Product Owner
- Begin story implementation with Dev agent
- Set up infrastructure with DevOps agent
3. Include specific prompts for next agents if needed
sections:
- id: architect-prompt
title: Architect Prompt
condition: Project has UI components
instruction: |
Create a brief prompt to hand off to Architect for Frontend Architecture creation. Include:
- Reference to this architecture document
- Key UI requirements from PRD
- Any frontend-specific decisions made here
- Request for detailed frontend architecture

View File

@ -0,0 +1,156 @@
template:
id: brainstorming-output-template-v2
name: Brainstorming Session Results
version: 2.0
output:
format: markdown
filename: docs/brainstorming-session-results.md
title: "Brainstorming Session Results"
workflow:
mode: non-interactive
sections:
- id: header
content: |
**Session Date:** {{date}}
**Facilitator:** {{agent_role}} {{agent_name}}
**Participant:** {{user_name}}
- id: executive-summary
title: Executive Summary
sections:
- id: summary-details
template: |
**Topic:** {{session_topic}}
**Session Goals:** {{stated_goals}}
**Techniques Used:** {{techniques_list}}
**Total Ideas Generated:** {{total_ideas}}
- id: key-themes
title: "Key Themes Identified:"
type: bullet-list
template: "- {{theme}}"
- id: technique-sessions
title: Technique Sessions
repeatable: true
sections:
- id: technique
title: "{{technique_name}} - {{duration}}"
sections:
- id: description
template: "**Description:** {{technique_description}}"
- id: ideas-generated
title: "Ideas Generated:"
type: numbered-list
template: "{{idea}}"
- id: insights
title: "Insights Discovered:"
type: bullet-list
template: "- {{insight}}"
- id: connections
title: "Notable Connections:"
type: bullet-list
template: "- {{connection}}"
- id: idea-categorization
title: Idea Categorization
sections:
- id: immediate-opportunities
title: Immediate Opportunities
content: "*Ideas ready to implement now*"
repeatable: true
type: numbered-list
template: |
**{{idea_name}}**
- Description: {{description}}
- Why immediate: {{rationale}}
- Resources needed: {{requirements}}
- id: future-innovations
title: Future Innovations
content: "*Ideas requiring development/research*"
repeatable: true
type: numbered-list
template: |
**{{idea_name}}**
- Description: {{description}}
- Development needed: {{development_needed}}
- Timeline estimate: {{timeline}}
- id: moonshots
title: Moonshots
content: "*Ambitious, transformative concepts*"
repeatable: true
type: numbered-list
template: |
**{{idea_name}}**
- Description: {{description}}
- Transformative potential: {{potential}}
- Challenges to overcome: {{challenges}}
- id: insights-learnings
title: Insights & Learnings
content: "*Key realizations from the session*"
type: bullet-list
template: "- {{insight}}: {{description_and_implications}}"
- id: action-planning
title: Action Planning
sections:
- id: top-priorities
title: Top 3 Priority Ideas
sections:
- id: priority-1
title: "#1 Priority: {{idea_name}}"
template: |
- Rationale: {{rationale}}
- Next steps: {{next_steps}}
- Resources needed: {{resources}}
- Timeline: {{timeline}}
- id: priority-2
title: "#2 Priority: {{idea_name}}"
template: |
- Rationale: {{rationale}}
- Next steps: {{next_steps}}
- Resources needed: {{resources}}
- Timeline: {{timeline}}
- id: priority-3
title: "#3 Priority: {{idea_name}}"
template: |
- Rationale: {{rationale}}
- Next steps: {{next_steps}}
- Resources needed: {{resources}}
- Timeline: {{timeline}}
- id: reflection-followup
title: Reflection & Follow-up
sections:
- id: what-worked
title: What Worked Well
type: bullet-list
template: "- {{aspect}}"
- id: areas-exploration
title: Areas for Further Exploration
type: bullet-list
template: "- {{area}}: {{reason}}"
- id: recommended-techniques
title: Recommended Follow-up Techniques
type: bullet-list
template: "- {{technique}}: {{reason}}"
- id: questions-emerged
title: Questions That Emerged
type: bullet-list
template: "- {{question}}"
- id: next-session
title: Next Session Planning
template: |
- **Suggested topics:** {{followup_topics}}
- **Recommended timeframe:** {{timeframe}}
- **Preparation needed:** {{preparation}}
- id: footer
content: |
---
*Session facilitated using the BMAD-METHOD™ brainstorming framework*

View File

@ -0,0 +1,477 @@
# <!-- Powered by BMAD™ Core -->
template:
id: brownfield-architecture-template-v2
name: Brownfield Enhancement Architecture
version: 2.0
output:
format: markdown
filename: docs/architecture.md
title: "{{project_name}} Brownfield Enhancement Architecture"
workflow:
mode: interactive
elicitation: advanced-elicitation
sections:
- id: introduction
title: Introduction
instruction: |
IMPORTANT - SCOPE AND ASSESSMENT REQUIRED:
This architecture document is for SIGNIFICANT enhancements to existing projects that require comprehensive architectural planning. Before proceeding:
1. **Verify Complexity**: Confirm this enhancement requires architectural planning. For simple additions, recommend: "For simpler changes that don't require architectural planning, consider using the brownfield-create-epic or brownfield-create-story task with the Product Owner instead."
2. **REQUIRED INPUTS**:
- Completed prd.md
- Existing project technical documentation (from docs folder or user-provided)
- Access to existing project structure (IDE or uploaded files)
3. **DEEP ANALYSIS MANDATE**: You MUST conduct thorough analysis of the existing codebase, architecture patterns, and technical constraints before making ANY architectural recommendations. Every suggestion must be based on actual project analysis, not assumptions.
4. **CONTINUOUS VALIDATION**: Throughout this process, explicitly validate your understanding with the user. For every architectural decision, confirm: "Based on my analysis of your existing system, I recommend [decision] because [evidence from actual project]. Does this align with your system's reality?"
If any required inputs are missing, request them before proceeding.
elicit: true
sections:
- id: intro-content
content: |
This document outlines the architectural approach for enhancing {{project_name}} with {{enhancement_description}}. Its primary goal is to serve as the guiding architectural blueprint for AI-driven development of new features while ensuring seamless integration with the existing system.
**Relationship to Existing Architecture:**
This document supplements existing project architecture by defining how new components will integrate with current systems. Where conflicts arise between new and existing patterns, this document provides guidance on maintaining consistency while implementing enhancements.
- id: existing-project-analysis
title: Existing Project Analysis
instruction: |
Analyze the existing project structure and architecture:
1. Review existing documentation in docs folder
2. Examine current technology stack and versions
3. Identify existing architectural patterns and conventions
4. Note current deployment and infrastructure setup
5. Document any constraints or limitations
CRITICAL: After your analysis, explicitly validate your findings: "Based on my analysis of your project, I've identified the following about your existing system: [key findings]. Please confirm these observations are accurate before I proceed with architectural recommendations."
elicit: true
sections:
- id: current-state
title: Current Project State
template: |
- **Primary Purpose:** {{existing_project_purpose}}
- **Current Tech Stack:** {{existing_tech_summary}}
- **Architecture Style:** {{existing_architecture_style}}
- **Deployment Method:** {{existing_deployment_approach}}
- id: available-docs
title: Available Documentation
type: bullet-list
template: "- {{existing_docs_summary}}"
- id: constraints
title: Identified Constraints
type: bullet-list
template: "- {{constraint}}"
- id: changelog
title: Change Log
type: table
columns: [Change, Date, Version, Description, Author]
instruction: Track document versions and changes
- id: enhancement-scope
title: Enhancement Scope and Integration Strategy
instruction: |
Define how the enhancement will integrate with the existing system:
1. Review the brownfield PRD enhancement scope
2. Identify integration points with existing code
3. Define boundaries between new and existing functionality
4. Establish compatibility requirements
VALIDATION CHECKPOINT: Before presenting the integration strategy, confirm: "Based on my analysis, the integration approach I'm proposing takes into account [specific existing system characteristics]. These integration points and boundaries respect your current architecture patterns. Is this assessment accurate?"
elicit: true
sections:
- id: enhancement-overview
title: Enhancement Overview
template: |
**Enhancement Type:** {{enhancement_type}}
**Scope:** {{enhancement_scope}}
**Integration Impact:** {{integration_impact_level}}
- id: integration-approach
title: Integration Approach
template: |
**Code Integration Strategy:** {{code_integration_approach}}
**Database Integration:** {{database_integration_approach}}
**API Integration:** {{api_integration_approach}}
**UI Integration:** {{ui_integration_approach}}
- id: compatibility-requirements
title: Compatibility Requirements
template: |
- **Existing API Compatibility:** {{api_compatibility}}
- **Database Schema Compatibility:** {{db_compatibility}}
- **UI/UX Consistency:** {{ui_compatibility}}
- **Performance Impact:** {{performance_constraints}}
- id: tech-stack
title: Tech Stack
instruction: |
Ensure new components align with existing technology choices:
1. Use existing technology stack as the foundation
2. Only introduce new technologies if absolutely necessary
3. Justify any new additions with clear rationale
4. Ensure version compatibility with existing dependencies
elicit: true
sections:
- id: existing-stack
title: Existing Technology Stack
type: table
columns: [Category, Current Technology, Version, Usage in Enhancement, Notes]
instruction: Document the current stack that must be maintained or integrated with
- id: new-tech-additions
title: New Technology Additions
condition: Enhancement requires new technologies
type: table
columns: [Technology, Version, Purpose, Rationale, Integration Method]
instruction: Only include if new technologies are required for the enhancement
- id: data-models
title: Data Models and Schema Changes
instruction: |
Define new data models and how they integrate with existing schema:
1. Identify new entities required for the enhancement
2. Define relationships with existing data models
3. Plan database schema changes (additions, modifications)
4. Ensure backward compatibility
elicit: true
sections:
- id: new-models
title: New Data Models
repeatable: true
sections:
- id: model
title: "{{model_name}}"
template: |
**Purpose:** {{model_purpose}}
**Integration:** {{integration_with_existing}}
**Key Attributes:**
- {{attribute_1}}: {{type_1}} - {{description_1}}
- {{attribute_2}}: {{type_2}} - {{description_2}}
**Relationships:**
- **With Existing:** {{existing_relationships}}
- **With New:** {{new_relationships}}
- id: schema-integration
title: Schema Integration Strategy
template: |
**Database Changes Required:**
- **New Tables:** {{new_tables_list}}
- **Modified Tables:** {{modified_tables_list}}
- **New Indexes:** {{new_indexes_list}}
- **Migration Strategy:** {{migration_approach}}
**Backward Compatibility:**
- {{compatibility_measure_1}}
- {{compatibility_measure_2}}
- id: component-architecture
title: Component Architecture
instruction: |
Define new components and their integration with existing architecture:
1. Identify new components required for the enhancement
2. Define interfaces with existing components
3. Establish clear boundaries and responsibilities
4. Plan integration points and data flow
MANDATORY VALIDATION: Before presenting component architecture, confirm: "The new components I'm proposing follow the existing architectural patterns I identified in your codebase: [specific patterns]. The integration interfaces respect your current component structure and communication patterns. Does this match your project's reality?"
elicit: true
sections:
- id: new-components
title: New Components
repeatable: true
sections:
- id: component
title: "{{component_name}}"
template: |
**Responsibility:** {{component_description}}
**Integration Points:** {{integration_points}}
**Key Interfaces:**
- {{interface_1}}
- {{interface_2}}
**Dependencies:**
- **Existing Components:** {{existing_dependencies}}
- **New Components:** {{new_dependencies}}
**Technology Stack:** {{component_tech_details}}
- id: interaction-diagram
title: Component Interaction Diagram
type: mermaid
mermaid_type: graph
instruction: Create Mermaid diagram showing how new components interact with existing ones
- id: api-design
title: API Design and Integration
condition: Enhancement requires API changes
instruction: |
Define new API endpoints and integration with existing APIs:
1. Plan new API endpoints required for the enhancement
2. Ensure consistency with existing API patterns
3. Define authentication and authorization integration
4. Plan versioning strategy if needed
elicit: true
sections:
- id: api-strategy
title: API Integration Strategy
template: |
**API Integration Strategy:** {{api_integration_strategy}}
**Authentication:** {{auth_integration}}
**Versioning:** {{versioning_approach}}
- id: new-endpoints
title: New API Endpoints
repeatable: true
sections:
- id: endpoint
title: "{{endpoint_name}}"
template: |
- **Method:** {{http_method}}
- **Endpoint:** {{endpoint_path}}
- **Purpose:** {{endpoint_purpose}}
- **Integration:** {{integration_with_existing}}
sections:
- id: request
title: Request
type: code
language: json
template: "{{request_schema}}"
- id: response
title: Response
type: code
language: json
template: "{{response_schema}}"
- id: external-api-integration
title: External API Integration
condition: Enhancement requires new external APIs
instruction: Document new external API integrations required for the enhancement
repeatable: true
sections:
- id: external-api
title: "{{api_name}} API"
template: |
- **Purpose:** {{api_purpose}}
- **Documentation:** {{api_docs_url}}
- **Base URL:** {{api_base_url}}
- **Authentication:** {{auth_method}}
- **Integration Method:** {{integration_approach}}
**Key Endpoints Used:**
- `{{method}} {{endpoint_path}}` - {{endpoint_purpose}}
**Error Handling:** {{error_handling_strategy}}
- id: source-tree
title: Source Tree
instruction: |
Define how new code will integrate with existing project structure:
1. Follow existing project organization patterns
2. Identify where new files/folders will be placed
3. Ensure consistency with existing naming conventions
4. Plan for minimal disruption to existing structure
elicit: true
sections:
- id: existing-structure
title: Existing Project Structure
type: code
language: plaintext
instruction: Document relevant parts of current structure
template: "{{existing_structure_relevant_parts}}"
- id: new-file-organization
title: New File Organization
type: code
language: plaintext
instruction: Show only new additions to existing structure
template: |
{{project-root}}/
├── {{existing_structure_context}}
│ ├── {{new_folder_1}}/ # {{purpose_1}}
│ │ ├── {{new_file_1}}
│ │ └── {{new_file_2}}
│ ├── {{existing_folder}}/ # Existing folder with additions
│ │ ├── {{existing_file}} # Existing file
│ │ └── {{new_file_3}} # New addition
│ └── {{new_folder_2}}/ # {{purpose_2}}
- id: integration-guidelines
title: Integration Guidelines
template: |
- **File Naming:** {{file_naming_consistency}}
- **Folder Organization:** {{folder_organization_approach}}
- **Import/Export Patterns:** {{import_export_consistency}}
- id: infrastructure-deployment
title: Infrastructure and Deployment Integration
instruction: |
Define how the enhancement will be deployed alongside existing infrastructure:
1. Use existing deployment pipeline and infrastructure
2. Identify any infrastructure changes needed
3. Plan deployment strategy to minimize risk
4. Define rollback procedures
elicit: true
sections:
- id: existing-infrastructure
title: Existing Infrastructure
template: |
**Current Deployment:** {{existing_deployment_summary}}
**Infrastructure Tools:** {{existing_infrastructure_tools}}
**Environments:** {{existing_environments}}
- id: enhancement-deployment
title: Enhancement Deployment Strategy
template: |
**Deployment Approach:** {{deployment_approach}}
**Infrastructure Changes:** {{infrastructure_changes}}
**Pipeline Integration:** {{pipeline_integration}}
- id: rollback-strategy
title: Rollback Strategy
template: |
**Rollback Method:** {{rollback_method}}
**Risk Mitigation:** {{risk_mitigation}}
**Monitoring:** {{monitoring_approach}}
- id: coding-standards
title: Coding Standards
instruction: |
Ensure new code follows existing project conventions:
1. Document existing coding standards from project analysis
2. Identify any enhancement-specific requirements
3. Ensure consistency with existing codebase patterns
4. Define standards for new code organization
elicit: true
sections:
- id: existing-standards
title: Existing Standards Compliance
template: |
**Code Style:** {{existing_code_style}}
**Linting Rules:** {{existing_linting}}
**Testing Patterns:** {{existing_test_patterns}}
**Documentation Style:** {{existing_doc_style}}
- id: enhancement-standards
title: Enhancement-Specific Standards
condition: New patterns needed for enhancement
repeatable: true
template: "- **{{standard_name}}:** {{standard_description}}"
- id: integration-rules
title: Critical Integration Rules
template: |
- **Existing API Compatibility:** {{api_compatibility_rule}}
- **Database Integration:** {{db_integration_rule}}
- **Error Handling:** {{error_handling_integration}}
- **Logging Consistency:** {{logging_consistency}}
- id: testing-strategy
title: Testing Strategy
instruction: |
Define testing approach for the enhancement:
1. Integrate with existing test suite
2. Ensure existing functionality remains intact
3. Plan for testing new features
4. Define integration testing approach
elicit: true
sections:
- id: existing-test-integration
title: Integration with Existing Tests
template: |
**Existing Test Framework:** {{existing_test_framework}}
**Test Organization:** {{existing_test_organization}}
**Coverage Requirements:** {{existing_coverage_requirements}}
- id: new-testing
title: New Testing Requirements
sections:
- id: unit-tests
title: Unit Tests for New Components
template: |
- **Framework:** {{test_framework}}
- **Location:** {{test_location}}
- **Coverage Target:** {{coverage_target}}
- **Integration with Existing:** {{test_integration}}
- id: integration-tests
title: Integration Tests
template: |
- **Scope:** {{integration_test_scope}}
- **Existing System Verification:** {{existing_system_verification}}
- **New Feature Testing:** {{new_feature_testing}}
- id: regression-tests
title: Regression Testing
template: |
- **Existing Feature Verification:** {{regression_test_approach}}
- **Automated Regression Suite:** {{automated_regression}}
- **Manual Testing Requirements:** {{manual_testing_requirements}}
- id: security-integration
title: Security Integration
instruction: |
Ensure security consistency with existing system:
1. Follow existing security patterns and tools
2. Ensure new features don't introduce vulnerabilities
3. Maintain existing security posture
4. Define security testing for new components
elicit: true
sections:
- id: existing-security
title: Existing Security Measures
template: |
**Authentication:** {{existing_auth}}
**Authorization:** {{existing_authz}}
**Data Protection:** {{existing_data_protection}}
**Security Tools:** {{existing_security_tools}}
- id: enhancement-security
title: Enhancement Security Requirements
template: |
**New Security Measures:** {{new_security_measures}}
**Integration Points:** {{security_integration_points}}
**Compliance Requirements:** {{compliance_requirements}}
- id: security-testing
title: Security Testing
template: |
**Existing Security Tests:** {{existing_security_tests}}
**New Security Test Requirements:** {{new_security_tests}}
**Penetration Testing:** {{pentest_requirements}}
- id: checklist-results
title: Checklist Results Report
instruction: Execute the architect-checklist and populate results here, focusing on brownfield-specific validation
- id: next-steps
title: Next Steps
instruction: |
After completing the brownfield architecture:
1. Review integration points with existing system
2. Begin story implementation with Dev agent
3. Set up deployment pipeline integration
4. Plan rollback and monitoring procedures
sections:
- id: story-manager-handoff
title: Story Manager Handoff
instruction: |
Create a brief prompt for Story Manager to work with this brownfield enhancement. Include:
- Reference to this architecture document
- Key integration requirements validated with user
- Existing system constraints based on actual project analysis
- First story to implement with clear integration checkpoints
- Emphasis on maintaining existing system integrity throughout implementation
- id: developer-handoff
title: Developer Handoff
instruction: |
Create a brief prompt for developers starting implementation. Include:
- Reference to this architecture and existing coding standards analyzed from actual project
- Integration requirements with existing codebase validated with user
- Key technical decisions based on real project constraints
- Existing system compatibility requirements with specific verification steps
- Clear sequencing of implementation to minimize risk to existing functionality

View File

@ -0,0 +1,281 @@
# <!-- Powered by BMAD™ Core -->
template:
id: brownfield-prd-template-v2
name: Brownfield Enhancement PRD
version: 2.0
output:
format: markdown
filename: docs/prd.md
title: "{{project_name}} Brownfield Enhancement PRD"
workflow:
mode: interactive
elicitation: advanced-elicitation
sections:
- id: intro-analysis
title: Intro Project Analysis and Context
instruction: |
IMPORTANT - SCOPE ASSESSMENT REQUIRED:
This PRD is for SIGNIFICANT enhancements to existing projects that require comprehensive planning and multiple stories. Before proceeding:
1. **Assess Enhancement Complexity**: If this is a simple feature addition or bug fix that could be completed in 1-2 focused development sessions, STOP and recommend: "For simpler changes, consider using the brownfield-create-epic or brownfield-create-story task with the Product Owner instead. This full PRD process is designed for substantial enhancements that require architectural planning and multiple coordinated stories."
2. **Project Context**: Determine if we're working in an IDE with the project already loaded or if the user needs to provide project information. If project files are available, analyze existing documentation in the docs folder. If insufficient documentation exists, recommend running the document-project task first.
3. **Deep Assessment Requirement**: You MUST thoroughly analyze the existing project structure, patterns, and constraints before making ANY suggestions. Every recommendation must be grounded in actual project analysis, not assumptions.
Gather comprehensive information about the existing project. This section must be completed before proceeding with requirements.
CRITICAL: Throughout this analysis, explicitly confirm your understanding with the user. For every assumption you make about the existing project, ask: "Based on my analysis, I understand that [assumption]. Is this correct?"
Do not proceed with any recommendations until the user has validated your understanding of the existing system.
sections:
- id: existing-project-overview
title: Existing Project Overview
instruction: Check if document-project analysis was already performed. If yes, reference that output instead of re-analyzing.
sections:
- id: analysis-source
title: Analysis Source
instruction: |
Indicate one of the following:
- Document-project output available at: {{path}}
- IDE-based fresh analysis
- User-provided information
- id: current-state
title: Current Project State
instruction: |
- If document-project output exists: Extract summary from "High Level Architecture" and "Technical Summary" sections
- Otherwise: Brief description of what the project currently does and its primary purpose
- id: documentation-analysis
title: Available Documentation Analysis
instruction: |
If document-project was run:
- Note: "Document-project analysis available - using existing technical documentation"
- List key documents created by document-project
- Skip the missing documentation check below
Otherwise, check for existing documentation:
sections:
- id: available-docs
title: Available Documentation
type: checklist
items:
- Tech Stack Documentation [[LLM: If from document-project, check ✓]]
- Source Tree/Architecture [[LLM: If from document-project, check ✓]]
- Coding Standards [[LLM: If from document-project, may be partial]]
- API Documentation [[LLM: If from document-project, check ✓]]
- External API Documentation [[LLM: If from document-project, check ✓]]
- UX/UI Guidelines [[LLM: May not be in document-project]]
- Technical Debt Documentation [[LLM: If from document-project, check ✓]]
- "Other: {{other_docs}}"
instruction: |
- If document-project was already run: "Using existing project analysis from document-project output."
- If critical documentation is missing and no document-project: "I recommend running the document-project task first..."
- id: enhancement-scope
title: Enhancement Scope Definition
instruction: Work with user to clearly define what type of enhancement this is. This is critical for scoping and approach.
sections:
- id: enhancement-type
title: Enhancement Type
type: checklist
instruction: Determine with user which applies
items:
- New Feature Addition
- Major Feature Modification
- Integration with New Systems
- Performance/Scalability Improvements
- UI/UX Overhaul
- Technology Stack Upgrade
- Bug Fix and Stability Improvements
- "Other: {{other_type}}"
- id: enhancement-description
title: Enhancement Description
instruction: 2-3 sentences describing what the user wants to add or change
- id: impact-assessment
title: Impact Assessment
type: checklist
instruction: Assess the scope of impact on existing codebase
items:
- Minimal Impact (isolated additions)
- Moderate Impact (some existing code changes)
- Significant Impact (substantial existing code changes)
- Major Impact (architectural changes required)
- id: goals-context
title: Goals and Background Context
sections:
- id: goals
title: Goals
type: bullet-list
instruction: Bullet list of 1-line desired outcomes this enhancement will deliver if successful
- id: background
title: Background Context
type: paragraphs
instruction: 1-2 short paragraphs explaining why this enhancement is needed, what problem it solves, and how it fits with the existing project
- id: changelog
title: Change Log
type: table
columns: [Change, Date, Version, Description, Author]
- id: requirements
title: Requirements
instruction: |
Draft functional and non-functional requirements based on your validated understanding of the existing project. Before presenting requirements, confirm: "These requirements are based on my understanding of your existing system. Please review carefully and confirm they align with your project's reality."
elicit: true
sections:
- id: functional
title: Functional
type: numbered-list
prefix: FR
instruction: Each Requirement will be a bullet markdown with identifier starting with FR
examples:
- "FR1: The existing Todo List will integrate with the new AI duplicate detection service without breaking current functionality."
- id: non-functional
title: Non Functional
type: numbered-list
prefix: NFR
instruction: Each Requirement will be a bullet markdown with identifier starting with NFR. Include constraints from existing system
examples:
- "NFR1: Enhancement must maintain existing performance characteristics and not exceed current memory usage by more than 20%."
- id: compatibility
title: Compatibility Requirements
instruction: Critical for brownfield - what must remain compatible
type: numbered-list
prefix: CR
template: "{{requirement}}: {{description}}"
items:
- id: cr1
template: "CR1: {{existing_api_compatibility}}"
- id: cr2
template: "CR2: {{database_schema_compatibility}}"
- id: cr3
template: "CR3: {{ui_ux_consistency}}"
- id: cr4
template: "CR4: {{integration_compatibility}}"
- id: ui-enhancement-goals
title: User Interface Enhancement Goals
condition: Enhancement includes UI changes
instruction: For UI changes, capture how they will integrate with existing UI patterns and design systems
sections:
- id: existing-ui-integration
title: Integration with Existing UI
instruction: Describe how new UI elements will fit with existing design patterns, style guides, and component libraries
- id: modified-screens
title: Modified/New Screens and Views
instruction: List only the screens/views that will be modified or added
- id: ui-consistency
title: UI Consistency Requirements
instruction: Specific requirements for maintaining visual and interaction consistency with existing application
- id: technical-constraints
title: Technical Constraints and Integration Requirements
instruction: This section replaces separate architecture documentation. Gather detailed technical constraints from existing project analysis.
sections:
- id: existing-tech-stack
title: Existing Technology Stack
instruction: |
If document-project output available:
- Extract from "Actual Tech Stack" table in High Level Architecture section
- Include version numbers and any noted constraints
Otherwise, document the current technology stack:
template: |
**Languages**: {{languages}}
**Frameworks**: {{frameworks}}
**Database**: {{database}}
**Infrastructure**: {{infrastructure}}
**External Dependencies**: {{external_dependencies}}
- id: integration-approach
title: Integration Approach
instruction: Define how the enhancement will integrate with existing architecture
template: |
**Database Integration Strategy**: {{database_integration}}
**API Integration Strategy**: {{api_integration}}
**Frontend Integration Strategy**: {{frontend_integration}}
**Testing Integration Strategy**: {{testing_integration}}
- id: code-organization
title: Code Organization and Standards
instruction: Based on existing project analysis, define how new code will fit existing patterns
template: |
**File Structure Approach**: {{file_structure}}
**Naming Conventions**: {{naming_conventions}}
**Coding Standards**: {{coding_standards}}
**Documentation Standards**: {{documentation_standards}}
- id: deployment-operations
title: Deployment and Operations
instruction: How the enhancement fits existing deployment pipeline
template: |
**Build Process Integration**: {{build_integration}}
**Deployment Strategy**: {{deployment_strategy}}
**Monitoring and Logging**: {{monitoring_logging}}
**Configuration Management**: {{config_management}}
- id: risk-assessment
title: Risk Assessment and Mitigation
instruction: |
If document-project output available:
- Reference "Technical Debt and Known Issues" section
- Include "Workarounds and Gotchas" that might impact enhancement
- Note any identified constraints from "Critical Technical Debt"
Build risk assessment incorporating existing known issues:
template: |
**Technical Risks**: {{technical_risks}}
**Integration Risks**: {{integration_risks}}
**Deployment Risks**: {{deployment_risks}}
**Mitigation Strategies**: {{mitigation_strategies}}
- id: epic-structure
title: Epic and Story Structure
instruction: |
For brownfield projects, favor a single comprehensive epic unless the user is clearly requesting multiple unrelated enhancements. Before presenting the epic structure, confirm: "Based on my analysis of your existing project, I believe this enhancement should be structured as [single epic/multiple epics] because [rationale based on actual project analysis]. Does this align with your understanding of the work required?"
elicit: true
sections:
- id: epic-approach
title: Epic Approach
instruction: Explain the rationale for epic structure - typically single epic for brownfield unless multiple unrelated features
template: "**Epic Structure Decision**: {{epic_decision}} with rationale"
- id: epic-details
title: "Epic 1: {{enhancement_title}}"
instruction: |
Comprehensive epic that delivers the brownfield enhancement while maintaining existing functionality
CRITICAL STORY SEQUENCING FOR BROWNFIELD:
- Stories must ensure existing functionality remains intact
- Each story should include verification that existing features still work
- Stories should be sequenced to minimize risk to existing system
- Include rollback considerations for each story
- Focus on incremental integration rather than big-bang changes
- Size stories for AI agent execution in existing codebase context
- MANDATORY: Present the complete story sequence and ask: "This story sequence is designed to minimize risk to your existing system. Does this order make sense given your project's architecture and constraints?"
- Stories must be logically sequential with clear dependencies identified
- Each story must deliver value while maintaining system integrity
template: |
**Epic Goal**: {{epic_goal}}
**Integration Requirements**: {{integration_requirements}}
sections:
- id: story
title: "Story 1.{{story_number}} {{story_title}}"
repeatable: true
template: |
As a {{user_type}},
I want {{action}},
so that {{benefit}}.
sections:
- id: acceptance-criteria
title: Acceptance Criteria
type: numbered-list
instruction: Define criteria that include both new functionality and existing system integrity
item_template: "{{criterion_number}}: {{criteria}}"
- id: integration-verification
title: Integration Verification
instruction: Specific verification steps to ensure existing functionality remains intact
type: numbered-list
prefix: IV
items:
- template: "IV1: {{existing_functionality_verification}}"
- template: "IV2: {{integration_point_verification}}"
- template: "IV3: {{performance_impact_verification}}"

View File

@ -0,0 +1,307 @@
# <!-- Powered by BMAD™ Core -->
template:
id: competitor-analysis-template-v2
name: Competitive Analysis Report
version: 2.0
output:
format: markdown
filename: docs/competitor-analysis.md
title: "Competitive Analysis Report: {{project_product_name}}"
workflow:
mode: interactive
elicitation: advanced-elicitation
custom_elicitation:
title: "Competitive Analysis Elicitation Actions"
options:
- "Deep dive on a specific competitor's strategy"
- "Analyze competitive dynamics in a specific segment"
- "War game competitive responses to your moves"
- "Explore partnership vs. competition scenarios"
- "Stress test differentiation claims"
- "Analyze disruption potential (yours or theirs)"
- "Compare to competition in adjacent markets"
- "Generate win/loss analysis insights"
- "If only we had known about [competitor X's plan]..."
- "Proceed to next section"
sections:
- id: executive-summary
title: Executive Summary
instruction: Provide high-level competitive insights, main threats and opportunities, and recommended strategic actions. Write this section LAST after completing all analysis.
- id: analysis-scope
title: Analysis Scope & Methodology
instruction: This template guides comprehensive competitor analysis. Start by understanding the user's competitive intelligence needs and strategic objectives. Help them identify and prioritize competitors before diving into detailed analysis.
sections:
- id: analysis-purpose
title: Analysis Purpose
instruction: |
Define the primary purpose:
- New market entry assessment
- Product positioning strategy
- Feature gap analysis
- Pricing strategy development
- Partnership/acquisition targets
- Competitive threat assessment
- id: competitor-categories
title: Competitor Categories Analyzed
instruction: |
List categories included:
- Direct Competitors: Same product/service, same target market
- Indirect Competitors: Different product, same need/problem
- Potential Competitors: Could enter market easily
- Substitute Products: Alternative solutions
- Aspirational Competitors: Best-in-class examples
- id: research-methodology
title: Research Methodology
instruction: |
Describe approach:
- Information sources used
- Analysis timeframe
- Confidence levels
- Limitations
- id: competitive-landscape
title: Competitive Landscape Overview
sections:
- id: market-structure
title: Market Structure
instruction: |
Describe the competitive environment:
- Number of active competitors
- Market concentration (fragmented/consolidated)
- Competitive dynamics
- Recent market entries/exits
- id: prioritization-matrix
title: Competitor Prioritization Matrix
instruction: |
Help categorize competitors by market share and strategic threat level
Create a 2x2 matrix:
- Priority 1 (Core Competitors): High Market Share + High Threat
- Priority 2 (Emerging Threats): Low Market Share + High Threat
- Priority 3 (Established Players): High Market Share + Low Threat
- Priority 4 (Monitor Only): Low Market Share + Low Threat
- id: competitor-profiles
title: Individual Competitor Profiles
instruction: Create detailed profiles for each Priority 1 and Priority 2 competitor. For Priority 3 and 4, create condensed profiles.
repeatable: true
sections:
- id: competitor
title: "{{competitor_name}} - Priority {{priority_level}}"
sections:
- id: company-overview
title: Company Overview
template: |
- **Founded:** {{year_founders}}
- **Headquarters:** {{location}}
- **Company Size:** {{employees_revenue}}
- **Funding:** {{total_raised_investors}}
- **Leadership:** {{key_executives}}
- id: business-model
title: Business Model & Strategy
template: |
- **Revenue Model:** {{revenue_model}}
- **Target Market:** {{customer_segments}}
- **Value Proposition:** {{value_promise}}
- **Go-to-Market Strategy:** {{gtm_approach}}
- **Strategic Focus:** {{current_priorities}}
- id: product-analysis
title: Product/Service Analysis
template: |
- **Core Offerings:** {{main_products}}
- **Key Features:** {{standout_capabilities}}
- **User Experience:** {{ux_assessment}}
- **Technology Stack:** {{tech_stack}}
- **Pricing:** {{pricing_model}}
- id: strengths-weaknesses
title: Strengths & Weaknesses
sections:
- id: strengths
title: Strengths
type: bullet-list
template: "- {{strength}}"
- id: weaknesses
title: Weaknesses
type: bullet-list
template: "- {{weakness}}"
- id: market-position
title: Market Position & Performance
template: |
- **Market Share:** {{market_share_estimate}}
- **Customer Base:** {{customer_size_notables}}
- **Growth Trajectory:** {{growth_trend}}
- **Recent Developments:** {{key_news}}
- id: comparative-analysis
title: Comparative Analysis
sections:
- id: feature-comparison
title: Feature Comparison Matrix
instruction: Create a detailed comparison table of key features across competitors
type: table
columns:
[
"Feature Category",
"{{your_company}}",
"{{competitor_1}}",
"{{competitor_2}}",
"{{competitor_3}}",
]
rows:
- category: "Core Functionality"
items:
- ["Feature A", "{{status}}", "{{status}}", "{{status}}", "{{status}}"]
- ["Feature B", "{{status}}", "{{status}}", "{{status}}", "{{status}}"]
- category: "User Experience"
items:
- ["Mobile App", "{{rating}}", "{{rating}}", "{{rating}}", "{{rating}}"]
- ["Onboarding Time", "{{time}}", "{{time}}", "{{time}}", "{{time}}"]
- category: "Integration & Ecosystem"
items:
- [
"API Availability",
"{{availability}}",
"{{availability}}",
"{{availability}}",
"{{availability}}",
]
- ["Third-party Integrations", "{{number}}", "{{number}}", "{{number}}", "{{number}}"]
- category: "Pricing & Plans"
items:
- ["Starting Price", "{{price}}", "{{price}}", "{{price}}", "{{price}}"]
- ["Free Tier", "{{yes_no}}", "{{yes_no}}", "{{yes_no}}", "{{yes_no}}"]
- id: swot-comparison
title: SWOT Comparison
instruction: Create SWOT analysis for your solution vs. top competitors
sections:
- id: your-solution
title: Your Solution
template: |
- **Strengths:** {{strengths}}
- **Weaknesses:** {{weaknesses}}
- **Opportunities:** {{opportunities}}
- **Threats:** {{threats}}
- id: vs-competitor
title: "vs. {{main_competitor}}"
template: |
- **Competitive Advantages:** {{your_advantages}}
- **Competitive Disadvantages:** {{their_advantages}}
- **Differentiation Opportunities:** {{differentiation}}
- id: positioning-map
title: Positioning Map
instruction: |
Describe competitor positions on key dimensions
Create a positioning description using 2 key dimensions relevant to the market, such as:
- Price vs. Features
- Ease of Use vs. Power
- Specialization vs. Breadth
- Self-Serve vs. High-Touch
- id: strategic-analysis
title: Strategic Analysis
sections:
- id: competitive-advantages
title: Competitive Advantages Assessment
sections:
- id: sustainable-advantages
title: Sustainable Advantages
instruction: |
Identify moats and defensible positions:
- Network effects
- Switching costs
- Brand strength
- Technology barriers
- Regulatory advantages
- id: vulnerable-points
title: Vulnerable Points
instruction: |
Where competitors could be challenged:
- Weak customer segments
- Missing features
- Poor user experience
- High prices
- Limited geographic presence
- id: blue-ocean
title: Blue Ocean Opportunities
instruction: |
Identify uncontested market spaces
List opportunities to create new market space:
- Underserved segments
- Unaddressed use cases
- New business models
- Geographic expansion
- Different value propositions
- id: strategic-recommendations
title: Strategic Recommendations
sections:
- id: differentiation-strategy
title: Differentiation Strategy
instruction: |
How to position against competitors:
- Unique value propositions to emphasize
- Features to prioritize
- Segments to target
- Messaging and positioning
- id: competitive-response
title: Competitive Response Planning
sections:
- id: offensive-strategies
title: Offensive Strategies
instruction: |
How to gain market share:
- Target competitor weaknesses
- Win competitive deals
- Capture their customers
- id: defensive-strategies
title: Defensive Strategies
instruction: |
How to protect your position:
- Strengthen vulnerable areas
- Build switching costs
- Deepen customer relationships
- id: partnership-ecosystem
title: Partnership & Ecosystem Strategy
instruction: |
Potential collaboration opportunities:
- Complementary players
- Channel partners
- Technology integrations
- Strategic alliances
- id: monitoring-plan
title: Monitoring & Intelligence Plan
sections:
- id: key-competitors
title: Key Competitors to Track
instruction: Priority list with rationale
- id: monitoring-metrics
title: Monitoring Metrics
instruction: |
What to track:
- Product updates
- Pricing changes
- Customer wins/losses
- Funding/M&A activity
- Market messaging
- id: intelligence-sources
title: Intelligence Sources
instruction: |
Where to gather ongoing intelligence:
- Company websites/blogs
- Customer reviews
- Industry reports
- Social media
- Patent filings
- id: update-cadence
title: Update Cadence
instruction: |
Recommended review schedule:
- Weekly: {{weekly_items}}
- Monthly: {{monthly_items}}
- Quarterly: {{quarterly_analysis}}

View File

@ -0,0 +1,219 @@
# <!-- Powered by BMAD™ Core -->
template:
id: frontend-architecture-template-v2
name: Frontend Architecture Document
version: 2.0
output:
format: markdown
filename: docs/ui-architecture.md
title: "{{project_name}} Frontend Architecture Document"
workflow:
mode: interactive
elicitation: advanced-elicitation
sections:
- id: template-framework-selection
title: Template and Framework Selection
instruction: |
Review provided documents including PRD, UX-UI Specification, and main Architecture Document. Focus on extracting technical implementation details needed for AI frontend tools and developer agents. Ask the user for any of these documents if you are unable to locate and were not provided.
Before proceeding with frontend architecture design, check if the project is using a frontend starter template or existing codebase:
1. Review the PRD, main architecture document, and brainstorming brief for mentions of:
- Frontend starter templates (e.g., Create React App, Next.js, Vite, Vue CLI, Angular CLI, etc.)
- UI kit or component library starters
- Existing frontend projects being used as a foundation
- Admin dashboard templates or other specialized starters
- Design system implementations
2. If a frontend starter template or existing project is mentioned:
- Ask the user to provide access via one of these methods:
- Link to the starter template documentation
- Upload/attach the project files (for small projects)
- Share a link to the project repository
- Analyze the starter/existing project to understand:
- Pre-installed dependencies and versions
- Folder structure and file organization
- Built-in components and utilities
- Styling approach (CSS modules, styled-components, Tailwind, etc.)
- State management setup (if any)
- Routing configuration
- Testing setup and patterns
- Build and development scripts
- Use this analysis to ensure your frontend architecture aligns with the starter's patterns
3. If no frontend starter is mentioned but this is a new UI, ensure we know what the ui language and framework is:
- Based on the framework choice, suggest appropriate starters:
- React: Create React App, Next.js, Vite + React
- Vue: Vue CLI, Nuxt.js, Vite + Vue
- Angular: Angular CLI
- Or suggest popular UI templates if applicable
- Explain benefits specific to frontend development
4. If the user confirms no starter template will be used:
- Note that all tooling, bundling, and configuration will need manual setup
- Proceed with frontend architecture from scratch
Document the starter template decision and any constraints it imposes before proceeding.
sections:
- id: changelog
title: Change Log
type: table
columns: [Date, Version, Description, Author]
instruction: Track document versions and changes
- id: frontend-tech-stack
title: Frontend Tech Stack
instruction: Extract from main architecture's Technology Stack Table. This section MUST remain synchronized with the main architecture document.
elicit: true
sections:
- id: tech-stack-table
title: Technology Stack Table
type: table
columns: [Category, Technology, Version, Purpose, Rationale]
instruction: Fill in appropriate technology choices based on the selected framework and project requirements.
rows:
- ["Framework", "{{framework}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["UI Library", "{{ui_library}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- [
"State Management",
"{{state_management}}",
"{{version}}",
"{{purpose}}",
"{{why_chosen}}",
]
- ["Routing", "{{routing_library}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Build Tool", "{{build_tool}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Styling", "{{styling_solution}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Testing", "{{test_framework}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- [
"Component Library",
"{{component_lib}}",
"{{version}}",
"{{purpose}}",
"{{why_chosen}}",
]
- ["Form Handling", "{{form_library}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Animation", "{{animation_lib}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Dev Tools", "{{dev_tools}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- id: project-structure
title: Project Structure
instruction: Define exact directory structure for AI tools based on the chosen framework. Be specific about where each type of file goes. Generate a structure that follows the framework's best practices and conventions.
elicit: true
type: code
language: plaintext
- id: component-standards
title: Component Standards
instruction: Define exact patterns for component creation based on the chosen framework.
elicit: true
sections:
- id: component-template
title: Component Template
instruction: Generate a minimal but complete component template following the framework's best practices. Include TypeScript types, proper imports, and basic structure.
type: code
language: typescript
- id: naming-conventions
title: Naming Conventions
instruction: Provide naming conventions specific to the chosen framework for components, files, services, state management, and other architectural elements.
- id: state-management
title: State Management
instruction: Define state management patterns based on the chosen framework.
elicit: true
sections:
- id: store-structure
title: Store Structure
instruction: Generate the state management directory structure appropriate for the chosen framework and selected state management solution.
type: code
language: plaintext
- id: state-template
title: State Management Template
instruction: Provide a basic state management template/example following the framework's recommended patterns. Include TypeScript types and common operations like setting, updating, and clearing state.
type: code
language: typescript
- id: api-integration
title: API Integration
instruction: Define API service patterns based on the chosen framework.
elicit: true
sections:
- id: service-template
title: Service Template
instruction: Provide an API service template that follows the framework's conventions. Include proper TypeScript types, error handling, and async patterns.
type: code
language: typescript
- id: api-client-config
title: API Client Configuration
instruction: Show how to configure the HTTP client for the chosen framework, including authentication interceptors/middleware and error handling.
type: code
language: typescript
- id: routing
title: Routing
instruction: Define routing structure and patterns based on the chosen framework.
elicit: true
sections:
- id: route-configuration
title: Route Configuration
instruction: Provide routing configuration appropriate for the chosen framework. Include protected route patterns, lazy loading where applicable, and authentication guards/middleware.
type: code
language: typescript
- id: styling-guidelines
title: Styling Guidelines
instruction: Define styling approach based on the chosen framework.
elicit: true
sections:
- id: styling-approach
title: Styling Approach
instruction: Describe the styling methodology appropriate for the chosen framework (CSS Modules, Styled Components, Tailwind, etc.) and provide basic patterns.
- id: global-theme
title: Global Theme Variables
instruction: Provide a CSS custom properties (CSS variables) theme system that works across all frameworks. Include colors, spacing, typography, shadows, and dark mode support.
type: code
language: css
- id: testing-requirements
title: Testing Requirements
instruction: Define minimal testing requirements based on the chosen framework.
elicit: true
sections:
- id: component-test-template
title: Component Test Template
instruction: Provide a basic component test template using the framework's recommended testing library. Include examples of rendering tests, user interaction tests, and mocking.
type: code
language: typescript
- id: testing-best-practices
title: Testing Best Practices
type: numbered-list
items:
- "**Unit Tests**: Test individual components in isolation"
- "**Integration Tests**: Test component interactions"
- "**E2E Tests**: Test critical user flows (using Cypress/Playwright)"
- "**Coverage Goals**: Aim for 80% code coverage"
- "**Test Structure**: Arrange-Act-Assert pattern"
- "**Mock External Dependencies**: API calls, routing, state management"
- id: environment-configuration
title: Environment Configuration
instruction: List required environment variables based on the chosen framework. Show the appropriate format and naming conventions for the framework.
elicit: true
- id: frontend-developer-standards
title: Frontend Developer Standards
sections:
- id: critical-coding-rules
title: Critical Coding Rules
instruction: List essential rules that prevent common AI mistakes, including both universal rules and framework-specific ones.
elicit: true
- id: quick-reference
title: Quick Reference
instruction: |
Create a framework-specific cheat sheet with:
- Common commands (dev server, build, test)
- Key import patterns
- File naming conventions
- Project-specific patterns and utilities

View File

@ -0,0 +1,350 @@
# <!-- Powered by BMAD™ Core -->
template:
id: frontend-spec-template-v2
name: UI/UX Specification
version: 2.0
output:
format: markdown
filename: docs/front-end-spec.md
title: "{{project_name}} UI/UX Specification"
workflow:
mode: interactive
elicitation: advanced-elicitation
sections:
- id: introduction
title: Introduction
instruction: |
Review provided documents including Project Brief, PRD, and any user research to gather context. Focus on understanding user needs, pain points, and desired outcomes before beginning the specification.
Establish the document's purpose and scope. Keep the content below but ensure project name is properly substituted.
content: |
This document defines the user experience goals, information architecture, user flows, and visual design specifications for {{project_name}}'s user interface. It serves as the foundation for visual design and frontend development, ensuring a cohesive and user-centered experience.
sections:
- id: ux-goals-principles
title: Overall UX Goals & Principles
instruction: |
Work with the user to establish and document the following. If not already defined, facilitate a discussion to determine:
1. Target User Personas - elicit details or confirm existing ones from PRD
2. Key Usability Goals - understand what success looks like for users
3. Core Design Principles - establish 3-5 guiding principles
elicit: true
sections:
- id: user-personas
title: Target User Personas
template: "{{persona_descriptions}}"
examples:
- "**Power User:** Technical professionals who need advanced features and efficiency"
- "**Casual User:** Occasional users who prioritize ease of use and clear guidance"
- "**Administrator:** System managers who need control and oversight capabilities"
- id: usability-goals
title: Usability Goals
template: "{{usability_goals}}"
examples:
- "Ease of learning: New users can complete core tasks within 5 minutes"
- "Efficiency of use: Power users can complete frequent tasks with minimal clicks"
- "Error prevention: Clear validation and confirmation for destructive actions"
- "Memorability: Infrequent users can return without relearning"
- id: design-principles
title: Design Principles
template: "{{design_principles}}"
type: numbered-list
examples:
- "**Clarity over cleverness** - Prioritize clear communication over aesthetic innovation"
- "**Progressive disclosure** - Show only what's needed, when it's needed"
- "**Consistent patterns** - Use familiar UI patterns throughout the application"
- "**Immediate feedback** - Every action should have a clear, immediate response"
- "**Accessible by default** - Design for all users from the start"
- id: changelog
title: Change Log
type: table
columns: [Date, Version, Description, Author]
instruction: Track document versions and changes
- id: information-architecture
title: Information Architecture (IA)
instruction: |
Collaborate with the user to create a comprehensive information architecture:
1. Build a Site Map or Screen Inventory showing all major areas
2. Define the Navigation Structure (primary, secondary, breadcrumbs)
3. Use Mermaid diagrams for visual representation
4. Consider user mental models and expected groupings
elicit: true
sections:
- id: sitemap
title: Site Map / Screen Inventory
type: mermaid
mermaid_type: graph
template: "{{sitemap_diagram}}"
examples:
- |
graph TD
A[Homepage] --> B[Dashboard]
A --> C[Products]
A --> D[Account]
B --> B1[Analytics]
B --> B2[Recent Activity]
C --> C1[Browse]
C --> C2[Search]
C --> C3[Product Details]
D --> D1[Profile]
D --> D2[Settings]
D --> D3[Billing]
- id: navigation-structure
title: Navigation Structure
template: |
**Primary Navigation:** {{primary_nav_description}}
**Secondary Navigation:** {{secondary_nav_description}}
**Breadcrumb Strategy:** {{breadcrumb_strategy}}
- id: user-flows
title: User Flows
instruction: |
For each critical user task identified in the PRD:
1. Define the user's goal clearly
2. Map out all steps including decision points
3. Consider edge cases and error states
4. Use Mermaid flow diagrams for clarity
5. Link to external tools (Figma/Miro) if detailed flows exist there
Create subsections for each major flow.
elicit: true
repeatable: true
sections:
- id: flow
title: "{{flow_name}}"
template: |
**User Goal:** {{flow_goal}}
**Entry Points:** {{entry_points}}
**Success Criteria:** {{success_criteria}}
sections:
- id: flow-diagram
title: Flow Diagram
type: mermaid
mermaid_type: graph
template: "{{flow_diagram}}"
- id: edge-cases
title: "Edge Cases & Error Handling:"
type: bullet-list
template: "- {{edge_case}}"
- id: notes
template: "**Notes:** {{flow_notes}}"
- id: wireframes-mockups
title: Wireframes & Mockups
instruction: |
Clarify where detailed visual designs will be created (Figma, Sketch, etc.) and how to reference them. If low-fidelity wireframes are needed, offer to help conceptualize layouts for key screens.
elicit: true
sections:
- id: design-files
template: "**Primary Design Files:** {{design_tool_link}}"
- id: key-screen-layouts
title: Key Screen Layouts
repeatable: true
sections:
- id: screen
title: "{{screen_name}}"
template: |
**Purpose:** {{screen_purpose}}
**Key Elements:**
- {{element_1}}
- {{element_2}}
- {{element_3}}
**Interaction Notes:** {{interaction_notes}}
**Design File Reference:** {{specific_frame_link}}
- id: component-library
title: Component Library / Design System
instruction: |
Discuss whether to use an existing design system or create a new one. If creating new, identify foundational components and their key states. Note that detailed technical specs belong in front-end-architecture.
elicit: true
sections:
- id: design-system-approach
template: "**Design System Approach:** {{design_system_approach}}"
- id: core-components
title: Core Components
repeatable: true
sections:
- id: component
title: "{{component_name}}"
template: |
**Purpose:** {{component_purpose}}
**Variants:** {{component_variants}}
**States:** {{component_states}}
**Usage Guidelines:** {{usage_guidelines}}
- id: branding-style
title: Branding & Style Guide
instruction: Link to existing style guide or define key brand elements. Ensure consistency with company brand guidelines if they exist.
elicit: true
sections:
- id: visual-identity
title: Visual Identity
template: "**Brand Guidelines:** {{brand_guidelines_link}}"
- id: color-palette
title: Color Palette
type: table
columns: ["Color Type", "Hex Code", "Usage"]
rows:
- ["Primary", "{{primary_color}}", "{{primary_usage}}"]
- ["Secondary", "{{secondary_color}}", "{{secondary_usage}}"]
- ["Accent", "{{accent_color}}", "{{accent_usage}}"]
- ["Success", "{{success_color}}", "Positive feedback, confirmations"]
- ["Warning", "{{warning_color}}", "Cautions, important notices"]
- ["Error", "{{error_color}}", "Errors, destructive actions"]
- ["Neutral", "{{neutral_colors}}", "Text, borders, backgrounds"]
- id: typography
title: Typography
sections:
- id: font-families
title: Font Families
template: |
- **Primary:** {{primary_font}}
- **Secondary:** {{secondary_font}}
- **Monospace:** {{mono_font}}
- id: type-scale
title: Type Scale
type: table
columns: ["Element", "Size", "Weight", "Line Height"]
rows:
- ["H1", "{{h1_size}}", "{{h1_weight}}", "{{h1_line}}"]
- ["H2", "{{h2_size}}", "{{h2_weight}}", "{{h2_line}}"]
- ["H3", "{{h3_size}}", "{{h3_weight}}", "{{h3_line}}"]
- ["Body", "{{body_size}}", "{{body_weight}}", "{{body_line}}"]
- ["Small", "{{small_size}}", "{{small_weight}}", "{{small_line}}"]
- id: iconography
title: Iconography
template: |
**Icon Library:** {{icon_library}}
**Usage Guidelines:** {{icon_guidelines}}
- id: spacing-layout
title: Spacing & Layout
template: |
**Grid System:** {{grid_system}}
**Spacing Scale:** {{spacing_scale}}
- id: accessibility
title: Accessibility Requirements
instruction: Define specific accessibility requirements based on target compliance level and user needs. Be comprehensive but practical.
elicit: true
sections:
- id: compliance-target
title: Compliance Target
template: "**Standard:** {{compliance_standard}}"
- id: key-requirements
title: Key Requirements
template: |
**Visual:**
- Color contrast ratios: {{contrast_requirements}}
- Focus indicators: {{focus_requirements}}
- Text sizing: {{text_requirements}}
**Interaction:**
- Keyboard navigation: {{keyboard_requirements}}
- Screen reader support: {{screen_reader_requirements}}
- Touch targets: {{touch_requirements}}
**Content:**
- Alternative text: {{alt_text_requirements}}
- Heading structure: {{heading_requirements}}
- Form labels: {{form_requirements}}
- id: testing-strategy
title: Testing Strategy
template: "{{accessibility_testing}}"
- id: responsiveness
title: Responsiveness Strategy
instruction: Define breakpoints and adaptation strategies for different device sizes. Consider both technical constraints and user contexts.
elicit: true
sections:
- id: breakpoints
title: Breakpoints
type: table
columns: ["Breakpoint", "Min Width", "Max Width", "Target Devices"]
rows:
- ["Mobile", "{{mobile_min}}", "{{mobile_max}}", "{{mobile_devices}}"]
- ["Tablet", "{{tablet_min}}", "{{tablet_max}}", "{{tablet_devices}}"]
- ["Desktop", "{{desktop_min}}", "{{desktop_max}}", "{{desktop_devices}}"]
- ["Wide", "{{wide_min}}", "-", "{{wide_devices}}"]
- id: adaptation-patterns
title: Adaptation Patterns
template: |
**Layout Changes:** {{layout_adaptations}}
**Navigation Changes:** {{nav_adaptations}}
**Content Priority:** {{content_adaptations}}
**Interaction Changes:** {{interaction_adaptations}}
- id: animation
title: Animation & Micro-interactions
instruction: Define motion design principles and key interactions. Keep performance and accessibility in mind.
elicit: true
sections:
- id: motion-principles
title: Motion Principles
template: "{{motion_principles}}"
- id: key-animations
title: Key Animations
repeatable: true
template: "- **{{animation_name}}:** {{animation_description}} (Duration: {{duration}}, Easing: {{easing}})"
- id: performance
title: Performance Considerations
instruction: Define performance goals and strategies that impact UX design decisions.
sections:
- id: performance-goals
title: Performance Goals
template: |
- **Page Load:** {{load_time_goal}}
- **Interaction Response:** {{interaction_goal}}
- **Animation FPS:** {{animation_goal}}
- id: design-strategies
title: Design Strategies
template: "{{performance_strategies}}"
- id: next-steps
title: Next Steps
instruction: |
After completing the UI/UX specification:
1. Recommend review with stakeholders
2. Suggest creating/updating visual designs in design tool
3. Prepare for handoff to Design Architect for frontend architecture
4. Note any open questions or decisions needed
sections:
- id: immediate-actions
title: Immediate Actions
type: numbered-list
template: "{{action}}"
- id: design-handoff-checklist
title: Design Handoff Checklist
type: checklist
items:
- "All user flows documented"
- "Component inventory complete"
- "Accessibility requirements defined"
- "Responsive strategy clear"
- "Brand guidelines incorporated"
- "Performance goals established"
- id: checklist-results
title: Checklist Results
instruction: If a UI/UX checklist exists, run it against this document and report results here.

View File

@ -0,0 +1,824 @@
# <!-- Powered by BMAD™ Core -->
template:
id: fullstack-architecture-template-v2
name: Fullstack Architecture Document
version: 2.0
output:
format: markdown
filename: docs/architecture.md
title: "{{project_name}} Fullstack Architecture Document"
workflow:
mode: interactive
elicitation: advanced-elicitation
sections:
- id: introduction
title: Introduction
instruction: |
If available, review any provided relevant documents to gather all relevant context before beginning. At minimum, you should have access to docs/prd.md and docs/front-end-spec.md. Ask the user for any documents you need but cannot locate. This template creates a unified architecture that covers both backend and frontend concerns to guide AI-driven fullstack development.
elicit: true
content: |
This document outlines the complete fullstack architecture for {{project_name}}, including backend systems, frontend implementation, and their integration. It serves as the single source of truth for AI-driven development, ensuring consistency across the entire technology stack.
This unified approach combines what would traditionally be separate backend and frontend architecture documents, streamlining the development process for modern fullstack applications where these concerns are increasingly intertwined.
sections:
- id: starter-template
title: Starter Template or Existing Project
instruction: |
Before proceeding with architecture design, check if the project is based on any starter templates or existing codebases:
1. Review the PRD and other documents for mentions of:
- Fullstack starter templates (e.g., T3 Stack, MEAN/MERN starters, Django + React templates)
- Monorepo templates (e.g., Nx, Turborepo starters)
- Platform-specific starters (e.g., Vercel templates, AWS Amplify starters)
- Existing projects being extended or cloned
2. If starter templates or existing projects are mentioned:
- Ask the user to provide access (links, repos, or files)
- Analyze to understand pre-configured choices and constraints
- Note any architectural decisions already made
- Identify what can be modified vs what must be retained
3. If no starter is mentioned but this is greenfield:
- Suggest appropriate fullstack starters based on tech preferences
- Consider platform-specific options (Vercel, AWS, etc.)
- Let user decide whether to use one
4. Document the decision and any constraints it imposes
If none, state "N/A - Greenfield project"
- id: changelog
title: Change Log
type: table
columns: [Date, Version, Description, Author]
instruction: Track document versions and changes
- id: high-level-architecture
title: High Level Architecture
instruction: This section contains multiple subsections that establish the foundation. Present all subsections together, then elicit feedback on the complete section.
elicit: true
sections:
- id: technical-summary
title: Technical Summary
instruction: |
Provide a comprehensive overview (4-6 sentences) covering:
- Overall architectural style and deployment approach
- Frontend framework and backend technology choices
- Key integration points between frontend and backend
- Infrastructure platform and services
- How this architecture achieves PRD goals
- id: platform-infrastructure
title: Platform and Infrastructure Choice
instruction: |
Based on PRD requirements and technical assumptions, make a platform recommendation:
1. Consider common patterns (not an exhaustive list, use your own best judgement and search the web as needed for emerging trends):
- **Vercel + Supabase**: For rapid development with Next.js, built-in auth/storage
- **AWS Full Stack**: For enterprise scale with Lambda, API Gateway, S3, Cognito
- **Azure**: For .NET ecosystems or enterprise Microsoft environments
- **Google Cloud**: For ML/AI heavy applications or Google ecosystem integration
2. Present 2-3 viable options with clear pros/cons
3. Make a recommendation with rationale
4. Get explicit user confirmation
Document the choice and key services that will be used.
template: |
**Platform:** {{selected_platform}}
**Key Services:** {{core_services_list}}
**Deployment Host and Regions:** {{regions}}
- id: repository-structure
title: Repository Structure
instruction: |
Define the repository approach based on PRD requirements and platform choice, explain your rationale or ask questions to the user if unsure:
1. For modern fullstack apps, monorepo is often preferred
2. Consider tooling (Nx, Turborepo, Lerna, npm workspaces)
3. Define package/app boundaries
4. Plan for shared code between frontend and backend
template: |
**Structure:** {{repo_structure_choice}}
**Monorepo Tool:** {{monorepo_tool_if_applicable}}
**Package Organization:** {{package_strategy}}
- id: architecture-diagram
title: High Level Architecture Diagram
type: mermaid
mermaid_type: graph
instruction: |
Create a Mermaid diagram showing the complete system architecture including:
- User entry points (web, mobile)
- Frontend application deployment
- API layer (REST/GraphQL)
- Backend services
- Databases and storage
- External integrations
- CDN and caching layers
Use appropriate diagram type for clarity.
- id: architectural-patterns
title: Architectural Patterns
instruction: |
List patterns that will guide both frontend and backend development. Include patterns for:
- Overall architecture (e.g., Jamstack, Serverless, Microservices)
- Frontend patterns (e.g., Component-based, State management)
- Backend patterns (e.g., Repository, CQRS, Event-driven)
- Integration patterns (e.g., BFF, API Gateway)
For each pattern, provide recommendation and rationale.
repeatable: true
template: "- **{{pattern_name}}:** {{pattern_description}} - _Rationale:_ {{rationale}}"
examples:
- "**Jamstack Architecture:** Static site generation with serverless APIs - _Rationale:_ Optimal performance and scalability for content-heavy applications"
- "**Component-Based UI:** Reusable React components with TypeScript - _Rationale:_ Maintainability and type safety across large codebases"
- "**Repository Pattern:** Abstract data access logic - _Rationale:_ Enables testing and future database migration flexibility"
- "**API Gateway Pattern:** Single entry point for all API calls - _Rationale:_ Centralized auth, rate limiting, and monitoring"
- id: tech-stack
title: Tech Stack
instruction: |
This is the DEFINITIVE technology selection for the entire project. Work with user to finalize all choices. This table is the single source of truth - all development must use these exact versions.
Key areas to cover:
- Frontend and backend languages/frameworks
- Databases and caching
- Authentication and authorization
- API approach
- Testing tools for both frontend and backend
- Build and deployment tools
- Monitoring and logging
Upon render, elicit feedback immediately.
elicit: true
sections:
- id: tech-stack-table
title: Technology Stack Table
type: table
columns: [Category, Technology, Version, Purpose, Rationale]
rows:
- ["Frontend Language", "{{fe_language}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- [
"Frontend Framework",
"{{fe_framework}}",
"{{version}}",
"{{purpose}}",
"{{why_chosen}}",
]
- [
"UI Component Library",
"{{ui_library}}",
"{{version}}",
"{{purpose}}",
"{{why_chosen}}",
]
- ["State Management", "{{state_mgmt}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Backend Language", "{{be_language}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- [
"Backend Framework",
"{{be_framework}}",
"{{version}}",
"{{purpose}}",
"{{why_chosen}}",
]
- ["API Style", "{{api_style}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Database", "{{database}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Cache", "{{cache}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["File Storage", "{{storage}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Authentication", "{{auth}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Frontend Testing", "{{fe_test}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Backend Testing", "{{be_test}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["E2E Testing", "{{e2e_test}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Build Tool", "{{build_tool}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Bundler", "{{bundler}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["IaC Tool", "{{iac_tool}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["CI/CD", "{{cicd}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Monitoring", "{{monitoring}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["Logging", "{{logging}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- ["CSS Framework", "{{css_framework}}", "{{version}}", "{{purpose}}", "{{why_chosen}}"]
- id: data-models
title: Data Models
instruction: |
Define the core data models/entities that will be shared between frontend and backend:
1. Review PRD requirements and identify key business entities
2. For each model, explain its purpose and relationships
3. Include key attributes and data types
4. Show relationships between models
5. Create TypeScript interfaces that can be shared
6. Discuss design decisions with user
Create a clear conceptual model before moving to database schema.
elicit: true
repeatable: true
sections:
- id: model
title: "{{model_name}}"
template: |
**Purpose:** {{model_purpose}}
**Key Attributes:**
- {{attribute_1}}: {{type_1}} - {{description_1}}
- {{attribute_2}}: {{type_2}} - {{description_2}}
sections:
- id: typescript-interface
title: TypeScript Interface
type: code
language: typescript
template: "{{model_interface}}"
- id: relationships
title: Relationships
type: bullet-list
template: "- {{relationship}}"
- id: api-spec
title: API Specification
instruction: |
Based on the chosen API style from Tech Stack:
1. If REST API, create an OpenAPI 3.0 specification
2. If GraphQL, provide the GraphQL schema
3. If tRPC, show router definitions
4. Include all endpoints from epics/stories
5. Define request/response schemas based on data models
6. Document authentication requirements
7. Include example requests/responses
Use appropriate format for the chosen API style. If no API (e.g., static site), skip this section.
elicit: true
sections:
- id: rest-api
title: REST API Specification
condition: API style is REST
type: code
language: yaml
template: |
openapi: 3.0.0
info:
title: {{api_title}}
version: {{api_version}}
description: {{api_description}}
servers:
- url: {{server_url}}
description: {{server_description}}
- id: graphql-api
title: GraphQL Schema
condition: API style is GraphQL
type: code
language: graphql
template: "{{graphql_schema}}"
- id: trpc-api
title: tRPC Router Definitions
condition: API style is tRPC
type: code
language: typescript
template: "{{trpc_routers}}"
- id: components
title: Components
instruction: |
Based on the architectural patterns, tech stack, and data models from above:
1. Identify major logical components/services across the fullstack
2. Consider both frontend and backend components
3. Define clear boundaries and interfaces between components
4. For each component, specify:
- Primary responsibility
- Key interfaces/APIs exposed
- Dependencies on other components
- Technology specifics based on tech stack choices
5. Create component diagrams where helpful
elicit: true
sections:
- id: component-list
repeatable: true
title: "{{component_name}}"
template: |
**Responsibility:** {{component_description}}
**Key Interfaces:**
- {{interface_1}}
- {{interface_2}}
**Dependencies:** {{dependencies}}
**Technology Stack:** {{component_tech_details}}
- id: component-diagrams
title: Component Diagrams
type: mermaid
instruction: |
Create Mermaid diagrams to visualize component relationships. Options:
- C4 Container diagram for high-level view
- Component diagram for detailed internal structure
- Sequence diagrams for complex interactions
Choose the most appropriate for clarity
- id: external-apis
title: External APIs
condition: Project requires external API integrations
instruction: |
For each external service integration:
1. Identify APIs needed based on PRD requirements and component design
2. If documentation URLs are unknown, ask user for specifics
3. Document authentication methods and security considerations
4. List specific endpoints that will be used
5. Note any rate limits or usage constraints
If no external APIs are needed, state this explicitly and skip to next section.
elicit: true
repeatable: true
sections:
- id: api
title: "{{api_name}} API"
template: |
- **Purpose:** {{api_purpose}}
- **Documentation:** {{api_docs_url}}
- **Base URL(s):** {{api_base_url}}
- **Authentication:** {{auth_method}}
- **Rate Limits:** {{rate_limits}}
**Key Endpoints Used:**
- `{{method}} {{endpoint_path}}` - {{endpoint_purpose}}
**Integration Notes:** {{integration_considerations}}
- id: core-workflows
title: Core Workflows
type: mermaid
mermaid_type: sequence
instruction: |
Illustrate key system workflows using sequence diagrams:
1. Identify critical user journeys from PRD
2. Show component interactions including external APIs
3. Include both frontend and backend flows
4. Include error handling paths
5. Document async operations
6. Create both high-level and detailed diagrams as needed
Focus on workflows that clarify architecture decisions or complex interactions.
elicit: true
- id: database-schema
title: Database Schema
instruction: |
Transform the conceptual data models into concrete database schemas:
1. Use the database type(s) selected in Tech Stack
2. Create schema definitions using appropriate notation
3. Include indexes, constraints, and relationships
4. Consider performance and scalability
5. For NoSQL, show document structures
Present schema in format appropriate to database type (SQL DDL, JSON schema, etc.)
elicit: true
- id: frontend-architecture
title: Frontend Architecture
instruction: Define frontend-specific architecture details. After each subsection, note if user wants to refine before continuing.
elicit: true
sections:
- id: component-architecture
title: Component Architecture
instruction: Define component organization and patterns based on chosen framework.
sections:
- id: component-organization
title: Component Organization
type: code
language: text
template: "{{component_structure}}"
- id: component-template
title: Component Template
type: code
language: typescript
template: "{{component_template}}"
- id: state-management
title: State Management Architecture
instruction: Detail state management approach based on chosen solution.
sections:
- id: state-structure
title: State Structure
type: code
language: typescript
template: "{{state_structure}}"
- id: state-patterns
title: State Management Patterns
type: bullet-list
template: "- {{pattern}}"
- id: routing-architecture
title: Routing Architecture
instruction: Define routing structure based on framework choice.
sections:
- id: route-organization
title: Route Organization
type: code
language: text
template: "{{route_structure}}"
- id: protected-routes
title: Protected Route Pattern
type: code
language: typescript
template: "{{protected_route_example}}"
- id: frontend-services
title: Frontend Services Layer
instruction: Define how frontend communicates with backend.
sections:
- id: api-client-setup
title: API Client Setup
type: code
language: typescript
template: "{{api_client_setup}}"
- id: service-example
title: Service Example
type: code
language: typescript
template: "{{service_example}}"
- id: backend-architecture
title: Backend Architecture
instruction: Define backend-specific architecture details. Consider serverless vs traditional server approaches.
elicit: true
sections:
- id: service-architecture
title: Service Architecture
instruction: Based on platform choice, define service organization.
sections:
- id: serverless-architecture
condition: Serverless architecture chosen
sections:
- id: function-organization
title: Function Organization
type: code
language: text
template: "{{function_structure}}"
- id: function-template
title: Function Template
type: code
language: typescript
template: "{{function_template}}"
- id: traditional-server
condition: Traditional server architecture chosen
sections:
- id: controller-organization
title: Controller/Route Organization
type: code
language: text
template: "{{controller_structure}}"
- id: controller-template
title: Controller Template
type: code
language: typescript
template: "{{controller_template}}"
- id: database-architecture
title: Database Architecture
instruction: Define database schema and access patterns.
sections:
- id: schema-design
title: Schema Design
type: code
language: sql
template: "{{database_schema}}"
- id: data-access-layer
title: Data Access Layer
type: code
language: typescript
template: "{{repository_pattern}}"
- id: auth-architecture
title: Authentication and Authorization
instruction: Define auth implementation details.
sections:
- id: auth-flow
title: Auth Flow
type: mermaid
mermaid_type: sequence
template: "{{auth_flow_diagram}}"
- id: auth-middleware
title: Middleware/Guards
type: code
language: typescript
template: "{{auth_middleware}}"
- id: unified-project-structure
title: Unified Project Structure
instruction: Create a monorepo structure that accommodates both frontend and backend. Adapt based on chosen tools and frameworks.
elicit: true
type: code
language: plaintext
examples:
- |
{{project-name}}/
├── .github/ # CI/CD workflows
│ └── workflows/
│ ├── ci.yaml
│ └── deploy.yaml
├── apps/ # Application packages
│ ├── web/ # Frontend application
│ │ ├── src/
│ │ │ ├── components/ # UI components
│ │ │ ├── pages/ # Page components/routes
│ │ │ ├── hooks/ # Custom React hooks
│ │ │ ├── services/ # API client services
│ │ │ ├── stores/ # State management
│ │ │ ├── styles/ # Global styles/themes
│ │ │ └── utils/ # Frontend utilities
│ │ ├── public/ # Static assets
│ │ ├── tests/ # Frontend tests
│ │ └── package.json
│ └── api/ # Backend application
│ ├── src/
│ │ ├── routes/ # API routes/controllers
│ │ ├── services/ # Business logic
│ │ ├── models/ # Data models
│ │ ├── middleware/ # Express/API middleware
│ │ ├── utils/ # Backend utilities
│ │ └── {{serverless_or_server_entry}}
│ ├── tests/ # Backend tests
│ └── package.json
├── packages/ # Shared packages
│ ├── shared/ # Shared types/utilities
│ │ ├── src/
│ │ │ ├── types/ # TypeScript interfaces
│ │ │ ├── constants/ # Shared constants
│ │ │ └── utils/ # Shared utilities
│ │ └── package.json
│ ├── ui/ # Shared UI components
│ │ ├── src/
│ │ └── package.json
│ └── config/ # Shared configuration
│ ├── eslint/
│ ├── typescript/
│ └── jest/
├── infrastructure/ # IaC definitions
│ └── {{iac_structure}}
├── scripts/ # Build/deploy scripts
├── docs/ # Documentation
│ ├── prd.md
│ ├── front-end-spec.md
│ └── fullstack-architecture.md
├── .env.example # Environment template
├── package.json # Root package.json
├── {{monorepo_config}} # Monorepo configuration
└── README.md
- id: development-workflow
title: Development Workflow
instruction: Define the development setup and workflow for the fullstack application.
elicit: true
sections:
- id: local-setup
title: Local Development Setup
sections:
- id: prerequisites
title: Prerequisites
type: code
language: bash
template: "{{prerequisites_commands}}"
- id: initial-setup
title: Initial Setup
type: code
language: bash
template: "{{setup_commands}}"
- id: dev-commands
title: Development Commands
type: code
language: bash
template: |
# Start all services
{{start_all_command}}
# Start frontend only
{{start_frontend_command}}
# Start backend only
{{start_backend_command}}
# Run tests
{{test_commands}}
- id: environment-config
title: Environment Configuration
sections:
- id: env-vars
title: Required Environment Variables
type: code
language: bash
template: |
# Frontend (.env.local)
{{frontend_env_vars}}
# Backend (.env)
{{backend_env_vars}}
# Shared
{{shared_env_vars}}
- id: deployment-architecture
title: Deployment Architecture
instruction: Define deployment strategy based on platform choice.
elicit: true
sections:
- id: deployment-strategy
title: Deployment Strategy
template: |
**Frontend Deployment:**
- **Platform:** {{frontend_deploy_platform}}
- **Build Command:** {{frontend_build_command}}
- **Output Directory:** {{frontend_output_dir}}
- **CDN/Edge:** {{cdn_strategy}}
**Backend Deployment:**
- **Platform:** {{backend_deploy_platform}}
- **Build Command:** {{backend_build_command}}
- **Deployment Method:** {{deployment_method}}
- id: cicd-pipeline
title: CI/CD Pipeline
type: code
language: yaml
template: "{{cicd_pipeline_config}}"
- id: environments
title: Environments
type: table
columns: [Environment, Frontend URL, Backend URL, Purpose]
rows:
- ["Development", "{{dev_fe_url}}", "{{dev_be_url}}", "Local development"]
- ["Staging", "{{staging_fe_url}}", "{{staging_be_url}}", "Pre-production testing"]
- ["Production", "{{prod_fe_url}}", "{{prod_be_url}}", "Live environment"]
- id: security-performance
title: Security and Performance
instruction: Define security and performance considerations for the fullstack application.
elicit: true
sections:
- id: security-requirements
title: Security Requirements
template: |
**Frontend Security:**
- CSP Headers: {{csp_policy}}
- XSS Prevention: {{xss_strategy}}
- Secure Storage: {{storage_strategy}}
**Backend Security:**
- Input Validation: {{validation_approach}}
- Rate Limiting: {{rate_limit_config}}
- CORS Policy: {{cors_config}}
**Authentication Security:**
- Token Storage: {{token_strategy}}
- Session Management: {{session_approach}}
- Password Policy: {{password_requirements}}
- id: performance-optimization
title: Performance Optimization
template: |
**Frontend Performance:**
- Bundle Size Target: {{bundle_size}}
- Loading Strategy: {{loading_approach}}
- Caching Strategy: {{fe_cache_strategy}}
**Backend Performance:**
- Response Time Target: {{response_target}}
- Database Optimization: {{db_optimization}}
- Caching Strategy: {{be_cache_strategy}}
- id: testing-strategy
title: Testing Strategy
instruction: Define comprehensive testing approach for fullstack application.
elicit: true
sections:
- id: testing-pyramid
title: Testing Pyramid
type: code
language: text
template: |
E2E Tests
/ \
Integration Tests
/ \
Frontend Unit Backend Unit
- id: test-organization
title: Test Organization
sections:
- id: frontend-tests
title: Frontend Tests
type: code
language: text
template: "{{frontend_test_structure}}"
- id: backend-tests
title: Backend Tests
type: code
language: text
template: "{{backend_test_structure}}"
- id: e2e-tests
title: E2E Tests
type: code
language: text
template: "{{e2e_test_structure}}"
- id: test-examples
title: Test Examples
sections:
- id: frontend-test
title: Frontend Component Test
type: code
language: typescript
template: "{{frontend_test_example}}"
- id: backend-test
title: Backend API Test
type: code
language: typescript
template: "{{backend_test_example}}"
- id: e2e-test
title: E2E Test
type: code
language: typescript
template: "{{e2e_test_example}}"
- id: coding-standards
title: Coding Standards
instruction: Define MINIMAL but CRITICAL standards for AI agents. Focus only on project-specific rules that prevent common mistakes. These will be used by dev agents.
elicit: true
sections:
- id: critical-rules
title: Critical Fullstack Rules
repeatable: true
template: "- **{{rule_name}}:** {{rule_description}}"
examples:
- "**Type Sharing:** Always define types in packages/shared and import from there"
- "**API Calls:** Never make direct HTTP calls - use the service layer"
- "**Environment Variables:** Access only through config objects, never process.env directly"
- "**Error Handling:** All API routes must use the standard error handler"
- "**State Updates:** Never mutate state directly - use proper state management patterns"
- id: naming-conventions
title: Naming Conventions
type: table
columns: [Element, Frontend, Backend, Example]
rows:
- ["Components", "PascalCase", "-", "`UserProfile.tsx`"]
- ["Hooks", "camelCase with 'use'", "-", "`useAuth.ts`"]
- ["API Routes", "-", "kebab-case", "`/api/user-profile`"]
- ["Database Tables", "-", "snake_case", "`user_profiles`"]
- id: error-handling
title: Error Handling Strategy
instruction: Define unified error handling across frontend and backend.
elicit: true
sections:
- id: error-flow
title: Error Flow
type: mermaid
mermaid_type: sequence
template: "{{error_flow_diagram}}"
- id: error-format
title: Error Response Format
type: code
language: typescript
template: |
interface ApiError {
error: {
code: string;
message: string;
details?: Record<string, any>;
timestamp: string;
requestId: string;
};
}
- id: frontend-error-handling
title: Frontend Error Handling
type: code
language: typescript
template: "{{frontend_error_handler}}"
- id: backend-error-handling
title: Backend Error Handling
type: code
language: typescript
template: "{{backend_error_handler}}"
- id: monitoring
title: Monitoring and Observability
instruction: Define monitoring strategy for fullstack application.
elicit: true
sections:
- id: monitoring-stack
title: Monitoring Stack
template: |
- **Frontend Monitoring:** {{frontend_monitoring}}
- **Backend Monitoring:** {{backend_monitoring}}
- **Error Tracking:** {{error_tracking}}
- **Performance Monitoring:** {{perf_monitoring}}
- id: key-metrics
title: Key Metrics
template: |
**Frontend Metrics:**
- Core Web Vitals
- JavaScript errors
- API response times
- User interactions
**Backend Metrics:**
- Request rate
- Error rate
- Response time
- Database query performance
- id: checklist-results
title: Checklist Results Report
instruction: Before running the checklist, offer to output the full architecture document. Once user confirms, execute the architect-checklist and populate results here.

View File

@ -0,0 +1,253 @@
# <!-- Powered by BMAD™ Core -->
template:
id: market-research-template-v2
name: Market Research Report
version: 2.0
output:
format: markdown
filename: docs/market-research.md
title: "Market Research Report: {{project_product_name}}"
workflow:
mode: interactive
elicitation: advanced-elicitation
custom_elicitation:
title: "Market Research Elicitation Actions"
options:
- "Expand market sizing calculations with sensitivity analysis"
- "Deep dive into a specific customer segment"
- "Analyze an emerging market trend in detail"
- "Compare this market to an analogous market"
- "Stress test market assumptions"
- "Explore adjacent market opportunities"
- "Challenge market definition and boundaries"
- "Generate strategic scenarios (best/base/worst case)"
- "If only we had considered [X market factor]..."
- "Proceed to next section"
sections:
- id: executive-summary
title: Executive Summary
instruction: Provide a high-level overview of key findings, market opportunity assessment, and strategic recommendations. Write this section LAST after completing all other sections.
- id: research-objectives
title: Research Objectives & Methodology
instruction: This template guides the creation of a comprehensive market research report. Begin by understanding what market insights the user needs and why. Work through each section systematically, using the appropriate analytical frameworks based on the research objectives.
sections:
- id: objectives
title: Research Objectives
instruction: |
List the primary objectives of this market research:
- What decisions will this research inform?
- What specific questions need to be answered?
- What are the success criteria for this research?
- id: methodology
title: Research Methodology
instruction: |
Describe the research approach:
- Data sources used (primary/secondary)
- Analysis frameworks applied
- Data collection timeframe
- Limitations and assumptions
- id: market-overview
title: Market Overview
sections:
- id: market-definition
title: Market Definition
instruction: |
Define the market being analyzed:
- Product/service category
- Geographic scope
- Customer segments included
- Value chain position
- id: market-size-growth
title: Market Size & Growth
instruction: |
Guide through TAM, SAM, SOM calculations with clear assumptions. Use one or more approaches:
- Top-down: Start with industry data, narrow down
- Bottom-up: Build from customer/unit economics
- Value theory: Based on value provided vs. alternatives
sections:
- id: tam
title: Total Addressable Market (TAM)
instruction: Calculate and explain the total market opportunity
- id: sam
title: Serviceable Addressable Market (SAM)
instruction: Define the portion of TAM you can realistically reach
- id: som
title: Serviceable Obtainable Market (SOM)
instruction: Estimate the portion you can realistically capture
- id: market-trends
title: Market Trends & Drivers
instruction: Analyze key trends shaping the market using appropriate frameworks like PESTEL
sections:
- id: key-trends
title: Key Market Trends
instruction: |
List and explain 3-5 major trends:
- Trend 1: Description and impact
- Trend 2: Description and impact
- etc.
- id: growth-drivers
title: Growth Drivers
instruction: Identify primary factors driving market growth
- id: market-inhibitors
title: Market Inhibitors
instruction: Identify factors constraining market growth
- id: customer-analysis
title: Customer Analysis
sections:
- id: segment-profiles
title: Target Segment Profiles
instruction: For each segment, create detailed profiles including demographics/firmographics, psychographics, behaviors, needs, and willingness to pay
repeatable: true
sections:
- id: segment
title: "Segment {{segment_number}}: {{segment_name}}"
template: |
- **Description:** {{brief_overview}}
- **Size:** {{number_of_customers_market_value}}
- **Characteristics:** {{key_demographics_firmographics}}
- **Needs & Pain Points:** {{primary_problems}}
- **Buying Process:** {{purchasing_decisions}}
- **Willingness to Pay:** {{price_sensitivity}}
- id: jobs-to-be-done
title: Jobs-to-be-Done Analysis
instruction: Uncover what customers are really trying to accomplish
sections:
- id: functional-jobs
title: Functional Jobs
instruction: List practical tasks and objectives customers need to complete
- id: emotional-jobs
title: Emotional Jobs
instruction: Describe feelings and perceptions customers seek
- id: social-jobs
title: Social Jobs
instruction: Explain how customers want to be perceived by others
- id: customer-journey
title: Customer Journey Mapping
instruction: Map the end-to-end customer experience for primary segments
template: |
For primary customer segment:
1. **Awareness:** {{discovery_process}}
2. **Consideration:** {{evaluation_criteria}}
3. **Purchase:** {{decision_triggers}}
4. **Onboarding:** {{initial_expectations}}
5. **Usage:** {{interaction_patterns}}
6. **Advocacy:** {{referral_behaviors}}
- id: competitive-landscape
title: Competitive Landscape
sections:
- id: market-structure
title: Market Structure
instruction: |
Describe the overall competitive environment:
- Number of competitors
- Market concentration
- Competitive intensity
- id: major-players
title: Major Players Analysis
instruction: |
For top 3-5 competitors:
- Company name and brief description
- Market share estimate
- Key strengths and weaknesses
- Target customer focus
- Pricing strategy
- id: competitive-positioning
title: Competitive Positioning
instruction: |
Analyze how competitors are positioned:
- Value propositions
- Differentiation strategies
- Market gaps and opportunities
- id: industry-analysis
title: Industry Analysis
sections:
- id: porters-five-forces
title: Porter's Five Forces Assessment
instruction: Analyze each force with specific evidence and implications
sections:
- id: supplier-power
title: "Supplier Power: {{power_level}}"
template: "{{analysis_and_implications}}"
- id: buyer-power
title: "Buyer Power: {{power_level}}"
template: "{{analysis_and_implications}}"
- id: competitive-rivalry
title: "Competitive Rivalry: {{intensity_level}}"
template: "{{analysis_and_implications}}"
- id: threat-new-entry
title: "Threat of New Entry: {{threat_level}}"
template: "{{analysis_and_implications}}"
- id: threat-substitutes
title: "Threat of Substitutes: {{threat_level}}"
template: "{{analysis_and_implications}}"
- id: adoption-lifecycle
title: Technology Adoption Lifecycle Stage
instruction: |
Identify where the market is in the adoption curve:
- Current stage and evidence
- Implications for strategy
- Expected progression timeline
- id: opportunity-assessment
title: Opportunity Assessment
sections:
- id: market-opportunities
title: Market Opportunities
instruction: Identify specific opportunities based on the analysis
repeatable: true
sections:
- id: opportunity
title: "Opportunity {{opportunity_number}}: {{name}}"
template: |
- **Description:** {{what_is_the_opportunity}}
- **Size/Potential:** {{quantified_potential}}
- **Requirements:** {{needed_to_capture}}
- **Risks:** {{key_challenges}}
- id: strategic-recommendations
title: Strategic Recommendations
sections:
- id: go-to-market
title: Go-to-Market Strategy
instruction: |
Recommend approach for market entry/expansion:
- Target segment prioritization
- Positioning strategy
- Channel strategy
- Partnership opportunities
- id: pricing-strategy
title: Pricing Strategy
instruction: |
Based on willingness to pay analysis and competitive landscape:
- Recommended pricing model
- Price points/ranges
- Value metric
- Competitive positioning
- id: risk-mitigation
title: Risk Mitigation
instruction: |
Key risks and mitigation strategies:
- Market risks
- Competitive risks
- Execution risks
- Regulatory/compliance risks
- id: appendices
title: Appendices
sections:
- id: data-sources
title: A. Data Sources
instruction: List all sources used in the research
- id: calculations
title: B. Detailed Calculations
instruction: Include any complex calculations or models
- id: additional-analysis
title: C. Additional Analysis
instruction: Any supplementary analysis not included in main body

View File

@ -0,0 +1,203 @@
# <!-- Powered by BMAD™ Core -->
template:
id: prd-template-v2
name: Product Requirements Document
version: 2.0
output:
format: markdown
filename: docs/prd.md
title: "{{project_name}} Product Requirements Document (PRD)"
workflow:
mode: interactive
elicitation: advanced-elicitation
sections:
- id: goals-context
title: Goals and Background Context
instruction: |
Ask if Project Brief document is available. If NO Project Brief exists, STRONGLY recommend creating one first using project-brief-tmpl (it provides essential foundation: problem statement, target users, success metrics, MVP scope, constraints). If user insists on PRD without brief, gather this information during Goals section. If Project Brief exists, review and use it to populate Goals (bullet list of desired outcomes) and Background Context (1-2 paragraphs on what this solves and why) so we can determine what is and is not in scope for PRD mvp. Either way this is critical to determine the requirements. Include Change Log table.
sections:
- id: goals
title: Goals
type: bullet-list
instruction: Bullet list of 1 line desired outcomes the PRD will deliver if successful - user and project desires
- id: background
title: Background Context
type: paragraphs
instruction: 1-2 short paragraphs summarizing the background context, such as what we learned in the brief without being redundant with the goals, what and why this solves a problem, what the current landscape or need is
- id: changelog
title: Change Log
type: table
columns: [Date, Version, Description, Author]
instruction: Track document versions and changes
- id: requirements
title: Requirements
instruction: Draft the list of functional and non functional requirements under the two child sections
elicit: true
sections:
- id: functional
title: Functional
type: numbered-list
prefix: FR
instruction: Each Requirement will be a bullet markdown and an identifier sequence starting with FR
examples:
- "FR6: The Todo List uses AI to detect and warn against potentially duplicate todo items that are worded differently."
- id: non-functional
title: Non Functional
type: numbered-list
prefix: NFR
instruction: Each Requirement will be a bullet markdown and an identifier sequence starting with NFR
examples:
- "NFR1: AWS service usage must aim to stay within free-tier limits where feasible."
- id: ui-goals
title: User Interface Design Goals
condition: PRD has UX/UI requirements
instruction: |
Capture high-level UI/UX vision to guide Design Architect and to inform story creation. Steps:
1. Pre-fill all subsections with educated guesses based on project context
2. Present the complete rendered section to user
3. Clearly let the user know where assumptions were made
4. Ask targeted questions for unclear/missing elements or areas needing more specification
5. This is NOT detailed UI spec - focus on product vision and user goals
elicit: true
choices:
accessibility: [None, WCAG AA, WCAG AAA]
platforms: [Web Responsive, Mobile Only, Desktop Only, Cross-Platform]
sections:
- id: ux-vision
title: Overall UX Vision
- id: interaction-paradigms
title: Key Interaction Paradigms
- id: core-screens
title: Core Screens and Views
instruction: From a product perspective, what are the most critical screens or views necessary to deliver the the PRD values and goals? This is meant to be Conceptual High Level to Drive Rough Epic or User Stories
examples:
- "Login Screen"
- "Main Dashboard"
- "Item Detail Page"
- "Settings Page"
- id: accessibility
title: "Accessibility: {None|WCAG AA|WCAG AAA|Custom Requirements}"
- id: branding
title: Branding
instruction: Any known branding elements or style guides that must be incorporated?
examples:
- "Replicate the look and feel of early 1900s black and white cinema, including animated effects replicating film damage or projector glitches during page or state transitions."
- "Attached is the full color pallet and tokens for our corporate branding."
- id: target-platforms
title: "Target Device and Platforms: {Web Responsive|Mobile Only|Desktop Only|Cross-Platform}"
examples:
- "Web Responsive, and all mobile platforms"
- "iPhone Only"
- "ASCII Windows Desktop"
- id: technical-assumptions
title: Technical Assumptions
instruction: |
Gather technical decisions that will guide the Architect. Steps:
1. Check if .bmad-core/data/technical-preferences.yaml or an attached technical-preferences file exists - use it to pre-populate choices
2. Ask user about: languages, frameworks, starter templates, libraries, APIs, deployment targets
3. For unknowns, offer guidance based on project goals and MVP scope
4. Document ALL technical choices with rationale (why this choice fits the project)
5. These become constraints for the Architect - be specific and complete
elicit: true
choices:
repository: [Monorepo, Polyrepo]
architecture: [Monolith, Microservices, Serverless]
testing: [Unit Only, Unit + Integration, Full Testing Pyramid]
sections:
- id: repository-structure
title: "Repository Structure: {Monorepo|Polyrepo|Multi-repo}"
- id: service-architecture
title: Service Architecture
instruction: "CRITICAL DECISION - Document the high-level service architecture (e.g., Monolith, Microservices, Serverless functions within a Monorepo)."
- id: testing-requirements
title: Testing Requirements
instruction: "CRITICAL DECISION - Document the testing requirements, unit only, integration, e2e, manual, need for manual testing convenience methods)."
- id: additional-assumptions
title: Additional Technical Assumptions and Requests
instruction: Throughout the entire process of drafting this document, if any other technical assumptions are raised or discovered appropriate for the architect, add them here as additional bulleted items
- id: epic-list
title: Epic List
instruction: |
Present a high-level list of all epics for user approval. Each epic should have a title and a short (1 sentence) goal statement. This allows the user to review the overall structure before diving into details.
CRITICAL: Epics MUST be logically sequential following agile best practices:
- Each epic should deliver a significant, end-to-end, fully deployable increment of testable functionality
- Epic 1 must establish foundational project infrastructure (app setup, Git, CI/CD, core services) unless we are adding new functionality to an existing app, while also delivering an initial piece of functionality, even as simple as a health-check route or display of a simple canary page - remember this when we produce the stories for the first epic!
- Each subsequent epic builds upon previous epics' functionality delivering major blocks of functionality that provide tangible value to users or business when deployed
- Not every project needs multiple epics, an epic needs to deliver value. For example, an API completed can deliver value even if a UI is not complete and planned for a separate epic.
- Err on the side of less epics, but let the user know your rationale and offer options for splitting them if it seems some are too large or focused on disparate things.
- Cross Cutting Concerns should flow through epics and stories and not be final stories. For example, adding a logging framework as a last story of an epic, or at the end of a project as a final epic or story would be terrible as we would not have logging from the beginning.
elicit: true
examples:
- "Epic 1: Foundation & Core Infrastructure: Establish project setup, authentication, and basic user management"
- "Epic 2: Core Business Entities: Create and manage primary domain objects with CRUD operations"
- "Epic 3: User Workflows & Interactions: Enable key user journeys and business processes"
- "Epic 4: Reporting & Analytics: Provide insights and data visualization for users"
- id: epic-details
title: Epic {{epic_number}} {{epic_title}}
repeatable: true
instruction: |
After the epic list is approved, present each epic with all its stories and acceptance criteria as a complete review unit.
For each epic provide expanded goal (2-3 sentences describing the objective and value all the stories will achieve).
CRITICAL STORY SEQUENCING REQUIREMENTS:
- Stories within each epic MUST be logically sequential
- Each story should be a "vertical slice" delivering complete functionality aside from early enabler stories for project foundation
- No story should depend on work from a later story or epic
- Identify and note any direct prerequisite stories
- Focus on "what" and "why" not "how" (leave technical implementation to Architect) yet be precise enough to support a logical sequential order of operations from story to story.
- Ensure each story delivers clear user or business value, try to avoid enablers and build them into stories that deliver value.
- Size stories for AI agent execution: Each story must be completable by a single AI agent in one focused session without context overflow
- Think "junior developer working for 2-4 hours" - stories must be small, focused, and self-contained
- If a story seems complex, break it down further as long as it can deliver a vertical slice
elicit: true
template: "{{epic_goal}}"
sections:
- id: story
title: Story {{epic_number}}.{{story_number}} {{story_title}}
repeatable: true
template: |
As a {{user_type}},
I want {{action}},
so that {{benefit}}.
sections:
- id: acceptance-criteria
title: Acceptance Criteria
type: numbered-list
item_template: "{{criterion_number}}: {{criteria}}"
repeatable: true
instruction: |
Define clear, comprehensive, and testable acceptance criteria that:
- Precisely define what "done" means from a functional perspective
- Are unambiguous and serve as basis for verification
- Include any critical non-functional requirements from the PRD
- Consider local testability for backend/data components
- Specify UI/UX requirements and framework adherence where applicable
- Avoid cross-cutting concerns that should be in other stories or PRD sections
- id: checklist-results
title: Checklist Results Report
instruction: Before running the checklist and drafting the prompts, offer to output the full updated PRD. If outputting it, confirm with the user that you will be proceeding to run the checklist and produce the report. Once the user confirms, execute the pm-checklist and populate the results in this section.
- id: next-steps
title: Next Steps
sections:
- id: ux-expert-prompt
title: UX Expert Prompt
instruction: This section will contain the prompt for the UX Expert, keep it short and to the point to initiate create architecture mode using this document as input.
- id: architect-prompt
title: Architect Prompt
instruction: This section will contain the prompt for the Architect, keep it short and to the point to initiate create architecture mode using this document as input.

View File

@ -0,0 +1,222 @@
# <!-- Powered by BMAD™ Core -->
template:
id: project-brief-template-v2
name: Project Brief
version: 2.0
output:
format: markdown
filename: docs/brief.md
title: "Project Brief: {{project_name}}"
workflow:
mode: interactive
elicitation: advanced-elicitation
custom_elicitation:
title: "Project Brief Elicitation Actions"
options:
- "Expand section with more specific details"
- "Validate against similar successful products"
- "Stress test assumptions with edge cases"
- "Explore alternative solution approaches"
- "Analyze resource/constraint trade-offs"
- "Generate risk mitigation strategies"
- "Challenge scope from MVP minimalist view"
- "Brainstorm creative feature possibilities"
- "If only we had [resource/capability/time]..."
- "Proceed to next section"
sections:
- id: introduction
instruction: |
This template guides creation of a comprehensive Project Brief that serves as the foundational input for product development.
Start by asking the user which mode they prefer:
1. **Interactive Mode** - Work through each section collaboratively
2. **YOLO Mode** - Generate complete draft for review and refinement
Before beginning, understand what inputs are available (brainstorming results, market research, competitive analysis, initial ideas) and gather project context.
- id: executive-summary
title: Executive Summary
instruction: |
Create a concise overview that captures the essence of the project. Include:
- Product concept in 1-2 sentences
- Primary problem being solved
- Target market identification
- Key value proposition
template: "{{executive_summary_content}}"
- id: problem-statement
title: Problem Statement
instruction: |
Articulate the problem with clarity and evidence. Address:
- Current state and pain points
- Impact of the problem (quantify if possible)
- Why existing solutions fall short
- Urgency and importance of solving this now
template: "{{detailed_problem_description}}"
- id: proposed-solution
title: Proposed Solution
instruction: |
Describe the solution approach at a high level. Include:
- Core concept and approach
- Key differentiators from existing solutions
- Why this solution will succeed where others haven't
- High-level vision for the product
template: "{{solution_description}}"
- id: target-users
title: Target Users
instruction: |
Define and characterize the intended users with specificity. For each user segment include:
- Demographic/firmographic profile
- Current behaviors and workflows
- Specific needs and pain points
- Goals they're trying to achieve
sections:
- id: primary-segment
title: "Primary User Segment: {{segment_name}}"
template: "{{primary_user_description}}"
- id: secondary-segment
title: "Secondary User Segment: {{segment_name}}"
condition: Has secondary user segment
template: "{{secondary_user_description}}"
- id: goals-metrics
title: Goals & Success Metrics
instruction: Establish clear objectives and how to measure success. Make goals SMART (Specific, Measurable, Achievable, Relevant, Time-bound)
sections:
- id: business-objectives
title: Business Objectives
type: bullet-list
template: "- {{objective_with_metric}}"
- id: user-success-metrics
title: User Success Metrics
type: bullet-list
template: "- {{user_metric}}"
- id: kpis
title: Key Performance Indicators (KPIs)
type: bullet-list
template: "- {{kpi}}: {{definition_and_target}}"
- id: mvp-scope
title: MVP Scope
instruction: Define the minimum viable product clearly. Be specific about what's in and what's out. Help user distinguish must-haves from nice-to-haves.
sections:
- id: core-features
title: Core Features (Must Have)
type: bullet-list
template: "- **{{feature}}:** {{description_and_rationale}}"
- id: out-of-scope
title: Out of Scope for MVP
type: bullet-list
template: "- {{feature_or_capability}}"
- id: mvp-success-criteria
title: MVP Success Criteria
template: "{{mvp_success_definition}}"
- id: post-mvp-vision
title: Post-MVP Vision
instruction: Outline the longer-term product direction without overcommitting to specifics
sections:
- id: phase-2-features
title: Phase 2 Features
template: "{{next_priority_features}}"
- id: long-term-vision
title: Long-term Vision
template: "{{one_two_year_vision}}"
- id: expansion-opportunities
title: Expansion Opportunities
template: "{{potential_expansions}}"
- id: technical-considerations
title: Technical Considerations
instruction: Document known technical constraints and preferences. Note these are initial thoughts, not final decisions.
sections:
- id: platform-requirements
title: Platform Requirements
template: |
- **Target Platforms:** {{platforms}}
- **Browser/OS Support:** {{specific_requirements}}
- **Performance Requirements:** {{performance_specs}}
- id: technology-preferences
title: Technology Preferences
template: |
- **Frontend:** {{frontend_preferences}}
- **Backend:** {{backend_preferences}}
- **Database:** {{database_preferences}}
- **Hosting/Infrastructure:** {{infrastructure_preferences}}
- id: architecture-considerations
title: Architecture Considerations
template: |
- **Repository Structure:** {{repo_thoughts}}
- **Service Architecture:** {{service_thoughts}}
- **Integration Requirements:** {{integration_needs}}
- **Security/Compliance:** {{security_requirements}}
- id: constraints-assumptions
title: Constraints & Assumptions
instruction: Clearly state limitations and assumptions to set realistic expectations
sections:
- id: constraints
title: Constraints
template: |
- **Budget:** {{budget_info}}
- **Timeline:** {{timeline_info}}
- **Resources:** {{resource_info}}
- **Technical:** {{technical_constraints}}
- id: key-assumptions
title: Key Assumptions
type: bullet-list
template: "- {{assumption}}"
- id: risks-questions
title: Risks & Open Questions
instruction: Identify unknowns and potential challenges proactively
sections:
- id: key-risks
title: Key Risks
type: bullet-list
template: "- **{{risk}}:** {{description_and_impact}}"
- id: open-questions
title: Open Questions
type: bullet-list
template: "- {{question}}"
- id: research-areas
title: Areas Needing Further Research
type: bullet-list
template: "- {{research_topic}}"
- id: appendices
title: Appendices
sections:
- id: research-summary
title: A. Research Summary
condition: Has research findings
instruction: |
If applicable, summarize key findings from:
- Market research
- Competitive analysis
- User interviews
- Technical feasibility studies
- id: stakeholder-input
title: B. Stakeholder Input
condition: Has stakeholder feedback
template: "{{stakeholder_feedback}}"
- id: references
title: C. References
template: "{{relevant_links_and_docs}}"
- id: next-steps
title: Next Steps
sections:
- id: immediate-actions
title: Immediate Actions
type: numbered-list
template: "{{action_item}}"
- id: pm-handoff
title: PM Handoff
content: |
This Project Brief provides the full context for {{project_name}}. Please start in 'PRD Generation Mode', review the brief thoroughly to work with the user to create the PRD section by section as the template indicates, asking for any necessary clarification or suggesting improvements.

View File

@ -0,0 +1,103 @@
# <!-- Powered by BMAD™ Core -->
template:
id: qa-gate-template-v1
name: Quality Gate Decision
version: 1.0
output:
format: yaml
filename: qa.qaLocation/gates/{{epic_num}}.{{story_num}}-{{story_slug}}.yml
title: "Quality Gate: {{epic_num}}.{{story_num}}"
# Required fields (keep these first)
schema: 1
story: "{{epic_num}}.{{story_num}}"
story_title: "{{story_title}}"
gate: "{{gate_status}}" # PASS|CONCERNS|FAIL|WAIVED
status_reason: "{{status_reason}}" # 1-2 sentence summary of why this gate decision
reviewer: "Quinn (Test Architect)"
updated: "{{iso_timestamp}}"
# Always present but only active when WAIVED
waiver: { active: false }
# Issues (if any) - Use fixed severity: low | medium | high
top_issues: []
# Risk summary (from risk-profile task if run)
risk_summary:
totals: { critical: 0, high: 0, medium: 0, low: 0 }
recommendations:
must_fix: []
monitor: []
# Examples section using block scalars for clarity
examples:
with_issues: |
top_issues:
- id: "SEC-001"
severity: high # ONLY: low|medium|high
finding: "No rate limiting on login endpoint"
suggested_action: "Add rate limiting middleware before production"
- id: "TEST-001"
severity: medium
finding: "Missing integration tests for auth flow"
suggested_action: "Add test coverage for critical paths"
when_waived: |
waiver:
active: true
reason: "Accepted for MVP release - will address in next sprint"
approved_by: "Product Owner"
# ============ Optional Extended Fields ============
# Uncomment and use if your team wants more detail
optional_fields_examples:
quality_and_expiry: |
quality_score: 75 # 0-100 (optional scoring)
expires: "2025-01-26T00:00:00Z" # Optional gate freshness window
evidence: |
evidence:
tests_reviewed: 15
risks_identified: 3
trace:
ac_covered: [1, 2, 3] # AC numbers with test coverage
ac_gaps: [4] # AC numbers lacking coverage
nfr_validation: |
nfr_validation:
security: { status: CONCERNS, notes: "Rate limiting missing" }
performance: { status: PASS, notes: "" }
reliability: { status: PASS, notes: "" }
maintainability: { status: PASS, notes: "" }
history: |
history: # Append-only audit trail
- at: "2025-01-12T10:00:00Z"
gate: FAIL
note: "Initial review - missing tests"
- at: "2025-01-12T15:00:00Z"
gate: CONCERNS
note: "Tests added but rate limiting still missing"
risk_summary: |
risk_summary: # From risk-profile task
totals:
critical: 0
high: 0
medium: 0
low: 0
# 'highest' is emitted only when risks exist
recommendations:
must_fix: []
monitor: []
recommendations: |
recommendations:
immediate: # Must fix before production
- action: "Add rate limiting to auth endpoints"
refs: ["api/auth/login.ts:42-68"]
future: # Can be addressed later
- action: "Consider caching for better performance"
refs: ["services/data.service.ts"]

View File

@ -0,0 +1,138 @@
# <!-- Powered by BMAD™ Core -->
template:
id: story-template-v2
name: Story Document
version: 2.0
output:
format: markdown
filename: docs/stories/{{epic_num}}.{{story_num}}.{{story_title_short}}.md
title: "Story {{epic_num}}.{{story_num}}: {{story_title_short}}"
workflow:
mode: interactive
elicitation: advanced-elicitation
agent_config:
editable_sections:
- Status
- Story
- Acceptance Criteria
- Tasks / Subtasks
- Dev Notes
- Testing
- Change Log
sections:
- id: status
title: Status
type: choice
choices: [Draft, Approved, InProgress, Review, Done]
instruction: Select the current status of the story
owner: scrum-master
editors: [scrum-master, dev-agent]
- id: story
title: Story
type: template-text
template: |
**As a** {{role}},
**I want** {{action}},
**so that** {{benefit}}
instruction: Define the user story using the standard format with role, action, and benefit
elicit: true
owner: scrum-master
editors: [scrum-master]
- id: acceptance-criteria
title: Acceptance Criteria
type: numbered-list
instruction: Copy the acceptance criteria numbered list from the epic file
elicit: true
owner: scrum-master
editors: [scrum-master]
- id: tasks-subtasks
title: Tasks / Subtasks
type: bullet-list
instruction: |
Break down the story into specific tasks and subtasks needed for implementation.
Reference applicable acceptance criteria numbers where relevant.
template: |
- [ ] Task 1 (AC: # if applicable)
- [ ] Subtask1.1...
- [ ] Task 2 (AC: # if applicable)
- [ ] Subtask 2.1...
- [ ] Task 3 (AC: # if applicable)
- [ ] Subtask 3.1...
elicit: true
owner: scrum-master
editors: [scrum-master, dev-agent]
- id: dev-notes
title: Dev Notes
instruction: |
Populate relevant information, only what was pulled from actual artifacts from docs folder, relevant to this story:
- Do not invent information
- If known add Relevant Source Tree info that relates to this story
- If there were important notes from previous story that are relevant to this one, include them here
- Put enough information in this section so that the dev agent should NEVER need to read the architecture documents, these notes along with the tasks and subtasks must give the Dev Agent the complete context it needs to comprehend with the least amount of overhead the information to complete the story, meeting all AC and completing all tasks+subtasks
elicit: true
owner: scrum-master
editors: [scrum-master]
sections:
- id: testing-standards
title: Testing
instruction: |
List Relevant Testing Standards from Architecture the Developer needs to conform to:
- Test file location
- Test standards
- Testing frameworks and patterns to use
- Any specific testing requirements for this story
elicit: true
owner: scrum-master
editors: [scrum-master]
- id: change-log
title: Change Log
type: table
columns: [Date, Version, Description, Author]
instruction: Track changes made to this story document
owner: scrum-master
editors: [scrum-master, dev-agent, qa-agent]
- id: dev-agent-record
title: Dev Agent Record
instruction: This section is populated by the development agent during implementation
owner: dev-agent
editors: [dev-agent]
sections:
- id: agent-model
title: Agent Model Used
template: "{{agent_model_name_version}}"
instruction: Record the specific AI agent model and version used for development
owner: dev-agent
editors: [dev-agent]
- id: debug-log-references
title: Debug Log References
instruction: Reference any debug logs or traces generated during development
owner: dev-agent
editors: [dev-agent]
- id: completion-notes
title: Completion Notes List
instruction: Notes about the completion of tasks and any issues encountered
owner: dev-agent
editors: [dev-agent]
- id: file-list
title: File List
instruction: List all files created, modified, or affected during story implementation
owner: dev-agent
editors: [dev-agent]
- id: qa-results
title: QA Results
instruction: Results from QA Agent QA review of the completed story implementation
owner: qa-agent
editors: [qa-agent]

View File

@ -0,0 +1,298 @@
# <!-- Powered by BMAD™ Core -->
workflow:
id: brownfield-fullstack
name: Brownfield Full-Stack Enhancement
description: >-
Agent workflow for enhancing existing full-stack applications with new features,
modernization, or significant changes. Handles existing system analysis and safe integration.
type: brownfield
project_types:
- feature-addition
- refactoring
- modernization
- integration-enhancement
sequence:
- step: enhancement_classification
agent: analyst
action: classify enhancement scope
notes: |
Determine enhancement complexity to route to appropriate path:
- Single story (< 4 hours) → Use brownfield-create-story task
- Small feature (1-3 stories) → Use brownfield-create-epic task
- Major enhancement (multiple epics) → Continue with full workflow
Ask user: "Can you describe the enhancement scope? Is this a small fix, a feature addition, or a major enhancement requiring architectural changes?"
- step: routing_decision
condition: based_on_classification
routes:
single_story:
agent: pm
uses: brownfield-create-story
notes: "Create single story for immediate implementation. Exit workflow after story creation."
small_feature:
agent: pm
uses: brownfield-create-epic
notes: "Create focused epic with 1-3 stories. Exit workflow after epic creation."
major_enhancement:
continue: to_next_step
notes: "Continue with comprehensive planning workflow below."
- step: documentation_check
agent: analyst
action: check existing documentation
condition: major_enhancement_path
notes: |
Check if adequate project documentation exists:
- Look for existing architecture docs, API specs, coding standards
- Assess if documentation is current and comprehensive
- If adequate: Skip document-project, proceed to PRD
- If inadequate: Run document-project first
- step: project_analysis
agent: architect
action: analyze existing project and use task document-project
creates: brownfield-architecture.md (or multiple documents)
condition: documentation_inadequate
notes: "Run document-project to capture current system state, technical debt, and constraints. Pass findings to PRD creation."
- agent: pm
creates: prd.md
uses: brownfield-prd-tmpl
requires: existing_documentation_or_analysis
notes: |
Creates PRD for major enhancement. If document-project was run, reference its output to avoid re-analysis.
If skipped, use existing project documentation.
SAVE OUTPUT: Copy final prd.md to your project's docs/ folder.
- step: architecture_decision
agent: pm/architect
action: determine if architecture document needed
condition: after_prd_creation
notes: |
Review PRD to determine if architectural planning is needed:
- New architectural patterns → Create architecture doc
- New libraries/frameworks → Create architecture doc
- Platform/infrastructure changes → Create architecture doc
- Following existing patterns → Skip to story creation
- agent: architect
creates: architecture.md
uses: brownfield-architecture-tmpl
requires: prd.md
condition: architecture_changes_needed
notes: "Creates architecture ONLY for significant architectural changes. SAVE OUTPUT: Copy final architecture.md to your project's docs/ folder."
- agent: po
validates: all_artifacts
uses: po-master-checklist
notes: "Validates all documents for integration safety and completeness. May require updates to any document."
- agent: various
updates: any_flagged_documents
condition: po_checklist_issues
notes: "If PO finds issues, return to relevant agent to fix and re-export updated documents to docs/ folder."
- agent: po
action: shard_documents
creates: sharded_docs
requires: all_artifacts_in_project
notes: |
Shard documents for IDE development:
- Option A: Use PO agent to shard: @po then ask to shard docs/prd.md
- Option B: Manual: Drag shard-doc task + docs/prd.md into chat
- Creates docs/prd/ and docs/architecture/ folders with sharded content
- agent: sm
action: create_story
creates: story.md
requires: sharded_docs_or_brownfield_docs
repeats: for_each_epic_or_enhancement
notes: |
Story creation cycle:
- For sharded PRD: @sm → *create (uses create-next-story)
- For brownfield docs: @sm → use create-brownfield-story task
- Creates story from available documentation
- Story starts in "Draft" status
- May require additional context gathering for brownfield
- agent: analyst/pm
action: review_draft_story
updates: story.md
requires: story.md
optional: true
condition: user_wants_story_review
notes: |
OPTIONAL: Review and approve draft story
- NOTE: story-review task coming soon
- Review story completeness and alignment
- Update story status: Draft → Approved
- agent: dev
action: implement_story
creates: implementation_files
requires: story.md
notes: |
Dev Agent (New Chat): @dev
- Implements approved story
- Updates File List with all changes
- Marks story as "Review" when complete
- agent: qa
action: review_implementation
updates: implementation_files
requires: implementation_files
optional: true
notes: |
OPTIONAL: QA Agent (New Chat): @qa → review-story
- Senior dev review with refactoring ability
- Fixes small issues directly
- Leaves checklist for remaining items
- Updates story status (Review → Done or stays Review)
- agent: dev
action: address_qa_feedback
updates: implementation_files
condition: qa_left_unchecked_items
notes: |
If QA left unchecked items:
- Dev Agent (New Chat): Address remaining items
- Return to QA for final approval
- step: repeat_development_cycle
action: continue_for_all_stories
notes: |
Repeat story cycle (SM → Dev → QA) for all epic stories
Continue until all stories in PRD are complete
- agent: po
action: epic_retrospective
creates: epic-retrospective.md
condition: epic_complete
optional: true
notes: |
OPTIONAL: After epic completion
- NOTE: epic-retrospective task coming soon
- Validate epic was completed correctly
- Document learnings and improvements
- step: workflow_end
action: project_complete
notes: |
All stories implemented and reviewed!
Project development phase complete.
Reference: .bmad-core/data/bmad-kb.md#IDE Development Workflow
flow_diagram: |
```mermaid
graph TD
A[Start: Brownfield Enhancement] --> B[analyst: classify enhancement scope]
B --> C{Enhancement Size?}
C -->|Single Story| D[pm: brownfield-create-story]
C -->|1-3 Stories| E[pm: brownfield-create-epic]
C -->|Major Enhancement| F[analyst: check documentation]
D --> END1[To Dev Implementation]
E --> END2[To Story Creation]
F --> G{Docs Adequate?}
G -->|No| H[architect: document-project]
G -->|Yes| I[pm: brownfield PRD]
H --> I
I --> J{Architecture Needed?}
J -->|Yes| K[architect: architecture.md]
J -->|No| L[po: validate artifacts]
K --> L
L --> M{PO finds issues?}
M -->|Yes| N[Fix issues]
M -->|No| O[po: shard documents]
N --> L
O --> P[sm: create story]
P --> Q{Story Type?}
Q -->|Sharded PRD| R[create-next-story]
Q -->|Brownfield Docs| S[create-brownfield-story]
R --> T{Review draft?}
S --> T
T -->|Yes| U[review & approve]
T -->|No| V[dev: implement]
U --> V
V --> W{QA review?}
W -->|Yes| X[qa: review]
W -->|No| Y{More stories?}
X --> Z{Issues?}
Z -->|Yes| AA[dev: fix]
Z -->|No| Y
AA --> X
Y -->|Yes| P
Y -->|No| AB{Retrospective?}
AB -->|Yes| AC[po: retrospective]
AB -->|No| AD[Complete]
AC --> AD
style AD fill:#90EE90
style END1 fill:#90EE90
style END2 fill:#90EE90
style D fill:#87CEEB
style E fill:#87CEEB
style I fill:#FFE4B5
style K fill:#FFE4B5
style O fill:#ADD8E6
style P fill:#ADD8E6
style V fill:#ADD8E6
style U fill:#F0E68C
style X fill:#F0E68C
style AC fill:#F0E68C
```
decision_guidance:
when_to_use:
- Enhancement requires coordinated stories
- Architectural changes are needed
- Significant integration work required
- Risk assessment and mitigation planning necessary
- Multiple team members will work on related changes
handoff_prompts:
classification_complete: |
Enhancement classified as: {{enhancement_type}}
{{if single_story}}: Proceeding with brownfield-create-story task for immediate implementation.
{{if small_feature}}: Creating focused epic with brownfield-create-epic task.
{{if major_enhancement}}: Continuing with comprehensive planning workflow.
documentation_assessment: |
Documentation assessment complete:
{{if adequate}}: Existing documentation is sufficient. Proceeding directly to PRD creation.
{{if inadequate}}: Running document-project to capture current system state before PRD.
document_project_to_pm: |
Project analysis complete. Key findings documented in:
- {{document_list}}
Use these findings to inform PRD creation and avoid re-analyzing the same aspects.
pm_to_architect_decision: |
PRD complete and saved as docs/prd.md.
Architectural changes identified: {{yes/no}}
{{if yes}}: Proceeding to create architecture document for: {{specific_changes}}
{{if no}}: No architectural changes needed. Proceeding to validation.
architect_to_po: "Architecture complete. Save it as docs/architecture.md. Please validate all artifacts for integration safety."
po_to_sm: |
All artifacts validated.
Documentation type available: {{sharded_prd / brownfield_docs}}
{{if sharded}}: Use standard create-next-story task.
{{if brownfield}}: Use create-brownfield-story task to handle varied documentation formats.
sm_story_creation: |
Creating story from {{documentation_type}}.
{{if missing_context}}: May need to gather additional context from user during story creation.
complete: "All planning artifacts validated and development can begin. Stories will be created based on available documentation format."

View File

@ -0,0 +1,188 @@
# <!-- Powered by BMAD™ Core -->
workflow:
id: brownfield-service
name: Brownfield Service/API Enhancement
description: >-
Agent workflow for enhancing existing backend services and APIs with new features,
modernization, or performance improvements. Handles existing system analysis and safe integration.
type: brownfield
project_types:
- service-modernization
- api-enhancement
- microservice-extraction
- performance-optimization
- integration-enhancement
sequence:
- step: service_analysis
agent: architect
action: analyze existing project and use task document-project
creates: multiple documents per the document-project template
notes: "Review existing service documentation, codebase, performance metrics, and identify integration dependencies."
- agent: pm
creates: prd.md
uses: brownfield-prd-tmpl
requires: existing_service_analysis
notes: "Creates comprehensive PRD focused on service enhancement with existing system analysis. SAVE OUTPUT: Copy final prd.md to your project's docs/ folder."
- agent: architect
creates: architecture.md
uses: brownfield-architecture-tmpl
requires: prd.md
notes: "Creates architecture with service integration strategy and API evolution planning. SAVE OUTPUT: Copy final architecture.md to your project's docs/ folder."
- agent: po
validates: all_artifacts
uses: po-master-checklist
notes: "Validates all documents for service integration safety and API compatibility. May require updates to any document."
- agent: various
updates: any_flagged_documents
condition: po_checklist_issues
notes: "If PO finds issues, return to relevant agent to fix and re-export updated documents to docs/ folder."
- agent: po
action: shard_documents
creates: sharded_docs
requires: all_artifacts_in_project
notes: |
Shard documents for IDE development:
- Option A: Use PO agent to shard: @po then ask to shard docs/prd.md
- Option B: Manual: Drag shard-doc task + docs/prd.md into chat
- Creates docs/prd/ and docs/architecture/ folders with sharded content
- agent: sm
action: create_story
creates: story.md
requires: sharded_docs
repeats: for_each_epic
notes: |
Story creation cycle:
- SM Agent (New Chat): @sm → *create
- Creates next story from sharded docs
- Story starts in "Draft" status
- agent: analyst/pm
action: review_draft_story
updates: story.md
requires: story.md
optional: true
condition: user_wants_story_review
notes: |
OPTIONAL: Review and approve draft story
- NOTE: story-review task coming soon
- Review story completeness and alignment
- Update story status: Draft → Approved
- agent: dev
action: implement_story
creates: implementation_files
requires: story.md
notes: |
Dev Agent (New Chat): @dev
- Implements approved story
- Updates File List with all changes
- Marks story as "Review" when complete
- agent: qa
action: review_implementation
updates: implementation_files
requires: implementation_files
optional: true
notes: |
OPTIONAL: QA Agent (New Chat): @qa → review-story
- Senior dev review with refactoring ability
- Fixes small issues directly
- Leaves checklist for remaining items
- Updates story status (Review → Done or stays Review)
- agent: dev
action: address_qa_feedback
updates: implementation_files
condition: qa_left_unchecked_items
notes: |
If QA left unchecked items:
- Dev Agent (New Chat): Address remaining items
- Return to QA for final approval
- step: repeat_development_cycle
action: continue_for_all_stories
notes: |
Repeat story cycle (SM → Dev → QA) for all epic stories
Continue until all stories in PRD are complete
- agent: po
action: epic_retrospective
creates: epic-retrospective.md
condition: epic_complete
optional: true
notes: |
OPTIONAL: After epic completion
- NOTE: epic-retrospective task coming soon
- Validate epic was completed correctly
- Document learnings and improvements
- step: workflow_end
action: project_complete
notes: |
All stories implemented and reviewed!
Project development phase complete.
Reference: .bmad-core/data/bmad-kb.md#IDE Development Workflow
flow_diagram: |
```mermaid
graph TD
A[Start: Service Enhancement] --> B[analyst: analyze existing service]
B --> C[pm: prd.md]
C --> D[architect: architecture.md]
D --> E[po: validate with po-master-checklist]
E --> F{PO finds issues?}
F -->|Yes| G[Return to relevant agent for fixes]
F -->|No| H[po: shard documents]
G --> E
H --> I[sm: create story]
I --> J{Review draft story?}
J -->|Yes| K[analyst/pm: review & approve story]
J -->|No| L[dev: implement story]
K --> L
L --> M{QA review?}
M -->|Yes| N[qa: review implementation]
M -->|No| O{More stories?}
N --> P{QA found issues?}
P -->|Yes| Q[dev: address QA feedback]
P -->|No| O
Q --> N
O -->|Yes| I
O -->|No| R{Epic retrospective?}
R -->|Yes| S[po: epic retrospective]
R -->|No| T[Project Complete]
S --> T
style T fill:#90EE90
style H fill:#ADD8E6
style I fill:#ADD8E6
style L fill:#ADD8E6
style C fill:#FFE4B5
style D fill:#FFE4B5
style K fill:#F0E68C
style N fill:#F0E68C
style S fill:#F0E68C
```
decision_guidance:
when_to_use:
- Service enhancement requires coordinated stories
- API versioning or breaking changes needed
- Database schema changes required
- Performance or scalability improvements needed
- Multiple integration points affected
handoff_prompts:
analyst_to_pm: "Service analysis complete. Create comprehensive PRD with service integration strategy."
pm_to_architect: "PRD ready. Save it as docs/prd.md, then create the service architecture."
architect_to_po: "Architecture complete. Save it as docs/architecture.md. Please validate all artifacts for service integration safety."
po_issues: "PO found issues with [document]. Please return to [agent] to fix and re-save the updated document."
complete: "All planning artifacts validated and saved in docs/ folder. Move to IDE environment to begin development."

View File

@ -0,0 +1,198 @@
# <!-- Powered by BMAD™ Core -->
workflow:
id: brownfield-ui
name: Brownfield UI/Frontend Enhancement
description: >-
Agent workflow for enhancing existing frontend applications with new features,
modernization, or design improvements. Handles existing UI analysis and safe integration.
type: brownfield
project_types:
- ui-modernization
- framework-migration
- design-refresh
- frontend-enhancement
sequence:
- step: ui_analysis
agent: architect
action: analyze existing project and use task document-project
creates: multiple documents per the document-project template
notes: "Review existing frontend application, user feedback, analytics data, and identify improvement areas."
- agent: pm
creates: prd.md
uses: brownfield-prd-tmpl
requires: existing_ui_analysis
notes: "Creates comprehensive PRD focused on UI enhancement with existing system analysis. SAVE OUTPUT: Copy final prd.md to your project's docs/ folder."
- agent: ux-expert
creates: front-end-spec.md
uses: front-end-spec-tmpl
requires: prd.md
notes: "Creates UI/UX specification that integrates with existing design patterns. SAVE OUTPUT: Copy final front-end-spec.md to your project's docs/ folder."
- agent: architect
creates: architecture.md
uses: brownfield-architecture-tmpl
requires:
- prd.md
- front-end-spec.md
notes: "Creates frontend architecture with component integration strategy and migration planning. SAVE OUTPUT: Copy final architecture.md to your project's docs/ folder."
- agent: po
validates: all_artifacts
uses: po-master-checklist
notes: "Validates all documents for UI integration safety and design consistency. May require updates to any document."
- agent: various
updates: any_flagged_documents
condition: po_checklist_issues
notes: "If PO finds issues, return to relevant agent to fix and re-export updated documents to docs/ folder."
- agent: po
action: shard_documents
creates: sharded_docs
requires: all_artifacts_in_project
notes: |
Shard documents for IDE development:
- Option A: Use PO agent to shard: @po then ask to shard docs/prd.md
- Option B: Manual: Drag shard-doc task + docs/prd.md into chat
- Creates docs/prd/ and docs/architecture/ folders with sharded content
- agent: sm
action: create_story
creates: story.md
requires: sharded_docs
repeats: for_each_epic
notes: |
Story creation cycle:
- SM Agent (New Chat): @sm → *create
- Creates next story from sharded docs
- Story starts in "Draft" status
- agent: analyst/pm
action: review_draft_story
updates: story.md
requires: story.md
optional: true
condition: user_wants_story_review
notes: |
OPTIONAL: Review and approve draft story
- NOTE: story-review task coming soon
- Review story completeness and alignment
- Update story status: Draft → Approved
- agent: dev
action: implement_story
creates: implementation_files
requires: story.md
notes: |
Dev Agent (New Chat): @dev
- Implements approved story
- Updates File List with all changes
- Marks story as "Review" when complete
- agent: qa
action: review_implementation
updates: implementation_files
requires: implementation_files
optional: true
notes: |
OPTIONAL: QA Agent (New Chat): @qa → review-story
- Senior dev review with refactoring ability
- Fixes small issues directly
- Leaves checklist for remaining items
- Updates story status (Review → Done or stays Review)
- agent: dev
action: address_qa_feedback
updates: implementation_files
condition: qa_left_unchecked_items
notes: |
If QA left unchecked items:
- Dev Agent (New Chat): Address remaining items
- Return to QA for final approval
- step: repeat_development_cycle
action: continue_for_all_stories
notes: |
Repeat story cycle (SM → Dev → QA) for all epic stories
Continue until all stories in PRD are complete
- agent: po
action: epic_retrospective
creates: epic-retrospective.md
condition: epic_complete
optional: true
notes: |
OPTIONAL: After epic completion
- NOTE: epic-retrospective task coming soon
- Validate epic was completed correctly
- Document learnings and improvements
- step: workflow_end
action: project_complete
notes: |
All stories implemented and reviewed!
Project development phase complete.
Reference: .bmad-core/data/bmad-kb.md#IDE Development Workflow
flow_diagram: |
```mermaid
graph TD
A[Start: UI Enhancement] --> B[analyst: analyze existing UI]
B --> C[pm: prd.md]
C --> D[ux-expert: front-end-spec.md]
D --> E[architect: architecture.md]
E --> F[po: validate with po-master-checklist]
F --> G{PO finds issues?}
G -->|Yes| H[Return to relevant agent for fixes]
G -->|No| I[po: shard documents]
H --> F
I --> J[sm: create story]
J --> K{Review draft story?}
K -->|Yes| L[analyst/pm: review & approve story]
K -->|No| M[dev: implement story]
L --> M
M --> N{QA review?}
N -->|Yes| O[qa: review implementation]
N -->|No| P{More stories?}
O --> Q{QA found issues?}
Q -->|Yes| R[dev: address QA feedback]
Q -->|No| P
R --> O
P -->|Yes| J
P -->|No| S{Epic retrospective?}
S -->|Yes| T[po: epic retrospective]
S -->|No| U[Project Complete]
T --> U
style U fill:#90EE90
style I fill:#ADD8E6
style J fill:#ADD8E6
style M fill:#ADD8E6
style C fill:#FFE4B5
style D fill:#FFE4B5
style E fill:#FFE4B5
style L fill:#F0E68C
style O fill:#F0E68C
style T fill:#F0E68C
```
decision_guidance:
when_to_use:
- UI enhancement requires coordinated stories
- Design system changes needed
- New component patterns required
- User research and testing needed
- Multiple team members will work on related changes
handoff_prompts:
analyst_to_pm: "UI analysis complete. Create comprehensive PRD with UI integration strategy."
pm_to_ux: "PRD ready. Save it as docs/prd.md, then create the UI/UX specification."
ux_to_architect: "UI/UX spec complete. Save it as docs/front-end-spec.md, then create the frontend architecture."
architect_to_po: "Architecture complete. Save it as docs/architecture.md. Please validate all artifacts for UI integration safety."
po_issues: "PO found issues with [document]. Please return to [agent] to fix and re-save the updated document."
complete: "All planning artifacts validated and saved in docs/ folder. Move to IDE environment to begin development."

View File

@ -0,0 +1,241 @@
# <!-- Powered by BMAD™ Core -->
workflow:
id: greenfield-fullstack
name: Greenfield Full-Stack Application Development
description: >-
Agent workflow for building full-stack applications from concept to development.
Supports both comprehensive planning for complex projects and rapid prototyping for simple ones.
type: greenfield
project_types:
- web-app
- saas
- enterprise-app
- prototype
- mvp
sequence:
- agent: analyst
creates: project-brief.md
optional_steps:
- brainstorming_session
- market_research_prompt
notes: "Can do brainstorming first, then optional deep research before creating project brief. SAVE OUTPUT: Copy final project-brief.md to your project's docs/ folder."
- agent: pm
creates: prd.md
requires: project-brief.md
notes: "Creates PRD from project brief using prd-tmpl. SAVE OUTPUT: Copy final prd.md to your project's docs/ folder."
- agent: ux-expert
creates: front-end-spec.md
requires: prd.md
optional_steps:
- user_research_prompt
notes: "Creates UI/UX specification using front-end-spec-tmpl. SAVE OUTPUT: Copy final front-end-spec.md to your project's docs/ folder."
- agent: ux-expert
creates: v0_prompt (optional)
requires: front-end-spec.md
condition: user_wants_ai_generation
notes: "OPTIONAL BUT RECOMMENDED: Generate AI UI prompt for tools like v0, Lovable, etc. Use the generate-ai-frontend-prompt task. User can then generate UI in external tool and download project structure."
- agent: architect
creates: fullstack-architecture.md
requires:
- prd.md
- front-end-spec.md
optional_steps:
- technical_research_prompt
- review_generated_ui_structure
notes: "Creates comprehensive architecture using fullstack-architecture-tmpl. If user generated UI with v0/Lovable, can incorporate the project structure into architecture. May suggest changes to PRD stories or new stories. SAVE OUTPUT: Copy final fullstack-architecture.md to your project's docs/ folder."
- agent: pm
updates: prd.md (if needed)
requires: fullstack-architecture.md
condition: architecture_suggests_prd_changes
notes: "If architect suggests story changes, update PRD and re-export the complete unredacted prd.md to docs/ folder."
- agent: po
validates: all_artifacts
uses: po-master-checklist
notes: "Validates all documents for consistency and completeness. May require updates to any document."
- agent: various
updates: any_flagged_documents
condition: po_checklist_issues
notes: "If PO finds issues, return to relevant agent to fix and re-export updated documents to docs/ folder."
- step: project_setup_guidance
action: guide_project_structure
condition: user_has_generated_ui
notes: "If user generated UI with v0/Lovable: For polyrepo setup, place downloaded project in separate frontend repo alongside backend repo. For monorepo, place in apps/web or packages/frontend directory. Review architecture document for specific guidance."
- step: development_order_guidance
action: guide_development_sequence
notes: "Based on PRD stories: If stories are frontend-heavy, start with frontend project/directory first. If backend-heavy or API-first, start with backend. For tightly coupled features, follow story sequence in monorepo setup. Reference sharded PRD epics for development order."
- agent: po
action: shard_documents
creates: sharded_docs
requires: all_artifacts_in_project
notes: |
Shard documents for IDE development:
- Option A: Use PO agent to shard: @po then ask to shard docs/prd.md
- Option B: Manual: Drag shard-doc task + docs/prd.md into chat
- Creates docs/prd/ and docs/architecture/ folders with sharded content
- agent: sm
action: create_story
creates: story.md
requires: sharded_docs
repeats: for_each_epic
notes: |
Story creation cycle:
- SM Agent (New Chat): @sm → *create
- Creates next story from sharded docs
- Story starts in "Draft" status
- agent: analyst/pm
action: review_draft_story
updates: story.md
requires: story.md
optional: true
condition: user_wants_story_review
notes: |
OPTIONAL: Review and approve draft story
- NOTE: story-review task coming soon
- Review story completeness and alignment
- Update story status: Draft → Approved
- agent: dev
action: implement_story
creates: implementation_files
requires: story.md
notes: |
Dev Agent (New Chat): @dev
- Implements approved story
- Updates File List with all changes
- Marks story as "Review" when complete
- agent: qa
action: review_implementation
updates: implementation_files
requires: implementation_files
optional: true
notes: |
OPTIONAL: QA Agent (New Chat): @qa → review-story
- Senior dev review with refactoring ability
- Fixes small issues directly
- Leaves checklist for remaining items
- Updates story status (Review → Done or stays Review)
- agent: dev
action: address_qa_feedback
updates: implementation_files
condition: qa_left_unchecked_items
notes: |
If QA left unchecked items:
- Dev Agent (New Chat): Address remaining items
- Return to QA for final approval
- step: repeat_development_cycle
action: continue_for_all_stories
notes: |
Repeat story cycle (SM → Dev → QA) for all epic stories
Continue until all stories in PRD are complete
- agent: po
action: epic_retrospective
creates: epic-retrospective.md
condition: epic_complete
optional: true
notes: |
OPTIONAL: After epic completion
- NOTE: epic-retrospective task coming soon
- Validate epic was completed correctly
- Document learnings and improvements
- step: workflow_end
action: project_complete
notes: |
All stories implemented and reviewed!
Project development phase complete.
Reference: .bmad-core/data/bmad-kb.md#IDE Development Workflow
flow_diagram: |
```mermaid
graph TD
A[Start: Greenfield Project] --> B[analyst: project-brief.md]
B --> C[pm: prd.md]
C --> D[ux-expert: front-end-spec.md]
D --> D2{Generate v0 prompt?}
D2 -->|Yes| D3[ux-expert: create v0 prompt]
D2 -->|No| E[architect: fullstack-architecture.md]
D3 --> D4[User: generate UI in v0/Lovable]
D4 --> E
E --> F{Architecture suggests PRD changes?}
F -->|Yes| G[pm: update prd.md]
F -->|No| H[po: validate all artifacts]
G --> H
H --> I{PO finds issues?}
I -->|Yes| J[Return to relevant agent for fixes]
I -->|No| K[po: shard documents]
J --> H
K --> L[sm: create story]
L --> M{Review draft story?}
M -->|Yes| N[analyst/pm: review & approve story]
M -->|No| O[dev: implement story]
N --> O
O --> P{QA review?}
P -->|Yes| Q[qa: review implementation]
P -->|No| R{More stories?}
Q --> S{QA found issues?}
S -->|Yes| T[dev: address QA feedback]
S -->|No| R
T --> Q
R -->|Yes| L
R -->|No| U{Epic retrospective?}
U -->|Yes| V[po: epic retrospective]
U -->|No| W[Project Complete]
V --> W
B -.-> B1[Optional: brainstorming]
B -.-> B2[Optional: market research]
D -.-> D1[Optional: user research]
E -.-> E1[Optional: technical research]
style W fill:#90EE90
style K fill:#ADD8E6
style L fill:#ADD8E6
style O fill:#ADD8E6
style D3 fill:#E6E6FA
style D4 fill:#E6E6FA
style B fill:#FFE4B5
style C fill:#FFE4B5
style D fill:#FFE4B5
style E fill:#FFE4B5
style N fill:#F0E68C
style Q fill:#F0E68C
style V fill:#F0E68C
```
decision_guidance:
when_to_use:
- Building production-ready applications
- Multiple team members will be involved
- Complex feature requirements
- Need comprehensive documentation
- Long-term maintenance expected
- Enterprise or customer-facing applications
handoff_prompts:
analyst_to_pm: "Project brief is complete. Save it as docs/project-brief.md in your project, then create the PRD."
pm_to_ux: "PRD is ready. Save it as docs/prd.md in your project, then create the UI/UX specification."
ux_to_architect: "UI/UX spec complete. Save it as docs/front-end-spec.md in your project, then create the fullstack architecture."
architect_review: "Architecture complete. Save it as docs/fullstack-architecture.md. Do you suggest any changes to the PRD stories or need new stories added?"
architect_to_pm: "Please update the PRD with the suggested story changes, then re-export the complete prd.md to docs/."
updated_to_po: "All documents ready in docs/ folder. Please validate all artifacts for consistency."
po_issues: "PO found issues with [document]. Please return to [agent] to fix and re-save the updated document."
complete: "All planning artifacts validated and saved in docs/ folder. Move to IDE environment to begin development."

View File

@ -0,0 +1,207 @@
# <!-- Powered by BMAD™ Core -->
workflow:
id: greenfield-service
name: Greenfield Service/API Development
description: >-
Agent workflow for building backend services from concept to development.
Supports both comprehensive planning for complex services and rapid prototyping for simple APIs.
type: greenfield
project_types:
- rest-api
- graphql-api
- microservice
- backend-service
- api-prototype
- simple-service
sequence:
- agent: analyst
creates: project-brief.md
optional_steps:
- brainstorming_session
- market_research_prompt
notes: "Can do brainstorming first, then optional deep research before creating project brief. SAVE OUTPUT: Copy final project-brief.md to your project's docs/ folder."
- agent: pm
creates: prd.md
requires: project-brief.md
notes: "Creates PRD from project brief using prd-tmpl, focused on API/service requirements. SAVE OUTPUT: Copy final prd.md to your project's docs/ folder."
- agent: architect
creates: architecture.md
requires: prd.md
optional_steps:
- technical_research_prompt
notes: "Creates backend/service architecture using architecture-tmpl. May suggest changes to PRD stories or new stories. SAVE OUTPUT: Copy final architecture.md to your project's docs/ folder."
- agent: pm
updates: prd.md (if needed)
requires: architecture.md
condition: architecture_suggests_prd_changes
notes: "If architect suggests story changes, update PRD and re-export the complete unredacted prd.md to docs/ folder."
- agent: po
validates: all_artifacts
uses: po-master-checklist
notes: "Validates all documents for consistency and completeness. May require updates to any document."
- agent: various
updates: any_flagged_documents
condition: po_checklist_issues
notes: "If PO finds issues, return to relevant agent to fix and re-export updated documents to docs/ folder."
- agent: po
action: shard_documents
creates: sharded_docs
requires: all_artifacts_in_project
notes: |
Shard documents for IDE development:
- Option A: Use PO agent to shard: @po then ask to shard docs/prd.md
- Option B: Manual: Drag shard-doc task + docs/prd.md into chat
- Creates docs/prd/ and docs/architecture/ folders with sharded content
- agent: sm
action: create_story
creates: story.md
requires: sharded_docs
repeats: for_each_epic
notes: |
Story creation cycle:
- SM Agent (New Chat): @sm → *create
- Creates next story from sharded docs
- Story starts in "Draft" status
- agent: analyst/pm
action: review_draft_story
updates: story.md
requires: story.md
optional: true
condition: user_wants_story_review
notes: |
OPTIONAL: Review and approve draft story
- NOTE: story-review task coming soon
- Review story completeness and alignment
- Update story status: Draft → Approved
- agent: dev
action: implement_story
creates: implementation_files
requires: story.md
notes: |
Dev Agent (New Chat): @dev
- Implements approved story
- Updates File List with all changes
- Marks story as "Review" when complete
- agent: qa
action: review_implementation
updates: implementation_files
requires: implementation_files
optional: true
notes: |
OPTIONAL: QA Agent (New Chat): @qa → review-story
- Senior dev review with refactoring ability
- Fixes small issues directly
- Leaves checklist for remaining items
- Updates story status (Review → Done or stays Review)
- agent: dev
action: address_qa_feedback
updates: implementation_files
condition: qa_left_unchecked_items
notes: |
If QA left unchecked items:
- Dev Agent (New Chat): Address remaining items
- Return to QA for final approval
- step: repeat_development_cycle
action: continue_for_all_stories
notes: |
Repeat story cycle (SM → Dev → QA) for all epic stories
Continue until all stories in PRD are complete
- agent: po
action: epic_retrospective
creates: epic-retrospective.md
condition: epic_complete
optional: true
notes: |
OPTIONAL: After epic completion
- NOTE: epic-retrospective task coming soon
- Validate epic was completed correctly
- Document learnings and improvements
- step: workflow_end
action: project_complete
notes: |
All stories implemented and reviewed!
Service development phase complete.
Reference: .bmad-core/data/bmad-kb.md#IDE Development Workflow
flow_diagram: |
```mermaid
graph TD
A[Start: Service Development] --> B[analyst: project-brief.md]
B --> C[pm: prd.md]
C --> D[architect: architecture.md]
D --> E{Architecture suggests PRD changes?}
E -->|Yes| F[pm: update prd.md]
E -->|No| G[po: validate all artifacts]
F --> G
G --> H{PO finds issues?}
H -->|Yes| I[Return to relevant agent for fixes]
H -->|No| J[po: shard documents]
I --> G
J --> K[sm: create story]
K --> L{Review draft story?}
L -->|Yes| M[analyst/pm: review & approve story]
L -->|No| N[dev: implement story]
M --> N
N --> O{QA review?}
O -->|Yes| P[qa: review implementation]
O -->|No| Q{More stories?}
P --> R{QA found issues?}
R -->|Yes| S[dev: address QA feedback]
R -->|No| Q
S --> P
Q -->|Yes| K
Q -->|No| T{Epic retrospective?}
T -->|Yes| U[po: epic retrospective]
T -->|No| V[Project Complete]
U --> V
B -.-> B1[Optional: brainstorming]
B -.-> B2[Optional: market research]
D -.-> D1[Optional: technical research]
style V fill:#90EE90
style J fill:#ADD8E6
style K fill:#ADD8E6
style N fill:#ADD8E6
style B fill:#FFE4B5
style C fill:#FFE4B5
style D fill:#FFE4B5
style M fill:#F0E68C
style P fill:#F0E68C
style U fill:#F0E68C
```
decision_guidance:
when_to_use:
- Building production APIs or microservices
- Multiple endpoints and complex business logic
- Need comprehensive documentation and testing
- Multiple team members will be involved
- Long-term maintenance expected
- Enterprise or external-facing APIs
handoff_prompts:
analyst_to_pm: "Project brief is complete. Save it as docs/project-brief.md in your project, then create the PRD."
pm_to_architect: "PRD is ready. Save it as docs/prd.md in your project, then create the service architecture."
architect_review: "Architecture complete. Save it as docs/architecture.md. Do you suggest any changes to the PRD stories or need new stories added?"
architect_to_pm: "Please update the PRD with the suggested story changes, then re-export the complete prd.md to docs/."
updated_to_po: "All documents ready in docs/ folder. Please validate all artifacts for consistency."
po_issues: "PO found issues with [document]. Please return to [agent] to fix and re-save the updated document."
complete: "All planning artifacts validated and saved in docs/ folder. Move to IDE environment to begin development."

View File

@ -0,0 +1,236 @@
# <!-- Powered by BMAD™ Core -->
workflow:
id: greenfield-ui
name: Greenfield UI/Frontend Development
description: >-
Agent workflow for building frontend applications from concept to development.
Supports both comprehensive planning for complex UIs and rapid prototyping for simple interfaces.
type: greenfield
project_types:
- spa
- mobile-app
- micro-frontend
- static-site
- ui-prototype
- simple-interface
sequence:
- agent: analyst
creates: project-brief.md
optional_steps:
- brainstorming_session
- market_research_prompt
notes: "Can do brainstorming first, then optional deep research before creating project brief. SAVE OUTPUT: Copy final project-brief.md to your project's docs/ folder."
- agent: pm
creates: prd.md
requires: project-brief.md
notes: "Creates PRD from project brief using prd-tmpl, focused on UI/frontend requirements. SAVE OUTPUT: Copy final prd.md to your project's docs/ folder."
- agent: ux-expert
creates: front-end-spec.md
requires: prd.md
optional_steps:
- user_research_prompt
notes: "Creates UI/UX specification using front-end-spec-tmpl. SAVE OUTPUT: Copy final front-end-spec.md to your project's docs/ folder."
- agent: ux-expert
creates: v0_prompt (optional)
requires: front-end-spec.md
condition: user_wants_ai_generation
notes: "OPTIONAL BUT RECOMMENDED: Generate AI UI prompt for tools like v0, Lovable, etc. Use the generate-ai-frontend-prompt task. User can then generate UI in external tool and download project structure."
- agent: architect
creates: front-end-architecture.md
requires: front-end-spec.md
optional_steps:
- technical_research_prompt
- review_generated_ui_structure
notes: "Creates frontend architecture using front-end-architecture-tmpl. If user generated UI with v0/Lovable, can incorporate the project structure into architecture. May suggest changes to PRD stories or new stories. SAVE OUTPUT: Copy final front-end-architecture.md to your project's docs/ folder."
- agent: pm
updates: prd.md (if needed)
requires: front-end-architecture.md
condition: architecture_suggests_prd_changes
notes: "If architect suggests story changes, update PRD and re-export the complete unredacted prd.md to docs/ folder."
- agent: po
validates: all_artifacts
uses: po-master-checklist
notes: "Validates all documents for consistency and completeness. May require updates to any document."
- agent: various
updates: any_flagged_documents
condition: po_checklist_issues
notes: "If PO finds issues, return to relevant agent to fix and re-export updated documents to docs/ folder."
- step: project_setup_guidance
action: guide_project_structure
condition: user_has_generated_ui
notes: "If user generated UI with v0/Lovable: For polyrepo setup, place downloaded project in separate frontend repo. For monorepo, place in apps/web or frontend/ directory. Review architecture document for specific guidance."
- agent: po
action: shard_documents
creates: sharded_docs
requires: all_artifacts_in_project
notes: |
Shard documents for IDE development:
- Option A: Use PO agent to shard: @po then ask to shard docs/prd.md
- Option B: Manual: Drag shard-doc task + docs/prd.md into chat
- Creates docs/prd/ and docs/architecture/ folders with sharded content
- agent: sm
action: create_story
creates: story.md
requires: sharded_docs
repeats: for_each_epic
notes: |
Story creation cycle:
- SM Agent (New Chat): @sm → *create
- Creates next story from sharded docs
- Story starts in "Draft" status
- agent: analyst/pm
action: review_draft_story
updates: story.md
requires: story.md
optional: true
condition: user_wants_story_review
notes: |
OPTIONAL: Review and approve draft story
- NOTE: story-review task coming soon
- Review story completeness and alignment
- Update story status: Draft → Approved
- agent: dev
action: implement_story
creates: implementation_files
requires: story.md
notes: |
Dev Agent (New Chat): @dev
- Implements approved story
- Updates File List with all changes
- Marks story as "Review" when complete
- agent: qa
action: review_implementation
updates: implementation_files
requires: implementation_files
optional: true
notes: |
OPTIONAL: QA Agent (New Chat): @qa → review-story
- Senior dev review with refactoring ability
- Fixes small issues directly
- Leaves checklist for remaining items
- Updates story status (Review → Done or stays Review)
- agent: dev
action: address_qa_feedback
updates: implementation_files
condition: qa_left_unchecked_items
notes: |
If QA left unchecked items:
- Dev Agent (New Chat): Address remaining items
- Return to QA for final approval
- step: repeat_development_cycle
action: continue_for_all_stories
notes: |
Repeat story cycle (SM → Dev → QA) for all epic stories
Continue until all stories in PRD are complete
- agent: po
action: epic_retrospective
creates: epic-retrospective.md
condition: epic_complete
optional: true
notes: |
OPTIONAL: After epic completion
- NOTE: epic-retrospective task coming soon
- Validate epic was completed correctly
- Document learnings and improvements
- step: workflow_end
action: project_complete
notes: |
All stories implemented and reviewed!
Project development phase complete.
Reference: .bmad-core/data/bmad-kb.md#IDE Development Workflow
flow_diagram: |
```mermaid
graph TD
A[Start: UI Development] --> B[analyst: project-brief.md]
B --> C[pm: prd.md]
C --> D[ux-expert: front-end-spec.md]
D --> D2{Generate v0 prompt?}
D2 -->|Yes| D3[ux-expert: create v0 prompt]
D2 -->|No| E[architect: front-end-architecture.md]
D3 --> D4[User: generate UI in v0/Lovable]
D4 --> E
E --> F{Architecture suggests PRD changes?}
F -->|Yes| G[pm: update prd.md]
F -->|No| H[po: validate all artifacts]
G --> H
H --> I{PO finds issues?}
I -->|Yes| J[Return to relevant agent for fixes]
I -->|No| K[po: shard documents]
J --> H
K --> L[sm: create story]
L --> M{Review draft story?}
M -->|Yes| N[analyst/pm: review & approve story]
M -->|No| O[dev: implement story]
N --> O
O --> P{QA review?}
P -->|Yes| Q[qa: review implementation]
P -->|No| R{More stories?}
Q --> S{QA found issues?}
S -->|Yes| T[dev: address QA feedback]
S -->|No| R
T --> Q
R -->|Yes| L
R -->|No| U{Epic retrospective?}
U -->|Yes| V[po: epic retrospective]
U -->|No| W[Project Complete]
V --> W
B -.-> B1[Optional: brainstorming]
B -.-> B2[Optional: market research]
D -.-> D1[Optional: user research]
E -.-> E1[Optional: technical research]
style W fill:#90EE90
style K fill:#ADD8E6
style L fill:#ADD8E6
style O fill:#ADD8E6
style D3 fill:#E6E6FA
style D4 fill:#E6E6FA
style B fill:#FFE4B5
style C fill:#FFE4B5
style D fill:#FFE4B5
style E fill:#FFE4B5
style N fill:#F0E68C
style Q fill:#F0E68C
style V fill:#F0E68C
```
decision_guidance:
when_to_use:
- Building production frontend applications
- Multiple views/pages with complex interactions
- Need comprehensive UI/UX design and testing
- Multiple team members will be involved
- Long-term maintenance expected
- Customer-facing applications
handoff_prompts:
analyst_to_pm: "Project brief is complete. Save it as docs/project-brief.md in your project, then create the PRD."
pm_to_ux: "PRD is ready. Save it as docs/prd.md in your project, then create the UI/UX specification."
ux_to_architect: "UI/UX spec complete. Save it as docs/front-end-spec.md in your project, then create the frontend architecture."
architect_review: "Frontend architecture complete. Save it as docs/front-end-architecture.md. Do you suggest any changes to the PRD stories or need new stories added?"
architect_to_pm: "Please update the PRD with the suggested story changes, then re-export the complete prd.md to docs/."
updated_to_po: "All documents ready in docs/ folder. Please validate all artifacts for consistency."
po_issues: "PO found issues with [document]. Please return to [agent] to fix and re-save the updated document."
complete: "All planning artifacts validated and saved in docs/ folder. Move to IDE environment to begin development."

36
.env.example Normal file
View File

@ -0,0 +1,36 @@
# 应用配置
APP_NAME=Vue3 Python Notepad
APP_VERSION=1.0.0
# 后端配置
BACKEND_HOST=0.0.0.0
BACKEND_PORT=8000
PYTHONPATH=/app
PYTHONUNBUFFERED=1
# 前端配置
VITE_API_BASE_URL=/api
# 文件存储
NOTES_DIR=/app/data
# 安全配置
# 请修改这个密码,建议使用强密码
FILE_LIST_PASSWORD=your_secure_password_here
# JWT 配置
JWT_SECRET_KEY=your_jwt_secret_key_here_change_this_in_production
JWT_ALGORITHM=HS256
JWT_EXPIRE_MINUTES=1440 # 24小时
# Docker 配置
COMPOSE_PROJECT_NAME=notepad
# 可选:日志级别
LOG_LEVEL=info
# 可选:最大文件大小(字节)
MAX_FILE_SIZE=100000
# 可选:文件名最大长度
MAX_FILENAME_LENGTH=200

147
.gitignore vendored Normal file
View File

@ -0,0 +1,147 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
ENV/
env.bak/
venv.bak/
*.egg-info/
.eggs/
dist/
build/
# Virtual environment
backend/venv/
backend/env/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Node.js
node_modules/
.pnpm-store/
.pnpm-debug.log*
# Build outputs
frontend/dist/
frontend/build/
backend/static/
# Cache
.cache/
.temp/
.tmp/
.parcel-cache/
# Coverage reports
coverage/
*.lcov
# Docker
.dockerignore
# Data files (keep structure but ignore content)
files/
backend/data/
*.txt
*.md
!README.md
!DOCKER_DEPLOY.md
# Backup files
*.bak
*.backup
*.old
# Lock files (keep package-lock.json but ignore others if needed)
# package-lock.json
# pnpm-lock.yaml
# Test files
tests/
coverage/
.nyc_output/
# Runtime data
pids/
*.pid
*.seed
*.pid.lock
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
public
# Storybook build outputs
.out
.storybook-out
# Temporary folders
tmp/
temp/

113
DOCKER_DEPLOY.md Normal file
View File

@ -0,0 +1,113 @@
# Vue3 + Python Notepad Docker 部署指南
## 快速开始
### 前提条件
- Docker
- Docker Compose
### 部署步骤
1. **克隆项目**
```bash
git clone <repository-url>
cd bmadtest
```
2. **构建并启动服务**
```bash
docker-compose up -d --build
```
3. **访问应用**
- 前端http://localhost
- APIhttp://localhost/api
- WebSocketws://localhost/ws
### 常用命令
**查看服务状态**
```bash
docker-compose ps
```
**查看日志**
```bash
# 查看所有服务日志
docker-compose logs
# 查看特定服务日志
docker-compose logs backend
docker-compose logs frontend
```
**停止服务**
```bash
docker-compose down
```
**重新构建并启动**
```bash
docker-compose up -d --build
```
### 数据持久化
文件数据存储在 `./files/notes/` 目录下。确保在宿主机上备份此目录以防止数据丢失。
### 环境变量配置
如需自定义配置,可以在 `docker-compose.yml` 中修改环境变量:
```yaml
environment:
- PYTHONPATH=/app
- PYTHONUNBUFFERED=1
# 其他环境变量...
```
### 端口配置
默认端口配置:
- 前端80
- 后端8000容器内部
如需修改前端端口,编辑 `docker-compose.yml` 中的 ports 配置:
```yaml
ports:
- "8080:80" # 将宿主机的 8080 端口映射到容器的 80 端口
```
### 故障排除
1. **端口被占用**
- 修改 docker-compose.yml 中的端口映射
- 或停止占用端口的服务
2. **权限问题**
- 确保 `./files` 目录有适当的写权限
- 运行:`chmod -R 755 ./files`
3. **构建失败**
- 清理 Docker 缓存:`docker system prune -a`
- 重新构建:`docker-compose build --no-cache`
### 生产环境建议
1. **使用 HTTPS**
- 配置 SSL 证书
- 使用反向代理(如 Traefik 或 Nginx
2. **安全配置**
- 修改默认密码
- 限制 API 访问频率
- 使用防火墙
3. **监控**
- 配置日志收集
- 设置健康检查
- 监控资源使用情况
4. **备份**
- 定期备份 `./files` 目录
- 考虑使用云存储

212
README.md Normal file
View File

@ -0,0 +1,212 @@
# Vue3 + Python Notepad 应用
一个简单的在线文本编辑器,支持实时自动保存和文件管理。
## 功能特性
- ✅ 实时文本编辑与自动保存
- ✅ URL驱动的文件访问
- ✅ 文件列表管理(需口令验证)
- ✅ WebSocket实时通信
- ✅ 响应式设计
- ✅ 文件大小限制10万字符
- ✅ 文件名验证与安全过滤
## 技术栈
- **前端**: Vue 3, TypeScript, Vite, Pinia, Vue Router
- **后端**: Python, FastAPI, WebSocket
## 快速开始
### 前置要求
- Node.js 18+
- Python 3.10+
- pnpm 8+
### 安装步骤
1. **克隆项目**
```bash
git clone <repository-url>
cd vue-python-notepad
```
2. **安装依赖**
```bash
# 安装前端依赖
cd frontend && pnpm install && cd ..
# 设置Python虚拟环境并安装后端依赖
cd backend
python -m venv venv
# Windows
venv\Scripts\activate
# macOS/Linux
source venv/bin/activate
pip install -r requirements.txt
cd ..
```
3. **配置环境变量**
```bash
# 复制环境变量模板
cp backend/.env.example .env
# 编辑.env文件设置必要的环境变量
```
4. **启动开发服务器**
**方法一:分别启动**
```bash
# 启动后端服务器终端1
cd backend
venv\Scripts\activate # Windows
python main.py
# 启动前端开发服务器终端2
cd frontend
pnpm dev
```
**方法二:同时启动**
```bash
# 在项目根目录
pnpm dev
```
5. **访问应用**
- 前端: http://localhost:5173
- 后端API: http://localhost:8000
- API文档: http://localhost:8000/docs
## 使用说明
### 基本操作
1. **创建/编辑文件**
- 访问 `http://localhost:5173/notes/filename.txt`
- 如果文件不存在,会自动创建
- 输入内容会自动保存500ms延迟
2. **文件列表**
- 访问 `http://localhost:5173/file-list`
- 输入口令默认your_secure_password
- 查看和管理所有文件
3. **URL分享**
- 直接分享文件URL给他人
- 例如:`http://localhost:5173/notes/shared-note.txt`
### 环境变量配置
```bash
# 前端环境变量
VITE_API_BASE_URL=http://localhost:8000/api
VITE_WS_BASE_URL=ws://localhost:8000/ws
# 后端环境变量
NOTES_DIR=./data/notes # 文件存储目录
FILE_LIST_PASSWORD=your_secure_password # 文件列表访问口令
JWT_SECRET_KEY=your_jwt_secret_key # JWT密钥
JWT_EXPIRE_HOURS=24 # 令牌过期时间
```
## 项目结构
```
vue-python-notepad/
├── frontend/ # Vue3前端应用
│ ├── src/
│ │ ├── components/ # UI组件
│ │ ├── views/ # 页面组件
│ │ ├── stores/ # 状态管理
│ │ ├── services/ # API服务
│ │ └── router/ # 路由配置
│ ├── package.json
│ └── vite.config.ts
├── backend/ # FastAPI后端应用
│ ├── src/
│ │ ├── api/ # API路由
│ │ ├── services/ # 业务逻辑
│ │ ├── models/ # 数据模型
│ │ └── utils/ # 工具函数
│ ├── main.py
│ └── requirements.txt
├── docs/ # 项目文档
├── package.json # 根配置文件
└── README.md
```
## 开发指南
### 添加新功能
1. **前端组件**
- 在 `frontend/src/components/` 中创建组件
- 在 `frontend/src/views/` 中创建页面
- 使用 Pinia 管理状态
2. **后端API**
- 在 `backend/src/api/` 中添加路由
- 在 `backend/src/services/` 中实现业务逻辑
- 在 `backend/src/models/` 中定义数据模型
### 测试
```bash
# 运行前端测试
pnpm test:frontend
# 运行后端测试
pnpm test:backend
# 运行所有测试
pnpm test
```
### 构建部署
```bash
# 构建前端
pnpm build
# 生产环境启动
cd backend
venv\Scripts\activate # Windows
python main.py
```
## 故障排除
### 常见问题
1. **端口冲突**
- 确保8000和5173端口未被占用
- 或修改配置文件中的端口设置
2. **Python依赖问题**
- 确保使用Python 3.10+
- 激活虚拟环境后安装依赖
3. **前端代理错误**
- 检查 `frontend/vite.config.ts` 中的代理配置
- 确保后端服务器正在运行
4. **WebSocket连接失败**
- 检查防火墙设置
- 确认WebSocket URL正确
## 贡献指南
1. Fork 项目
2. 创建功能分支
3. 提交更改
4. 推送到分支
5. 创建 Pull Request
## 许可证
MIT License

13
backend/.env.example Normal file
View File

@ -0,0 +1,13 @@
# 文件存储配置
NOTES_DIR=./data/notes
# 认证配置 - 请在生产环境中更改这些值
FILE_LIST_PASSWORD=your_secure_password_change_this
JWT_SECRET_KEY=your_jwt_secret_key_change_this_in_production
JWT_ALGORITHM=HS256
JWT_EXPIRE_HOURS=24
# 服务器配置
HOST=0.0.0.0
PORT=8000
DEBUG=true

30
backend/Dockerfile Normal file
View File

@ -0,0 +1,30 @@
FROM python:3.11-slim
WORKDIR /app
# 安装系统依赖
RUN apt-get update && apt-get install -y \
gcc \
&& rm -rf /var/lib/apt/lists/*
# 复制依赖文件
COPY requirements.txt .
# 安装 Python 依赖
RUN pip install --no-cache-dir -r requirements.txt
# 复制源代码
COPY . .
# 创建数据目录
RUN mkdir -p data/notes
# 暴露端口
EXPOSE 8000
# 设置环境变量
ENV PYTHONPATH=/app
ENV PYTHONUNBUFFERED=1
# 启动命令
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

47
backend/main.py Normal file
View File

@ -0,0 +1,47 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import uvicorn
import os
from src.api import notes, files, websocket
from src.utils.config import get_settings
app = FastAPI(
title="Vue3 + Python Notepad API",
description="简单的文本编辑器API支持文件读写和列表功能",
version="1.0.0"
)
# 配置CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173", "ws://localhost:5173"], # Vue开发服务器
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 注册路由
app.include_router(notes.router, prefix="/api", tags=["notes"])
app.include_router(files.router, prefix="/api", tags=["files"])
app.include_router(websocket.router, prefix="/ws", tags=["websocket"])
# 静态文件服务(用于生产环境)
if os.path.exists("./static"):
app.mount("/", StaticFiles(directory="./static", html=True), name="static")
@app.get("/health")
async def health_check():
"""健康检查端点"""
return {"status": "healthy"}
if __name__ == "__main__":
settings = get_settings()
uvicorn.run(
"main:app",
host="0.0.0.0",
port=8000,
reload=True,
log_level="info"
)

0
backend/src/__init__.py Normal file
View File

View File

85
backend/src/api/files.py Normal file
View File

@ -0,0 +1,85 @@
from fastapi import APIRouter, HTTPException, Depends, Query
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from ..services.file_service import FileService
from ..services.auth_service import AuthService
from ..models.text_file import FileListItem, FileListResponse, PasswordRequest, AuthToken
router = APIRouter(prefix="/files", tags=["files"])
file_service = FileService()
auth_service = AuthService()
security = HTTPBearer()
async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
"""验证JWT令牌"""
token = credentials.credentials
if not auth_service.validate_token(token):
raise HTTPException(
status_code=403,
detail="Invalid or expired token"
)
return token
@router.post("/verify-password", response_model=AuthToken)
async def verify_password(request: PasswordRequest):
"""验证访问口令"""
try:
token = auth_service.verify_password(request.password)
return token
except ValueError as e:
raise HTTPException(status_code=401, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.get("/list", response_model=FileListResponse, dependencies=[Depends(verify_token)])
async def get_files_list(
page: int = Query(1, ge=1, description="页码"),
limit: int = Query(50, ge=1, le=100, description="每页文件数")
):
"""获取文件列表(需要认证)"""
try:
files = file_service.list_files(page, limit)
total = file_service.get_total_files_count()
return FileListResponse(
files=files,
total=total,
page=page,
limit=limit
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.delete("/{filename}")
async def delete_file(filename: str):
"""删除文件"""
try:
if not file_service.file_exists(filename):
raise HTTPException(status_code=404, detail="File not found")
file_service.delete_file(filename)
return {"message": f"File {filename} deleted successfully"}
except FileNotFoundError:
raise HTTPException(status_code=404, detail="File not found")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.put("/{filename}/rename")
async def rename_file(filename: str, new_filename: str = Query(..., description="新文件名")):
"""重命名文件"""
try:
if not file_service.file_exists(filename):
raise HTTPException(status_code=404, detail="File not found")
if file_service.file_exists(new_filename):
raise HTTPException(status_code=400, detail="File with new name already exists")
file_service.rename_file(filename, new_filename)
return {"message": f"File renamed from {filename} to {new_filename}"}
except FileNotFoundError:
raise HTTPException(status_code=404, detail="File not found")
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))

40
backend/src/api/notes.py Normal file
View File

@ -0,0 +1,40 @@
from fastapi import APIRouter, HTTPException, Path
from ..services.file_service import FileService
from ..models.text_file import TextFile, SaveRequest
router = APIRouter(prefix="/notes", tags=["notes"])
file_service = FileService()
@router.get("/{filename}", response_model=TextFile)
async def get_file(filename: str = Path(..., min_length=1, max_length=200)):
"""获取文件内容"""
try:
if file_service.file_exists(filename):
return file_service.read_file(filename)
else:
# 文件不存在时返回一个空的文件对象,不实际创建文件
from datetime import datetime
return TextFile(
filename=filename,
content="",
created_at=datetime.now(),
updated_at=datetime.now(),
size=0
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.post("/{filename}", response_model=TextFile)
async def save_file(
filename: str = Path(..., min_length=1, max_length=200),
request: SaveRequest = None
):
"""保存文件内容"""
try:
return file_service.write_file(filename, request.content)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))

View File

@ -0,0 +1,101 @@
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from typing import Dict
import json
import asyncio
from ..services.file_service import FileService
router = APIRouter()
file_service = FileService()
class ConnectionManager:
def __init__(self):
self.active_connections: Dict[str, WebSocket] = {}
async def connect(self, websocket: WebSocket, filename: str):
await websocket.accept()
self.active_connections[filename] = websocket
def disconnect(self, filename: str):
if filename in self.active_connections:
del self.active_connections[filename]
async def send_message(self, message: dict, filename: str):
if filename in self.active_connections:
websocket = self.active_connections[filename]
try:
await websocket.send_text(json.dumps(message))
except:
# 连接已断开,清理
self.disconnect(filename)
manager = ConnectionManager()
@router.websocket("/{filename}")
async def websocket_endpoint(websocket: WebSocket, filename: str):
print(f"WebSocket connection attempt for file: {filename}")
try:
await manager.connect(websocket, filename)
print(f"WebSocket connected for file: {filename}")
except Exception as e:
print(f"WebSocket connection failed: {e}")
await websocket.close(code=1006)
try:
while True:
# 接收客户端消息
data = await websocket.receive_text()
message = json.loads(data)
# 处理保存请求
if message.get("type") == "save":
try:
content = message.get("content", "")
# 检查内容是否为空
if not content or content.strip() == "":
# 删除空文件
if file_service.file_exists(filename):
file_service.delete_file(filename)
response = {
"type": "save_response",
"status": "success",
"message": "空文件已删除",
"timestamp": message.get("timestamp")
}
else:
response = {
"type": "save_response",
"status": "success",
"message": "文件不存在",
"timestamp": message.get("timestamp")
}
else:
# 保存非空文件
file_service.write_file(filename, content)
response = {
"type": "save_response",
"status": "success",
"message": "保存成功",
"timestamp": message.get("timestamp")
}
except Exception as e:
# 发送失败响应
response = {
"type": "save_response",
"status": "error",
"message": str(e),
"timestamp": message.get("timestamp")
}
await manager.send_message(response, filename)
except WebSocketDisconnect:
manager.disconnect(filename)
except Exception as e:
# 发送错误响应
error_response = {
"type": "error",
"message": str(e)
}
await manager.send_message(error_response, filename)
manager.disconnect(filename)

View File

View File

@ -0,0 +1,32 @@
from pydantic import BaseModel
from datetime import datetime
from typing import Optional, List
class TextFile(BaseModel):
filename: str
content: str
created_at: datetime
updated_at: datetime
size: int
class FileListItem(BaseModel):
filename: str
created_at: datetime
size: int
preview: Optional[str] = None
class SaveRequest(BaseModel):
content: str
class AuthToken(BaseModel):
token: str
expires_at: datetime
class PasswordRequest(BaseModel):
password: str
class FileListResponse(BaseModel):
files: List[FileListItem]
total: int
page: int
limit: int

View File

View File

@ -0,0 +1,46 @@
from datetime import datetime, timedelta
from typing import Optional
import jwt
from ..models.text_file import AuthToken
from ..utils.config import get_settings
class AuthService:
def __init__(self):
self.settings = get_settings()
def verify_password(self, password: str) -> AuthToken:
"""验证口令并生成令牌"""
if password != self.settings.file_list_password:
raise ValueError("Invalid password")
# 生成JWT令牌
expires_delta = timedelta(hours=self.settings.jwt_expire_hours)
expires_at = datetime.utcnow() + expires_delta
to_encode = {
"exp": expires_at,
"sub": "file_list_access"
}
token = jwt.encode(
to_encode,
self.settings.jwt_secret_key,
algorithm=self.settings.jwt_algorithm
)
return AuthToken(
token=token,
expires_at=expires_at
)
def validate_token(self, token: str) -> bool:
"""验证JWT令牌"""
try:
jwt.decode(
token,
self.settings.jwt_secret_key,
algorithms=[self.settings.jwt_algorithm]
)
return True
except jwt.PyJWTError:
return False

View File

@ -0,0 +1,194 @@
import os
import re
from datetime import datetime
from typing import List, Optional
from pathlib import Path
from ..models.text_file import TextFile, FileListItem
from ..utils.config import get_settings
class FileService:
def __init__(self):
self.settings = get_settings()
self.notes_dir = Path(self.settings.notes_dir)
self.notes_dir.mkdir(parents=True, exist_ok=True)
def _validate_filename(self, filename: str) -> bool:
"""验证文件名是否安全"""
# 检查文件名长度
if len(filename) > 200 or len(filename) < 1:
return False
# 检查文件名是否包含非法字符
illegal_chars = r'[<>:"/\\|?*\x00-\x1f]'
if re.search(illegal_chars, filename):
return False
# 检查路径遍历攻击
if '..' in filename or filename.startswith('/'):
return False
# 确保文件扩展名为.txt
if not filename.lower().endswith('.txt'):
return False
return True
def read_file(self, filename: str) -> TextFile:
"""读取文件内容"""
if not self._validate_filename(filename):
raise ValueError(f"Invalid filename: {filename}")
file_path = self.notes_dir / filename
if not file_path.exists():
raise FileNotFoundError(f"File {filename} not found")
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
stat = file_path.stat()
return TextFile(
filename=filename,
content=content,
created_at=datetime.fromtimestamp(stat.st_ctime),
updated_at=datetime.fromtimestamp(stat.st_mtime),
size=len(content)
)
except UnicodeDecodeError:
raise ValueError(f"File {filename} is not a valid text file")
except Exception as e:
raise RuntimeError(f"Error reading file {filename}: {str(e)}")
def write_file(self, filename: str, content: str) -> TextFile:
"""写入文件内容"""
if not self._validate_filename(filename):
raise ValueError(f"Invalid filename: {filename}")
if content is None:
raise ValueError("Content cannot be None")
if len(content) > 100000:
raise ValueError("File content too large (max 100,000 characters)")
file_path = self.notes_dir / filename
try:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
stat = file_path.stat()
return TextFile(
filename=filename,
content=content,
created_at=datetime.fromtimestamp(stat.st_ctime),
updated_at=datetime.fromtimestamp(stat.st_mtime),
size=len(content)
)
except Exception as e:
raise RuntimeError(f"Error writing file {filename}: {str(e)}")
def create_file(self, filename: str) -> TextFile:
"""创建新文件"""
return self.write_file(filename, "")
def list_files(self, page: int = 1, limit: int = 50) -> List[FileListItem]:
"""列出文件"""
if page < 1:
page = 1
if limit < 1 or limit > 100:
limit = 50
files = []
try:
for file_path in self.notes_dir.glob("*.txt"):
stat = file_path.stat()
# 读取文件前100个字符作为预览
preview = ""
if stat.st_size > 0:
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read(100)
# 清理预览内容,移除换行符
preview = content.replace('\n', ' ').replace('\r', '').strip()
if len(preview) > 50:
preview = preview[:50] + "..."
except UnicodeDecodeError:
preview = "[非文本文件]"
except Exception:
preview = ""
files.append(FileListItem(
filename=file_path.name,
created_at=datetime.fromtimestamp(stat.st_ctime),
size=stat.st_size,
preview=preview
))
except Exception as e:
raise RuntimeError(f"Error listing files: {str(e)}")
# 按创建时间倒序排列
files.sort(key=lambda x: x.created_at, reverse=True)
# 分页
start = (page - 1) * limit
end = start + limit
return files[start:end]
def get_total_files_count(self) -> int:
"""获取文件总数"""
try:
return len(list(self.notes_dir.glob("*.txt")))
except Exception:
return 0
def file_exists(self, filename: str) -> bool:
"""检查文件是否存在"""
if not self._validate_filename(filename):
return False
file_path = self.notes_dir / filename
return file_path.exists() and file_path.is_file()
def delete_file(self, filename: str) -> bool:
"""删除文件"""
if not self._validate_filename(filename):
raise ValueError(f"Invalid filename: {filename}")
file_path = self.notes_dir / filename
if not file_path.exists():
raise FileNotFoundError(f"File {filename} not found")
try:
file_path.unlink()
return True
except Exception as e:
raise RuntimeError(f"Error deleting file {filename}: {str(e)}")
def rename_file(self, old_filename: str, new_filename: str) -> bool:
"""重命名文件"""
if not self._validate_filename(old_filename):
raise ValueError(f"Invalid old filename: {old_filename}")
if not self._validate_filename(new_filename):
raise ValueError(f"Invalid new filename: {new_filename}")
old_path = self.notes_dir / old_filename
new_path = self.notes_dir / new_filename
if not old_path.exists():
raise FileNotFoundError(f"File {old_filename} not found")
if new_path.exists():
raise ValueError(f"File {new_filename} already exists")
try:
old_path.rename(new_path)
return True
except Exception as e:
raise RuntimeError(f"Error renaming file {old_filename}: {str(e)}")

View File

View File

@ -0,0 +1,43 @@
from pydantic_settings import BaseSettings
from pathlib import Path
import os
class Settings(BaseSettings):
"""应用配置"""
# 基础配置
app_name: str = os.getenv("APP_NAME", "Vue3 + Python Notepad")
app_version: str = os.getenv("APP_VERSION", "1.0.0")
debug: bool = os.getenv("DEBUG", "false").lower() == "true"
# 文件存储配置
notes_dir: str = os.getenv("NOTES_DIR", "/app/data")
# 安全配置
file_list_password: str = os.getenv("FILE_LIST_PASSWORD", "admin123")
# JWT配置
jwt_secret_key: str = os.getenv("JWT_SECRET_KEY", "your-secret-key-change-this-in-production")
jwt_algorithm: str = os.getenv("JWT_ALGORITHM", "HS256")
jwt_expire_minutes: int = int(os.getenv("JWT_EXPIRE_MINUTES", "1440")) # 24小时
# 文件限制
max_file_size: int = int(os.getenv("MAX_FILE_SIZE", "100000")) # 100KB
max_filename_length: int = int(os.getenv("MAX_FILENAME_LENGTH", "200"))
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
# 创建全局设置实例
settings = Settings()
def get_settings() -> Settings:
return settings
# 确保数据目录存在
def ensure_data_directory():
os.makedirs(settings.notes_dir, exist_ok=True)
# 在导入时创建目录
ensure_data_directory()

38
docker-compose.yml Normal file
View File

@ -0,0 +1,38 @@
version: '3.8'
services:
backend:
build:
context: ./backend
dockerfile: Dockerfile
container_name: notepad-backend
restart: unless-stopped
volumes:
- ./files:/app/data
env_file:
- .env
networks:
- notepad-network
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
container_name: notepad-frontend
restart: unless-stopped
ports:
- "80:80"
depends_on:
- backend
env_file:
- .env
networks:
- notepad-network
networks:
notepad-network:
driver: bridge
volumes:
notepad-data:
driver: local

34
frontend/Dockerfile Normal file
View File

@ -0,0 +1,34 @@
# 构建阶段
FROM node:18-alpine as build-stage
WORKDIR /app
# 复制 package.json 和 pnpm-lock.yaml
COPY package*.json pnpm-lock.yaml* ./
# 安装 pnpm
RUN npm install -g pnpm
# 安装依赖
RUN pnpm install --frozen-lockfile
# 复制源代码
COPY . .
# 构建应用
RUN pnpm run build
# 生产阶段
FROM nginx:alpine as production-stage
# 复制构建产物到 nginx
COPY --from=build-stage /app/dist /usr/share/nginx/html
# 复制 nginx 配置
COPY nginx.conf /etc/nginx/nginx.conf
# 暴露端口
EXPOSE 80
# 启动 nginx
CMD ["nginx", "-g", "daemon off;"]

7
frontend/env.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
/// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}

13
frontend/index.html Normal file
View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue3 + Python Notepad</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

80
frontend/nginx.conf Normal file
View File

@ -0,0 +1,80 @@
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
# 基本设置
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip 压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/javascript
application/xml+rss
application/json;
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# 处理前端路由
location / {
try_files $uri $uri/ /index.html;
}
# 代理 API 请求到后端
location /api {
proxy_pass http://backend:8000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
# 代理 WebSocket 请求到后端
location /ws {
proxy_pass http://backend:8000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 86400;
}
# 静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
}

36
frontend/package.json Normal file
View File

@ -0,0 +1,36 @@
{
"name": "vue-python-notepad-web",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc && vite build",
"preview": "vite preview",
"test": "vitest",
"test:ui": "vitest --ui",
"test:e2e": "playwright test",
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
"type-check": "vue-tsc --noEmit"
},
"dependencies": {
"vue": "^3.3.8",
"vue-router": "^4.2.5",
"pinia": "^2.1.7",
"axios": "^1.6.2"
},
"devDependencies": {
"@types/node": "^20.10.4",
"@vitejs/plugin-vue": "^4.5.2",
"@vue/eslint-config-typescript": "^12.0.0",
"@vue/test-utils": "^2.4.3",
"@vue/tsconfig": "^0.5.1",
"eslint": "^8.56.0",
"eslint-plugin-vue": "^9.19.2",
"jsdom": "^23.0.1",
"playwright": "^1.40.1",
"typescript": "~5.3.3",
"vite": "^5.0.10",
"vitest": "^1.0.4",
"vue-tsc": "^1.8.25"
}
}

3355
frontend/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

21
frontend/src/App.vue Normal file
View File

@ -0,0 +1,21 @@
<template>
<div id="app">
<RouterView />
</div>
</template>
<script setup lang="ts">
import { RouterView } from 'vue-router'
</script>
<style>
#app {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
height: 100vh;
margin: 0;
padding: 0;
}
</style>

View File

@ -0,0 +1,132 @@
<template>
<div :class="statusClasses" class="status-indicator">
<div v-if="status === 'saving'" class="loading-spinner"></div>
<div v-else class="status-dot"></div>
<span class="status-text">{{ statusText }}</span>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
interface Props {
status: 'saved' | 'saving' | 'error'
}
const props = defineProps<Props>()
const statusClasses = computed(() => ({
'status-saved': props.status === 'saved',
'status-saving': props.status === 'saving',
'status-error': props.status === 'error'
}))
const statusText = computed(() => {
switch (props.status) {
case 'saved':
return '已保存'
case 'saving':
return '保存中...'
case 'error':
return '保存失败'
default:
return ''
}
})
</script>
<style scoped>
.status-indicator {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.25rem 0.5rem;
border-radius: 4px;
font-size: 12px;
font-weight: 500;
transition: all 0.2s ease;
}
.status-saved {
background-color: #d5f4e6;
color: #27ae60;
}
.status-saving {
background-color: #fef9e7;
color: #f39c12;
}
.status-error {
background-color: #fadbd8;
color: #e74c3c;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
}
.status-saved .status-dot {
background-color: #27ae60;
}
.status-error .status-dot {
background-color: #e74c3c;
}
.loading-spinner {
width: 12px;
height: 12px;
border: 2px solid #f39c12;
border-top: 2px solid transparent;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* 移动端适配 */
@media (max-width: 768px) {
.status-indicator {
padding: 0.2rem 0.4rem;
font-size: 11px;
}
.status-dot {
width: 6px;
height: 6px;
}
.loading-spinner {
width: 10px;
height: 10px;
border-width: 1.5px;
}
}
@media (max-width: 480px) {
.status-indicator {
padding: 0.15rem 0.3rem;
font-size: 10px;
}
.status-text {
display: none;
}
.status-dot {
width: 6px;
height: 6px;
}
.loading-spinner {
width: 8px;
height: 8px;
}
}
</style>

13
frontend/src/main.ts Normal file
View File

@ -0,0 +1,13 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from './router'
import App from './App.vue'
import './styles/main.css'
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.use(router)
app.mount('#app')

View File

@ -0,0 +1,38 @@
import { createRouter, createWebHistory } from 'vue-router'
import EditorView from '@/views/EditorView.vue'
import FileListView from '@/views/FileListView.vue'
import TestView from '@/views/TestView.vue'
const routes = [
{
path: '/notes/:filename',
name: 'editor',
component: EditorView,
props: true
},
{
path: '/list',
name: 'list',
component: FileListView
},
{
path: '/test',
name: 'test',
component: TestView
},
{
path: '/',
redirect: () => {
// 生成随机文件名
const timestamp = Date.now().toString(36)
const random = Math.random().toString(36).substr(2, 5)
return `/notes/${timestamp}-${random}`
}
}]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router

View File

@ -0,0 +1,75 @@
import axios from 'axios'
const api = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
timeout: 10000
})
// 请求拦截器 - 添加认证令牌
api.interceptors.request.use((config) => {
const token = localStorage.getItem('authToken')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
// 响应拦截器 - 处理错误
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
// 令牌过期,清除本地存储
localStorage.removeItem('authToken')
window.location.reload()
}
return Promise.reject(error)
}
)
export interface TextFile {
filename: string
content: string
created_at: string
updated_at: string
size: number
}
export interface FileListItem {
filename: string
created_at: string
size: number
}
export interface AuthToken {
token: string
expires_at: string
}
export interface FileListResponse {
files: FileListItem[]
total: number
page: number
limit: number
}
export const notesApi = {
getFile: (filename: string) => api.get<TextFile>(`/notes/${filename}`),
saveFile: (filename: string, content: string) =>
api.post<TextFile>(`/notes/${filename}`, { content })
}
export const filesApi = {
getList: (page = 1, limit = 50) =>
api.get<FileListResponse>(
'/files/list', { params: { page, limit } }
),
verifyPassword: (password: string) =>
api.post<AuthToken>('/files/verify-password', { password }),
deleteFile: (filename: string) =>
api.delete(`/files/${filename}`),
renameFile: (filename: string, newFilename: string) =>
api.put(`/files/${filename}/rename?new_filename=${encodeURIComponent(newFilename)}`)
}
export default api

View File

@ -0,0 +1,108 @@
import { ref } from 'vue'
import { useEditorStore } from '@/stores/editor'
export function useWebSocket() {
let ws: WebSocket | null = null
const reconnectAttempts = ref(0)
const maxReconnectAttempts = 5
const editorStore = useEditorStore()
const connect = (filename: string) => {
if (ws) {
ws.close()
}
// 使用相对路径,通过 Vite 代理
const wsUrl = `/ws/${filename}`
if (import.meta.env.DEV) console.log(`Connecting to WebSocket at: ${wsUrl}`)
try {
ws = new WebSocket(wsUrl)
ws.onopen = () => {
reconnectAttempts.value = 0
// 只在开发环境输出
if (import.meta.env.DEV) console.log('WebSocket connected')
}
ws.onmessage = (event) => {
// 只在开发环境输出
if (import.meta.env.DEV) {
console.log('📨 WebSocket message received:', event.data)
}
const message = JSON.parse(event.data)
if (import.meta.env.DEV) {
console.log('📨 Parsed message:', message)
}
handleMessage(message)
}
ws.onclose = (event) => {
// 只在开发环境输出
if (import.meta.env.DEV) console.log('WebSocket closed:', event.code, event.reason)
if (reconnectAttempts.value < maxReconnectAttempts) {
setTimeout(() => {
reconnectAttempts.value++
if (import.meta.env.DEV) console.log(`Reconnecting... attempt ${reconnectAttempts.value}`)
connect(filename)
}, 1000 * reconnectAttempts.value)
} else {
console.error('Max reconnection attempts reached')
editorStore.setSaveStatus('error')
}
}
ws.onerror = (error) => {
console.error('WebSocket error:', error)
editorStore.setSaveStatus('error')
}
} catch (error) {
if (import.meta.env.DEV) console.error('Failed to create WebSocket:', error)
editorStore.setSaveStatus('error')
}
}
const sendSave = (filename: string, content: string) => {
if (ws?.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
type: 'save',
content,
timestamp: new Date().toISOString()
}))
}
}
const disconnect = () => {
if (ws) {
ws.close()
ws = null
}
}
const handleMessage = (message: any) => {
if (import.meta.env.DEV) console.log('🔄 Handling WebSocket message:', message)
switch (message.type) {
case 'save_response':
if (import.meta.env.DEV) console.log('✅ Save response received:', message.status)
editorStore.setSaveStatus(
message.status === 'success' ? 'saved' : 'error'
)
break
case 'error':
console.error('❌ WebSocket error:', message.message)
editorStore.setSaveStatus('error')
break
default:
if (import.meta.env.DEV) console.log('❓ Unknown message type:', message.type)
}
}
const getWebSocket = () => ws
return {
connect,
sendSave,
disconnect,
getWebSocket
}
}

View File

@ -0,0 +1,41 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useEditorStore = defineStore('editor', () => {
const currentFile = ref<string>('')
const content = ref<string>('')
const saveStatus = ref<'saved' | 'saving' | 'error'>('saved')
const lastSaved = ref<Date | null>(null)
const isLoading = ref(false)
const setContent = (newContent: string) => {
content.value = newContent
}
const setSaveStatus = (status: 'saved' | 'saving' | 'error') => {
saveStatus.value = status
if (status === 'saved') {
lastSaved.value = new Date()
}
}
const setLoading = (loading: boolean) => {
isLoading.value = loading
}
const setCurrentFile = (filename: string) => {
currentFile.value = filename
}
return {
currentFile,
content,
saveStatus,
lastSaved,
isLoading,
setContent,
setSaveStatus,
setLoading,
setCurrentFile
}
})

View File

@ -0,0 +1,143 @@
/* Reset and base styles */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body {
height: 100%;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 14px;
line-height: 1.5;
color: #2c3e50;
background-color: #ffffff;
}
/* Utility classes */
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
/* Focus styles */
*:focus {
outline: 2px solid #3498db;
outline-offset: 2px;
}
/* Button styles */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.5rem 1rem;
border: 1px solid transparent;
border-radius: 4px;
font-size: 14px;
font-weight: 500;
text-decoration: none;
cursor: pointer;
transition: all 0.2s ease;
}
.btn-primary {
background-color: #3498db;
color: white;
border-color: #3498db;
}
.btn-primary:hover {
background-color: #2980b9;
border-color: #2980b9;
}
.btn-secondary {
background-color: #ecf0f1;
color: #2c3e50;
border-color: #bdc3c7;
}
.btn-secondary:hover {
background-color: #d5dbdd;
border-color: #95a5a6;
}
/* Status indicator */
.status-indicator {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.25rem 0.5rem;
border-radius: 4px;
font-size: 12px;
font-weight: 500;
}
.status-saved {
background-color: #d5f4e6;
color: #27ae60;
}
.status-saving {
background-color: #fef9e7;
color: #f39c12;
}
.status-error {
background-color: #fadbd8;
color: #e74c3c;
}
/* Form styles */
.form-group {
margin-bottom: 1rem;
}
.form-label {
display: block;
margin-bottom: 0.5rem;
font-weight: 500;
}
.form-input {
width: 100%;
padding: 0.5rem;
border: 1px solid #bdc3c7;
border-radius: 4px;
font-size: 14px;
transition: border-color 0.2s ease;
}
.form-input:focus {
border-color: #3498db;
outline: none;
}
.form-error {
color: #e74c3c;
font-size: 12px;
margin-top: 0.25rem;
}
/* Loading spinner */
.loading-spinner {
width: 20px;
height: 20px;
border: 2px solid #ecf0f1;
border-top: 2px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}

View File

@ -0,0 +1,621 @@
<template>
<div class="editor-view">
<div class="editor-header">
<div class="editor-title">
<h2>{{ displayName }}</h2>
<div class="editor-actions">
<button
@click="startRename"
class="btn btn-secondary btn-sm"
title="重命名文件"
>
重命名
</button>
<button
@click="deleteFile"
class="btn btn-danger btn-sm"
title="删除文件"
:disabled="deletingFile"
>
{{ deletingFile ? '删除中...' : '删除' }}
</button>
</div>
</div>
<StatusIndicator :status="editorStore.saveStatus" />
</div>
<div class="editor-content">
<textarea
ref="editorElement"
v-model="editorStore.content"
@input="handleInput"
:disabled="editorStore.isLoading"
class="editor-textarea"
placeholder="开始输入..."
/>
</div>
<!-- 调试工具仅在测试模式下显示 -->
<div v-if="testingMode" class="debug-tools">
<button @click="testSave" class="btn btn-info btn-sm">测试保存</button>
<button @click="toggleTestingMode" class="btn btn-secondary btn-sm">关闭调试</button>
<div class="debug-info">
<p>当前文件: {{ editorStore.currentFile }}</p>
<p>保存状态: {{ editorStore.saveStatus }}</p>
<p>内容长度: {{ editorStore.content.length }}</p>
</div>
</div>
<!-- 重命名对话框 -->
<div v-if="renamingFile" class="modal-overlay" @click="cancelRename">
<div class="modal-content" @click.stop>
<h3>重命名文件</h3>
<form @submit.prevent="confirmRename">
<div class="form-group">
<label for="newFilename">新文件名</label>
<input
id="newFilename"
v-model="newFilename"
type="text"
placeholder="请输入新文件名"
class="form-input"
ref="renameInput"
maxlength="20"
required
/>
<small class="form-help">文件名最多20个字符不能包含特殊字符</small>
</div>
<div class="modal-actions">
<button
type="button"
@click="cancelRename"
class="btn btn-secondary"
>
取消
</button>
<button
type="submit"
class="btn btn-primary"
:disabled="!newFilename.trim()"
>
确认
</button>
</div>
</form>
<p v-if="renameError" class="error-message">{{ renameError }}</p>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useEditorStore } from '@/stores/editor'
import { notesApi, filesApi } from '@/services/api'
import { useWebSocket } from '@/services/websocket'
import StatusIndicator from '@/components/common/StatusIndicator.vue'
const route = useRoute()
const router = useRouter()
const editorStore = useEditorStore()
const { connect, sendSave, disconnect, getWebSocket } = useWebSocket()
const editorElement = ref<HTMLTextAreaElement>()
const renamingFile = ref(false)
const newFilename = ref('')
const renameError = ref('')
const renameInput = ref<HTMLInputElement>()
const deletingFile = ref(false)
const testingMode = ref(false) //
// .txt
const displayName = computed(() => {
const filename = editorStore.currentFile
if (filename.toLowerCase().endsWith('.txt')) {
return filename.slice(0, -4)
}
return filename
})
const getDisplayName = (filename: string) => {
if (filename.toLowerCase().endsWith('.txt')) {
return filename.slice(0, -4)
}
return filename
}
let saveTimeout: number | null = null
const handleInput = () => {
if (saveTimeout) {
clearTimeout(saveTimeout)
}
editorStore.setSaveStatus('saving')
saveTimeout = window.setTimeout(async () => {
if (testingMode.value) {
console.log('=== Auto Save Triggered ===')
console.log('Attempting to save file:', editorStore.currentFile)
console.log('Content length:', editorStore.content.length)
}
// WebSocket
const ws = getWebSocket()
if (testingMode.value) {
console.log('WebSocket instance:', ws)
console.log('WebSocket readyState:', ws?.readyState)
console.log('WebSocket OPEN constant:', WebSocket.OPEN)
}
if (ws && ws.readyState === WebSocket.OPEN) {
if (testingMode.value) console.log('✅ Using WebSocket to save')
try {
// .txt
const filename = editorStore.currentFile.toLowerCase().endsWith('.txt')
? editorStore.currentFile
: `${editorStore.currentFile}.txt`
if (testingMode.value) console.log('Sending to WebSocket with filename:', filename)
sendSave(filename, editorStore.content)
if (testingMode.value) console.log('WebSocket message sent, waiting for response...')
// WebSocket 5退 HTTP
setTimeout(() => {
if (editorStore.saveStatus === 'saving') {
if (testingMode.value) console.warn('⚠️ WebSocket save timeout (5s), falling back to HTTP')
saveViaHttp()
}
}, 5000)
} catch (error) {
if (testingMode.value) console.warn('❌ WebSocket save failed, falling back to HTTP:', error)
await saveViaHttp()
}
} else {
if (testingMode.value) {
console.log('❌ WebSocket not available, using HTTP')
console.log('WebSocket available:', !!ws)
console.log('WebSocket state:', ws?.readyState)
}
await saveViaHttp()
}
}, 500)
}
const startRename = () => {
renamingFile.value = true
newFilename.value = displayName.value
renameError.value = ''
//
nextTick(() => {
renameInput.value?.focus()
renameInput.value?.select()
})
}
const cancelRename = () => {
renamingFile.value = false
newFilename.value = ''
renameError.value = ''
}
const deleteFile = async () => {
if (!confirm(`确定要删除文件 "${displayName}" 吗?此操作不可恢复。`)) {
return
}
deletingFile.value = true
try {
await filesApi.deleteFile(editorStore.currentFile)
//
router.push('/')
} catch (err: any) {
console.error('Delete error:', err)
alert(err.response?.data?.detail || '删除文件失败')
} finally {
deletingFile.value = false
}
}
const testSave = async () => {
// .txt
const filename = editorStore.currentFile.toLowerCase().endsWith('.txt')
? editorStore.currentFile
: `${editorStore.currentFile}.txt`
if (testingMode.value) {
console.log('=== Manual Test Save ===')
console.log('Current file:', filename)
console.log('Content length:', editorStore.content.length)
console.log('Content preview:', editorStore.content.substring(0, 100))
}
editorStore.setSaveStatus('saving')
try {
const response = await notesApi.saveFile(filename, editorStore.content)
if (testingMode.value) console.log('Test save response:', response)
editorStore.setSaveStatus('saved')
if (testingMode.value) console.log('✅ Test save successful!')
} catch (error: any) {
if (testingMode.value) {
console.error('❌ Test save failed:', error)
console.error('Error details:', {
message: error.message,
status: error.response?.status,
data: error.response?.data,
headers: error.response?.headers
})
}
editorStore.setSaveStatus('error')
}
}
const toggleTestingMode = () => {
testingMode.value = !testingMode.value
}
const confirmRename = async () => {
if (!newFilename.value.trim()) {
renameError.value = '文件名不能为空'
return
}
//
if (newFilename.value.length > 20) {
renameError.value = '文件名不能超过20个字符'
return
}
//
const invalidChars = /[<>:"/\\|?*\x00-\x1f]/
if (invalidChars.test(newFilename.value)) {
renameError.value = '文件名包含无效字符'
return
}
try {
const oldFilename = editorStore.currentFile
const newFullFilename = newFilename.value.toLowerCase().endsWith('.txt')
? newFilename.value
: `${newFilename.value}.txt`
await filesApi.renameFile(oldFilename, newFullFilename)
//
editorStore.setCurrentFile(newFullFilename)
// URL
router.replace(`/notes/${getDisplayName(newFullFilename)}`)
cancelRename()
} catch (err: any) {
console.error('Rename error:', err)
renameError.value = err.response?.data?.detail || '重命名失败'
}
}
const saveViaHttp = async () => {
try {
// .txt
const filename = editorStore.currentFile.toLowerCase().endsWith('.txt')
? editorStore.currentFile
: `${editorStore.currentFile}.txt`
//
if (!editorStore.content || editorStore.content.trim() === '') {
if (testingMode.value) console.log('Content is empty, deleting file:', filename)
await filesApi.deleteFile(filename)
editorStore.setSaveStatus('saved')
if (testingMode.value) console.log('Empty file deleted successfully')
return
}
if (testingMode.value) {
console.log('Attempting HTTP save for:', filename)
console.log('Request payload:', { content: editorStore.content })
}
const response = await notesApi.saveFile(filename, editorStore.content)
if (testingMode.value) console.log('HTTP save response:', response)
editorStore.setSaveStatus('saved')
if (testingMode.value) console.log('HTTP save successful')
} catch (error: any) {
if (testingMode.value) {
console.error('HTTP save failed:', error)
console.error('Error response:', error.response)
console.error('Error status:', error.response?.status)
console.error('Error data:', error.response?.data)
}
editorStore.setSaveStatus('error')
//
if (error.code === 'NETWORK_ERROR' || error.message?.includes('Network Error')) {
if (testingMode.value) console.log('Network error detected, retrying in 2 seconds...')
setTimeout(() => {
if (editorStore.saveStatus === 'error') {
saveViaHttp()
}
}, 2000)
}
}
}
const loadFile = async (filename: string) => {
// .txt
const fullFilename = filename.toLowerCase().endsWith('.txt') ? filename : `${filename}.txt`
editorStore.setLoading(true)
editorStore.setCurrentFile(fullFilename)
try {
const response = await notesApi.getFile(fullFilename)
editorStore.setContent(response.data.content)
editorStore.setSaveStatus('saved')
} catch (error) {
console.error('Load failed:', error)
editorStore.setContent('')
editorStore.setSaveStatus('error')
} finally {
editorStore.setLoading(false)
}
}
onMounted(() => {
editorElement.value?.focus()
const filename = route.params.filename as string
loadFile(filename)
// WebSocket使.txt
const fullFilename = filename.toLowerCase().endsWith('.txt') ? filename : `${filename}.txt`
connect(fullFilename)
})
onUnmounted(() => {
disconnect()
})
watch(() => route.params.filename, (newFilename) => {
const filename = newFilename as string
loadFile(filename)
// WebSocket使.txt
const fullFilename = filename.toLowerCase().endsWith('.txt') ? filename : `${filename}.txt`
connect(fullFilename)
})
</script>
<style scoped>
.editor-view {
display: flex;
flex-direction: column;
height: 100vh;
}
.editor-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
border-bottom: 1px solid #ecf0f1;
background-color: #ffffff;
}
.editor-title {
display: flex;
align-items: center;
gap: 0.5rem;
}
.editor-actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
.editor-header h2 {
font-size: 18px;
font-weight: 600;
color: #2c3e50;
}
.editor-content {
flex: 1;
display: flex;
flex-direction: column;
}
.editor-textarea {
flex: 1;
border: none;
padding: 1rem;
font-family: 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;
font-size: 14px;
line-height: 1.5;
resize: none;
outline: none;
background-color: #ffffff;
color: #2c3e50;
}
.editor-textarea:disabled {
background-color: #f8f9fa;
color: #6c757d;
}
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-content {
background-color: white;
padding: 2rem;
border-radius: 8px;
width: 100%;
max-width: 400px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}
.modal-content h3 {
margin-bottom: 1.5rem;
color: #2c3e50;
}
.form-group {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-bottom: 1rem;
}
.form-group label {
font-weight: 500;
color: #2c3e50;
}
.form-input {
padding: 0.75rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 16px;
}
.form-input:focus {
outline: none;
border-color: #3498db;
box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}
.form-help {
color: #7f8c8d;
font-size: 12px;
}
.modal-actions {
display: flex;
gap: 1rem;
justify-content: flex-end;
}
.debug-tools {
position: fixed;
top: 10px;
right: 10px;
background-color: rgba(0, 0, 0, 0.9);
color: white;
padding: 1rem;
border-radius: 4px;
z-index: 9999;
}
.debug-info {
font-size: 12px;
margin-top: 0.5rem;
}
.debug-info p {
margin: 0;
color: white;
}
/* 移动端适配 */
@media (max-width: 768px) {
.editor-header {
padding: 0.75rem 1rem;
flex-direction: column;
align-items: stretch;
gap: 0.75rem;
}
.editor-title {
flex-direction: column;
align-items: stretch;
gap: 0.5rem;
}
.editor-title h2 {
font-size: 16px;
text-align: center;
}
.editor-actions {
justify-content: center;
gap: 0.5rem;
}
.editor-actions .btn {
flex: 1;
font-size: 13px;
}
.editor-textarea {
padding: 0.75rem;
font-size: 13px;
}
.modal-content {
margin: 1rem;
padding: 1.5rem;
width: calc(100% - 2rem);
}
.modal-content h3 {
font-size: 18px;
}
.modal-actions {
flex-direction: column;
gap: 0.5rem;
}
.modal-actions .btn {
width: 100%;
}
.debug-tools {
position: fixed;
top: 5px;
right: 5px;
left: 5px;
padding: 0.75rem;
}
}
@media (max-width: 480px) {
.editor-header {
padding: 0.5rem;
}
.editor-title h2 {
font-size: 15px;
}
.editor-actions .btn {
padding: 0.5rem 0.75rem;
font-size: 12px;
}
.editor-textarea {
padding: 0.5rem;
font-size: 12px;
}
.modal-content {
margin: 0.5rem;
padding: 1rem;
}
.form-input {
padding: 0.6rem;
font-size: 14px;
}
}
</style>

View File

@ -0,0 +1,761 @@
<template>
<div class="file-list-view">
<!-- 未认证时显示密码输入 -->
<div v-if="!isAuthenticated" class="auth-container">
<div class="auth-card">
<h2>访问文件列表</h2>
<p class="auth-description">请输入访问口令以查看文件列表</p>
<form @submit.prevent="verifyPassword" class="auth-form">
<div class="form-group">
<label for="password">访问口令</label>
<input
id="password"
v-model="password"
type="password"
placeholder="请输入口令"
class="form-input"
required
/>
</div>
<button
type="submit"
class="btn btn-primary"
:disabled="loading"
>
{{ loading ? '验证中...' : '验证' }}
</button>
<p v-if="error" class="error-message">{{ error }}</p>
</form>
</div>
</div>
<!-- 已认证时显示文件列表 -->
<div v-else>
<div class="file-list-header">
<h1>文件列表</h1>
<div class="header-right">
<div class="search-box">
<input
v-model="searchQuery"
type="text"
placeholder="搜索文件名..."
class="search-input"
/>
<button
v-if="searchQuery"
@click="clearSearch"
class="btn btn-secondary btn-sm"
>
清除
</button>
</div>
<div class="header-actions">
<RouterLink to="/notes/new-file" class="btn btn-primary">
新建文件
</RouterLink> <button @click="logout" class="btn btn-secondary">
退出
</button>
</div>
</div>
</div>
<div v-if="loading" class="loading-container">
<div class="loading-spinner"></div>
<p>加载中...</p>
</div>
<div v-else-if="error" class="error-container">
<p class="error-message">{{ error }}</p>
<button @click="fetchFiles" class="btn btn-secondary">重试</button>
</div>
<div v-else-if="filteredFiles.length === 0" class="empty-container">
<p v-if="searchQuery">
没有找到匹配 "{{ searchQuery }}" 的文件
</p>
<p v-else>
还没有文件创建您的第一个文件吧
</p>
<RouterLink to="/notes/new-file" class="btn btn-primary">
创建文件
</RouterLink>
</div>
<div v-else class="file-list">
<div
v-for="file in filteredFiles"
:key="file.filename"
class="file-item"
>
<RouterLink
:to="`/notes/${getDisplayName(file.filename)}`"
class="file-link"
>
<div class="file-info">
<div class="file-name">{{ getDisplayName(file.filename) }}</div>
<div v-if="file.preview" class="file-preview">
{{ file.preview }}
</div>
<div class="file-meta">
创建时间: {{ formatDate(file.created_at) }} |
大小: {{ formatFileSize(file.size) }}
</div>
</div>
</RouterLink>
<div class="file-actions">
<button
@click.prevent="startRename(file.filename)"
class="btn btn-secondary btn-sm"
>
重命名
</button>
<button
@click.prevent="deleteFile(file.filename)"
class="btn btn-danger btn-sm"
:disabled="deleting === file.filename"
>
{{ deleting === file.filename ? '删除中...' : '删除' }}
</button>
</div>
</div>
</div>
<!-- 重命名对话框 -->
<div v-if="renamingFile" class="modal-overlay" @click="cancelRename">
<div class="modal-content" @click.stop>
<h3>重命名文件</h3>
<form @submit.prevent="confirmRename">
<div class="form-group">
<label for="newFilename">新文件名</label>
<input
id="newFilename"
v-model="newFilename"
type="text"
placeholder="请输入新文件名"
class="form-input"
ref="renameInput"
required
/>
</div>
<div class="modal-actions">
<button
type="button"
@click="cancelRename"
class="btn btn-secondary"
>
取消
</button>
<button
type="submit"
class="btn btn-primary"
:disabled="!newFilename || renaming"
>
{{ renaming ? '重命名中...' : '确认' }}
</button>
</div>
</form>
<p v-if="renameError" class="error-message">{{ renameError }}</p>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue'
import { RouterLink, useRouter } from 'vue-router'
import { filesApi, type FileListItem } from '@/services/api'
const router = useRouter()
const files = ref<FileListItem[]>([])
const filteredFiles = ref<FileListItem[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
const searchQuery = ref('')
const deleting = ref<string | null>(null)
const renamingFile = ref<string | null>(null)
const newFilename = ref('')
const renaming = ref(false)
const renameError = ref<string | null>(null)
const renameInput = ref<HTMLInputElement>()
const isAuthenticated = ref(false)
const password = ref('')
const fetchFiles = async () => {
loading.value = true
error.value = null
try {
const response = await filesApi.getList()
files.value = response.data.files
filterFiles()
} catch (err) {
if (err.response?.status === 401) {
//
isAuthenticated.value = false
} else {
error.value = err instanceof Error ? err.message : '获取文件列表失败'
}
} finally {
loading.value = false
}
}
const filterFiles = () => {
if (!searchQuery.value.trim()) {
filteredFiles.value = [...files.value]
} else {
const query = searchQuery.value.toLowerCase()
filteredFiles.value = files.value.filter(file =>
getDisplayName(file.filename).toLowerCase().includes(query)
)
}
}
const clearSearch = () => {
searchQuery.value = ''
filterFiles()
}
const verifyPassword = async () => {
if (!password.value) {
error.value = '请输入口令'
return
}
loading.value = true
error.value = null
try {
const response = await filesApi.verifyPassword(password.value)
localStorage.setItem('authToken', response.data.token)
isAuthenticated.value = true
await fetchFiles()
} catch (err) {
error.value = err.response?.data?.detail || '口令验证失败'
} finally {
loading.value = false
}
}
const logout = () => {
localStorage.removeItem('authToken')
isAuthenticated.value = false
error.value = null
files.value = []
}
const deleteFile = async (filename: string) => {
if (!confirm(`确定要删除文件 "${filename}" 吗?此操作不可恢复。`)) {
return
}
deleting.value = filename
try {
await filesApi.deleteFile(filename)
//
files.value = files.value.filter(f => f.filename !== filename)
// filterFiles filteredFiles
} catch (err) {
error.value = err.response?.data?.detail || '删除文件失败'
} finally {
deleting.value = null
}
}
const startRename = (filename: string) => {
renamingFile.value = filename
// .txt
newFilename.value = getDisplayName(filename)
renameError.value = null
//
nextTick(() => {
renameInput.value?.focus()
renameInput.value?.select()
})
}
const cancelRename = () => {
renamingFile.value = null
newFilename.value = ''
renameError.value = null
}
const confirmRename = async () => {
if (!renamingFile.value || !newFilename.value) {
return
}
// .txt
const finalFilename = newFilename.value.toLowerCase().endsWith('.txt')
? newFilename.value
: `${newFilename.value}.txt`
renaming.value = true
renameError.value = null
try {
await filesApi.renameFile(renamingFile.value, finalFilename)
//
const fileIndex = files.value.findIndex(f => f.filename === renamingFile.value)
if (fileIndex !== -1) {
files.value[fileIndex].filename = finalFilename
}
cancelRename()
} catch (err) {
renameError.value = err.response?.data?.detail || '重命名失败'
} finally {
renaming.value = false
}
}
const checkAuth = () => {
const token = localStorage.getItem('authToken')
if (token) {
isAuthenticated.value = true
fetchFiles()
}
}
//
watch(searchQuery, filterFiles)
//
watch(files, filterFiles)
const formatDate = (date: string | Date) => {
// Date
const dateObj = typeof date === 'string' ? new Date(date) : date
//
if (isNaN(dateObj.getTime())) {
return '未知时间'
}
return new Intl.DateTimeFormat('zh-CN', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
}).format(dateObj)
}
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
const getDisplayName = (filename: string) => {
// .txt
if (filename.toLowerCase().endsWith('.txt')) {
return filename.slice(0, -4)
}
return filename
}
onMounted(() => {
checkAuth()
})
</script>
<style scoped>
.file-list-view {
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
}
.auth-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 60vh;
}
.auth-card {
background-color: #ffffff;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 400px;
}
.auth-card h2 {
font-size: 24px;
font-weight: 600;
color: #2c3e50;
margin-bottom: 0.5rem;
}
.auth-description {
color: #7f8c8d;
margin-bottom: 1.5rem;
}
.auth-form {
display: flex;
flex-direction: column;
gap: 1rem;
}
.form-group {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.form-group label {
font-weight: 500;
color: #2c3e50;
}
.form-input {
padding: 0.75rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 16px;
}
.form-input:focus {
outline: none;
border-color: #3498db;
box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}
.file-list-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
}
.file-list-header h1 {
font-size: 24px;
font-weight: 600;
color: #2c3e50;
}
.header-right {
display: flex;
align-items: center;
gap: 1rem;
}
.search-box {
display: flex;
align-items: center;
gap: 0.5rem;
}
.search-input {
padding: 0.5rem 1rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
width: 250px;
}
.search-input:focus {
outline: none;
border-color: #3498db;
box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}
.loading-container,
.error-container,
.empty-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 4rem 2rem;
text-align: center;
}
.loading-container p,
.error-container .error-message,
.empty-container p {
margin-top: 1rem;
color: #7f8c8d;
}
.error-message {
color: #e74c3c;
}
.file-list {
display: grid;
gap: 1rem;
}
.file-item {
border: 1px solid #ecf0f1;
border-radius: 8px;
background-color: #ffffff;
transition: box-shadow 0.2s ease, border-color 0.2s ease;
display: flex;
align-items: center;
}
.file-item:hover {
border-color: #3498db;
box-shadow: 0 2px 8px rgba(52, 152, 219, 0.1);
}
.file-link {
flex: 1;
padding: 1rem;
text-decoration: none;
color: inherit;
}
.file-actions {
padding: 0 1rem;
display: flex;
gap: 0.5rem;
}
.btn-sm {
padding: 0.5rem 1rem;
font-size: 12px;
}
.btn-danger {
background-color: #e74c3c;
color: white;
}
.btn-danger:hover:not(:disabled) {
background-color: #c0392b;
}
.file-info {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.file-name {
font-size: 16px;
font-weight: 500;
color: #2c3e50;
}
.file-preview {
font-size: 13px;
color: #7f8c8d;
margin-top: 4px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-style: italic;
}
.file-meta {
font-size: 12px;
color: #7f8c8d;
margin-top: 4px;
}
.btn {
padding: 0.75rem 1.5rem;
border: none;
border-radius: 4px;
font-size: 14px;
font-weight: 500;
text-decoration: none;
cursor: pointer;
transition: all 0.2s ease;
display: inline-block;
}
.btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.btn-primary {
background-color: #3498db;
color: white;
}
.btn-primary:hover:not(:disabled) {
background-color: #2980b9;
}
.btn-secondary {
background-color: #95a5a6;
color: white;
}
.btn-secondary:hover:not(:disabled) {
background-color: #7f8c8d;
}
.header-actions {
display: flex;
gap: 1rem;
}
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-content {
background-color: white;
padding: 2rem;
border-radius: 8px;
width: 100%;
max-width: 400px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}
.modal-content h3 {
margin-bottom: 1.5rem;
color: #2c3e50;
}
.modal-actions {
display: flex;
gap: 1rem;
justify-content: flex-end;
margin-top: 1.5rem;
}
@media (max-width: 768px) {
.file-list-view {
padding: 0.5rem;
}
.file-list-header {
flex-direction: column;
align-items: stretch;
gap: 1rem;
padding: 1rem;
}
.header-right {
flex-direction: column;
gap: 1rem;
}
.search-box {
width: 100%;
}
.search-input {
width: 100%;
flex: 1;
}
.header-actions {
width: 100%;
justify-content: stretch;
gap: 0.5rem;
}
.header-actions .btn {
flex: 1;
}
.file-item {
flex-direction: column;
align-items: stretch;
}
.file-link {
padding: 1rem;
}
.file-actions {
padding: 0 1rem 1rem;
justify-content: stretch;
gap: 0.5rem;
}
.file-actions .btn {
flex: 1;
}
.modal-content {
margin: 1rem;
padding: 1.5rem;
width: calc(100% - 2rem);
}
.modal-actions {
flex-direction: column;
gap: 0.5rem;
}
.modal-actions .btn {
width: 100%;
}
}
@media (max-width: 480px) {
.file-list-view {
padding: 0.25rem;
}
.file-list-header {
padding: 0.75rem;
}
.file-list-header h1 {
font-size: 20px;
}
.auth-card {
margin: 0.5rem;
padding: 1.5rem;
}
.file-link {
padding: 0.75rem;
}
.file-name {
font-size: 15px;
}
.file-preview {
font-size: 12px;
}
.file-meta {
font-size: 11px;
}
.btn {
padding: 0.6rem 1rem;
font-size: 13px;
}
.btn-sm {
padding: 0.4rem 0.8rem;
font-size: 11px;
}
}
</style>

View File

@ -0,0 +1,100 @@
<template>
<div class="test-view">
<h1>WebSocket 测试</h1>
<div class="test-controls">
<button @click="testWebSocket">测试 WebSocket 连接</button>
<button @click="testHttpApi">测试 HTTP API</button>
</div>
<div class="test-results">
<h3>测试结果</h3>
<pre>{{ results }}</pre>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { notesApi } from '@/services/api'
import { useWebSocket } from '@/services/websocket'
const results = ref('')
const { connect, disconnect, sendSave } = useWebSocket()
const testWebSocket = async () => {
results.value = '开始测试 WebSocket...\n'
try {
//
connect('test-websocket.txt')
results.value += 'WebSocket 连接已尝试\n'
//
setTimeout(() => {
sendSave('test-websocket.txt', 'WebSocket 测试内容')
results.value += 'WebSocket 消息已发送\n'
}, 1000)
// 5
setTimeout(() => {
disconnect()
results.value += 'WebSocket 已断开\n'
}, 5000)
} catch (error) {
results.value += `WebSocket 错误: ${error}\n`
}
}
const testHttpApi = async () => {
results.value = '开始测试 HTTP API...\n'
try {
//
const saveResponse = await notesApi.saveFile('test-http.txt', 'HTTP API 测试内容')
results.value += `保存成功: ${JSON.stringify(saveResponse.data, null, 2)}\n`
//
const getResponse = await notesApi.getFile('test-http.txt')
results.value += `读取成功: ${JSON.stringify(getResponse.data, null, 2)}\n`
} catch (error) {
results.value += `HTTP API 错误: ${error}\n`
}
}
</script>
<style scoped>
.test-view {
padding: 2rem;
max-width: 800px;
margin: 0 auto;
}
.test-controls {
margin: 1rem 0;
}
.test-controls button {
margin-right: 1rem;
padding: 0.5rem 1rem;
background-color: #3498db;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.test-controls button:hover {
background-color: #2980b9;
}
.test-results {
margin-top: 1rem;
padding: 1rem;
background-color: #f8f9fa;
border-radius: 4px;
}
pre {
white-space: pre-wrap;
word-wrap: break-word;
}
</style>

18
frontend/tsconfig.json Normal file
View File

@ -0,0 +1,18 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": [
"env.d.ts",
"src/**/*",
"src/**/*.vue"
],
"exclude": [
"src/**/__tests__/*"
],
"compilerOptions": {
"composite": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}

28
frontend/vite.config.ts Normal file
View File

@ -0,0 +1,28 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true
},
'/ws': {
target: 'ws://localhost:8000',
ws: true
}
}
},
build: {
outDir: '../backend/static'
}
})

22
package.json Normal file
View File

@ -0,0 +1,22 @@
{
"name": "vue-python-notepad",
"version": "1.0.0",
"description": "Vue3 + Python Notepad 应用",
"private": true,
"scripts": {
"dev:frontend": "cd frontend && pnpm dev",
"dev:backend": "cd backend && venv\\Scripts\\python main.py",
"dev": "concurrently \"pnpm dev:frontend\" \"pnpm dev:backend\"",
"build": "cd frontend && pnpm build",
"test:frontend": "cd frontend && pnpm test",
"test:backend": "cd backend && venv\\Scripts\\pytest",
"test": "pnpm test:frontend && pnpm test:backend"
},
"devDependencies": {
"concurrently": "^8.2.2"
},
"engines": {
"node": ">=18.0.0",
"pnpm": ">=8.0.0"
}
}