Initial commit
EBO <eric.bouhana@softalys.com> committé le 2026-03-05 23:06
2c871e64a768923d588f2c08e341dc8cb371855b
29 fichiers modifiés
+5712
-0
A
.cursor/commands/speckit.analyze.md
+184
-0
@@ -0,0 +1,184 @@
| 1 | +--- | |
| 2 | +description: Perform a non-destructive cross-artifact consistency and quality analysis across spec.md, plan.md, and tasks.md after task generation. | |
| 3 | +--- | |
| 4 | + | |
| 5 | +## User Input | |
| 6 | + | |
| 7 | +```text | |
| 8 | +$ARGUMENTS | |
| 9 | +``` | |
| 10 | + | |
| 11 | +You **MUST** consider the user input before proceeding (if not empty). | |
| 12 | + | |
| 13 | +## Goal | |
| 14 | + | |
| 15 | +Identify inconsistencies, duplications, ambiguities, and underspecified items across the three core artifacts (`spec.md`, `plan.md`, `tasks.md`) before implementation. This command MUST run only after `/speckit.tasks` has successfully produced a complete `tasks.md`. | |
| 16 | + | |
| 17 | +## Operating Constraints | |
| 18 | + | |
| 19 | +**STRICTLY READ-ONLY**: Do **not** modify any files. Output a structured analysis report. Offer an optional remediation plan (user must explicitly approve before any follow-up editing commands would be invoked manually). | |
| 20 | + | |
| 21 | +**Constitution Authority**: The project constitution (`.specify/memory/constitution.md`) is **non-negotiable** within this analysis scope. Constitution conflicts are automatically CRITICAL and require adjustment of the spec, plan, or tasks—not dilution, reinterpretation, or silent ignoring of the principle. If a principle itself needs to change, that must occur in a separate, explicit constitution update outside `/speckit.analyze`. | |
| 22 | + | |
| 23 | +## Execution Steps | |
| 24 | + | |
| 25 | +### 1. Initialize Analysis Context | |
| 26 | + | |
| 27 | +Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` once from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS. Derive absolute paths: | |
| 28 | + | |
| 29 | +- SPEC = FEATURE_DIR/spec.md | |
| 30 | +- PLAN = FEATURE_DIR/plan.md | |
| 31 | +- TASKS = FEATURE_DIR/tasks.md | |
| 32 | + | |
| 33 | +Abort with an error message if any required file is missing (instruct the user to run missing prerequisite command). | |
| 34 | +For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). | |
| 35 | + | |
| 36 | +### 2. Load Artifacts (Progressive Disclosure) | |
| 37 | + | |
| 38 | +Load only the minimal necessary context from each artifact: | |
| 39 | + | |
| 40 | +**From spec.md:** | |
| 41 | + | |
| 42 | +- Overview/Context | |
| 43 | +- Functional Requirements | |
| 44 | +- Non-Functional Requirements | |
| 45 | +- User Stories | |
| 46 | +- Edge Cases (if present) | |
| 47 | + | |
| 48 | +**From plan.md:** | |
| 49 | + | |
| 50 | +- Architecture/stack choices | |
| 51 | +- Data Model references | |
| 52 | +- Phases | |
| 53 | +- Technical constraints | |
| 54 | + | |
| 55 | +**From tasks.md:** | |
| 56 | + | |
| 57 | +- Task IDs | |
| 58 | +- Descriptions | |
| 59 | +- Phase grouping | |
| 60 | +- Parallel markers [P] | |
| 61 | +- Referenced file paths | |
| 62 | + | |
| 63 | +**From constitution:** | |
| 64 | + | |
| 65 | +- Load `.specify/memory/constitution.md` for principle validation | |
| 66 | + | |
| 67 | +### 3. Build Semantic Models | |
| 68 | + | |
| 69 | +Create internal representations (do not include raw artifacts in output): | |
| 70 | + | |
| 71 | +- **Requirements inventory**: Each functional + non-functional requirement with a stable key (derive slug based on imperative phrase; e.g., "User can upload file" → `user-can-upload-file`) | |
| 72 | +- **User story/action inventory**: Discrete user actions with acceptance criteria | |
| 73 | +- **Task coverage mapping**: Map each task to one or more requirements or stories (inference by keyword / explicit reference patterns like IDs or key phrases) | |
| 74 | +- **Constitution rule set**: Extract principle names and MUST/SHOULD normative statements | |
| 75 | + | |
| 76 | +### 4. Detection Passes (Token-Efficient Analysis) | |
| 77 | + | |
| 78 | +Focus on high-signal findings. Limit to 50 findings total; aggregate remainder in overflow summary. | |
| 79 | + | |
| 80 | +#### A. Duplication Detection | |
| 81 | + | |
| 82 | +- Identify near-duplicate requirements | |
| 83 | +- Mark lower-quality phrasing for consolidation | |
| 84 | + | |
| 85 | +#### B. Ambiguity Detection | |
| 86 | + | |
| 87 | +- Flag vague adjectives (fast, scalable, secure, intuitive, robust) lacking measurable criteria | |
| 88 | +- Flag unresolved placeholders (TODO, TKTK, ???, `<placeholder>`, etc.) | |
| 89 | + | |
| 90 | +#### C. Underspecification | |
| 91 | + | |
| 92 | +- Requirements with verbs but missing object or measurable outcome | |
| 93 | +- User stories missing acceptance criteria alignment | |
| 94 | +- Tasks referencing files or components not defined in spec/plan | |
| 95 | + | |
| 96 | +#### D. Constitution Alignment | |
| 97 | + | |
| 98 | +- Any requirement or plan element conflicting with a MUST principle | |
| 99 | +- Missing mandated sections or quality gates from constitution | |
| 100 | + | |
| 101 | +#### E. Coverage Gaps | |
| 102 | + | |
| 103 | +- Requirements with zero associated tasks | |
| 104 | +- Tasks with no mapped requirement/story | |
| 105 | +- Non-functional requirements not reflected in tasks (e.g., performance, security) | |
| 106 | + | |
| 107 | +#### F. Inconsistency | |
| 108 | + | |
| 109 | +- Terminology drift (same concept named differently across files) | |
| 110 | +- Data entities referenced in plan but absent in spec (or vice versa) | |
| 111 | +- Task ordering contradictions (e.g., integration tasks before foundational setup tasks without dependency note) | |
| 112 | +- Conflicting requirements (e.g., one requires Next.js while other specifies Vue) | |
| 113 | + | |
| 114 | +### 5. Severity Assignment | |
| 115 | + | |
| 116 | +Use this heuristic to prioritize findings: | |
| 117 | + | |
| 118 | +- **CRITICAL**: Violates constitution MUST, missing core spec artifact, or requirement with zero coverage that blocks baseline functionality | |
| 119 | +- **HIGH**: Duplicate or conflicting requirement, ambiguous security/performance attribute, untestable acceptance criterion | |
| 120 | +- **MEDIUM**: Terminology drift, missing non-functional task coverage, underspecified edge case | |
| 121 | +- **LOW**: Style/wording improvements, minor redundancy not affecting execution order | |
| 122 | + | |
| 123 | +### 6. Produce Compact Analysis Report | |
| 124 | + | |
| 125 | +Output a Markdown report (no file writes) with the following structure: | |
| 126 | + | |
| 127 | +## Specification Analysis Report | |
| 128 | + | |
| 129 | +| ID | Category | Severity | Location(s) | Summary | Recommendation | | |
| 130 | +|----|----------|----------|-------------|---------|----------------| | |
| 131 | +| A1 | Duplication | HIGH | spec.md:L120-134 | Two similar requirements ... | Merge phrasing; keep clearer version | | |
| 132 | + | |
| 133 | +(Add one row per finding; generate stable IDs prefixed by category initial.) | |
| 134 | + | |
| 135 | +**Coverage Summary Table:** | |
| 136 | + | |
| 137 | +| Requirement Key | Has Task? | Task IDs | Notes | | |
| 138 | +|-----------------|-----------|----------|-------| | |
| 139 | + | |
| 140 | +**Constitution Alignment Issues:** (if any) | |
| 141 | + | |
| 142 | +**Unmapped Tasks:** (if any) | |
| 143 | + | |
| 144 | +**Metrics:** | |
| 145 | + | |
| 146 | +- Total Requirements | |
| 147 | +- Total Tasks | |
| 148 | +- Coverage % (requirements with >=1 task) | |
| 149 | +- Ambiguity Count | |
| 150 | +- Duplication Count | |
| 151 | +- Critical Issues Count | |
| 152 | + | |
| 153 | +### 7. Provide Next Actions | |
| 154 | + | |
| 155 | +At end of report, output a concise Next Actions block: | |
| 156 | + | |
| 157 | +- If CRITICAL issues exist: Recommend resolving before `/speckit.implement` | |
| 158 | +- If only LOW/MEDIUM: User may proceed, but provide improvement suggestions | |
| 159 | +- Provide explicit command suggestions: e.g., "Run /speckit.specify with refinement", "Run /speckit.plan to adjust architecture", "Manually edit tasks.md to add coverage for 'performance-metrics'" | |
| 160 | + | |
| 161 | +### 8. Offer Remediation | |
| 162 | + | |
| 163 | +Ask the user: "Would you like me to suggest concrete remediation edits for the top N issues?" (Do NOT apply them automatically.) | |
| 164 | + | |
| 165 | +## Operating Principles | |
| 166 | + | |
| 167 | +### Context Efficiency | |
| 168 | + | |
| 169 | +- **Minimal high-signal tokens**: Focus on actionable findings, not exhaustive documentation | |
| 170 | +- **Progressive disclosure**: Load artifacts incrementally; don't dump all content into analysis | |
| 171 | +- **Token-efficient output**: Limit findings table to 50 rows; summarize overflow | |
| 172 | +- **Deterministic results**: Rerunning without changes should produce consistent IDs and counts | |
| 173 | + | |
| 174 | +### Analysis Guidelines | |
| 175 | + | |
| 176 | +- **NEVER modify files** (this is read-only analysis) | |
| 177 | +- **NEVER hallucinate missing sections** (if absent, report them accurately) | |
| 178 | +- **Prioritize constitution violations** (these are always CRITICAL) | |
| 179 | +- **Use examples over exhaustive rules** (cite specific instances, not generic patterns) | |
| 180 | +- **Report zero issues gracefully** (emit success report with coverage statistics) | |
| 181 | + | |
| 182 | +## Context | |
| 183 | + | |
| 184 | +$ARGUMENTS |
A
.cursor/commands/speckit.checklist.md
+295
-0
@@ -0,0 +1,295 @@
| 1 | +--- | |
| 2 | +description: Generate a custom checklist for the current feature based on user requirements. | |
| 3 | +--- | |
| 4 | + | |
| 5 | +## Checklist Purpose: "Unit Tests for English" | |
| 6 | + | |
| 7 | +**CRITICAL CONCEPT**: Checklists are **UNIT TESTS FOR REQUIREMENTS WRITING** - they validate the quality, clarity, and completeness of requirements in a given domain. | |
| 8 | + | |
| 9 | +**NOT for verification/testing**: | |
| 10 | + | |
| 11 | +- ❌ NOT "Verify the button clicks correctly" | |
| 12 | +- ❌ NOT "Test error handling works" | |
| 13 | +- ❌ NOT "Confirm the API returns 200" | |
| 14 | +- ❌ NOT checking if code/implementation matches the spec | |
| 15 | + | |
| 16 | +**FOR requirements quality validation**: | |
| 17 | + | |
| 18 | +- ✅ "Are visual hierarchy requirements defined for all card types?" (completeness) | |
| 19 | +- ✅ "Is 'prominent display' quantified with specific sizing/positioning?" (clarity) | |
| 20 | +- ✅ "Are hover state requirements consistent across all interactive elements?" (consistency) | |
| 21 | +- ✅ "Are accessibility requirements defined for keyboard navigation?" (coverage) | |
| 22 | +- ✅ "Does the spec define what happens when logo image fails to load?" (edge cases) | |
| 23 | + | |
| 24 | +**Metaphor**: If your spec is code written in English, the checklist is its unit test suite. You're testing whether the requirements are well-written, complete, unambiguous, and ready for implementation - NOT whether the implementation works. | |
| 25 | + | |
| 26 | +## User Input | |
| 27 | + | |
| 28 | +```text | |
| 29 | +$ARGUMENTS | |
| 30 | +``` | |
| 31 | + | |
| 32 | +You **MUST** consider the user input before proceeding (if not empty). | |
| 33 | + | |
| 34 | +## Execution Steps | |
| 35 | + | |
| 36 | +1. **Setup**: Run `.specify/scripts/bash/check-prerequisites.sh --json` from repo root and parse JSON for FEATURE_DIR and AVAILABLE_DOCS list. | |
| 37 | + - All file paths must be absolute. | |
| 38 | + - For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). | |
| 39 | + | |
| 40 | +2. **Clarify intent (dynamic)**: Derive up to THREE initial contextual clarifying questions (no pre-baked catalog). They MUST: | |
| 41 | + - Be generated from the user's phrasing + extracted signals from spec/plan/tasks | |
| 42 | + - Only ask about information that materially changes checklist content | |
| 43 | + - Be skipped individually if already unambiguous in `$ARGUMENTS` | |
| 44 | + - Prefer precision over breadth | |
| 45 | + | |
| 46 | + Generation algorithm: | |
| 47 | + 1. Extract signals: feature domain keywords (e.g., auth, latency, UX, API), risk indicators ("critical", "must", "compliance"), stakeholder hints ("QA", "review", "security team"), and explicit deliverables ("a11y", "rollback", "contracts"). | |
| 48 | + 2. Cluster signals into candidate focus areas (max 4) ranked by relevance. | |
| 49 | + 3. Identify probable audience & timing (author, reviewer, QA, release) if not explicit. | |
| 50 | + 4. Detect missing dimensions: scope breadth, depth/rigor, risk emphasis, exclusion boundaries, measurable acceptance criteria. | |
| 51 | + 5. Formulate questions chosen from these archetypes: | |
| 52 | + - Scope refinement (e.g., "Should this include integration touchpoints with X and Y or stay limited to local module correctness?") | |
| 53 | + - Risk prioritization (e.g., "Which of these potential risk areas should receive mandatory gating checks?") | |
| 54 | + - Depth calibration (e.g., "Is this a lightweight pre-commit sanity list or a formal release gate?") | |
| 55 | + - Audience framing (e.g., "Will this be used by the author only or peers during PR review?") | |
| 56 | + - Boundary exclusion (e.g., "Should we explicitly exclude performance tuning items this round?") | |
| 57 | + - Scenario class gap (e.g., "No recovery flows detected—are rollback / partial failure paths in scope?") | |
| 58 | + | |
| 59 | + Question formatting rules: | |
| 60 | + - If presenting options, generate a compact table with columns: Option | Candidate | Why It Matters | |
| 61 | + - Limit to A–E options maximum; omit table if a free-form answer is clearer | |
| 62 | + - Never ask the user to restate what they already said | |
| 63 | + - Avoid speculative categories (no hallucination). If uncertain, ask explicitly: "Confirm whether X belongs in scope." | |
| 64 | + | |
| 65 | + Defaults when interaction impossible: | |
| 66 | + - Depth: Standard | |
| 67 | + - Audience: Reviewer (PR) if code-related; Author otherwise | |
| 68 | + - Focus: Top 2 relevance clusters | |
| 69 | + | |
| 70 | + Output the questions (label Q1/Q2/Q3). After answers: if ≥2 scenario classes (Alternate / Exception / Recovery / Non-Functional domain) remain unclear, you MAY ask up to TWO more targeted follow‑ups (Q4/Q5) with a one-line justification each (e.g., "Unresolved recovery path risk"). Do not exceed five total questions. Skip escalation if user explicitly declines more. | |
| 71 | + | |
| 72 | +3. **Understand user request**: Combine `$ARGUMENTS` + clarifying answers: | |
| 73 | + - Derive checklist theme (e.g., security, review, deploy, ux) | |
| 74 | + - Consolidate explicit must-have items mentioned by user | |
| 75 | + - Map focus selections to category scaffolding | |
| 76 | + - Infer any missing context from spec/plan/tasks (do NOT hallucinate) | |
| 77 | + | |
| 78 | +4. **Load feature context**: Read from FEATURE_DIR: | |
| 79 | + - spec.md: Feature requirements and scope | |
| 80 | + - plan.md (if exists): Technical details, dependencies | |
| 81 | + - tasks.md (if exists): Implementation tasks | |
| 82 | + | |
| 83 | + **Context Loading Strategy**: | |
| 84 | + - Load only necessary portions relevant to active focus areas (avoid full-file dumping) | |
| 85 | + - Prefer summarizing long sections into concise scenario/requirement bullets | |
| 86 | + - Use progressive disclosure: add follow-on retrieval only if gaps detected | |
| 87 | + - If source docs are large, generate interim summary items instead of embedding raw text | |
| 88 | + | |
| 89 | +5. **Generate checklist** - Create "Unit Tests for Requirements": | |
| 90 | + - Create `FEATURE_DIR/checklists/` directory if it doesn't exist | |
| 91 | + - Generate unique checklist filename: | |
| 92 | + - Use short, descriptive name based on domain (e.g., `ux.md`, `api.md`, `security.md`) | |
| 93 | + - Format: `[domain].md` | |
| 94 | + - File handling behavior: | |
| 95 | + - If file does NOT exist: Create new file and number items starting from CHK001 | |
| 96 | + - If file exists: Append new items to existing file, continuing from the last CHK ID (e.g., if last item is CHK015, start new items at CHK016) | |
| 97 | + - Never delete or replace existing checklist content - always preserve and append | |
| 98 | + | |
| 99 | + **CORE PRINCIPLE - Test the Requirements, Not the Implementation**: | |
| 100 | + Every checklist item MUST evaluate the REQUIREMENTS THEMSELVES for: | |
| 101 | + - **Completeness**: Are all necessary requirements present? | |
| 102 | + - **Clarity**: Are requirements unambiguous and specific? | |
| 103 | + - **Consistency**: Do requirements align with each other? | |
| 104 | + - **Measurability**: Can requirements be objectively verified? | |
| 105 | + - **Coverage**: Are all scenarios/edge cases addressed? | |
| 106 | + | |
| 107 | + **Category Structure** - Group items by requirement quality dimensions: | |
| 108 | + - **Requirement Completeness** (Are all necessary requirements documented?) | |
| 109 | + - **Requirement Clarity** (Are requirements specific and unambiguous?) | |
| 110 | + - **Requirement Consistency** (Do requirements align without conflicts?) | |
| 111 | + - **Acceptance Criteria Quality** (Are success criteria measurable?) | |
| 112 | + - **Scenario Coverage** (Are all flows/cases addressed?) | |
| 113 | + - **Edge Case Coverage** (Are boundary conditions defined?) | |
| 114 | + - **Non-Functional Requirements** (Performance, Security, Accessibility, etc. - are they specified?) | |
| 115 | + - **Dependencies & Assumptions** (Are they documented and validated?) | |
| 116 | + - **Ambiguities & Conflicts** (What needs clarification?) | |
| 117 | + | |
| 118 | + **HOW TO WRITE CHECKLIST ITEMS - "Unit Tests for English"**: | |
| 119 | + | |
| 120 | + ❌ **WRONG** (Testing implementation): | |
| 121 | + - "Verify landing page displays 3 episode cards" | |
| 122 | + - "Test hover states work on desktop" | |
| 123 | + - "Confirm logo click navigates home" | |
| 124 | + | |
| 125 | + ✅ **CORRECT** (Testing requirements quality): | |
| 126 | + - "Are the exact number and layout of featured episodes specified?" [Completeness] | |
| 127 | + - "Is 'prominent display' quantified with specific sizing/positioning?" [Clarity] | |
| 128 | + - "Are hover state requirements consistent across all interactive elements?" [Consistency] | |
| 129 | + - "Are keyboard navigation requirements defined for all interactive UI?" [Coverage] | |
| 130 | + - "Is the fallback behavior specified when logo image fails to load?" [Edge Cases] | |
| 131 | + - "Are loading states defined for asynchronous episode data?" [Completeness] | |
| 132 | + - "Does the spec define visual hierarchy for competing UI elements?" [Clarity] | |
| 133 | + | |
| 134 | + **ITEM STRUCTURE**: | |
| 135 | + Each item should follow this pattern: | |
| 136 | + - Question format asking about requirement quality | |
| 137 | + - Focus on what's WRITTEN (or not written) in the spec/plan | |
| 138 | + - Include quality dimension in brackets [Completeness/Clarity/Consistency/etc.] | |
| 139 | + - Reference spec section `[Spec §X.Y]` when checking existing requirements | |
| 140 | + - Use `[Gap]` marker when checking for missing requirements | |
| 141 | + | |
| 142 | + **EXAMPLES BY QUALITY DIMENSION**: | |
| 143 | + | |
| 144 | + Completeness: | |
| 145 | + - "Are error handling requirements defined for all API failure modes? [Gap]" | |
| 146 | + - "Are accessibility requirements specified for all interactive elements? [Completeness]" | |
| 147 | + - "Are mobile breakpoint requirements defined for responsive layouts? [Gap]" | |
| 148 | + | |
| 149 | + Clarity: | |
| 150 | + - "Is 'fast loading' quantified with specific timing thresholds? [Clarity, Spec §NFR-2]" | |
| 151 | + - "Are 'related episodes' selection criteria explicitly defined? [Clarity, Spec §FR-5]" | |
| 152 | + - "Is 'prominent' defined with measurable visual properties? [Ambiguity, Spec §FR-4]" | |
| 153 | + | |
| 154 | + Consistency: | |
| 155 | + - "Do navigation requirements align across all pages? [Consistency, Spec §FR-10]" | |
| 156 | + - "Are card component requirements consistent between landing and detail pages? [Consistency]" | |
| 157 | + | |
| 158 | + Coverage: | |
| 159 | + - "Are requirements defined for zero-state scenarios (no episodes)? [Coverage, Edge Case]" | |
| 160 | + - "Are concurrent user interaction scenarios addressed? [Coverage, Gap]" | |
| 161 | + - "Are requirements specified for partial data loading failures? [Coverage, Exception Flow]" | |
| 162 | + | |
| 163 | + Measurability: | |
| 164 | + - "Are visual hierarchy requirements measurable/testable? [Acceptance Criteria, Spec §FR-1]" | |
| 165 | + - "Can 'balanced visual weight' be objectively verified? [Measurability, Spec §FR-2]" | |
| 166 | + | |
| 167 | + **Scenario Classification & Coverage** (Requirements Quality Focus): | |
| 168 | + - Check if requirements exist for: Primary, Alternate, Exception/Error, Recovery, Non-Functional scenarios | |
| 169 | + - For each scenario class, ask: "Are [scenario type] requirements complete, clear, and consistent?" | |
| 170 | + - If scenario class missing: "Are [scenario type] requirements intentionally excluded or missing? [Gap]" | |
| 171 | + - Include resilience/rollback when state mutation occurs: "Are rollback requirements defined for migration failures? [Gap]" | |
| 172 | + | |
| 173 | + **Traceability Requirements**: | |
| 174 | + - MINIMUM: ≥80% of items MUST include at least one traceability reference | |
| 175 | + - Each item should reference: spec section `[Spec §X.Y]`, or use markers: `[Gap]`, `[Ambiguity]`, `[Conflict]`, `[Assumption]` | |
| 176 | + - If no ID system exists: "Is a requirement & acceptance criteria ID scheme established? [Traceability]" | |
| 177 | + | |
| 178 | + **Surface & Resolve Issues** (Requirements Quality Problems): | |
| 179 | + Ask questions about the requirements themselves: | |
| 180 | + - Ambiguities: "Is the term 'fast' quantified with specific metrics? [Ambiguity, Spec §NFR-1]" | |
| 181 | + - Conflicts: "Do navigation requirements conflict between §FR-10 and §FR-10a? [Conflict]" | |
| 182 | + - Assumptions: "Is the assumption of 'always available podcast API' validated? [Assumption]" | |
| 183 | + - Dependencies: "Are external podcast API requirements documented? [Dependency, Gap]" | |
| 184 | + - Missing definitions: "Is 'visual hierarchy' defined with measurable criteria? [Gap]" | |
| 185 | + | |
| 186 | + **Content Consolidation**: | |
| 187 | + - Soft cap: If raw candidate items > 40, prioritize by risk/impact | |
| 188 | + - Merge near-duplicates checking the same requirement aspect | |
| 189 | + - If >5 low-impact edge cases, create one item: "Are edge cases X, Y, Z addressed in requirements? [Coverage]" | |
| 190 | + | |
| 191 | + **🚫 ABSOLUTELY PROHIBITED** - These make it an implementation test, not a requirements test: | |
| 192 | + - ❌ Any item starting with "Verify", "Test", "Confirm", "Check" + implementation behavior | |
| 193 | + - ❌ References to code execution, user actions, system behavior | |
| 194 | + - ❌ "Displays correctly", "works properly", "functions as expected" | |
| 195 | + - ❌ "Click", "navigate", "render", "load", "execute" | |
| 196 | + - ❌ Test cases, test plans, QA procedures | |
| 197 | + - ❌ Implementation details (frameworks, APIs, algorithms) | |
| 198 | + | |
| 199 | + **✅ REQUIRED PATTERNS** - These test requirements quality: | |
| 200 | + - ✅ "Are [requirement type] defined/specified/documented for [scenario]?" | |
| 201 | + - ✅ "Is [vague term] quantified/clarified with specific criteria?" | |
| 202 | + - ✅ "Are requirements consistent between [section A] and [section B]?" | |
| 203 | + - ✅ "Can [requirement] be objectively measured/verified?" | |
| 204 | + - ✅ "Are [edge cases/scenarios] addressed in requirements?" | |
| 205 | + - ✅ "Does the spec define [missing aspect]?" | |
| 206 | + | |
| 207 | +6. **Structure Reference**: Generate the checklist following the canonical template in `.specify/templates/checklist-template.md` for title, meta section, category headings, and ID formatting. If template is unavailable, use: H1 title, purpose/created meta lines, `##` category sections containing `- [ ] CHK### <requirement item>` lines with globally incrementing IDs starting at CHK001. | |
| 208 | + | |
| 209 | +7. **Report**: Output full path to checklist file, item count, and summarize whether the run created a new file or appended to an existing one. Summarize: | |
| 210 | + - Focus areas selected | |
| 211 | + - Depth level | |
| 212 | + - Actor/timing | |
| 213 | + - Any explicit user-specified must-have items incorporated | |
| 214 | + | |
| 215 | +**Important**: Each `/speckit.checklist` command invocation uses a short, descriptive checklist filename and either creates a new file or appends to an existing one. This allows: | |
| 216 | + | |
| 217 | +- Multiple checklists of different types (e.g., `ux.md`, `test.md`, `security.md`) | |
| 218 | +- Simple, memorable filenames that indicate checklist purpose | |
| 219 | +- Easy identification and navigation in the `checklists/` folder | |
| 220 | + | |
| 221 | +To avoid clutter, use descriptive types and clean up obsolete checklists when done. | |
| 222 | + | |
| 223 | +## Example Checklist Types & Sample Items | |
| 224 | + | |
| 225 | +**UX Requirements Quality:** `ux.md` | |
| 226 | + | |
| 227 | +Sample items (testing the requirements, NOT the implementation): | |
| 228 | + | |
| 229 | +- "Are visual hierarchy requirements defined with measurable criteria? [Clarity, Spec §FR-1]" | |
| 230 | +- "Is the number and positioning of UI elements explicitly specified? [Completeness, Spec §FR-1]" | |
| 231 | +- "Are interaction state requirements (hover, focus, active) consistently defined? [Consistency]" | |
| 232 | +- "Are accessibility requirements specified for all interactive elements? [Coverage, Gap]" | |
| 233 | +- "Is fallback behavior defined when images fail to load? [Edge Case, Gap]" | |
| 234 | +- "Can 'prominent display' be objectively measured? [Measurability, Spec §FR-4]" | |
| 235 | + | |
| 236 | +**API Requirements Quality:** `api.md` | |
| 237 | + | |
| 238 | +Sample items: | |
| 239 | + | |
| 240 | +- "Are error response formats specified for all failure scenarios? [Completeness]" | |
| 241 | +- "Are rate limiting requirements quantified with specific thresholds? [Clarity]" | |
| 242 | +- "Are authentication requirements consistent across all endpoints? [Consistency]" | |
| 243 | +- "Are retry/timeout requirements defined for external dependencies? [Coverage, Gap]" | |
| 244 | +- "Is versioning strategy documented in requirements? [Gap]" | |
| 245 | + | |
| 246 | +**Performance Requirements Quality:** `performance.md` | |
| 247 | + | |
| 248 | +Sample items: | |
| 249 | + | |
| 250 | +- "Are performance requirements quantified with specific metrics? [Clarity]" | |
| 251 | +- "Are performance targets defined for all critical user journeys? [Coverage]" | |
| 252 | +- "Are performance requirements under different load conditions specified? [Completeness]" | |
| 253 | +- "Can performance requirements be objectively measured? [Measurability]" | |
| 254 | +- "Are degradation requirements defined for high-load scenarios? [Edge Case, Gap]" | |
| 255 | + | |
| 256 | +**Security Requirements Quality:** `security.md` | |
| 257 | + | |
| 258 | +Sample items: | |
| 259 | + | |
| 260 | +- "Are authentication requirements specified for all protected resources? [Coverage]" | |
| 261 | +- "Are data protection requirements defined for sensitive information? [Completeness]" | |
| 262 | +- "Is the threat model documented and requirements aligned to it? [Traceability]" | |
| 263 | +- "Are security requirements consistent with compliance obligations? [Consistency]" | |
| 264 | +- "Are security failure/breach response requirements defined? [Gap, Exception Flow]" | |
| 265 | + | |
| 266 | +## Anti-Examples: What NOT To Do | |
| 267 | + | |
| 268 | +**❌ WRONG - These test implementation, not requirements:** | |
| 269 | + | |
| 270 | +```markdown | |
| 271 | +- [ ] CHK001 - Verify landing page displays 3 episode cards [Spec §FR-001] | |
| 272 | +- [ ] CHK002 - Test hover states work correctly on desktop [Spec §FR-003] | |
| 273 | +- [ ] CHK003 - Confirm logo click navigates to home page [Spec §FR-010] | |
| 274 | +- [ ] CHK004 - Check that related episodes section shows 3-5 items [Spec §FR-005] | |
| 275 | +``` | |
| 276 | + | |
| 277 | +**✅ CORRECT - These test requirements quality:** | |
| 278 | + | |
| 279 | +```markdown | |
| 280 | +- [ ] CHK001 - Are the number and layout of featured episodes explicitly specified? [Completeness, Spec §FR-001] | |
| 281 | +- [ ] CHK002 - Are hover state requirements consistently defined for all interactive elements? [Consistency, Spec §FR-003] | |
| 282 | +- [ ] CHK003 - Are navigation requirements clear for all clickable brand elements? [Clarity, Spec §FR-010] | |
| 283 | +- [ ] CHK004 - Is the selection criteria for related episodes documented? [Gap, Spec §FR-005] | |
| 284 | +- [ ] CHK005 - Are loading state requirements defined for asynchronous episode data? [Gap] | |
| 285 | +- [ ] CHK006 - Can "visual hierarchy" requirements be objectively measured? [Measurability, Spec §FR-001] | |
| 286 | +``` | |
| 287 | + | |
| 288 | +**Key Differences:** | |
| 289 | + | |
| 290 | +- Wrong: Tests if the system works correctly | |
| 291 | +- Correct: Tests if the requirements are written correctly | |
| 292 | +- Wrong: Verification of behavior | |
| 293 | +- Correct: Validation of requirement quality | |
| 294 | +- Wrong: "Does it do X?" | |
| 295 | +- Correct: "Is X clearly specified?" |
A
.cursor/commands/speckit.clarify.md
+181
-0
@@ -0,0 +1,181 @@
| 1 | +--- | |
| 2 | +description: Identify underspecified areas in the current feature spec by asking up to 5 highly targeted clarification questions and encoding answers back into the spec. | |
| 3 | +handoffs: | |
| 4 | + - label: Build Technical Plan | |
| 5 | + agent: speckit.plan | |
| 6 | + prompt: Create a plan for the spec. I am building with... | |
| 7 | +--- | |
| 8 | + | |
| 9 | +## User Input | |
| 10 | + | |
| 11 | +```text | |
| 12 | +$ARGUMENTS | |
| 13 | +``` | |
| 14 | + | |
| 15 | +You **MUST** consider the user input before proceeding (if not empty). | |
| 16 | + | |
| 17 | +## Outline | |
| 18 | + | |
| 19 | +Goal: Detect and reduce ambiguity or missing decision points in the active feature specification and record the clarifications directly in the spec file. | |
| 20 | + | |
| 21 | +Note: This clarification workflow is expected to run (and be completed) BEFORE invoking `/speckit.plan`. If the user explicitly states they are skipping clarification (e.g., exploratory spike), you may proceed, but must warn that downstream rework risk increases. | |
| 22 | + | |
| 23 | +Execution steps: | |
| 24 | + | |
| 25 | +1. Run `.specify/scripts/bash/check-prerequisites.sh --json --paths-only` from repo root **once** (combined `--json --paths-only` mode / `-Json -PathsOnly`). Parse minimal JSON payload fields: | |
| 26 | + - `FEATURE_DIR` | |
| 27 | + - `FEATURE_SPEC` | |
| 28 | + - (Optionally capture `IMPL_PLAN`, `TASKS` for future chained flows.) | |
| 29 | + - If JSON parsing fails, abort and instruct user to re-run `/speckit.specify` or verify feature branch environment. | |
| 30 | + - For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). | |
| 31 | + | |
| 32 | +2. Load the current spec file. Perform a structured ambiguity & coverage scan using this taxonomy. For each category, mark status: Clear / Partial / Missing. Produce an internal coverage map used for prioritization (do not output raw map unless no questions will be asked). | |
| 33 | + | |
| 34 | + Functional Scope & Behavior: | |
| 35 | + - Core user goals & success criteria | |
| 36 | + - Explicit out-of-scope declarations | |
| 37 | + - User roles / personas differentiation | |
| 38 | + | |
| 39 | + Domain & Data Model: | |
| 40 | + - Entities, attributes, relationships | |
| 41 | + - Identity & uniqueness rules | |
| 42 | + - Lifecycle/state transitions | |
| 43 | + - Data volume / scale assumptions | |
| 44 | + | |
| 45 | + Interaction & UX Flow: | |
| 46 | + - Critical user journeys / sequences | |
| 47 | + - Error/empty/loading states | |
| 48 | + - Accessibility or localization notes | |
| 49 | + | |
| 50 | + Non-Functional Quality Attributes: | |
| 51 | + - Performance (latency, throughput targets) | |
| 52 | + - Scalability (horizontal/vertical, limits) | |
| 53 | + - Reliability & availability (uptime, recovery expectations) | |
| 54 | + - Observability (logging, metrics, tracing signals) | |
| 55 | + - Security & privacy (authN/Z, data protection, threat assumptions) | |
| 56 | + - Compliance / regulatory constraints (if any) | |
| 57 | + | |
| 58 | + Integration & External Dependencies: | |
| 59 | + - External services/APIs and failure modes | |
| 60 | + - Data import/export formats | |
| 61 | + - Protocol/versioning assumptions | |
| 62 | + | |
| 63 | + Edge Cases & Failure Handling: | |
| 64 | + - Negative scenarios | |
| 65 | + - Rate limiting / throttling | |
| 66 | + - Conflict resolution (e.g., concurrent edits) | |
| 67 | + | |
| 68 | + Constraints & Tradeoffs: | |
| 69 | + - Technical constraints (language, storage, hosting) | |
| 70 | + - Explicit tradeoffs or rejected alternatives | |
| 71 | + | |
| 72 | + Terminology & Consistency: | |
| 73 | + - Canonical glossary terms | |
| 74 | + - Avoided synonyms / deprecated terms | |
| 75 | + | |
| 76 | + Completion Signals: | |
| 77 | + - Acceptance criteria testability | |
| 78 | + - Measurable Definition of Done style indicators | |
| 79 | + | |
| 80 | + Misc / Placeholders: | |
| 81 | + - TODO markers / unresolved decisions | |
| 82 | + - Ambiguous adjectives ("robust", "intuitive") lacking quantification | |
| 83 | + | |
| 84 | + For each category with Partial or Missing status, add a candidate question opportunity unless: | |
| 85 | + - Clarification would not materially change implementation or validation strategy | |
| 86 | + - Information is better deferred to planning phase (note internally) | |
| 87 | + | |
| 88 | +3. Generate (internally) a prioritized queue of candidate clarification questions (maximum 5). Do NOT output them all at once. Apply these constraints: | |
| 89 | + - Maximum of 5 total questions across the whole session. | |
| 90 | + - Each question must be answerable with EITHER: | |
| 91 | + - A short multiple‑choice selection (2–5 distinct, mutually exclusive options), OR | |
| 92 | + - A one-word / short‑phrase answer (explicitly constrain: "Answer in <=5 words"). | |
| 93 | + - Only include questions whose answers materially impact architecture, data modeling, task decomposition, test design, UX behavior, operational readiness, or compliance validation. | |
| 94 | + - Ensure category coverage balance: attempt to cover the highest impact unresolved categories first; avoid asking two low-impact questions when a single high-impact area (e.g., security posture) is unresolved. | |
| 95 | + - Exclude questions already answered, trivial stylistic preferences, or plan-level execution details (unless blocking correctness). | |
| 96 | + - Favor clarifications that reduce downstream rework risk or prevent misaligned acceptance tests. | |
| 97 | + - If more than 5 categories remain unresolved, select the top 5 by (Impact * Uncertainty) heuristic. | |
| 98 | + | |
| 99 | +4. Sequential questioning loop (interactive): | |
| 100 | + - Present EXACTLY ONE question at a time. | |
| 101 | + - For multiple‑choice questions: | |
| 102 | + - **Analyze all options** and determine the **most suitable option** based on: | |
| 103 | + - Best practices for the project type | |
| 104 | + - Common patterns in similar implementations | |
| 105 | + - Risk reduction (security, performance, maintainability) | |
| 106 | + - Alignment with any explicit project goals or constraints visible in the spec | |
| 107 | + - Present your **recommended option prominently** at the top with clear reasoning (1-2 sentences explaining why this is the best choice). | |
| 108 | + - Format as: `**Recommended:** Option [X] - <reasoning>` | |
| 109 | + - Then render all options as a Markdown table: | |
| 110 | + | |
| 111 | + | Option | Description | | |
| 112 | + |--------|-------------| | |
| 113 | + | A | <Option A description> | | |
| 114 | + | B | <Option B description> | | |
| 115 | + | C | <Option C description> (add D/E as needed up to 5) | | |
| 116 | + | Short | Provide a different short answer (<=5 words) (Include only if free-form alternative is appropriate) | | |
| 117 | + | |
| 118 | + - After the table, add: `You can reply with the option letter (e.g., "A"), accept the recommendation by saying "yes" or "recommended", or provide your own short answer.` | |
| 119 | + - For short‑answer style (no meaningful discrete options): | |
| 120 | + - Provide your **suggested answer** based on best practices and context. | |
| 121 | + - Format as: `**Suggested:** <your proposed answer> - <brief reasoning>` | |
| 122 | + - Then output: `Format: Short answer (<=5 words). You can accept the suggestion by saying "yes" or "suggested", or provide your own answer.` | |
| 123 | + - After the user answers: | |
| 124 | + - If the user replies with "yes", "recommended", or "suggested", use your previously stated recommendation/suggestion as the answer. | |
| 125 | + - Otherwise, validate the answer maps to one option or fits the <=5 word constraint. | |
| 126 | + - If ambiguous, ask for a quick disambiguation (count still belongs to same question; do not advance). | |
| 127 | + - Once satisfactory, record it in working memory (do not yet write to disk) and move to the next queued question. | |
| 128 | + - Stop asking further questions when: | |
| 129 | + - All critical ambiguities resolved early (remaining queued items become unnecessary), OR | |
| 130 | + - User signals completion ("done", "good", "no more"), OR | |
| 131 | + - You reach 5 asked questions. | |
| 132 | + - Never reveal future queued questions in advance. | |
| 133 | + - If no valid questions exist at start, immediately report no critical ambiguities. | |
| 134 | + | |
| 135 | +5. Integration after EACH accepted answer (incremental update approach): | |
| 136 | + - Maintain in-memory representation of the spec (loaded once at start) plus the raw file contents. | |
| 137 | + - For the first integrated answer in this session: | |
| 138 | + - Ensure a `## Clarifications` section exists (create it just after the highest-level contextual/overview section per the spec template if missing). | |
| 139 | + - Under it, create (if not present) a `### Session YYYY-MM-DD` subheading for today. | |
| 140 | + - Append a bullet line immediately after acceptance: `- Q: <question> → A: <final answer>`. | |
| 141 | + - Then immediately apply the clarification to the most appropriate section(s): | |
| 142 | + - Functional ambiguity → Update or add a bullet in Functional Requirements. | |
| 143 | + - User interaction / actor distinction → Update User Stories or Actors subsection (if present) with clarified role, constraint, or scenario. | |
| 144 | + - Data shape / entities → Update Data Model (add fields, types, relationships) preserving ordering; note added constraints succinctly. | |
| 145 | + - Non-functional constraint → Add/modify measurable criteria in Non-Functional / Quality Attributes section (convert vague adjective to metric or explicit target). | |
| 146 | + - Edge case / negative flow → Add a new bullet under Edge Cases / Error Handling (or create such subsection if template provides placeholder for it). | |
| 147 | + - Terminology conflict → Normalize term across spec; retain original only if necessary by adding `(formerly referred to as "X")` once. | |
| 148 | + - If the clarification invalidates an earlier ambiguous statement, replace that statement instead of duplicating; leave no obsolete contradictory text. | |
| 149 | + - Save the spec file AFTER each integration to minimize risk of context loss (atomic overwrite). | |
| 150 | + - Preserve formatting: do not reorder unrelated sections; keep heading hierarchy intact. | |
| 151 | + - Keep each inserted clarification minimal and testable (avoid narrative drift). | |
| 152 | + | |
| 153 | +6. Validation (performed after EACH write plus final pass): | |
| 154 | + - Clarifications session contains exactly one bullet per accepted answer (no duplicates). | |
| 155 | + - Total asked (accepted) questions ≤ 5. | |
| 156 | + - Updated sections contain no lingering vague placeholders the new answer was meant to resolve. | |
| 157 | + - No contradictory earlier statement remains (scan for now-invalid alternative choices removed). | |
| 158 | + - Markdown structure valid; only allowed new headings: `## Clarifications`, `### Session YYYY-MM-DD`. | |
| 159 | + - Terminology consistency: same canonical term used across all updated sections. | |
| 160 | + | |
| 161 | +7. Write the updated spec back to `FEATURE_SPEC`. | |
| 162 | + | |
| 163 | +8. Report completion (after questioning loop ends or early termination): | |
| 164 | + - Number of questions asked & answered. | |
| 165 | + - Path to updated spec. | |
| 166 | + - Sections touched (list names). | |
| 167 | + - Coverage summary table listing each taxonomy category with Status: Resolved (was Partial/Missing and addressed), Deferred (exceeds question quota or better suited for planning), Clear (already sufficient), Outstanding (still Partial/Missing but low impact). | |
| 168 | + - If any Outstanding or Deferred remain, recommend whether to proceed to `/speckit.plan` or run `/speckit.clarify` again later post-plan. | |
| 169 | + - Suggested next command. | |
| 170 | + | |
| 171 | +Behavior rules: | |
| 172 | + | |
| 173 | +- If no meaningful ambiguities found (or all potential questions would be low-impact), respond: "No critical ambiguities detected worth formal clarification." and suggest proceeding. | |
| 174 | +- If spec file missing, instruct user to run `/speckit.specify` first (do not create a new spec here). | |
| 175 | +- Never exceed 5 total asked questions (clarification retries for a single question do not count as new questions). | |
| 176 | +- Avoid speculative tech stack questions unless the absence blocks functional clarity. | |
| 177 | +- Respect user early termination signals ("stop", "done", "proceed"). | |
| 178 | +- If no questions asked due to full coverage, output a compact coverage summary (all categories Clear) then suggest advancing. | |
| 179 | +- If quota reached with unresolved high-impact categories remaining, explicitly flag them under Deferred with rationale. | |
| 180 | + | |
| 181 | +Context for prioritization: $ARGUMENTS |
A
.cursor/commands/speckit.constitution.md
+84
-0
@@ -0,0 +1,84 @@
| 1 | +--- | |
| 2 | +description: Create or update the project constitution from interactive or provided principle inputs, ensuring all dependent templates stay in sync. | |
| 3 | +handoffs: | |
| 4 | + - label: Build Specification | |
| 5 | + agent: speckit.specify | |
| 6 | + prompt: Implement the feature specification based on the updated constitution. I want to build... | |
| 7 | +--- | |
| 8 | + | |
| 9 | +## User Input | |
| 10 | + | |
| 11 | +```text | |
| 12 | +$ARGUMENTS | |
| 13 | +``` | |
| 14 | + | |
| 15 | +You **MUST** consider the user input before proceeding (if not empty). | |
| 16 | + | |
| 17 | +## Outline | |
| 18 | + | |
| 19 | +You are updating the project constitution at `.specify/memory/constitution.md`. This file is a TEMPLATE containing placeholder tokens in square brackets (e.g. `[PROJECT_NAME]`, `[PRINCIPLE_1_NAME]`). Your job is to (a) collect/derive concrete values, (b) fill the template precisely, and (c) propagate any amendments across dependent artifacts. | |
| 20 | + | |
| 21 | +**Note**: If `.specify/memory/constitution.md` does not exist yet, it should have been initialized from `.specify/templates/constitution-template.md` during project setup. If it's missing, copy the template first. | |
| 22 | + | |
| 23 | +Follow this execution flow: | |
| 24 | + | |
| 25 | +1. Load the existing constitution at `.specify/memory/constitution.md`. | |
| 26 | + - Identify every placeholder token of the form `[ALL_CAPS_IDENTIFIER]`. | |
| 27 | + **IMPORTANT**: The user might require less or more principles than the ones used in the template. If a number is specified, respect that - follow the general template. You will update the doc accordingly. | |
| 28 | + | |
| 29 | +2. Collect/derive values for placeholders: | |
| 30 | + - If user input (conversation) supplies a value, use it. | |
| 31 | + - Otherwise infer from existing repo context (README, docs, prior constitution versions if embedded). | |
| 32 | + - For governance dates: `RATIFICATION_DATE` is the original adoption date (if unknown ask or mark TODO), `LAST_AMENDED_DATE` is today if changes are made, otherwise keep previous. | |
| 33 | + - `CONSTITUTION_VERSION` must increment according to semantic versioning rules: | |
| 34 | + - MAJOR: Backward incompatible governance/principle removals or redefinitions. | |
| 35 | + - MINOR: New principle/section added or materially expanded guidance. | |
| 36 | + - PATCH: Clarifications, wording, typo fixes, non-semantic refinements. | |
| 37 | + - If version bump type ambiguous, propose reasoning before finalizing. | |
| 38 | + | |
| 39 | +3. Draft the updated constitution content: | |
| 40 | + - Replace every placeholder with concrete text (no bracketed tokens left except intentionally retained template slots that the project has chosen not to define yet—explicitly justify any left). | |
| 41 | + - Preserve heading hierarchy and comments can be removed once replaced unless they still add clarifying guidance. | |
| 42 | + - Ensure each Principle section: succinct name line, paragraph (or bullet list) capturing non‑negotiable rules, explicit rationale if not obvious. | |
| 43 | + - Ensure Governance section lists amendment procedure, versioning policy, and compliance review expectations. | |
| 44 | + | |
| 45 | +4. Consistency propagation checklist (convert prior checklist into active validations): | |
| 46 | + - Read `.specify/templates/plan-template.md` and ensure any "Constitution Check" or rules align with updated principles. | |
| 47 | + - Read `.specify/templates/spec-template.md` for scope/requirements alignment—update if constitution adds/removes mandatory sections or constraints. | |
| 48 | + - Read `.specify/templates/tasks-template.md` and ensure task categorization reflects new or removed principle-driven task types (e.g., observability, versioning, testing discipline). | |
| 49 | + - Read each command file in `.specify/templates/commands/*.md` (including this one) to verify no outdated references (agent-specific names like CLAUDE only) remain when generic guidance is required. | |
| 50 | + - Read any runtime guidance docs (e.g., `README.md`, `docs/quickstart.md`, or agent-specific guidance files if present). Update references to principles changed. | |
| 51 | + | |
| 52 | +5. Produce a Sync Impact Report (prepend as an HTML comment at top of the constitution file after update): | |
| 53 | + - Version change: old → new | |
| 54 | + - List of modified principles (old title → new title if renamed) | |
| 55 | + - Added sections | |
| 56 | + - Removed sections | |
| 57 | + - Templates requiring updates (✅ updated / ⚠ pending) with file paths | |
| 58 | + - Follow-up TODOs if any placeholders intentionally deferred. | |
| 59 | + | |
| 60 | +6. Validation before final output: | |
| 61 | + - No remaining unexplained bracket tokens. | |
| 62 | + - Version line matches report. | |
| 63 | + - Dates ISO format YYYY-MM-DD. | |
| 64 | + - Principles are declarative, testable, and free of vague language ("should" → replace with MUST/SHOULD rationale where appropriate). | |
| 65 | + | |
| 66 | +7. Write the completed constitution back to `.specify/memory/constitution.md` (overwrite). | |
| 67 | + | |
| 68 | +8. Output a final summary to the user with: | |
| 69 | + - New version and bump rationale. | |
| 70 | + - Any files flagged for manual follow-up. | |
| 71 | + - Suggested commit message (e.g., `docs: amend constitution to vX.Y.Z (principle additions + governance update)`). | |
| 72 | + | |
| 73 | +Formatting & Style Requirements: | |
| 74 | + | |
| 75 | +- Use Markdown headings exactly as in the template (do not demote/promote levels). | |
| 76 | +- Wrap long rationale lines to keep readability (<100 chars ideally) but do not hard enforce with awkward breaks. | |
| 77 | +- Keep a single blank line between sections. | |
| 78 | +- Avoid trailing whitespace. | |
| 79 | + | |
| 80 | +If the user supplies partial updates (e.g., only one principle revision), still perform validation and version decision steps. | |
| 81 | + | |
| 82 | +If critical info missing (e.g., ratification date truly unknown), insert `TODO(<FIELD_NAME>): explanation` and include in the Sync Impact Report under deferred items. | |
| 83 | + | |
| 84 | +Do not create a new template; always operate on the existing `.specify/memory/constitution.md` file. |
A
.cursor/commands/speckit.implement.md
+135
-0
@@ -0,0 +1,135 @@
| 1 | +--- | |
| 2 | +description: Execute the implementation plan by processing and executing all tasks defined in tasks.md | |
| 3 | +--- | |
| 4 | + | |
| 5 | +## User Input | |
| 6 | + | |
| 7 | +```text | |
| 8 | +$ARGUMENTS | |
| 9 | +``` | |
| 10 | + | |
| 11 | +You **MUST** consider the user input before proceeding (if not empty). | |
| 12 | + | |
| 13 | +## Outline | |
| 14 | + | |
| 15 | +1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). | |
| 16 | + | |
| 17 | +2. **Check checklists status** (if FEATURE_DIR/checklists/ exists): | |
| 18 | + - Scan all checklist files in the checklists/ directory | |
| 19 | + - For each checklist, count: | |
| 20 | + - Total items: All lines matching `- [ ]` or `- [X]` or `- [x]` | |
| 21 | + - Completed items: Lines matching `- [X]` or `- [x]` | |
| 22 | + - Incomplete items: Lines matching `- [ ]` | |
| 23 | + - Create a status table: | |
| 24 | + | |
| 25 | + ```text | |
| 26 | + | Checklist | Total | Completed | Incomplete | Status | | |
| 27 | + |-----------|-------|-----------|------------|--------| | |
| 28 | + | ux.md | 12 | 12 | 0 | ✓ PASS | | |
| 29 | + | test.md | 8 | 5 | 3 | ✗ FAIL | | |
| 30 | + | security.md | 6 | 6 | 0 | ✓ PASS | | |
| 31 | + ``` | |
| 32 | + | |
| 33 | + - Calculate overall status: | |
| 34 | + - **PASS**: All checklists have 0 incomplete items | |
| 35 | + - **FAIL**: One or more checklists have incomplete items | |
| 36 | + | |
| 37 | + - **If any checklist is incomplete**: | |
| 38 | + - Display the table with incomplete item counts | |
| 39 | + - **STOP** and ask: "Some checklists are incomplete. Do you want to proceed with implementation anyway? (yes/no)" | |
| 40 | + - Wait for user response before continuing | |
| 41 | + - If user says "no" or "wait" or "stop", halt execution | |
| 42 | + - If user says "yes" or "proceed" or "continue", proceed to step 3 | |
| 43 | + | |
| 44 | + - **If all checklists are complete**: | |
| 45 | + - Display the table showing all checklists passed | |
| 46 | + - Automatically proceed to step 3 | |
| 47 | + | |
| 48 | +3. Load and analyze the implementation context: | |
| 49 | + - **REQUIRED**: Read tasks.md for the complete task list and execution plan | |
| 50 | + - **REQUIRED**: Read plan.md for tech stack, architecture, and file structure | |
| 51 | + - **IF EXISTS**: Read data-model.md for entities and relationships | |
| 52 | + - **IF EXISTS**: Read contracts/ for API specifications and test requirements | |
| 53 | + - **IF EXISTS**: Read research.md for technical decisions and constraints | |
| 54 | + - **IF EXISTS**: Read quickstart.md for integration scenarios | |
| 55 | + | |
| 56 | +4. **Project Setup Verification**: | |
| 57 | + - **REQUIRED**: Create/verify ignore files based on actual project setup: | |
| 58 | + | |
| 59 | + **Detection & Creation Logic**: | |
| 60 | + - Check if the following command succeeds to determine if the repository is a git repo (create/verify .gitignore if so): | |
| 61 | + | |
| 62 | + ```sh | |
| 63 | + git rev-parse --git-dir 2>/dev/null | |
| 64 | + ``` | |
| 65 | + | |
| 66 | + - Check if Dockerfile* exists or Docker in plan.md → create/verify .dockerignore | |
| 67 | + - Check if .eslintrc* exists → create/verify .eslintignore | |
| 68 | + - Check if eslint.config.* exists → ensure the config's `ignores` entries cover required patterns | |
| 69 | + - Check if .prettierrc* exists → create/verify .prettierignore | |
| 70 | + - Check if .npmrc or package.json exists → create/verify .npmignore (if publishing) | |
| 71 | + - Check if terraform files (*.tf) exist → create/verify .terraformignore | |
| 72 | + - Check if .helmignore needed (helm charts present) → create/verify .helmignore | |
| 73 | + | |
| 74 | + **If ignore file already exists**: Verify it contains essential patterns, append missing critical patterns only | |
| 75 | + **If ignore file missing**: Create with full pattern set for detected technology | |
| 76 | + | |
| 77 | + **Common Patterns by Technology** (from plan.md tech stack): | |
| 78 | + - **Node.js/JavaScript/TypeScript**: `node_modules/`, `dist/`, `build/`, `*.log`, `.env*` | |
| 79 | + - **Python**: `__pycache__/`, `*.pyc`, `.venv/`, `venv/`, `dist/`, `*.egg-info/` | |
| 80 | + - **Java**: `target/`, `*.class`, `*.jar`, `.gradle/`, `build/` | |
| 81 | + - **C#/.NET**: `bin/`, `obj/`, `*.user`, `*.suo`, `packages/` | |
| 82 | + - **Go**: `*.exe`, `*.test`, `vendor/`, `*.out` | |
| 83 | + - **Ruby**: `.bundle/`, `log/`, `tmp/`, `*.gem`, `vendor/bundle/` | |
| 84 | + - **PHP**: `vendor/`, `*.log`, `*.cache`, `*.env` | |
| 85 | + - **Rust**: `target/`, `debug/`, `release/`, `*.rs.bk`, `*.rlib`, `*.prof*`, `.idea/`, `*.log`, `.env*` | |
| 86 | + - **Kotlin**: `build/`, `out/`, `.gradle/`, `.idea/`, `*.class`, `*.jar`, `*.iml`, `*.log`, `.env*` | |
| 87 | + - **C++**: `build/`, `bin/`, `obj/`, `out/`, `*.o`, `*.so`, `*.a`, `*.exe`, `*.dll`, `.idea/`, `*.log`, `.env*` | |
| 88 | + - **C**: `build/`, `bin/`, `obj/`, `out/`, `*.o`, `*.a`, `*.so`, `*.exe`, `autom4te.cache/`, `config.status`, `config.log`, `.idea/`, `*.log`, `.env*` | |
| 89 | + - **Swift**: `.build/`, `DerivedData/`, `*.swiftpm/`, `Packages/` | |
| 90 | + - **R**: `.Rproj.user/`, `.Rhistory`, `.RData`, `.Ruserdata`, `*.Rproj`, `packrat/`, `renv/` | |
| 91 | + - **Universal**: `.DS_Store`, `Thumbs.db`, `*.tmp`, `*.swp`, `.vscode/`, `.idea/` | |
| 92 | + | |
| 93 | + **Tool-Specific Patterns**: | |
| 94 | + - **Docker**: `node_modules/`, `.git/`, `Dockerfile*`, `.dockerignore`, `*.log*`, `.env*`, `coverage/` | |
| 95 | + - **ESLint**: `node_modules/`, `dist/`, `build/`, `coverage/`, `*.min.js` | |
| 96 | + - **Prettier**: `node_modules/`, `dist/`, `build/`, `coverage/`, `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml` | |
| 97 | + - **Terraform**: `.terraform/`, `*.tfstate*`, `*.tfvars`, `.terraform.lock.hcl` | |
| 98 | + - **Kubernetes/k8s**: `*.secret.yaml`, `secrets/`, `.kube/`, `kubeconfig*`, `*.key`, `*.crt` | |
| 99 | + | |
| 100 | +5. Parse tasks.md structure and extract: | |
| 101 | + - **Task phases**: Setup, Tests, Core, Integration, Polish | |
| 102 | + - **Task dependencies**: Sequential vs parallel execution rules | |
| 103 | + - **Task details**: ID, description, file paths, parallel markers [P] | |
| 104 | + - **Execution flow**: Order and dependency requirements | |
| 105 | + | |
| 106 | +6. Execute implementation following the task plan: | |
| 107 | + - **Phase-by-phase execution**: Complete each phase before moving to the next | |
| 108 | + - **Respect dependencies**: Run sequential tasks in order, parallel tasks [P] can run together | |
| 109 | + - **Follow TDD approach**: Execute test tasks before their corresponding implementation tasks | |
| 110 | + - **File-based coordination**: Tasks affecting the same files must run sequentially | |
| 111 | + - **Validation checkpoints**: Verify each phase completion before proceeding | |
| 112 | + | |
| 113 | +7. Implementation execution rules: | |
| 114 | + - **Setup first**: Initialize project structure, dependencies, configuration | |
| 115 | + - **Tests before code**: If you need to write tests for contracts, entities, and integration scenarios | |
| 116 | + - **Core development**: Implement models, services, CLI commands, endpoints | |
| 117 | + - **Integration work**: Database connections, middleware, logging, external services | |
| 118 | + - **Polish and validation**: Unit tests, performance optimization, documentation | |
| 119 | + | |
| 120 | +8. Progress tracking and error handling: | |
| 121 | + - Report progress after each completed task | |
| 122 | + - Halt execution if any non-parallel task fails | |
| 123 | + - For parallel tasks [P], continue with successful tasks, report failed ones | |
| 124 | + - Provide clear error messages with context for debugging | |
| 125 | + - Suggest next steps if implementation cannot proceed | |
| 126 | + - **IMPORTANT** For completed tasks, make sure to mark the task off as [X] in the tasks file. | |
| 127 | + | |
| 128 | +9. Completion validation: | |
| 129 | + - Verify all required tasks are completed | |
| 130 | + - Check that implemented features match the original specification | |
| 131 | + - Validate that tests pass and coverage meets requirements | |
| 132 | + - Confirm the implementation follows the technical plan | |
| 133 | + - Report final status with summary of completed work | |
| 134 | + | |
| 135 | +Note: This command assumes a complete task breakdown exists in tasks.md. If tasks are incomplete or missing, suggest running `/speckit.tasks` first to regenerate the task list. |
A
.cursor/commands/speckit.plan.md
+90
-0
@@ -0,0 +1,90 @@
| 1 | +--- | |
| 2 | +description: Execute the implementation planning workflow using the plan template to generate design artifacts. | |
| 3 | +handoffs: | |
| 4 | + - label: Create Tasks | |
| 5 | + agent: speckit.tasks | |
| 6 | + prompt: Break the plan into tasks | |
| 7 | + send: true | |
| 8 | + - label: Create Checklist | |
| 9 | + agent: speckit.checklist | |
| 10 | + prompt: Create a checklist for the following domain... | |
| 11 | +--- | |
| 12 | + | |
| 13 | +## User Input | |
| 14 | + | |
| 15 | +```text | |
| 16 | +$ARGUMENTS | |
| 17 | +``` | |
| 18 | + | |
| 19 | +You **MUST** consider the user input before proceeding (if not empty). | |
| 20 | + | |
| 21 | +## Outline | |
| 22 | + | |
| 23 | +1. **Setup**: Run `.specify/scripts/bash/setup-plan.sh --json` from repo root and parse JSON for FEATURE_SPEC, IMPL_PLAN, SPECS_DIR, BRANCH. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). | |
| 24 | + | |
| 25 | +2. **Load context**: Read FEATURE_SPEC and `.specify/memory/constitution.md`. Load IMPL_PLAN template (already copied). | |
| 26 | + | |
| 27 | +3. **Execute plan workflow**: Follow the structure in IMPL_PLAN template to: | |
| 28 | + - Fill Technical Context (mark unknowns as "NEEDS CLARIFICATION") | |
| 29 | + - Fill Constitution Check section from constitution | |
| 30 | + - Evaluate gates (ERROR if violations unjustified) | |
| 31 | + - Phase 0: Generate research.md (resolve all NEEDS CLARIFICATION) | |
| 32 | + - Phase 1: Generate data-model.md, contracts/, quickstart.md | |
| 33 | + - Phase 1: Update agent context by running the agent script | |
| 34 | + - Re-evaluate Constitution Check post-design | |
| 35 | + | |
| 36 | +4. **Stop and report**: Command ends after Phase 2 planning. Report branch, IMPL_PLAN path, and generated artifacts. | |
| 37 | + | |
| 38 | +## Phases | |
| 39 | + | |
| 40 | +### Phase 0: Outline & Research | |
| 41 | + | |
| 42 | +1. **Extract unknowns from Technical Context** above: | |
| 43 | + - For each NEEDS CLARIFICATION → research task | |
| 44 | + - For each dependency → best practices task | |
| 45 | + - For each integration → patterns task | |
| 46 | + | |
| 47 | +2. **Generate and dispatch research agents**: | |
| 48 | + | |
| 49 | + ```text | |
| 50 | + For each unknown in Technical Context: | |
| 51 | + Task: "Research {unknown} for {feature context}" | |
| 52 | + For each technology choice: | |
| 53 | + Task: "Find best practices for {tech} in {domain}" | |
| 54 | + ``` | |
| 55 | + | |
| 56 | +3. **Consolidate findings** in `research.md` using format: | |
| 57 | + - Decision: [what was chosen] | |
| 58 | + - Rationale: [why chosen] | |
| 59 | + - Alternatives considered: [what else evaluated] | |
| 60 | + | |
| 61 | +**Output**: research.md with all NEEDS CLARIFICATION resolved | |
| 62 | + | |
| 63 | +### Phase 1: Design & Contracts | |
| 64 | + | |
| 65 | +**Prerequisites:** `research.md` complete | |
| 66 | + | |
| 67 | +1. **Extract entities from feature spec** → `data-model.md`: | |
| 68 | + - Entity name, fields, relationships | |
| 69 | + - Validation rules from requirements | |
| 70 | + - State transitions if applicable | |
| 71 | + | |
| 72 | +2. **Define interface contracts** (if project has external interfaces) → `/contracts/`: | |
| 73 | + - Identify what interfaces the project exposes to users or other systems | |
| 74 | + - Document the contract format appropriate for the project type | |
| 75 | + - Examples: public APIs for libraries, command schemas for CLI tools, endpoints for web services, grammars for parsers, UI contracts for applications | |
| 76 | + - Skip if project is purely internal (build scripts, one-off tools, etc.) | |
| 77 | + | |
| 78 | +3. **Agent context update**: | |
| 79 | + - Run `.specify/scripts/bash/update-agent-context.sh cursor-agent` | |
| 80 | + - These scripts detect which AI agent is in use | |
| 81 | + - Update the appropriate agent-specific context file | |
| 82 | + - Add only new technology from current plan | |
| 83 | + - Preserve manual additions between markers | |
| 84 | + | |
| 85 | +**Output**: data-model.md, /contracts/*, quickstart.md, agent-specific file | |
| 86 | + | |
| 87 | +## Key rules | |
| 88 | + | |
| 89 | +- Use absolute paths | |
| 90 | +- ERROR on gate failures or unresolved clarifications |
A
.cursor/commands/speckit.specify.md
+258
-0
@@ -0,0 +1,258 @@
| 1 | +--- | |
| 2 | +description: Create or update the feature specification from a natural language feature description. | |
| 3 | +handoffs: | |
| 4 | + - label: Build Technical Plan | |
| 5 | + agent: speckit.plan | |
| 6 | + prompt: Create a plan for the spec. I am building with... | |
| 7 | + - label: Clarify Spec Requirements | |
| 8 | + agent: speckit.clarify | |
| 9 | + prompt: Clarify specification requirements | |
| 10 | + send: true | |
| 11 | +--- | |
| 12 | + | |
| 13 | +## User Input | |
| 14 | + | |
| 15 | +```text | |
| 16 | +$ARGUMENTS | |
| 17 | +``` | |
| 18 | + | |
| 19 | +You **MUST** consider the user input before proceeding (if not empty). | |
| 20 | + | |
| 21 | +## Outline | |
| 22 | + | |
| 23 | +The text the user typed after `/speckit.specify` in the triggering message **is** the feature description. Assume you always have it available in this conversation even if `$ARGUMENTS` appears literally below. Do not ask the user to repeat it unless they provided an empty command. | |
| 24 | + | |
| 25 | +Given that feature description, do this: | |
| 26 | + | |
| 27 | +1. **Generate a concise short name** (2-4 words) for the branch: | |
| 28 | + - Analyze the feature description and extract the most meaningful keywords | |
| 29 | + - Create a 2-4 word short name that captures the essence of the feature | |
| 30 | + - Use action-noun format when possible (e.g., "add-user-auth", "fix-payment-bug") | |
| 31 | + - Preserve technical terms and acronyms (OAuth2, API, JWT, etc.) | |
| 32 | + - Keep it concise but descriptive enough to understand the feature at a glance | |
| 33 | + - Examples: | |
| 34 | + - "I want to add user authentication" → "user-auth" | |
| 35 | + - "Implement OAuth2 integration for the API" → "oauth2-api-integration" | |
| 36 | + - "Create a dashboard for analytics" → "analytics-dashboard" | |
| 37 | + - "Fix payment processing timeout bug" → "fix-payment-timeout" | |
| 38 | + | |
| 39 | +2. **Check for existing branches before creating new one**: | |
| 40 | + | |
| 41 | + a. First, fetch all remote branches to ensure we have the latest information: | |
| 42 | + | |
| 43 | + ```bash | |
| 44 | + git fetch --all --prune | |
| 45 | + ``` | |
| 46 | + | |
| 47 | + b. Find the highest feature number across all sources for the short-name: | |
| 48 | + - Remote branches: `git ls-remote --heads origin | grep -E 'refs/heads/[0-9]+-<short-name>$'` | |
| 49 | + - Local branches: `git branch | grep -E '^[* ]*[0-9]+-<short-name>$'` | |
| 50 | + - Specs directories: Check for directories matching `specs/[0-9]+-<short-name>` | |
| 51 | + | |
| 52 | + c. Determine the next available number: | |
| 53 | + - Extract all numbers from all three sources | |
| 54 | + - Find the highest number N | |
| 55 | + - Use N+1 for the new branch number | |
| 56 | + | |
| 57 | + d. Run the script `.specify/scripts/bash/create-new-feature.sh --json "$ARGUMENTS"` with the calculated number and short-name: | |
| 58 | + - Pass `--number N+1` and `--short-name "your-short-name"` along with the feature description | |
| 59 | + - Bash example: `.specify/scripts/bash/create-new-feature.sh --json "$ARGUMENTS" --json --number 5 --short-name "user-auth" "Add user authentication"` | |
| 60 | + - PowerShell example: `.specify/scripts/bash/create-new-feature.sh --json "$ARGUMENTS" -Json -Number 5 -ShortName "user-auth" "Add user authentication"` | |
| 61 | + | |
| 62 | + **IMPORTANT**: | |
| 63 | + - Check all three sources (remote branches, local branches, specs directories) to find the highest number | |
| 64 | + - Only match branches/directories with the exact short-name pattern | |
| 65 | + - If no existing branches/directories found with this short-name, start with number 1 | |
| 66 | + - You must only ever run this script once per feature | |
| 67 | + - The JSON is provided in the terminal as output - always refer to it to get the actual content you're looking for | |
| 68 | + - The JSON output will contain BRANCH_NAME and SPEC_FILE paths | |
| 69 | + - For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot") | |
| 70 | + | |
| 71 | +3. Load `.specify/templates/spec-template.md` to understand required sections. | |
| 72 | + | |
| 73 | +4. Follow this execution flow: | |
| 74 | + | |
| 75 | + 1. Parse user description from Input | |
| 76 | + If empty: ERROR "No feature description provided" | |
| 77 | + 2. Extract key concepts from description | |
| 78 | + Identify: actors, actions, data, constraints | |
| 79 | + 3. For unclear aspects: | |
| 80 | + - Make informed guesses based on context and industry standards | |
| 81 | + - Only mark with [NEEDS CLARIFICATION: specific question] if: | |
| 82 | + - The choice significantly impacts feature scope or user experience | |
| 83 | + - Multiple reasonable interpretations exist with different implications | |
| 84 | + - No reasonable default exists | |
| 85 | + - **LIMIT: Maximum 3 [NEEDS CLARIFICATION] markers total** | |
| 86 | + - Prioritize clarifications by impact: scope > security/privacy > user experience > technical details | |
| 87 | + 4. Fill User Scenarios & Testing section | |
| 88 | + If no clear user flow: ERROR "Cannot determine user scenarios" | |
| 89 | + 5. Generate Functional Requirements | |
| 90 | + Each requirement must be testable | |
| 91 | + Use reasonable defaults for unspecified details (document assumptions in Assumptions section) | |
| 92 | + 6. Define Success Criteria | |
| 93 | + Create measurable, technology-agnostic outcomes | |
| 94 | + Include both quantitative metrics (time, performance, volume) and qualitative measures (user satisfaction, task completion) | |
| 95 | + Each criterion must be verifiable without implementation details | |
| 96 | + 7. Identify Key Entities (if data involved) | |
| 97 | + 8. Return: SUCCESS (spec ready for planning) | |
| 98 | + | |
| 99 | +5. Write the specification to SPEC_FILE using the template structure, replacing placeholders with concrete details derived from the feature description (arguments) while preserving section order and headings. | |
| 100 | + | |
| 101 | +6. **Specification Quality Validation**: After writing the initial spec, validate it against quality criteria: | |
| 102 | + | |
| 103 | + a. **Create Spec Quality Checklist**: Generate a checklist file at `FEATURE_DIR/checklists/requirements.md` using the checklist template structure with these validation items: | |
| 104 | + | |
| 105 | + ```markdown | |
| 106 | + # Specification Quality Checklist: [FEATURE NAME] | |
| 107 | + | |
| 108 | + **Purpose**: Validate specification completeness and quality before proceeding to planning | |
| 109 | + **Created**: [DATE] | |
| 110 | + **Feature**: [Link to spec.md] | |
| 111 | + | |
| 112 | + ## Content Quality | |
| 113 | + | |
| 114 | + - [ ] No implementation details (languages, frameworks, APIs) | |
| 115 | + - [ ] Focused on user value and business needs | |
| 116 | + - [ ] Written for non-technical stakeholders | |
| 117 | + - [ ] All mandatory sections completed | |
| 118 | + | |
| 119 | + ## Requirement Completeness | |
| 120 | + | |
| 121 | + - [ ] No [NEEDS CLARIFICATION] markers remain | |
| 122 | + - [ ] Requirements are testable and unambiguous | |
| 123 | + - [ ] Success criteria are measurable | |
| 124 | + - [ ] Success criteria are technology-agnostic (no implementation details) | |
| 125 | + - [ ] All acceptance scenarios are defined | |
| 126 | + - [ ] Edge cases are identified | |
| 127 | + - [ ] Scope is clearly bounded | |
| 128 | + - [ ] Dependencies and assumptions identified | |
| 129 | + | |
| 130 | + ## Feature Readiness | |
| 131 | + | |
| 132 | + - [ ] All functional requirements have clear acceptance criteria | |
| 133 | + - [ ] User scenarios cover primary flows | |
| 134 | + - [ ] Feature meets measurable outcomes defined in Success Criteria | |
| 135 | + - [ ] No implementation details leak into specification | |
| 136 | + | |
| 137 | + ## Notes | |
| 138 | + | |
| 139 | + - Items marked incomplete require spec updates before `/speckit.clarify` or `/speckit.plan` | |
| 140 | + ``` | |
| 141 | + | |
| 142 | + b. **Run Validation Check**: Review the spec against each checklist item: | |
| 143 | + - For each item, determine if it passes or fails | |
| 144 | + - Document specific issues found (quote relevant spec sections) | |
| 145 | + | |
| 146 | + c. **Handle Validation Results**: | |
| 147 | + | |
| 148 | + - **If all items pass**: Mark checklist complete and proceed to step 6 | |
| 149 | + | |
| 150 | + - **If items fail (excluding [NEEDS CLARIFICATION])**: | |
| 151 | + 1. List the failing items and specific issues | |
| 152 | + 2. Update the spec to address each issue | |
| 153 | + 3. Re-run validation until all items pass (max 3 iterations) | |
| 154 | + 4. If still failing after 3 iterations, document remaining issues in checklist notes and warn user | |
| 155 | + | |
| 156 | + - **If [NEEDS CLARIFICATION] markers remain**: | |
| 157 | + 1. Extract all [NEEDS CLARIFICATION: ...] markers from the spec | |
| 158 | + 2. **LIMIT CHECK**: If more than 3 markers exist, keep only the 3 most critical (by scope/security/UX impact) and make informed guesses for the rest | |
| 159 | + 3. For each clarification needed (max 3), present options to user in this format: | |
| 160 | + | |
| 161 | + ```markdown | |
| 162 | + ## Question [N]: [Topic] | |
| 163 | + | |
| 164 | + **Context**: [Quote relevant spec section] | |
| 165 | + | |
| 166 | + **What we need to know**: [Specific question from NEEDS CLARIFICATION marker] | |
| 167 | + | |
| 168 | + **Suggested Answers**: | |
| 169 | + | |
| 170 | + | Option | Answer | Implications | | |
| 171 | + |--------|--------|--------------| | |
| 172 | + | A | [First suggested answer] | [What this means for the feature] | | |
| 173 | + | B | [Second suggested answer] | [What this means for the feature] | | |
| 174 | + | C | [Third suggested answer] | [What this means for the feature] | | |
| 175 | + | Custom | Provide your own answer | [Explain how to provide custom input] | | |
| 176 | + | |
| 177 | + **Your choice**: _[Wait for user response]_ | |
| 178 | + ``` | |
| 179 | + | |
| 180 | + 4. **CRITICAL - Table Formatting**: Ensure markdown tables are properly formatted: | |
| 181 | + - Use consistent spacing with pipes aligned | |
| 182 | + - Each cell should have spaces around content: `| Content |` not `|Content|` | |
| 183 | + - Header separator must have at least 3 dashes: `|--------|` | |
| 184 | + - Test that the table renders correctly in markdown preview | |
| 185 | + 5. Number questions sequentially (Q1, Q2, Q3 - max 3 total) | |
| 186 | + 6. Present all questions together before waiting for responses | |
| 187 | + 7. Wait for user to respond with their choices for all questions (e.g., "Q1: A, Q2: Custom - [details], Q3: B") | |
| 188 | + 8. Update the spec by replacing each [NEEDS CLARIFICATION] marker with the user's selected or provided answer | |
| 189 | + 9. Re-run validation after all clarifications are resolved | |
| 190 | + | |
| 191 | + d. **Update Checklist**: After each validation iteration, update the checklist file with current pass/fail status | |
| 192 | + | |
| 193 | +7. Report completion with branch name, spec file path, checklist results, and readiness for the next phase (`/speckit.clarify` or `/speckit.plan`). | |
| 194 | + | |
| 195 | +**NOTE:** The script creates and checks out the new branch and initializes the spec file before writing. | |
| 196 | + | |
| 197 | +## General Guidelines | |
| 198 | + | |
| 199 | +## Quick Guidelines | |
| 200 | + | |
| 201 | +- Focus on **WHAT** users need and **WHY**. | |
| 202 | +- Avoid HOW to implement (no tech stack, APIs, code structure). | |
| 203 | +- Written for business stakeholders, not developers. | |
| 204 | +- DO NOT create any checklists that are embedded in the spec. That will be a separate command. | |
| 205 | + | |
| 206 | +### Section Requirements | |
| 207 | + | |
| 208 | +- **Mandatory sections**: Must be completed for every feature | |
| 209 | +- **Optional sections**: Include only when relevant to the feature | |
| 210 | +- When a section doesn't apply, remove it entirely (don't leave as "N/A") | |
| 211 | + | |
| 212 | +### For AI Generation | |
| 213 | + | |
| 214 | +When creating this spec from a user prompt: | |
| 215 | + | |
| 216 | +1. **Make informed guesses**: Use context, industry standards, and common patterns to fill gaps | |
| 217 | +2. **Document assumptions**: Record reasonable defaults in the Assumptions section | |
| 218 | +3. **Limit clarifications**: Maximum 3 [NEEDS CLARIFICATION] markers - use only for critical decisions that: | |
| 219 | + - Significantly impact feature scope or user experience | |
| 220 | + - Have multiple reasonable interpretations with different implications | |
| 221 | + - Lack any reasonable default | |
| 222 | +4. **Prioritize clarifications**: scope > security/privacy > user experience > technical details | |
| 223 | +5. **Think like a tester**: Every vague requirement should fail the "testable and unambiguous" checklist item | |
| 224 | +6. **Common areas needing clarification** (only if no reasonable default exists): | |
| 225 | + - Feature scope and boundaries (include/exclude specific use cases) | |
| 226 | + - User types and permissions (if multiple conflicting interpretations possible) | |
| 227 | + - Security/compliance requirements (when legally/financially significant) | |
| 228 | + | |
| 229 | +**Examples of reasonable defaults** (don't ask about these): | |
| 230 | + | |
| 231 | +- Data retention: Industry-standard practices for the domain | |
| 232 | +- Performance targets: Standard web/mobile app expectations unless specified | |
| 233 | +- Error handling: User-friendly messages with appropriate fallbacks | |
| 234 | +- Authentication method: Standard session-based or OAuth2 for web apps | |
| 235 | +- Integration patterns: Use project-appropriate patterns (REST/GraphQL for web services, function calls for libraries, CLI args for tools, etc.) | |
| 236 | + | |
| 237 | +### Success Criteria Guidelines | |
| 238 | + | |
| 239 | +Success criteria must be: | |
| 240 | + | |
| 241 | +1. **Measurable**: Include specific metrics (time, percentage, count, rate) | |
| 242 | +2. **Technology-agnostic**: No mention of frameworks, languages, databases, or tools | |
| 243 | +3. **User-focused**: Describe outcomes from user/business perspective, not system internals | |
| 244 | +4. **Verifiable**: Can be tested/validated without knowing implementation details | |
| 245 | + | |
| 246 | +**Good examples**: | |
| 247 | + | |
| 248 | +- "Users can complete checkout in under 3 minutes" | |
| 249 | +- "System supports 10,000 concurrent users" | |
| 250 | +- "95% of searches return results in under 1 second" | |
| 251 | +- "Task completion rate improves by 40%" | |
| 252 | + | |
| 253 | +**Bad examples** (implementation-focused): | |
| 254 | + | |
| 255 | +- "API response time is under 200ms" (too technical, use "Users see results instantly") | |
| 256 | +- "Database can handle 1000 TPS" (implementation detail, use user-facing metric) | |
| 257 | +- "React components render efficiently" (framework-specific) | |
| 258 | +- "Redis cache hit rate above 80%" (technology-specific) |
A
.cursor/commands/speckit.tasks.md
+137
-0
@@ -0,0 +1,137 @@
| 1 | +--- | |
| 2 | +description: Generate an actionable, dependency-ordered tasks.md for the feature based on available design artifacts. | |
| 3 | +handoffs: | |
| 4 | + - label: Analyze For Consistency | |
| 5 | + agent: speckit.analyze | |
| 6 | + prompt: Run a project analysis for consistency | |
| 7 | + send: true | |
| 8 | + - label: Implement Project | |
| 9 | + agent: speckit.implement | |
| 10 | + prompt: Start the implementation in phases | |
| 11 | + send: true | |
| 12 | +--- | |
| 13 | + | |
| 14 | +## User Input | |
| 15 | + | |
| 16 | +```text | |
| 17 | +$ARGUMENTS | |
| 18 | +``` | |
| 19 | + | |
| 20 | +You **MUST** consider the user input before proceeding (if not empty). | |
| 21 | + | |
| 22 | +## Outline | |
| 23 | + | |
| 24 | +1. **Setup**: Run `.specify/scripts/bash/check-prerequisites.sh --json` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). | |
| 25 | + | |
| 26 | +2. **Load design documents**: Read from FEATURE_DIR: | |
| 27 | + - **Required**: plan.md (tech stack, libraries, structure), spec.md (user stories with priorities) | |
| 28 | + - **Optional**: data-model.md (entities), contracts/ (interface contracts), research.md (decisions), quickstart.md (test scenarios) | |
| 29 | + - Note: Not all projects have all documents. Generate tasks based on what's available. | |
| 30 | + | |
| 31 | +3. **Execute task generation workflow**: | |
| 32 | + - Load plan.md and extract tech stack, libraries, project structure | |
| 33 | + - Load spec.md and extract user stories with their priorities (P1, P2, P3, etc.) | |
| 34 | + - If data-model.md exists: Extract entities and map to user stories | |
| 35 | + - If contracts/ exists: Map interface contracts to user stories | |
| 36 | + - If research.md exists: Extract decisions for setup tasks | |
| 37 | + - Generate tasks organized by user story (see Task Generation Rules below) | |
| 38 | + - Generate dependency graph showing user story completion order | |
| 39 | + - Create parallel execution examples per user story | |
| 40 | + - Validate task completeness (each user story has all needed tasks, independently testable) | |
| 41 | + | |
| 42 | +4. **Generate tasks.md**: Use `.specify/templates/tasks-template.md` as structure, fill with: | |
| 43 | + - Correct feature name from plan.md | |
| 44 | + - Phase 1: Setup tasks (project initialization) | |
| 45 | + - Phase 2: Foundational tasks (blocking prerequisites for all user stories) | |
| 46 | + - Phase 3+: One phase per user story (in priority order from spec.md) | |
| 47 | + - Each phase includes: story goal, independent test criteria, tests (if requested), implementation tasks | |
| 48 | + - Final Phase: Polish & cross-cutting concerns | |
| 49 | + - All tasks must follow the strict checklist format (see Task Generation Rules below) | |
| 50 | + - Clear file paths for each task | |
| 51 | + - Dependencies section showing story completion order | |
| 52 | + - Parallel execution examples per story | |
| 53 | + - Implementation strategy section (MVP first, incremental delivery) | |
| 54 | + | |
| 55 | +5. **Report**: Output path to generated tasks.md and summary: | |
| 56 | + - Total task count | |
| 57 | + - Task count per user story | |
| 58 | + - Parallel opportunities identified | |
| 59 | + - Independent test criteria for each story | |
| 60 | + - Suggested MVP scope (typically just User Story 1) | |
| 61 | + - Format validation: Confirm ALL tasks follow the checklist format (checkbox, ID, labels, file paths) | |
| 62 | + | |
| 63 | +Context for task generation: $ARGUMENTS | |
| 64 | + | |
| 65 | +The tasks.md should be immediately executable - each task must be specific enough that an LLM can complete it without additional context. | |
| 66 | + | |
| 67 | +## Task Generation Rules | |
| 68 | + | |
| 69 | +**CRITICAL**: Tasks MUST be organized by user story to enable independent implementation and testing. | |
| 70 | + | |
| 71 | +**Tests are OPTIONAL**: Only generate test tasks if explicitly requested in the feature specification or if user requests TDD approach. | |
| 72 | + | |
| 73 | +### Checklist Format (REQUIRED) | |
| 74 | + | |
| 75 | +Every task MUST strictly follow this format: | |
| 76 | + | |
| 77 | +```text | |
| 78 | +- [ ] [TaskID] [P?] [Story?] Description with file path | |
| 79 | +``` | |
| 80 | + | |
| 81 | +**Format Components**: | |
| 82 | + | |
| 83 | +1. **Checkbox**: ALWAYS start with `- [ ]` (markdown checkbox) | |
| 84 | +2. **Task ID**: Sequential number (T001, T002, T003...) in execution order | |
| 85 | +3. **[P] marker**: Include ONLY if task is parallelizable (different files, no dependencies on incomplete tasks) | |
| 86 | +4. **[Story] label**: REQUIRED for user story phase tasks only | |
| 87 | + - Format: [US1], [US2], [US3], etc. (maps to user stories from spec.md) | |
| 88 | + - Setup phase: NO story label | |
| 89 | + - Foundational phase: NO story label | |
| 90 | + - User Story phases: MUST have story label | |
| 91 | + - Polish phase: NO story label | |
| 92 | +5. **Description**: Clear action with exact file path | |
| 93 | + | |
| 94 | +**Examples**: | |
| 95 | + | |
| 96 | +- ✅ CORRECT: `- [ ] T001 Create project structure per implementation plan` | |
| 97 | +- ✅ CORRECT: `- [ ] T005 [P] Implement authentication middleware in src/middleware/auth.py` | |
| 98 | +- ✅ CORRECT: `- [ ] T012 [P] [US1] Create User model in src/models/user.py` | |
| 99 | +- ✅ CORRECT: `- [ ] T014 [US1] Implement UserService in src/services/user_service.py` | |
| 100 | +- ❌ WRONG: `- [ ] Create User model` (missing ID and Story label) | |
| 101 | +- ❌ WRONG: `T001 [US1] Create model` (missing checkbox) | |
| 102 | +- ❌ WRONG: `- [ ] [US1] Create User model` (missing Task ID) | |
| 103 | +- ❌ WRONG: `- [ ] T001 [US1] Create model` (missing file path) | |
| 104 | + | |
| 105 | +### Task Organization | |
| 106 | + | |
| 107 | +1. **From User Stories (spec.md)** - PRIMARY ORGANIZATION: | |
| 108 | + - Each user story (P1, P2, P3...) gets its own phase | |
| 109 | + - Map all related components to their story: | |
| 110 | + - Models needed for that story | |
| 111 | + - Services needed for that story | |
| 112 | + - Interfaces/UI needed for that story | |
| 113 | + - If tests requested: Tests specific to that story | |
| 114 | + - Mark story dependencies (most stories should be independent) | |
| 115 | + | |
| 116 | +2. **From Contracts**: | |
| 117 | + - Map each interface contract → to the user story it serves | |
| 118 | + - If tests requested: Each interface contract → contract test task [P] before implementation in that story's phase | |
| 119 | + | |
| 120 | +3. **From Data Model**: | |
| 121 | + - Map each entity to the user story(ies) that need it | |
| 122 | + - If entity serves multiple stories: Put in earliest story or Setup phase | |
| 123 | + - Relationships → service layer tasks in appropriate story phase | |
| 124 | + | |
| 125 | +4. **From Setup/Infrastructure**: | |
| 126 | + - Shared infrastructure → Setup phase (Phase 1) | |
| 127 | + - Foundational/blocking tasks → Foundational phase (Phase 2) | |
| 128 | + - Story-specific setup → within that story's phase | |
| 129 | + | |
| 130 | +### Phase Structure | |
| 131 | + | |
| 132 | +- **Phase 1**: Setup (project initialization) | |
| 133 | +- **Phase 2**: Foundational (blocking prerequisites - MUST complete before user stories) | |
| 134 | +- **Phase 3+**: User Stories in priority order (P1, P2, P3...) | |
| 135 | + - Within each story: Tests (if requested) → Models → Services → Endpoints → Integration | |
| 136 | + - Each phase should be a complete, independently testable increment | |
| 137 | +- **Final Phase**: Polish & Cross-Cutting Concerns |
A
.cursor/commands/speckit.taskstoissues.md
+30
-0
@@ -0,0 +1,30 @@
| 1 | +--- | |
| 2 | +description: Convert existing tasks into actionable, dependency-ordered GitHub issues for the feature based on available design artifacts. | |
| 3 | +tools: ['github/github-mcp-server/issue_write'] | |
| 4 | +--- | |
| 5 | + | |
| 6 | +## User Input | |
| 7 | + | |
| 8 | +```text | |
| 9 | +$ARGUMENTS | |
| 10 | +``` | |
| 11 | + | |
| 12 | +You **MUST** consider the user input before proceeding (if not empty). | |
| 13 | + | |
| 14 | +## Outline | |
| 15 | + | |
| 16 | +1. Run `.specify/scripts/bash/check-prerequisites.sh --json --require-tasks --include-tasks` from repo root and parse FEATURE_DIR and AVAILABLE_DOCS list. All paths must be absolute. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot"). | |
| 17 | +1. From the executed script, extract the path to **tasks**. | |
| 18 | +1. Get the Git remote by running: | |
| 19 | + | |
| 20 | +```bash | |
| 21 | +git config --get remote.origin.url | |
| 22 | +``` | |
| 23 | + | |
| 24 | +> [!CAUTION] | |
| 25 | +> ONLY PROCEED TO NEXT STEPS IF THE REMOTE IS A GITHUB URL | |
| 26 | + | |
| 27 | +1. For each task in the list, use the GitHub MCP server to create a new issue in the repository that is representative of the Git remote. | |
| 28 | + | |
| 29 | +> [!CAUTION] | |
| 30 | +> UNDER NO CIRCUMSTANCES EVER CREATE ISSUES IN REPOSITORIES THAT DO NOT MATCH THE REMOTE URL |
A
.gitignore
+44
-0
@@ -0,0 +1,44 @@
| 1 | +# Rust / Cargo | |
| 2 | +/target/ | |
| 3 | +**/*.rs.bk | |
| 4 | +# Cargo.lock : à commiter pour les binaires/applications (recommandation Rust) | |
| 5 | + | |
| 6 | +# Environment & secrets (constitution: no secrets in repo) | |
| 7 | +.env | |
| 8 | +.env.* | |
| 9 | +!.env.example | |
| 10 | +*.pem | |
| 11 | +*.key | |
| 12 | + | |
| 13 | +# IDE & editors | |
| 14 | +.idea/ | |
| 15 | +*.swp | |
| 16 | +*.swo | |
| 17 | +*~ | |
| 18 | +.vscode/ | |
| 19 | +# Uncomment to share workspace settings: !.vscode/settings.json | |
| 20 | + | |
| 21 | +# OS | |
| 22 | +.DS_Store | |
| 23 | +Thumbs.db | |
| 24 | + | |
| 25 | +# Logs & local runtime | |
| 26 | +*.log | |
| 27 | +/logs/ | |
| 28 | +/tmp/ | |
| 29 | +/temp/ | |
| 30 | + | |
| 31 | +# Database (local dev data, dumps) | |
| 32 | +database/*.sql | |
| 33 | +database/data/ | |
| 34 | +*.dump | |
| 35 | + | |
| 36 | +# Build & coverage | |
| 37 | +coverage/ | |
| 38 | +*.profraw | |
| 39 | +*.profdata | |
| 40 | + | |
| 41 | +# Debug | |
| 42 | +*.d | |
| 43 | +*.so | |
| 44 | +*.dylib |
A
.specify/memory/constitution.md
+150
-0
@@ -0,0 +1,150 @@
| 1 | +<!-- | |
| 2 | +Sync Impact Report: | |
| 3 | +- Version change: (none) → 0.5.2 (initial placement) | |
| 4 | +- Source: Rustwarden/constitution.md — constitution complète importée pour le nouveau projet | |
| 5 | +- Modified principles: N/A (placement initial) | |
| 6 | +- Added sections: Constitution complète (Core Principles I–V, Technical Constraints, Development Workflow, Governance) | |
| 7 | +- Removed sections: None | |
| 8 | +- Templates requiring updates: | |
| 9 | + ✅ plan-template.md (Constitution Check / gates — aligné, pas de modification) | |
| 10 | + ✅ spec-template.md (scope/requirements — aligné, pas de modification) | |
| 11 | + ✅ tasks-template.md (catégorisation tâches — aligné, pas de modification) | |
| 12 | + ✅ .cursor/commands/*.md (référence .specify/memory/constitution.md — valide) | |
| 13 | +- Follow-up TODOs: None | |
| 14 | +--> | |
| 15 | + | |
| 16 | +# Rustwarden Constitution | |
| 17 | + | |
| 18 | +## Core Principles | |
| 19 | + | |
| 20 | +### I. Qualité de Code | |
| 21 | + | |
| 22 | +Toutes les fonctions publiques DOIVENT être documentées avec `///` (doc comments Rust). Le code DOIT respecter les bonnes pratiques Rust (clippy warnings = 0). Les structures de données DOIVENT utiliser `#[derive(Debug, Clone)]` où approprié. La gestion d'erreurs DOIT utiliser `Result<T, E>` avec des types d'erreur explicites. | |
| 23 | + | |
| 24 | +**Rationale**: La documentation et la qualité du code facilitent la maintenance, la collaboration et réduisent les bugs. Rust offre des outils puissants (clippy, rustfmt) qui doivent être utilisés. | |
| 25 | + | |
| 26 | +### II. Architecture Axum et SeaORM | |
| 27 | + | |
| 28 | +Toutes les routes HTTP DOIVENT être définies avec Axum uniquement (`axum::Router`). Toutes les interactions avec la base de données DOIVENT passer par SeaORM (aucun raw SQL autorisé). Les migrations DOIVENT être gérées via le système de migrations SeaORM (`migrations/src/`). Le serveur DOIT utiliser Tokio comme runtime async (requis par Axum). | |
| 29 | + | |
| 30 | +**Documentation SeaORM** (amendement v0.4.1): Toutes les interactions avec la base de données DOIVENT être implémentées en référence à la [documentation officielle SeaORM](https://www.sea-ql.org/SeaORM/docs/index/). Avant d'implémenter une nouvelle fonctionnalité de base de données (requêtes, relations, transactions, etc.), la documentation SeaORM DOIT être consultée pour garantir l'utilisation des bonnes pratiques et des patterns recommandés. Les exemples de code et les patterns documentés dans la documentation SeaORM DOIVENT être privilégiés par rapport aux approches personnalisées. | |
| 31 | + | |
| 32 | +**Implémentation obligatoire des handlers serveur** (amendement v0.5.0): TOUJOURS implémenter les handlers serveur pour que l'API soit fonctionnelle. Les handlers stub (retournant `501 Not Implemented`) sont INTERDITS dans le code de production. Chaque route définie DOIT avoir un handler complet qui : | |
| 33 | +- Injecte l'état nécessaire (`State<DatabaseConnection>`, `Extension<Claims>`, etc.) | |
| 34 | +- Utilise les services métier appropriés | |
| 35 | +- Retourne des réponses fonctionnelles avec données réelles | |
| 36 | +- Gère les erreurs de manière appropriée | |
| 37 | + | |
| 38 | +Les handlers stub sont uniquement autorisés temporairement pendant le développement incrémental, mais DOIVENT être remplacés par des implémentations complètes avant que la feature soit considérée comme terminée. Toute documentation d'API (OpenAPI, guides, exemples) qui référence un endpoint DOIT correspondre à un handler serveur fonctionnel. | |
| 39 | + | |
| 40 | +**Rationale**: Axum et SeaORM sont les frameworks standard pour Rust, offrant sécurité, performance et maintenabilité. L'utilisation exclusive de ces outils garantit la cohérence de l'architecture. La documentation officielle SeaORM contient les meilleures pratiques, les patterns recommandés et les solutions aux problèmes courants. En s'y référant systématiquement, on évite les erreurs d'implémentation, on améliore la maintenabilité et on garantit la compatibilité avec les futures versions de SeaORM. L'implémentation complète des handlers serveur est essentielle pour que l'API soit réellement utilisable par les clients. Des handlers stub créent une fausse impression de fonctionnalité et empêchent les tests d'intégration réels. Cette règle garantit que toute documentation d'API correspond à une implémentation fonctionnelle, évitant les frustrations des développeurs clients. | |
| 41 | + | |
| 42 | +### III. Développement Incrémental | |
| 43 | + | |
| 44 | +Chaque fonctionnalité DOIT être complète et testée avant de passer à la suivante. L'architecture DOIT être modulaire (structure de dossiers claire, séparation des responsabilités). Les user stories DOIVENT être indépendantes et testables individuellement. | |
| 45 | + | |
| 46 | +**Rationale**: Le développement incrémental permet de livrer de la valeur rapidement, facilite les tests et réduit la complexité. Chaque étape doit être validée avant de continuer. | |
| 47 | + | |
| 48 | +### IV. Sécurité par Défaut | |
| 49 | + | |
| 50 | +Tous les secrets DOIVENT être stockés dans des variables d'environnement, JAMAIS dans le code. La validation et la sanitization des entrées utilisateur DOIVENT être effectuées systématiquement. L'authentification et l'autorisation RBAC DOIVENT être implémentées pour toutes les routes protégées. | |
| 51 | + | |
| 52 | +**JWT Authentication Standard** (amendement v0.3.1): Le système DOIT extraire et vérifier les JWT tokens depuis le header `Authorization` au format `Bearer <token>`. Cette extraction DOIT être la méthode principale pour l'authentification API. Les cookies HttpOnly peuvent être utilisés comme méthode alternative pour les clients web, mais le header Authorization a priorité pour permettre aux clients API de surcharger l'authentification par cookie. | |
| 53 | + | |
| 54 | +**Conformité ANSSI Rust** (amendement v0.4.0): Le code DOIT respecter les recommandations du [Guide ANSSI pour le développement sécurisé en Rust](https://anssi-fr.github.io/rust-guide/). Spécifiquement : | |
| 55 | +- Le code DOIT compiler avec `#![deny(warnings)]` activé (ou au minimum `#![warn(warnings)]`) | |
| 56 | +- Toute utilisation de `unsafe` DOIT être justifiée et documentée avec un commentaire `// SAFETY:` expliquant pourquoi `unsafe` est nécessaire et quels invariants doivent être respectés | |
| 57 | +- Les `unwrap()` et `expect()` sont INTERDITS dans le code de production (sauf dans les tests unitaires). Toutes les erreurs DOIVENT être gérées explicitement avec `Result<T, E>` et l'opérateur `?` | |
| 58 | +- L'utilisation de `std::mem::uninitialized` est INTERDITE (dépréciée). L'utilisation de `std::mem::MaybeUninit` DOIT être justifiée pour chaque cas d'usage | |
| 59 | +- Les outils `cargo-audit` et `cargo-outdated` DOIVENT être exécutés régulièrement. Les vulnérabilités détectées DOIVENT être corrigées avant chaque release | |
| 60 | +- Toutes les considérations de sécurité, invariants et garanties DOIVENT être documentées | |
| 61 | + | |
| 62 | +Voir `docs/ANSSI_COMPLIANCE_REPORT.md` pour le rapport de conformité détaillé et les actions prioritaires. | |
| 63 | + | |
| 64 | +**Rationale**: La sécurité est critique pour un système cloud. Les secrets dans le code sont une vulnérabilité majeure. La validation des entrées prévient les attaques par injection. L'authentification JWT via header Authorization est le standard de l'industrie pour les APIs REST et permet une authentification stateless sécurisée. Les guidelines ANSSI représentent les meilleures pratiques pour le développement sécurisé en Rust. Leur respect garantit que les garanties de sécurité offertes par Rust ne sont pas invalidées par une utilisation incorrecte du langage. | |
| 65 | + | |
| 66 | +### V. Tests et Validation Continue | |
| 67 | + | |
| 68 | +Tous les composants DOIVENT avoir des tests unitaires et d'intégration. La couverture de tests DOIT être > 80% (objectif > 90% pour les composants critiques). Les tests DOIVENT être exécutés avant chaque commit (`cargo test`). Les tests DOIVENT suivre les bonnes pratiques Rust (structure `#[cfg(test)]`, tests d'intégration dans `tests/integration/`). | |
| 69 | + | |
| 70 | +**Rationale**: Les tests garantissent la qualité et la fiabilité du code. Une couverture élevée réduit les régressions et facilite les refactorings. L'exécution automatique des tests avant commit maintient la qualité du codebase. | |
| 71 | + | |
| 72 | +## Technical Constraints | |
| 73 | + | |
| 74 | +### Framework Requirements | |
| 75 | + | |
| 76 | +- **Rust Version**: Rust 1.91.1+ (Edition 2024) - **IMPORTANT**: Version minimale requise pour Axum/SeaORM | |
| 77 | +- **Web Framework**: Axum 0.8.7+ (dernière version stable) | |
| 78 | +- **ORM**: SeaORM 2.0.x+ (requis pour toutes les interactions DB) | |
| 79 | +- **Runtime**: Tokio 1.x (requis par Axum) | |
| 80 | +- **Database**: PostgreSQL 18+ (recommandé) | |
| 81 | + | |
| 82 | +### Development Environment | |
| 83 | + | |
| 84 | +**Docker pour Base de Données** (amendement v0.5.2): En développement, la base de données PostgreSQL DOIT être lancée via Docker depuis le dossier `database/` à la racine du projet. Le développeur DOIT utiliser le fichier `database/docker-compose.yml` pour démarrer la base de données. La base de données est lancée et gérée par le développeur (pas automatiquement par le système). Cette configuration garantit un environnement de développement cohérent et isolé, facilite le partage de configuration entre développeurs, et permet un reset rapide de la base de données pour les tests. | |
| 85 | + | |
| 86 | +**Rationale**: L'utilisation de Docker pour PostgreSQL en développement standardise l'environnement de développement, évite les conflits de versions entre développeurs, et simplifie la configuration initiale. Le développeur garde le contrôle sur le démarrage/arrêt de la base de données, permettant une meilleure gestion des ressources et une flexibilité dans le workflow de développement. | |
| 87 | + | |
| 88 | +### Code Quality Requirements | |
| 89 | + | |
| 90 | +- Toutes les fonctions publiques DOIVENT avoir une documentation `///` | |
| 91 | +- `cargo clippy -- -D warnings` DOIT passer sans erreur | |
| 92 | +- `cargo fmt` DOIT être appliqué avant chaque commit | |
| 93 | +- Les erreurs DOIVENT utiliser des types explicites (`Result<T, AppError>`) | |
| 94 | +- `#![deny(warnings)]` DOIT être activé dans `src/lib.rs` ou `src/main.rs` (conformité ANSSI) | |
| 95 | +- Les `unwrap()` et `expect()` sont INTERDITS dans le code de production (conformité ANSSI) | |
| 96 | +- Toute utilisation de `unsafe` DOIT être documentée avec `// SAFETY:` (conformité ANSSI) | |
| 97 | + | |
| 98 | +### Testing Requirements | |
| 99 | + | |
| 100 | +- Tests unitaires dans le même fichier avec `#[cfg(test)]` ou dans `tests/unit/` | |
| 101 | +- Tests d'intégration dans `tests/integration/` | |
| 102 | +- Tests de contrat dans `tests/contract/` | |
| 103 | +- Couverture > 80% (objectif > 90% pour auth, security, core services) | |
| 104 | + | |
| 105 | +### Security Requirements | |
| 106 | + | |
| 107 | +- Pas de secrets hardcodés (variables d'environnement uniquement) | |
| 108 | +- Validation de toutes les entrées utilisateur | |
| 109 | +- Hashing des mots de passe (bcrypt, jamais en clair) | |
| 110 | +- JWT tokens: extraction depuis header `Authorization: Bearer <token>` (priorité 1) | |
| 111 | +- Cookies HttpOnly pour les clients web (fallback, priorité 2) | |
| 112 | +- Rate limiting sur les endpoints d'authentification | |
| 113 | +- Logging de tous les événements d'authentification (succès et échecs) | |
| 114 | +- Conformité aux guidelines ANSSI Rust (voir `docs/ANSSI_COMPLIANCE_REPORT.md`) | |
| 115 | +- Code `unsafe` minimisé et documenté avec `// SAFETY:` | |
| 116 | +- Gestion d'erreurs explicite (pas de panics en production) | |
| 117 | + | |
| 118 | +## Development Workflow | |
| 119 | + | |
| 120 | +### Code Review Process | |
| 121 | + | |
| 122 | +Toutes les pull requests DOIVENT être revues avant merge. Les reviewers DOIVENT vérifier la conformité avec cette constitution. Les violations constitutionnelles DOIVENT être corrigées avant merge. | |
| 123 | + | |
| 124 | +### Quality Gates | |
| 125 | + | |
| 126 | +- ✅ `cargo build` passe sans erreur | |
| 127 | +- ✅ `cargo test` passe (tous les tests) | |
| 128 | +- ✅ `cargo clippy -- -D warnings` passe | |
| 129 | +- ✅ `cargo fmt --check` passe | |
| 130 | +- ✅ Couverture de tests > 80% | |
| 131 | +- ✅ Documentation complète (`cargo doc` génère sans warnings) | |
| 132 | +- ✅ `cargo audit` ne signale pas de vulnérabilités (avant release, conformité ANSSI) | |
| 133 | +- ✅ `cargo outdated` a été vérifié (avant release, conformité ANSSI) | |
| 134 | +- ✅ Aucun `unwrap()`/`expect()` dans le code de production (sauf tests, conformité ANSSI) | |
| 135 | +- ✅ Tous les blocs `unsafe` sont documentés avec `// SAFETY:` (conformité ANSSI) | |
| 136 | + | |
| 137 | +### Testing Strategy | |
| 138 | + | |
| 139 | +1. **TDD recommandé**: Écrire les tests avant l'implémentation pour les nouvelles fonctionnalités | |
| 140 | +2. **Tests unitaires**: Pour chaque fonction publique, tester les cas normaux et d'erreur | |
| 141 | +3. **Tests d'intégration**: Pour chaque endpoint API, tester les scénarios complets | |
| 142 | +4. **Tests de contrat**: Pour chaque endpoint public, valider le format de réponse | |
| 143 | + | |
| 144 | +## Governance | |
| 145 | + | |
| 146 | +Cette constitution prévaut sur toutes les autres pratiques du projet. Les amendements nécessitent une documentation, une approbation et un plan de migration si nécessaire. | |
| 147 | + | |
| 148 | +**Version**: 0.5.2 | **Ratified**: 2025-12-09 | **Last Amended**: 2025-03-05 | |
| 149 | + | |
| 150 | +**Compliance**: Toutes les PRs et reviews DOIVENT vérifier la conformité avec cette constitution. La complexité DOIT être justifiée. Utiliser les templates dans `.specify/templates/` pour la documentation des features. |
A
.specify/scripts/bash/check-prerequisites.sh
+166
-0
@@ -0,0 +1,166 @@
| 1 | +#!/usr/bin/env bash | |
| 2 | + | |
| 3 | +# Consolidated prerequisite checking script | |
| 4 | +# | |
| 5 | +# This script provides unified prerequisite checking for Spec-Driven Development workflow. | |
| 6 | +# It replaces the functionality previously spread across multiple scripts. | |
| 7 | +# | |
| 8 | +# Usage: ./check-prerequisites.sh [OPTIONS] | |
| 9 | +# | |
| 10 | +# OPTIONS: | |
| 11 | +# --json Output in JSON format | |
| 12 | +# --require-tasks Require tasks.md to exist (for implementation phase) | |
| 13 | +# --include-tasks Include tasks.md in AVAILABLE_DOCS list | |
| 14 | +# --paths-only Only output path variables (no validation) | |
| 15 | +# --help, -h Show help message | |
| 16 | +# | |
| 17 | +# OUTPUTS: | |
| 18 | +# JSON mode: {"FEATURE_DIR":"...", "AVAILABLE_DOCS":["..."]} | |
| 19 | +# Text mode: FEATURE_DIR:... \n AVAILABLE_DOCS: \n ✓/✗ file.md | |
| 20 | +# Paths only: REPO_ROOT: ... \n BRANCH: ... \n FEATURE_DIR: ... etc. | |
| 21 | + | |
| 22 | +set -e | |
| 23 | + | |
| 24 | +# Parse command line arguments | |
| 25 | +JSON_MODE=false | |
| 26 | +REQUIRE_TASKS=false | |
| 27 | +INCLUDE_TASKS=false | |
| 28 | +PATHS_ONLY=false | |
| 29 | + | |
| 30 | +for arg in "$@"; do | |
| 31 | + case "$arg" in | |
| 32 | + --json) | |
| 33 | + JSON_MODE=true | |
| 34 | + ;; | |
| 35 | + --require-tasks) | |
| 36 | + REQUIRE_TASKS=true | |
| 37 | + ;; | |
| 38 | + --include-tasks) | |
| 39 | + INCLUDE_TASKS=true | |
| 40 | + ;; | |
| 41 | + --paths-only) | |
| 42 | + PATHS_ONLY=true | |
| 43 | + ;; | |
| 44 | + --help|-h) | |
| 45 | + cat << 'EOF' | |
| 46 | +Usage: check-prerequisites.sh [OPTIONS] | |
| 47 | + | |
| 48 | +Consolidated prerequisite checking for Spec-Driven Development workflow. | |
| 49 | + | |
| 50 | +OPTIONS: | |
| 51 | + --json Output in JSON format | |
| 52 | + --require-tasks Require tasks.md to exist (for implementation phase) | |
| 53 | + --include-tasks Include tasks.md in AVAILABLE_DOCS list | |
| 54 | + --paths-only Only output path variables (no prerequisite validation) | |
| 55 | + --help, -h Show this help message | |
| 56 | + | |
| 57 | +EXAMPLES: | |
| 58 | + # Check task prerequisites (plan.md required) | |
| 59 | + ./check-prerequisites.sh --json | |
| 60 | + | |
| 61 | + # Check implementation prerequisites (plan.md + tasks.md required) | |
| 62 | + ./check-prerequisites.sh --json --require-tasks --include-tasks | |
| 63 | + | |
| 64 | + # Get feature paths only (no validation) | |
| 65 | + ./check-prerequisites.sh --paths-only | |
| 66 | + | |
| 67 | +EOF | |
| 68 | + exit 0 | |
| 69 | + ;; | |
| 70 | + *) | |
| 71 | + echo "ERROR: Unknown option '$arg'. Use --help for usage information." >&2 | |
| 72 | + exit 1 | |
| 73 | + ;; | |
| 74 | + esac | |
| 75 | +done | |
| 76 | + | |
| 77 | +# Source common functions | |
| 78 | +SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" | |
| 79 | +source "$SCRIPT_DIR/common.sh" | |
| 80 | + | |
| 81 | +# Get feature paths and validate branch | |
| 82 | +eval $(get_feature_paths) | |
| 83 | +check_feature_branch "$CURRENT_BRANCH" "$HAS_GIT" || exit 1 | |
| 84 | + | |
| 85 | +# If paths-only mode, output paths and exit (support JSON + paths-only combined) | |
| 86 | +if $PATHS_ONLY; then | |
| 87 | + if $JSON_MODE; then | |
| 88 | + # Minimal JSON paths payload (no validation performed) | |
| 89 | + printf '{"REPO_ROOT":"%s","BRANCH":"%s","FEATURE_DIR":"%s","FEATURE_SPEC":"%s","IMPL_PLAN":"%s","TASKS":"%s"}\n' \ | |
| 90 | + "$REPO_ROOT" "$CURRENT_BRANCH" "$FEATURE_DIR" "$FEATURE_SPEC" "$IMPL_PLAN" "$TASKS" | |
| 91 | + else | |
| 92 | + echo "REPO_ROOT: $REPO_ROOT" | |
| 93 | + echo "BRANCH: $CURRENT_BRANCH" | |
| 94 | + echo "FEATURE_DIR: $FEATURE_DIR" | |
| 95 | + echo "FEATURE_SPEC: $FEATURE_SPEC" | |
| 96 | + echo "IMPL_PLAN: $IMPL_PLAN" | |
| 97 | + echo "TASKS: $TASKS" | |
| 98 | + fi | |
| 99 | + exit 0 | |
| 100 | +fi | |
| 101 | + | |
| 102 | +# Validate required directories and files | |
| 103 | +if [[ ! -d "$FEATURE_DIR" ]]; then | |
| 104 | + echo "ERROR: Feature directory not found: $FEATURE_DIR" >&2 | |
| 105 | + echo "Run /speckit.specify first to create the feature structure." >&2 | |
| 106 | + exit 1 | |
| 107 | +fi | |
| 108 | + | |
| 109 | +if [[ ! -f "$IMPL_PLAN" ]]; then | |
| 110 | + echo "ERROR: plan.md not found in $FEATURE_DIR" >&2 | |
| 111 | + echo "Run /speckit.plan first to create the implementation plan." >&2 | |
| 112 | + exit 1 | |
| 113 | +fi | |
| 114 | + | |
| 115 | +# Check for tasks.md if required | |
| 116 | +if $REQUIRE_TASKS && [[ ! -f "$TASKS" ]]; then | |
| 117 | + echo "ERROR: tasks.md not found in $FEATURE_DIR" >&2 | |
| 118 | + echo "Run /speckit.tasks first to create the task list." >&2 | |
| 119 | + exit 1 | |
| 120 | +fi | |
| 121 | + | |
| 122 | +# Build list of available documents | |
| 123 | +docs=() | |
| 124 | + | |
| 125 | +# Always check these optional docs | |
| 126 | +[[ -f "$RESEARCH" ]] && docs+=("research.md") | |
| 127 | +[[ -f "$DATA_MODEL" ]] && docs+=("data-model.md") | |
| 128 | + | |
| 129 | +# Check contracts directory (only if it exists and has files) | |
| 130 | +if [[ -d "$CONTRACTS_DIR" ]] && [[ -n "$(ls -A "$CONTRACTS_DIR" 2>/dev/null)" ]]; then | |
| 131 | + docs+=("contracts/") | |
| 132 | +fi | |
| 133 | + | |
| 134 | +[[ -f "$QUICKSTART" ]] && docs+=("quickstart.md") | |
| 135 | + | |
| 136 | +# Include tasks.md if requested and it exists | |
| 137 | +if $INCLUDE_TASKS && [[ -f "$TASKS" ]]; then | |
| 138 | + docs+=("tasks.md") | |
| 139 | +fi | |
| 140 | + | |
| 141 | +# Output results | |
| 142 | +if $JSON_MODE; then | |
| 143 | + # Build JSON array of documents | |
| 144 | + if [[ ${#docs[@]} -eq 0 ]]; then | |
| 145 | + json_docs="[]" | |
| 146 | + else | |
| 147 | + json_docs=$(printf '"%s",' "${docs[@]}") | |
| 148 | + json_docs="[${json_docs%,}]" | |
| 149 | + fi | |
| 150 | + | |
| 151 | + printf '{"FEATURE_DIR":"%s","AVAILABLE_DOCS":%s}\n' "$FEATURE_DIR" "$json_docs" | |
| 152 | +else | |
| 153 | + # Text output | |
| 154 | + echo "FEATURE_DIR:$FEATURE_DIR" | |
| 155 | + echo "AVAILABLE_DOCS:" | |
| 156 | + | |
| 157 | + # Show status of each potential document | |
| 158 | + check_file "$RESEARCH" "research.md" | |
| 159 | + check_file "$DATA_MODEL" "data-model.md" | |
| 160 | + check_dir "$CONTRACTS_DIR" "contracts/" | |
| 161 | + check_file "$QUICKSTART" "quickstart.md" | |
| 162 | + | |
| 163 | + if $INCLUDE_TASKS; then | |
| 164 | + check_file "$TASKS" "tasks.md" | |
| 165 | + fi | |
| 166 | +fi |
A
.specify/scripts/bash/common.sh
+156
-0
@@ -0,0 +1,156 @@
| 1 | +#!/usr/bin/env bash | |
| 2 | +# Common functions and variables for all scripts | |
| 3 | + | |
| 4 | +# Get repository root, with fallback for non-git repositories | |
| 5 | +get_repo_root() { | |
| 6 | + if git rev-parse --show-toplevel >/dev/null 2>&1; then | |
| 7 | + git rev-parse --show-toplevel | |
| 8 | + else | |
| 9 | + # Fall back to script location for non-git repos | |
| 10 | + local script_dir="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" | |
| 11 | + (cd "$script_dir/../../.." && pwd) | |
| 12 | + fi | |
| 13 | +} | |
| 14 | + | |
| 15 | +# Get current branch, with fallback for non-git repositories | |
| 16 | +get_current_branch() { | |
| 17 | + # First check if SPECIFY_FEATURE environment variable is set | |
| 18 | + if [[ -n "${SPECIFY_FEATURE:-}" ]]; then | |
| 19 | + echo "$SPECIFY_FEATURE" | |
| 20 | + return | |
| 21 | + fi | |
| 22 | + | |
| 23 | + # Then check git if available | |
| 24 | + if git rev-parse --abbrev-ref HEAD >/dev/null 2>&1; then | |
| 25 | + git rev-parse --abbrev-ref HEAD | |
| 26 | + return | |
| 27 | + fi | |
| 28 | + | |
| 29 | + # For non-git repos, try to find the latest feature directory | |
| 30 | + local repo_root=$(get_repo_root) | |
| 31 | + local specs_dir="$repo_root/specs" | |
| 32 | + | |
| 33 | + if [[ -d "$specs_dir" ]]; then | |
| 34 | + local latest_feature="" | |
| 35 | + local highest=0 | |
| 36 | + | |
| 37 | + for dir in "$specs_dir"/*; do | |
| 38 | + if [[ -d "$dir" ]]; then | |
| 39 | + local dirname=$(basename "$dir") | |
| 40 | + if [[ "$dirname" =~ ^([0-9]{3})- ]]; then | |
| 41 | + local number=${BASH_REMATCH[1]} | |
| 42 | + number=$((10#$number)) | |
| 43 | + if [[ "$number" -gt "$highest" ]]; then | |
| 44 | + highest=$number | |
| 45 | + latest_feature=$dirname | |
| 46 | + fi | |
| 47 | + fi | |
| 48 | + fi | |
| 49 | + done | |
| 50 | + | |
| 51 | + if [[ -n "$latest_feature" ]]; then | |
| 52 | + echo "$latest_feature" | |
| 53 | + return | |
| 54 | + fi | |
| 55 | + fi | |
| 56 | + | |
| 57 | + echo "main" # Final fallback | |
| 58 | +} | |
| 59 | + | |
| 60 | +# Check if we have git available | |
| 61 | +has_git() { | |
| 62 | + git rev-parse --show-toplevel >/dev/null 2>&1 | |
| 63 | +} | |
| 64 | + | |
| 65 | +check_feature_branch() { | |
| 66 | + local branch="$1" | |
| 67 | + local has_git_repo="$2" | |
| 68 | + | |
| 69 | + # For non-git repos, we can't enforce branch naming but still provide output | |
| 70 | + if [[ "$has_git_repo" != "true" ]]; then | |
| 71 | + echo "[specify] Warning: Git repository not detected; skipped branch validation" >&2 | |
| 72 | + return 0 | |
| 73 | + fi | |
| 74 | + | |
| 75 | + if [[ ! "$branch" =~ ^[0-9]{3}- ]]; then | |
| 76 | + echo "ERROR: Not on a feature branch. Current branch: $branch" >&2 | |
| 77 | + echo "Feature branches should be named like: 001-feature-name" >&2 | |
| 78 | + return 1 | |
| 79 | + fi | |
| 80 | + | |
| 81 | + return 0 | |
| 82 | +} | |
| 83 | + | |
| 84 | +get_feature_dir() { echo "$1/specs/$2"; } | |
| 85 | + | |
| 86 | +# Find feature directory by numeric prefix instead of exact branch match | |
| 87 | +# This allows multiple branches to work on the same spec (e.g., 004-fix-bug, 004-add-feature) | |
| 88 | +find_feature_dir_by_prefix() { | |
| 89 | + local repo_root="$1" | |
| 90 | + local branch_name="$2" | |
| 91 | + local specs_dir="$repo_root/specs" | |
| 92 | + | |
| 93 | + # Extract numeric prefix from branch (e.g., "004" from "004-whatever") | |
| 94 | + if [[ ! "$branch_name" =~ ^([0-9]{3})- ]]; then | |
| 95 | + # If branch doesn't have numeric prefix, fall back to exact match | |
| 96 | + echo "$specs_dir/$branch_name" | |
| 97 | + return | |
| 98 | + fi | |
| 99 | + | |
| 100 | + local prefix="${BASH_REMATCH[1]}" | |
| 101 | + | |
| 102 | + # Search for directories in specs/ that start with this prefix | |
| 103 | + local matches=() | |
| 104 | + if [[ -d "$specs_dir" ]]; then | |
| 105 | + for dir in "$specs_dir"/"$prefix"-*; do | |
| 106 | + if [[ -d "$dir" ]]; then | |
| 107 | + matches+=("$(basename "$dir")") | |
| 108 | + fi | |
| 109 | + done | |
| 110 | + fi | |
| 111 | + | |
| 112 | + # Handle results | |
| 113 | + if [[ ${#matches[@]} -eq 0 ]]; then | |
| 114 | + # No match found - return the branch name path (will fail later with clear error) | |
| 115 | + echo "$specs_dir/$branch_name" | |
| 116 | + elif [[ ${#matches[@]} -eq 1 ]]; then | |
| 117 | + # Exactly one match - perfect! | |
| 118 | + echo "$specs_dir/${matches[0]}" | |
| 119 | + else | |
| 120 | + # Multiple matches - this shouldn't happen with proper naming convention | |
| 121 | + echo "ERROR: Multiple spec directories found with prefix '$prefix': ${matches[*]}" >&2 | |
| 122 | + echo "Please ensure only one spec directory exists per numeric prefix." >&2 | |
| 123 | + echo "$specs_dir/$branch_name" # Return something to avoid breaking the script | |
| 124 | + fi | |
| 125 | +} | |
| 126 | + | |
| 127 | +get_feature_paths() { | |
| 128 | + local repo_root=$(get_repo_root) | |
| 129 | + local current_branch=$(get_current_branch) | |
| 130 | + local has_git_repo="false" | |
| 131 | + | |
| 132 | + if has_git; then | |
| 133 | + has_git_repo="true" | |
| 134 | + fi | |
| 135 | + | |
| 136 | + # Use prefix-based lookup to support multiple branches per spec | |
| 137 | + local feature_dir=$(find_feature_dir_by_prefix "$repo_root" "$current_branch") | |
| 138 | + | |
| 139 | + cat <<EOF | |
| 140 | +REPO_ROOT='$repo_root' | |
| 141 | +CURRENT_BRANCH='$current_branch' | |
| 142 | +HAS_GIT='$has_git_repo' | |
| 143 | +FEATURE_DIR='$feature_dir' | |
| 144 | +FEATURE_SPEC='$feature_dir/spec.md' | |
| 145 | +IMPL_PLAN='$feature_dir/plan.md' | |
| 146 | +TASKS='$feature_dir/tasks.md' | |
| 147 | +RESEARCH='$feature_dir/research.md' | |
| 148 | +DATA_MODEL='$feature_dir/data-model.md' | |
| 149 | +QUICKSTART='$feature_dir/quickstart.md' | |
| 150 | +CONTRACTS_DIR='$feature_dir/contracts' | |
| 151 | +EOF | |
| 152 | +} | |
| 153 | + | |
| 154 | +check_file() { [[ -f "$1" ]] && echo " ✓ $2" || echo " ✗ $2"; } | |
| 155 | +check_dir() { [[ -d "$1" && -n $(ls -A "$1" 2>/dev/null) ]] && echo " ✓ $2" || echo " ✗ $2"; } | |
| 156 | + |
A
.specify/scripts/bash/create-new-feature.sh
+313
-0
@@ -0,0 +1,313 @@
| 1 | +#!/usr/bin/env bash | |
| 2 | + | |
| 3 | +set -e | |
| 4 | + | |
| 5 | +JSON_MODE=false | |
| 6 | +SHORT_NAME="" | |
| 7 | +BRANCH_NUMBER="" | |
| 8 | +ARGS=() | |
| 9 | +i=1 | |
| 10 | +while [ $i -le $# ]; do | |
| 11 | + arg="${!i}" | |
| 12 | + case "$arg" in | |
| 13 | + --json) | |
| 14 | + JSON_MODE=true | |
| 15 | + ;; | |
| 16 | + --short-name) | |
| 17 | + if [ $((i + 1)) -gt $# ]; then | |
| 18 | + echo 'Error: --short-name requires a value' >&2 | |
| 19 | + exit 1 | |
| 20 | + fi | |
| 21 | + i=$((i + 1)) | |
| 22 | + next_arg="${!i}" | |
| 23 | + # Check if the next argument is another option (starts with --) | |
| 24 | + if [[ "$next_arg" == --* ]]; then | |
| 25 | + echo 'Error: --short-name requires a value' >&2 | |
| 26 | + exit 1 | |
| 27 | + fi | |
| 28 | + SHORT_NAME="$next_arg" | |
| 29 | + ;; | |
| 30 | + --number) | |
| 31 | + if [ $((i + 1)) -gt $# ]; then | |
| 32 | + echo 'Error: --number requires a value' >&2 | |
| 33 | + exit 1 | |
| 34 | + fi | |
| 35 | + i=$((i + 1)) | |
| 36 | + next_arg="${!i}" | |
| 37 | + if [[ "$next_arg" == --* ]]; then | |
| 38 | + echo 'Error: --number requires a value' >&2 | |
| 39 | + exit 1 | |
| 40 | + fi | |
| 41 | + BRANCH_NUMBER="$next_arg" | |
| 42 | + ;; | |
| 43 | + --help|-h) | |
| 44 | + echo "Usage: $0 [--json] [--short-name <name>] [--number N] <feature_description>" | |
| 45 | + echo "" | |
| 46 | + echo "Options:" | |
| 47 | + echo " --json Output in JSON format" | |
| 48 | + echo " --short-name <name> Provide a custom short name (2-4 words) for the branch" | |
| 49 | + echo " --number N Specify branch number manually (overrides auto-detection)" | |
| 50 | + echo " --help, -h Show this help message" | |
| 51 | + echo "" | |
| 52 | + echo "Examples:" | |
| 53 | + echo " $0 'Add user authentication system' --short-name 'user-auth'" | |
| 54 | + echo " $0 'Implement OAuth2 integration for API' --number 5" | |
| 55 | + exit 0 | |
| 56 | + ;; | |
| 57 | + *) | |
| 58 | + ARGS+=("$arg") | |
| 59 | + ;; | |
| 60 | + esac | |
| 61 | + i=$((i + 1)) | |
| 62 | +done | |
| 63 | + | |
| 64 | +FEATURE_DESCRIPTION="${ARGS[*]}" | |
| 65 | +if [ -z "$FEATURE_DESCRIPTION" ]; then | |
| 66 | + echo "Usage: $0 [--json] [--short-name <name>] [--number N] <feature_description>" >&2 | |
| 67 | + exit 1 | |
| 68 | +fi | |
| 69 | + | |
| 70 | +# Trim whitespace and validate description is not empty (e.g., user passed only whitespace) | |
| 71 | +FEATURE_DESCRIPTION=$(echo "$FEATURE_DESCRIPTION" | xargs) | |
| 72 | +if [ -z "$FEATURE_DESCRIPTION" ]; then | |
| 73 | + echo "Error: Feature description cannot be empty or contain only whitespace" >&2 | |
| 74 | + exit 1 | |
| 75 | +fi | |
| 76 | + | |
| 77 | +# Function to find the repository root by searching for existing project markers | |
| 78 | +find_repo_root() { | |
| 79 | + local dir="$1" | |
| 80 | + while [ "$dir" != "/" ]; do | |
| 81 | + if [ -d "$dir/.git" ] || [ -d "$dir/.specify" ]; then | |
| 82 | + echo "$dir" | |
| 83 | + return 0 | |
| 84 | + fi | |
| 85 | + dir="$(dirname "$dir")" | |
| 86 | + done | |
| 87 | + return 1 | |
| 88 | +} | |
| 89 | + | |
| 90 | +# Function to get highest number from specs directory | |
| 91 | +get_highest_from_specs() { | |
| 92 | + local specs_dir="$1" | |
| 93 | + local highest=0 | |
| 94 | + | |
| 95 | + if [ -d "$specs_dir" ]; then | |
| 96 | + for dir in "$specs_dir"/*; do | |
| 97 | + [ -d "$dir" ] || continue | |
| 98 | + dirname=$(basename "$dir") | |
| 99 | + number=$(echo "$dirname" | grep -o '^[0-9]\+' || echo "0") | |
| 100 | + number=$((10#$number)) | |
| 101 | + if [ "$number" -gt "$highest" ]; then | |
| 102 | + highest=$number | |
| 103 | + fi | |
| 104 | + done | |
| 105 | + fi | |
| 106 | + | |
| 107 | + echo "$highest" | |
| 108 | +} | |
| 109 | + | |
| 110 | +# Function to get highest number from git branches | |
| 111 | +get_highest_from_branches() { | |
| 112 | + local highest=0 | |
| 113 | + | |
| 114 | + # Get all branches (local and remote) | |
| 115 | + branches=$(git branch -a 2>/dev/null || echo "") | |
| 116 | + | |
| 117 | + if [ -n "$branches" ]; then | |
| 118 | + while IFS= read -r branch; do | |
| 119 | + # Clean branch name: remove leading markers and remote prefixes | |
| 120 | + clean_branch=$(echo "$branch" | sed 's/^[* ]*//; s|^remotes/[^/]*/||') | |
| 121 | + | |
| 122 | + # Extract feature number if branch matches pattern ###-* | |
| 123 | + if echo "$clean_branch" | grep -q '^[0-9]\{3\}-'; then | |
| 124 | + number=$(echo "$clean_branch" | grep -o '^[0-9]\{3\}' || echo "0") | |
| 125 | + number=$((10#$number)) | |
| 126 | + if [ "$number" -gt "$highest" ]; then | |
| 127 | + highest=$number | |
| 128 | + fi | |
| 129 | + fi | |
| 130 | + done <<< "$branches" | |
| 131 | + fi | |
| 132 | + | |
| 133 | + echo "$highest" | |
| 134 | +} | |
| 135 | + | |
| 136 | +# Function to check existing branches (local and remote) and return next available number | |
| 137 | +check_existing_branches() { | |
| 138 | + local specs_dir="$1" | |
| 139 | + | |
| 140 | + # Fetch all remotes to get latest branch info (suppress errors if no remotes) | |
| 141 | + git fetch --all --prune 2>/dev/null || true | |
| 142 | + | |
| 143 | + # Get highest number from ALL branches (not just matching short name) | |
| 144 | + local highest_branch=$(get_highest_from_branches) | |
| 145 | + | |
| 146 | + # Get highest number from ALL specs (not just matching short name) | |
| 147 | + local highest_spec=$(get_highest_from_specs "$specs_dir") | |
| 148 | + | |
| 149 | + # Take the maximum of both | |
| 150 | + local max_num=$highest_branch | |
| 151 | + if [ "$highest_spec" -gt "$max_num" ]; then | |
| 152 | + max_num=$highest_spec | |
| 153 | + fi | |
| 154 | + | |
| 155 | + # Return next number | |
| 156 | + echo $((max_num + 1)) | |
| 157 | +} | |
| 158 | + | |
| 159 | +# Function to clean and format a branch name | |
| 160 | +clean_branch_name() { | |
| 161 | + local name="$1" | |
| 162 | + echo "$name" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/-\+/-/g' | sed 's/^-//' | sed 's/-$//' | |
| 163 | +} | |
| 164 | + | |
| 165 | +# Resolve repository root. Prefer git information when available, but fall back | |
| 166 | +# to searching for repository markers so the workflow still functions in repositories that | |
| 167 | +# were initialised with --no-git. | |
| 168 | +SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" | |
| 169 | + | |
| 170 | +if git rev-parse --show-toplevel >/dev/null 2>&1; then | |
| 171 | + REPO_ROOT=$(git rev-parse --show-toplevel) | |
| 172 | + HAS_GIT=true | |
| 173 | +else | |
| 174 | + REPO_ROOT="$(find_repo_root "$SCRIPT_DIR")" | |
| 175 | + if [ -z "$REPO_ROOT" ]; then | |
| 176 | + echo "Error: Could not determine repository root. Please run this script from within the repository." >&2 | |
| 177 | + exit 1 | |
| 178 | + fi | |
| 179 | + HAS_GIT=false | |
| 180 | +fi | |
| 181 | + | |
| 182 | +cd "$REPO_ROOT" | |
| 183 | + | |
| 184 | +SPECS_DIR="$REPO_ROOT/specs" | |
| 185 | +mkdir -p "$SPECS_DIR" | |
| 186 | + | |
| 187 | +# Function to generate branch name with stop word filtering and length filtering | |
| 188 | +generate_branch_name() { | |
| 189 | + local description="$1" | |
| 190 | + | |
| 191 | + # Common stop words to filter out | |
| 192 | + local stop_words="^(i|a|an|the|to|for|of|in|on|at|by|with|from|is|are|was|were|be|been|being|have|has|had|do|does|did|will|would|should|could|can|may|might|must|shall|this|that|these|those|my|your|our|their|want|need|add|get|set)$" | |
| 193 | + | |
| 194 | + # Convert to lowercase and split into words | |
| 195 | + local clean_name=$(echo "$description" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/ /g') | |
| 196 | + | |
| 197 | + # Filter words: remove stop words and words shorter than 3 chars (unless they're uppercase acronyms in original) | |
| 198 | + local meaningful_words=() | |
| 199 | + for word in $clean_name; do | |
| 200 | + # Skip empty words | |
| 201 | + [ -z "$word" ] && continue | |
| 202 | + | |
| 203 | + # Keep words that are NOT stop words AND (length >= 3 OR are potential acronyms) | |
| 204 | + if ! echo "$word" | grep -qiE "$stop_words"; then | |
| 205 | + if [ ${#word} -ge 3 ]; then | |
| 206 | + meaningful_words+=("$word") | |
| 207 | + elif echo "$description" | grep -q "\b${word^^}\b"; then | |
| 208 | + # Keep short words if they appear as uppercase in original (likely acronyms) | |
| 209 | + meaningful_words+=("$word") | |
| 210 | + fi | |
| 211 | + fi | |
| 212 | + done | |
| 213 | + | |
| 214 | + # If we have meaningful words, use first 3-4 of them | |
| 215 | + if [ ${#meaningful_words[@]} -gt 0 ]; then | |
| 216 | + local max_words=3 | |
| 217 | + if [ ${#meaningful_words[@]} -eq 4 ]; then max_words=4; fi | |
| 218 | + | |
| 219 | + local result="" | |
| 220 | + local count=0 | |
| 221 | + for word in "${meaningful_words[@]}"; do | |
| 222 | + if [ $count -ge $max_words ]; then break; fi | |
| 223 | + if [ -n "$result" ]; then result="$result-"; fi | |
| 224 | + result="$result$word" | |
| 225 | + count=$((count + 1)) | |
| 226 | + done | |
| 227 | + echo "$result" | |
| 228 | + else | |
| 229 | + # Fallback to original logic if no meaningful words found | |
| 230 | + local cleaned=$(clean_branch_name "$description") | |
| 231 | + echo "$cleaned" | tr '-' '\n' | grep -v '^$' | head -3 | tr '\n' '-' | sed 's/-$//' | |
| 232 | + fi | |
| 233 | +} | |
| 234 | + | |
| 235 | +# Generate branch name | |
| 236 | +if [ -n "$SHORT_NAME" ]; then | |
| 237 | + # Use provided short name, just clean it up | |
| 238 | + BRANCH_SUFFIX=$(clean_branch_name "$SHORT_NAME") | |
| 239 | +else | |
| 240 | + # Generate from description with smart filtering | |
| 241 | + BRANCH_SUFFIX=$(generate_branch_name "$FEATURE_DESCRIPTION") | |
| 242 | +fi | |
| 243 | + | |
| 244 | +# Determine branch number | |
| 245 | +if [ -z "$BRANCH_NUMBER" ]; then | |
| 246 | + if [ "$HAS_GIT" = true ]; then | |
| 247 | + # Check existing branches on remotes | |
| 248 | + BRANCH_NUMBER=$(check_existing_branches "$SPECS_DIR") | |
| 249 | + else | |
| 250 | + # Fall back to local directory check | |
| 251 | + HIGHEST=$(get_highest_from_specs "$SPECS_DIR") | |
| 252 | + BRANCH_NUMBER=$((HIGHEST + 1)) | |
| 253 | + fi | |
| 254 | +fi | |
| 255 | + | |
| 256 | +# Force base-10 interpretation to prevent octal conversion (e.g., 010 → 8 in octal, but should be 10 in decimal) | |
| 257 | +FEATURE_NUM=$(printf "%03d" "$((10#$BRANCH_NUMBER))") | |
| 258 | +BRANCH_NAME="${FEATURE_NUM}-${BRANCH_SUFFIX}" | |
| 259 | + | |
| 260 | +# GitHub enforces a 244-byte limit on branch names | |
| 261 | +# Validate and truncate if necessary | |
| 262 | +MAX_BRANCH_LENGTH=244 | |
| 263 | +if [ ${#BRANCH_NAME} -gt $MAX_BRANCH_LENGTH ]; then | |
| 264 | + # Calculate how much we need to trim from suffix | |
| 265 | + # Account for: feature number (3) + hyphen (1) = 4 chars | |
| 266 | + MAX_SUFFIX_LENGTH=$((MAX_BRANCH_LENGTH - 4)) | |
| 267 | + | |
| 268 | + # Truncate suffix at word boundary if possible | |
| 269 | + TRUNCATED_SUFFIX=$(echo "$BRANCH_SUFFIX" | cut -c1-$MAX_SUFFIX_LENGTH) | |
| 270 | + # Remove trailing hyphen if truncation created one | |
| 271 | + TRUNCATED_SUFFIX=$(echo "$TRUNCATED_SUFFIX" | sed 's/-$//') | |
| 272 | + | |
| 273 | + ORIGINAL_BRANCH_NAME="$BRANCH_NAME" | |
| 274 | + BRANCH_NAME="${FEATURE_NUM}-${TRUNCATED_SUFFIX}" | |
| 275 | + | |
| 276 | + >&2 echo "[specify] Warning: Branch name exceeded GitHub's 244-byte limit" | |
| 277 | + >&2 echo "[specify] Original: $ORIGINAL_BRANCH_NAME (${#ORIGINAL_BRANCH_NAME} bytes)" | |
| 278 | + >&2 echo "[specify] Truncated to: $BRANCH_NAME (${#BRANCH_NAME} bytes)" | |
| 279 | +fi | |
| 280 | + | |
| 281 | +if [ "$HAS_GIT" = true ]; then | |
| 282 | + if ! git checkout -b "$BRANCH_NAME" 2>/dev/null; then | |
| 283 | + # Check if branch already exists | |
| 284 | + if git branch --list "$BRANCH_NAME" | grep -q .; then | |
| 285 | + >&2 echo "Error: Branch '$BRANCH_NAME' already exists. Please use a different feature name or specify a different number with --number." | |
| 286 | + exit 1 | |
| 287 | + else | |
| 288 | + >&2 echo "Error: Failed to create git branch '$BRANCH_NAME'. Please check your git configuration and try again." | |
| 289 | + exit 1 | |
| 290 | + fi | |
| 291 | + fi | |
| 292 | +else | |
| 293 | + >&2 echo "[specify] Warning: Git repository not detected; skipped branch creation for $BRANCH_NAME" | |
| 294 | +fi | |
| 295 | + | |
| 296 | +FEATURE_DIR="$SPECS_DIR/$BRANCH_NAME" | |
| 297 | +mkdir -p "$FEATURE_DIR" | |
| 298 | + | |
| 299 | +TEMPLATE="$REPO_ROOT/.specify/templates/spec-template.md" | |
| 300 | +SPEC_FILE="$FEATURE_DIR/spec.md" | |
| 301 | +if [ -f "$TEMPLATE" ]; then cp "$TEMPLATE" "$SPEC_FILE"; else touch "$SPEC_FILE"; fi | |
| 302 | + | |
| 303 | +# Set the SPECIFY_FEATURE environment variable for the current session | |
| 304 | +export SPECIFY_FEATURE="$BRANCH_NAME" | |
| 305 | + | |
| 306 | +if $JSON_MODE; then | |
| 307 | + printf '{"BRANCH_NAME":"%s","SPEC_FILE":"%s","FEATURE_NUM":"%s"}\n' "$BRANCH_NAME" "$SPEC_FILE" "$FEATURE_NUM" | |
| 308 | +else | |
| 309 | + echo "BRANCH_NAME: $BRANCH_NAME" | |
| 310 | + echo "SPEC_FILE: $SPEC_FILE" | |
| 311 | + echo "FEATURE_NUM: $FEATURE_NUM" | |
| 312 | + echo "SPECIFY_FEATURE environment variable set to: $BRANCH_NAME" | |
| 313 | +fi |
A
.specify/scripts/bash/setup-plan.sh
+61
-0
@@ -0,0 +1,61 @@
| 1 | +#!/usr/bin/env bash | |
| 2 | + | |
| 3 | +set -e | |
| 4 | + | |
| 5 | +# Parse command line arguments | |
| 6 | +JSON_MODE=false | |
| 7 | +ARGS=() | |
| 8 | + | |
| 9 | +for arg in "$@"; do | |
| 10 | + case "$arg" in | |
| 11 | + --json) | |
| 12 | + JSON_MODE=true | |
| 13 | + ;; | |
| 14 | + --help|-h) | |
| 15 | + echo "Usage: $0 [--json]" | |
| 16 | + echo " --json Output results in JSON format" | |
| 17 | + echo " --help Show this help message" | |
| 18 | + exit 0 | |
| 19 | + ;; | |
| 20 | + *) | |
| 21 | + ARGS+=("$arg") | |
| 22 | + ;; | |
| 23 | + esac | |
| 24 | +done | |
| 25 | + | |
| 26 | +# Get script directory and load common functions | |
| 27 | +SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" | |
| 28 | +source "$SCRIPT_DIR/common.sh" | |
| 29 | + | |
| 30 | +# Get all paths and variables from common functions | |
| 31 | +eval $(get_feature_paths) | |
| 32 | + | |
| 33 | +# Check if we're on a proper feature branch (only for git repos) | |
| 34 | +check_feature_branch "$CURRENT_BRANCH" "$HAS_GIT" || exit 1 | |
| 35 | + | |
| 36 | +# Ensure the feature directory exists | |
| 37 | +mkdir -p "$FEATURE_DIR" | |
| 38 | + | |
| 39 | +# Copy plan template if it exists | |
| 40 | +TEMPLATE="$REPO_ROOT/.specify/templates/plan-template.md" | |
| 41 | +if [[ -f "$TEMPLATE" ]]; then | |
| 42 | + cp "$TEMPLATE" "$IMPL_PLAN" | |
| 43 | + echo "Copied plan template to $IMPL_PLAN" | |
| 44 | +else | |
| 45 | + echo "Warning: Plan template not found at $TEMPLATE" | |
| 46 | + # Create a basic plan file if template doesn't exist | |
| 47 | + touch "$IMPL_PLAN" | |
| 48 | +fi | |
| 49 | + | |
| 50 | +# Output results | |
| 51 | +if $JSON_MODE; then | |
| 52 | + printf '{"FEATURE_SPEC":"%s","IMPL_PLAN":"%s","SPECS_DIR":"%s","BRANCH":"%s","HAS_GIT":"%s"}\n' \ | |
| 53 | + "$FEATURE_SPEC" "$IMPL_PLAN" "$FEATURE_DIR" "$CURRENT_BRANCH" "$HAS_GIT" | |
| 54 | +else | |
| 55 | + echo "FEATURE_SPEC: $FEATURE_SPEC" | |
| 56 | + echo "IMPL_PLAN: $IMPL_PLAN" | |
| 57 | + echo "SPECS_DIR: $FEATURE_DIR" | |
| 58 | + echo "BRANCH: $CURRENT_BRANCH" | |
| 59 | + echo "HAS_GIT: $HAS_GIT" | |
| 60 | +fi | |
| 61 | + |
A
.specify/scripts/bash/update-agent-context.sh
+829
-0
@@ -0,0 +1,829 @@
| 1 | +#!/usr/bin/env bash | |
| 2 | + | |
| 3 | +# Update agent context files with information from plan.md | |
| 4 | +# | |
| 5 | +# This script maintains AI agent context files by parsing feature specifications | |
| 6 | +# and updating agent-specific configuration files with project information. | |
| 7 | +# | |
| 8 | +# MAIN FUNCTIONS: | |
| 9 | +# 1. Environment Validation | |
| 10 | +# - Verifies git repository structure and branch information | |
| 11 | +# - Checks for required plan.md files and templates | |
| 12 | +# - Validates file permissions and accessibility | |
| 13 | +# | |
| 14 | +# 2. Plan Data Extraction | |
| 15 | +# - Parses plan.md files to extract project metadata | |
| 16 | +# - Identifies language/version, frameworks, databases, and project types | |
| 17 | +# - Handles missing or incomplete specification data gracefully | |
| 18 | +# | |
| 19 | +# 3. Agent File Management | |
| 20 | +# - Creates new agent context files from templates when needed | |
| 21 | +# - Updates existing agent files with new project information | |
| 22 | +# - Preserves manual additions and custom configurations | |
| 23 | +# - Supports multiple AI agent formats and directory structures | |
| 24 | +# | |
| 25 | +# 4. Content Generation | |
| 26 | +# - Generates language-specific build/test commands | |
| 27 | +# - Creates appropriate project directory structures | |
| 28 | +# - Updates technology stacks and recent changes sections | |
| 29 | +# - Maintains consistent formatting and timestamps | |
| 30 | +# | |
| 31 | +# 5. Multi-Agent Support | |
| 32 | +# - Handles agent-specific file paths and naming conventions | |
| 33 | +# - Supports: Claude, Gemini, Copilot, Cursor, Qwen, opencode, Codex, Windsurf, Kilo Code, Auggie CLI, Roo Code, CodeBuddy CLI, Qoder CLI, Amp, SHAI, Kiro CLI, or Antigravity | |
| 34 | +# - Can update single agents or all existing agent files | |
| 35 | +# - Creates default Claude file if no agent files exist | |
| 36 | +# | |
| 37 | +# Usage: ./update-agent-context.sh [agent_type] | |
| 38 | +# Agent types: claude|gemini|copilot|cursor-agent|qwen|opencode|codex|windsurf|kilocode|auggie|roo|codebuddy|amp|shai|kiro-cli|agy|bob|qodercli | |
| 39 | +# Leave empty to update all existing agent files | |
| 40 | + | |
| 41 | +set -e | |
| 42 | + | |
| 43 | +# Enable strict error handling | |
| 44 | +set -u | |
| 45 | +set -o pipefail | |
| 46 | + | |
| 47 | +#============================================================================== | |
| 48 | +# Configuration and Global Variables | |
| 49 | +#============================================================================== | |
| 50 | + | |
| 51 | +# Get script directory and load common functions | |
| 52 | +SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" | |
| 53 | +source "$SCRIPT_DIR/common.sh" | |
| 54 | + | |
| 55 | +# Get all paths and variables from common functions | |
| 56 | +eval $(get_feature_paths) | |
| 57 | + | |
| 58 | +NEW_PLAN="$IMPL_PLAN" # Alias for compatibility with existing code | |
| 59 | +AGENT_TYPE="${1:-}" | |
| 60 | + | |
| 61 | +# Agent-specific file paths | |
| 62 | +CLAUDE_FILE="$REPO_ROOT/CLAUDE.md" | |
| 63 | +GEMINI_FILE="$REPO_ROOT/GEMINI.md" | |
| 64 | +COPILOT_FILE="$REPO_ROOT/.github/agents/copilot-instructions.md" | |
| 65 | +CURSOR_FILE="$REPO_ROOT/.cursor/rules/specify-rules.mdc" | |
| 66 | +QWEN_FILE="$REPO_ROOT/QWEN.md" | |
| 67 | +AGENTS_FILE="$REPO_ROOT/AGENTS.md" | |
| 68 | +WINDSURF_FILE="$REPO_ROOT/.windsurf/rules/specify-rules.md" | |
| 69 | +KILOCODE_FILE="$REPO_ROOT/.kilocode/rules/specify-rules.md" | |
| 70 | +AUGGIE_FILE="$REPO_ROOT/.augment/rules/specify-rules.md" | |
| 71 | +ROO_FILE="$REPO_ROOT/.roo/rules/specify-rules.md" | |
| 72 | +CODEBUDDY_FILE="$REPO_ROOT/CODEBUDDY.md" | |
| 73 | +QODER_FILE="$REPO_ROOT/QODER.md" | |
| 74 | +AMP_FILE="$REPO_ROOT/AGENTS.md" | |
| 75 | +SHAI_FILE="$REPO_ROOT/SHAI.md" | |
| 76 | +KIRO_FILE="$REPO_ROOT/AGENTS.md" | |
| 77 | +AGY_FILE="$REPO_ROOT/.agent/rules/specify-rules.md" | |
| 78 | +BOB_FILE="$REPO_ROOT/AGENTS.md" | |
| 79 | + | |
| 80 | +# Template file | |
| 81 | +TEMPLATE_FILE="$REPO_ROOT/.specify/templates/agent-file-template.md" | |
| 82 | + | |
| 83 | +# Global variables for parsed plan data | |
| 84 | +NEW_LANG="" | |
| 85 | +NEW_FRAMEWORK="" | |
| 86 | +NEW_DB="" | |
| 87 | +NEW_PROJECT_TYPE="" | |
| 88 | + | |
| 89 | +#============================================================================== | |
| 90 | +# Utility Functions | |
| 91 | +#============================================================================== | |
| 92 | + | |
| 93 | +log_info() { | |
| 94 | + echo "INFO: $1" | |
| 95 | +} | |
| 96 | + | |
| 97 | +log_success() { | |
| 98 | + echo "✓ $1" | |
| 99 | +} | |
| 100 | + | |
| 101 | +log_error() { | |
| 102 | + echo "ERROR: $1" >&2 | |
| 103 | +} | |
| 104 | + | |
| 105 | +log_warning() { | |
| 106 | + echo "WARNING: $1" >&2 | |
| 107 | +} | |
| 108 | + | |
| 109 | +# Cleanup function for temporary files | |
| 110 | +cleanup() { | |
| 111 | + local exit_code=$? | |
| 112 | + rm -f /tmp/agent_update_*_$$ | |
| 113 | + rm -f /tmp/manual_additions_$$ | |
| 114 | + exit $exit_code | |
| 115 | +} | |
| 116 | + | |
| 117 | +# Set up cleanup trap | |
| 118 | +trap cleanup EXIT INT TERM | |
| 119 | + | |
| 120 | +#============================================================================== | |
| 121 | +# Validation Functions | |
| 122 | +#============================================================================== | |
| 123 | + | |
| 124 | +validate_environment() { | |
| 125 | + # Check if we have a current branch/feature (git or non-git) | |
| 126 | + if [[ -z "$CURRENT_BRANCH" ]]; then | |
| 127 | + log_error "Unable to determine current feature" | |
| 128 | + if [[ "$HAS_GIT" == "true" ]]; then | |
| 129 | + log_info "Make sure you're on a feature branch" | |
| 130 | + else | |
| 131 | + log_info "Set SPECIFY_FEATURE environment variable or create a feature first" | |
| 132 | + fi | |
| 133 | + exit 1 | |
| 134 | + fi | |
| 135 | + | |
| 136 | + # Check if plan.md exists | |
| 137 | + if [[ ! -f "$NEW_PLAN" ]]; then | |
| 138 | + log_error "No plan.md found at $NEW_PLAN" | |
| 139 | + log_info "Make sure you're working on a feature with a corresponding spec directory" | |
| 140 | + if [[ "$HAS_GIT" != "true" ]]; then | |
| 141 | + log_info "Use: export SPECIFY_FEATURE=your-feature-name or create a new feature first" | |
| 142 | + fi | |
| 143 | + exit 1 | |
| 144 | + fi | |
| 145 | + | |
| 146 | + # Check if template exists (needed for new files) | |
| 147 | + if [[ ! -f "$TEMPLATE_FILE" ]]; then | |
| 148 | + log_warning "Template file not found at $TEMPLATE_FILE" | |
| 149 | + log_warning "Creating new agent files will fail" | |
| 150 | + fi | |
| 151 | +} | |
| 152 | + | |
| 153 | +#============================================================================== | |
| 154 | +# Plan Parsing Functions | |
| 155 | +#============================================================================== | |
| 156 | + | |
| 157 | +extract_plan_field() { | |
| 158 | + local field_pattern="$1" | |
| 159 | + local plan_file="$2" | |
| 160 | + | |
| 161 | + grep "^\*\*${field_pattern}\*\*: " "$plan_file" 2>/dev/null | \ | |
| 162 | + head -1 | \ | |
| 163 | + sed "s|^\*\*${field_pattern}\*\*: ||" | \ | |
| 164 | + sed 's/^[ \t]*//;s/[ \t]*$//' | \ | |
| 165 | + grep -v "NEEDS CLARIFICATION" | \ | |
| 166 | + grep -v "^N/A$" || echo "" | |
| 167 | +} | |
| 168 | + | |
| 169 | +parse_plan_data() { | |
| 170 | + local plan_file="$1" | |
| 171 | + | |
| 172 | + if [[ ! -f "$plan_file" ]]; then | |
| 173 | + log_error "Plan file not found: $plan_file" | |
| 174 | + return 1 | |
| 175 | + fi | |
| 176 | + | |
| 177 | + if [[ ! -r "$plan_file" ]]; then | |
| 178 | + log_error "Plan file is not readable: $plan_file" | |
| 179 | + return 1 | |
| 180 | + fi | |
| 181 | + | |
| 182 | + log_info "Parsing plan data from $plan_file" | |
| 183 | + | |
| 184 | + NEW_LANG=$(extract_plan_field "Language/Version" "$plan_file") | |
| 185 | + NEW_FRAMEWORK=$(extract_plan_field "Primary Dependencies" "$plan_file") | |
| 186 | + NEW_DB=$(extract_plan_field "Storage" "$plan_file") | |
| 187 | + NEW_PROJECT_TYPE=$(extract_plan_field "Project Type" "$plan_file") | |
| 188 | + | |
| 189 | + # Log what we found | |
| 190 | + if [[ -n "$NEW_LANG" ]]; then | |
| 191 | + log_info "Found language: $NEW_LANG" | |
| 192 | + else | |
| 193 | + log_warning "No language information found in plan" | |
| 194 | + fi | |
| 195 | + | |
| 196 | + if [[ -n "$NEW_FRAMEWORK" ]]; then | |
| 197 | + log_info "Found framework: $NEW_FRAMEWORK" | |
| 198 | + fi | |
| 199 | + | |
| 200 | + if [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]]; then | |
| 201 | + log_info "Found database: $NEW_DB" | |
| 202 | + fi | |
| 203 | + | |
| 204 | + if [[ -n "$NEW_PROJECT_TYPE" ]]; then | |
| 205 | + log_info "Found project type: $NEW_PROJECT_TYPE" | |
| 206 | + fi | |
| 207 | +} | |
| 208 | + | |
| 209 | +format_technology_stack() { | |
| 210 | + local lang="$1" | |
| 211 | + local framework="$2" | |
| 212 | + local parts=() | |
| 213 | + | |
| 214 | + # Add non-empty parts | |
| 215 | + [[ -n "$lang" && "$lang" != "NEEDS CLARIFICATION" ]] && parts+=("$lang") | |
| 216 | + [[ -n "$framework" && "$framework" != "NEEDS CLARIFICATION" && "$framework" != "N/A" ]] && parts+=("$framework") | |
| 217 | + | |
| 218 | + # Join with proper formatting | |
| 219 | + if [[ ${#parts[@]} -eq 0 ]]; then | |
| 220 | + echo "" | |
| 221 | + elif [[ ${#parts[@]} -eq 1 ]]; then | |
| 222 | + echo "${parts[0]}" | |
| 223 | + else | |
| 224 | + # Join multiple parts with " + " | |
| 225 | + local result="${parts[0]}" | |
| 226 | + for ((i=1; i<${#parts[@]}; i++)); do | |
| 227 | + result="$result + ${parts[i]}" | |
| 228 | + done | |
| 229 | + echo "$result" | |
| 230 | + fi | |
| 231 | +} | |
| 232 | + | |
| 233 | +#============================================================================== | |
| 234 | +# Template and Content Generation Functions | |
| 235 | +#============================================================================== | |
| 236 | + | |
| 237 | +get_project_structure() { | |
| 238 | + local project_type="$1" | |
| 239 | + | |
| 240 | + if [[ "$project_type" == *"web"* ]]; then | |
| 241 | + echo "backend/\\nfrontend/\\ntests/" | |
| 242 | + else | |
| 243 | + echo "src/\\ntests/" | |
| 244 | + fi | |
| 245 | +} | |
| 246 | + | |
| 247 | +get_commands_for_language() { | |
| 248 | + local lang="$1" | |
| 249 | + | |
| 250 | + case "$lang" in | |
| 251 | + *"Python"*) | |
| 252 | + echo "cd src && pytest && ruff check ." | |
| 253 | + ;; | |
| 254 | + *"Rust"*) | |
| 255 | + echo "cargo test && cargo clippy" | |
| 256 | + ;; | |
| 257 | + *"JavaScript"*|*"TypeScript"*) | |
| 258 | + echo "npm test \\&\\& npm run lint" | |
| 259 | + ;; | |
| 260 | + *) | |
| 261 | + echo "# Add commands for $lang" | |
| 262 | + ;; | |
| 263 | + esac | |
| 264 | +} | |
| 265 | + | |
| 266 | +get_language_conventions() { | |
| 267 | + local lang="$1" | |
| 268 | + echo "$lang: Follow standard conventions" | |
| 269 | +} | |
| 270 | + | |
| 271 | +create_new_agent_file() { | |
| 272 | + local target_file="$1" | |
| 273 | + local temp_file="$2" | |
| 274 | + local project_name="$3" | |
| 275 | + local current_date="$4" | |
| 276 | + | |
| 277 | + if [[ ! -f "$TEMPLATE_FILE" ]]; then | |
| 278 | + log_error "Template not found at $TEMPLATE_FILE" | |
| 279 | + return 1 | |
| 280 | + fi | |
| 281 | + | |
| 282 | + if [[ ! -r "$TEMPLATE_FILE" ]]; then | |
| 283 | + log_error "Template file is not readable: $TEMPLATE_FILE" | |
| 284 | + return 1 | |
| 285 | + fi | |
| 286 | + | |
| 287 | + log_info "Creating new agent context file from template..." | |
| 288 | + | |
| 289 | + if ! cp "$TEMPLATE_FILE" "$temp_file"; then | |
| 290 | + log_error "Failed to copy template file" | |
| 291 | + return 1 | |
| 292 | + fi | |
| 293 | + | |
| 294 | + # Replace template placeholders | |
| 295 | + local project_structure | |
| 296 | + project_structure=$(get_project_structure "$NEW_PROJECT_TYPE") | |
| 297 | + | |
| 298 | + local commands | |
| 299 | + commands=$(get_commands_for_language "$NEW_LANG") | |
| 300 | + | |
| 301 | + local language_conventions | |
| 302 | + language_conventions=$(get_language_conventions "$NEW_LANG") | |
| 303 | + | |
| 304 | + # Perform substitutions with error checking using safer approach | |
| 305 | + # Escape special characters for sed by using a different delimiter or escaping | |
| 306 | + local escaped_lang=$(printf '%s\n' "$NEW_LANG" | sed 's/[\[\.*^$()+{}|]/\\&/g') | |
| 307 | + local escaped_framework=$(printf '%s\n' "$NEW_FRAMEWORK" | sed 's/[\[\.*^$()+{}|]/\\&/g') | |
| 308 | + local escaped_branch=$(printf '%s\n' "$CURRENT_BRANCH" | sed 's/[\[\.*^$()+{}|]/\\&/g') | |
| 309 | + | |
| 310 | + # Build technology stack and recent change strings conditionally | |
| 311 | + local tech_stack | |
| 312 | + if [[ -n "$escaped_lang" && -n "$escaped_framework" ]]; then | |
| 313 | + tech_stack="- $escaped_lang + $escaped_framework ($escaped_branch)" | |
| 314 | + elif [[ -n "$escaped_lang" ]]; then | |
| 315 | + tech_stack="- $escaped_lang ($escaped_branch)" | |
| 316 | + elif [[ -n "$escaped_framework" ]]; then | |
| 317 | + tech_stack="- $escaped_framework ($escaped_branch)" | |
| 318 | + else | |
| 319 | + tech_stack="- ($escaped_branch)" | |
| 320 | + fi | |
| 321 | + | |
| 322 | + local recent_change | |
| 323 | + if [[ -n "$escaped_lang" && -n "$escaped_framework" ]]; then | |
| 324 | + recent_change="- $escaped_branch: Added $escaped_lang + $escaped_framework" | |
| 325 | + elif [[ -n "$escaped_lang" ]]; then | |
| 326 | + recent_change="- $escaped_branch: Added $escaped_lang" | |
| 327 | + elif [[ -n "$escaped_framework" ]]; then | |
| 328 | + recent_change="- $escaped_branch: Added $escaped_framework" | |
| 329 | + else | |
| 330 | + recent_change="- $escaped_branch: Added" | |
| 331 | + fi | |
| 332 | + | |
| 333 | + local substitutions=( | |
| 334 | + "s|\[PROJECT NAME\]|$project_name|" | |
| 335 | + "s|\[DATE\]|$current_date|" | |
| 336 | + "s|\[EXTRACTED FROM ALL PLAN.MD FILES\]|$tech_stack|" | |
| 337 | + "s|\[ACTUAL STRUCTURE FROM PLANS\]|$project_structure|g" | |
| 338 | + "s|\[ONLY COMMANDS FOR ACTIVE TECHNOLOGIES\]|$commands|" | |
| 339 | + "s|\[LANGUAGE-SPECIFIC, ONLY FOR LANGUAGES IN USE\]|$language_conventions|" | |
| 340 | + "s|\[LAST 3 FEATURES AND WHAT THEY ADDED\]|$recent_change|" | |
| 341 | + ) | |
| 342 | + | |
| 343 | + for substitution in "${substitutions[@]}"; do | |
| 344 | + if ! sed -i.bak -e "$substitution" "$temp_file"; then | |
| 345 | + log_error "Failed to perform substitution: $substitution" | |
| 346 | + rm -f "$temp_file" "$temp_file.bak" | |
| 347 | + return 1 | |
| 348 | + fi | |
| 349 | + done | |
| 350 | + | |
| 351 | + # Convert \n sequences to actual newlines | |
| 352 | + newline=$(printf '\n') | |
| 353 | + sed -i.bak2 "s/\\\\n/${newline}/g" "$temp_file" | |
| 354 | + | |
| 355 | + # Clean up backup files | |
| 356 | + rm -f "$temp_file.bak" "$temp_file.bak2" | |
| 357 | + | |
| 358 | + # Prepend Cursor frontmatter for .mdc files so rules are auto-included | |
| 359 | + if [[ "$target_file" == *.mdc ]]; then | |
| 360 | + local frontmatter_file | |
| 361 | + frontmatter_file=$(mktemp) || return 1 | |
| 362 | + printf '%s\n' "---" "description: Project Development Guidelines" "globs: [\"**/*\"]" "alwaysApply: true" "---" "" > "$frontmatter_file" | |
| 363 | + cat "$temp_file" >> "$frontmatter_file" | |
| 364 | + mv "$frontmatter_file" "$temp_file" | |
| 365 | + fi | |
| 366 | + | |
| 367 | + return 0 | |
| 368 | +} | |
| 369 | + | |
| 370 | + | |
| 371 | + | |
| 372 | + | |
| 373 | +update_existing_agent_file() { | |
| 374 | + local target_file="$1" | |
| 375 | + local current_date="$2" | |
| 376 | + | |
| 377 | + log_info "Updating existing agent context file..." | |
| 378 | + | |
| 379 | + # Use a single temporary file for atomic update | |
| 380 | + local temp_file | |
| 381 | + temp_file=$(mktemp) || { | |
| 382 | + log_error "Failed to create temporary file" | |
| 383 | + return 1 | |
| 384 | + } | |
| 385 | + | |
| 386 | + # Process the file in one pass | |
| 387 | + local tech_stack=$(format_technology_stack "$NEW_LANG" "$NEW_FRAMEWORK") | |
| 388 | + local new_tech_entries=() | |
| 389 | + local new_change_entry="" | |
| 390 | + | |
| 391 | + # Prepare new technology entries | |
| 392 | + if [[ -n "$tech_stack" ]] && ! grep -q "$tech_stack" "$target_file"; then | |
| 393 | + new_tech_entries+=("- $tech_stack ($CURRENT_BRANCH)") | |
| 394 | + fi | |
| 395 | + | |
| 396 | + if [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]] && [[ "$NEW_DB" != "NEEDS CLARIFICATION" ]] && ! grep -q "$NEW_DB" "$target_file"; then | |
| 397 | + new_tech_entries+=("- $NEW_DB ($CURRENT_BRANCH)") | |
| 398 | + fi | |
| 399 | + | |
| 400 | + # Prepare new change entry | |
| 401 | + if [[ -n "$tech_stack" ]]; then | |
| 402 | + new_change_entry="- $CURRENT_BRANCH: Added $tech_stack" | |
| 403 | + elif [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]] && [[ "$NEW_DB" != "NEEDS CLARIFICATION" ]]; then | |
| 404 | + new_change_entry="- $CURRENT_BRANCH: Added $NEW_DB" | |
| 405 | + fi | |
| 406 | + | |
| 407 | + # Check if sections exist in the file | |
| 408 | + local has_active_technologies=0 | |
| 409 | + local has_recent_changes=0 | |
| 410 | + | |
| 411 | + if grep -q "^## Active Technologies" "$target_file" 2>/dev/null; then | |
| 412 | + has_active_technologies=1 | |
| 413 | + fi | |
| 414 | + | |
| 415 | + if grep -q "^## Recent Changes" "$target_file" 2>/dev/null; then | |
| 416 | + has_recent_changes=1 | |
| 417 | + fi | |
| 418 | + | |
| 419 | + # Process file line by line | |
| 420 | + local in_tech_section=false | |
| 421 | + local in_changes_section=false | |
| 422 | + local tech_entries_added=false | |
| 423 | + local changes_entries_added=false | |
| 424 | + local existing_changes_count=0 | |
| 425 | + local file_ended=false | |
| 426 | + | |
| 427 | + while IFS= read -r line || [[ -n "$line" ]]; do | |
| 428 | + # Handle Active Technologies section | |
| 429 | + if [[ "$line" == "## Active Technologies" ]]; then | |
| 430 | + echo "$line" >> "$temp_file" | |
| 431 | + in_tech_section=true | |
| 432 | + continue | |
| 433 | + elif [[ $in_tech_section == true ]] && [[ "$line" =~ ^##[[:space:]] ]]; then | |
| 434 | + # Add new tech entries before closing the section | |
| 435 | + if [[ $tech_entries_added == false ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then | |
| 436 | + printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file" | |
| 437 | + tech_entries_added=true | |
| 438 | + fi | |
| 439 | + echo "$line" >> "$temp_file" | |
| 440 | + in_tech_section=false | |
| 441 | + continue | |
| 442 | + elif [[ $in_tech_section == true ]] && [[ -z "$line" ]]; then | |
| 443 | + # Add new tech entries before empty line in tech section | |
| 444 | + if [[ $tech_entries_added == false ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then | |
| 445 | + printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file" | |
| 446 | + tech_entries_added=true | |
| 447 | + fi | |
| 448 | + echo "$line" >> "$temp_file" | |
| 449 | + continue | |
| 450 | + fi | |
| 451 | + | |
| 452 | + # Handle Recent Changes section | |
| 453 | + if [[ "$line" == "## Recent Changes" ]]; then | |
| 454 | + echo "$line" >> "$temp_file" | |
| 455 | + # Add new change entry right after the heading | |
| 456 | + if [[ -n "$new_change_entry" ]]; then | |
| 457 | + echo "$new_change_entry" >> "$temp_file" | |
| 458 | + fi | |
| 459 | + in_changes_section=true | |
| 460 | + changes_entries_added=true | |
| 461 | + continue | |
| 462 | + elif [[ $in_changes_section == true ]] && [[ "$line" =~ ^##[[:space:]] ]]; then | |
| 463 | + echo "$line" >> "$temp_file" | |
| 464 | + in_changes_section=false | |
| 465 | + continue | |
| 466 | + elif [[ $in_changes_section == true ]] && [[ "$line" == "- "* ]]; then | |
| 467 | + # Keep only first 2 existing changes | |
| 468 | + if [[ $existing_changes_count -lt 2 ]]; then | |
| 469 | + echo "$line" >> "$temp_file" | |
| 470 | + ((existing_changes_count++)) | |
| 471 | + fi | |
| 472 | + continue | |
| 473 | + fi | |
| 474 | + | |
| 475 | + # Update timestamp | |
| 476 | + if [[ "$line" =~ \*\*Last\ updated\*\*:.*[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] ]]; then | |
| 477 | + echo "$line" | sed "s/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]/$current_date/" >> "$temp_file" | |
| 478 | + else | |
| 479 | + echo "$line" >> "$temp_file" | |
| 480 | + fi | |
| 481 | + done < "$target_file" | |
| 482 | + | |
| 483 | + # Post-loop check: if we're still in the Active Technologies section and haven't added new entries | |
| 484 | + if [[ $in_tech_section == true ]] && [[ $tech_entries_added == false ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then | |
| 485 | + printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file" | |
| 486 | + tech_entries_added=true | |
| 487 | + fi | |
| 488 | + | |
| 489 | + # If sections don't exist, add them at the end of the file | |
| 490 | + if [[ $has_active_technologies -eq 0 ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then | |
| 491 | + echo "" >> "$temp_file" | |
| 492 | + echo "## Active Technologies" >> "$temp_file" | |
| 493 | + printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file" | |
| 494 | + tech_entries_added=true | |
| 495 | + fi | |
| 496 | + | |
| 497 | + if [[ $has_recent_changes -eq 0 ]] && [[ -n "$new_change_entry" ]]; then | |
| 498 | + echo "" >> "$temp_file" | |
| 499 | + echo "## Recent Changes" >> "$temp_file" | |
| 500 | + echo "$new_change_entry" >> "$temp_file" | |
| 501 | + changes_entries_added=true | |
| 502 | + fi | |
| 503 | + | |
| 504 | + # Ensure Cursor .mdc files have YAML frontmatter for auto-inclusion | |
| 505 | + if [[ "$target_file" == *.mdc ]]; then | |
| 506 | + if ! head -1 "$temp_file" | grep -q '^---'; then | |
| 507 | + local frontmatter_file | |
| 508 | + frontmatter_file=$(mktemp) || { rm -f "$temp_file"; return 1; } | |
| 509 | + printf '%s\n' "---" "description: Project Development Guidelines" "globs: [\"**/*\"]" "alwaysApply: true" "---" "" > "$frontmatter_file" | |
| 510 | + cat "$temp_file" >> "$frontmatter_file" | |
| 511 | + mv "$frontmatter_file" "$temp_file" | |
| 512 | + fi | |
| 513 | + fi | |
| 514 | + | |
| 515 | + # Move temp file to target atomically | |
| 516 | + if ! mv "$temp_file" "$target_file"; then | |
| 517 | + log_error "Failed to update target file" | |
| 518 | + rm -f "$temp_file" | |
| 519 | + return 1 | |
| 520 | + fi | |
| 521 | + | |
| 522 | + return 0 | |
| 523 | +} | |
| 524 | +#============================================================================== | |
| 525 | +# Main Agent File Update Function | |
| 526 | +#============================================================================== | |
| 527 | + | |
| 528 | +update_agent_file() { | |
| 529 | + local target_file="$1" | |
| 530 | + local agent_name="$2" | |
| 531 | + | |
| 532 | + if [[ -z "$target_file" ]] || [[ -z "$agent_name" ]]; then | |
| 533 | + log_error "update_agent_file requires target_file and agent_name parameters" | |
| 534 | + return 1 | |
| 535 | + fi | |
| 536 | + | |
| 537 | + log_info "Updating $agent_name context file: $target_file" | |
| 538 | + | |
| 539 | + local project_name | |
| 540 | + project_name=$(basename "$REPO_ROOT") | |
| 541 | + local current_date | |
| 542 | + current_date=$(date +%Y-%m-%d) | |
| 543 | + | |
| 544 | + # Create directory if it doesn't exist | |
| 545 | + local target_dir | |
| 546 | + target_dir=$(dirname "$target_file") | |
| 547 | + if [[ ! -d "$target_dir" ]]; then | |
| 548 | + if ! mkdir -p "$target_dir"; then | |
| 549 | + log_error "Failed to create directory: $target_dir" | |
| 550 | + return 1 | |
| 551 | + fi | |
| 552 | + fi | |
| 553 | + | |
| 554 | + if [[ ! -f "$target_file" ]]; then | |
| 555 | + # Create new file from template | |
| 556 | + local temp_file | |
| 557 | + temp_file=$(mktemp) || { | |
| 558 | + log_error "Failed to create temporary file" | |
| 559 | + return 1 | |
| 560 | + } | |
| 561 | + | |
| 562 | + if create_new_agent_file "$target_file" "$temp_file" "$project_name" "$current_date"; then | |
| 563 | + if mv "$temp_file" "$target_file"; then | |
| 564 | + log_success "Created new $agent_name context file" | |
| 565 | + else | |
| 566 | + log_error "Failed to move temporary file to $target_file" | |
| 567 | + rm -f "$temp_file" | |
| 568 | + return 1 | |
| 569 | + fi | |
| 570 | + else | |
| 571 | + log_error "Failed to create new agent file" | |
| 572 | + rm -f "$temp_file" | |
| 573 | + return 1 | |
| 574 | + fi | |
| 575 | + else | |
| 576 | + # Update existing file | |
| 577 | + if [[ ! -r "$target_file" ]]; then | |
| 578 | + log_error "Cannot read existing file: $target_file" | |
| 579 | + return 1 | |
| 580 | + fi | |
| 581 | + | |
| 582 | + if [[ ! -w "$target_file" ]]; then | |
| 583 | + log_error "Cannot write to existing file: $target_file" | |
| 584 | + return 1 | |
| 585 | + fi | |
| 586 | + | |
| 587 | + if update_existing_agent_file "$target_file" "$current_date"; then | |
| 588 | + log_success "Updated existing $agent_name context file" | |
| 589 | + else | |
| 590 | + log_error "Failed to update existing agent file" | |
| 591 | + return 1 | |
| 592 | + fi | |
| 593 | + fi | |
| 594 | + | |
| 595 | + return 0 | |
| 596 | +} | |
| 597 | + | |
| 598 | +#============================================================================== | |
| 599 | +# Agent Selection and Processing | |
| 600 | +#============================================================================== | |
| 601 | + | |
| 602 | +update_specific_agent() { | |
| 603 | + local agent_type="$1" | |
| 604 | + | |
| 605 | + case "$agent_type" in | |
| 606 | + claude) | |
| 607 | + update_agent_file "$CLAUDE_FILE" "Claude Code" | |
| 608 | + ;; | |
| 609 | + gemini) | |
| 610 | + update_agent_file "$GEMINI_FILE" "Gemini CLI" | |
| 611 | + ;; | |
| 612 | + copilot) | |
| 613 | + update_agent_file "$COPILOT_FILE" "GitHub Copilot" | |
| 614 | + ;; | |
| 615 | + cursor-agent) | |
| 616 | + update_agent_file "$CURSOR_FILE" "Cursor IDE" | |
| 617 | + ;; | |
| 618 | + qwen) | |
| 619 | + update_agent_file "$QWEN_FILE" "Qwen Code" | |
| 620 | + ;; | |
| 621 | + opencode) | |
| 622 | + update_agent_file "$AGENTS_FILE" "opencode" | |
| 623 | + ;; | |
| 624 | + codex) | |
| 625 | + update_agent_file "$AGENTS_FILE" "Codex CLI" | |
| 626 | + ;; | |
| 627 | + windsurf) | |
| 628 | + update_agent_file "$WINDSURF_FILE" "Windsurf" | |
| 629 | + ;; | |
| 630 | + kilocode) | |
| 631 | + update_agent_file "$KILOCODE_FILE" "Kilo Code" | |
| 632 | + ;; | |
| 633 | + auggie) | |
| 634 | + update_agent_file "$AUGGIE_FILE" "Auggie CLI" | |
| 635 | + ;; | |
| 636 | + roo) | |
| 637 | + update_agent_file "$ROO_FILE" "Roo Code" | |
| 638 | + ;; | |
| 639 | + codebuddy) | |
| 640 | + update_agent_file "$CODEBUDDY_FILE" "CodeBuddy CLI" | |
| 641 | + ;; | |
| 642 | + qodercli) | |
| 643 | + update_agent_file "$QODER_FILE" "Qoder CLI" | |
| 644 | + ;; | |
| 645 | + amp) | |
| 646 | + update_agent_file "$AMP_FILE" "Amp" | |
| 647 | + ;; | |
| 648 | + shai) | |
| 649 | + update_agent_file "$SHAI_FILE" "SHAI" | |
| 650 | + ;; | |
| 651 | + kiro-cli) | |
| 652 | + update_agent_file "$KIRO_FILE" "Kiro CLI" | |
| 653 | + ;; | |
| 654 | + agy) | |
| 655 | + update_agent_file "$AGY_FILE" "Antigravity" | |
| 656 | + ;; | |
| 657 | + bob) | |
| 658 | + update_agent_file "$BOB_FILE" "IBM Bob" | |
| 659 | + ;; | |
| 660 | + generic) | |
| 661 | + log_info "Generic agent: no predefined context file. Use the agent-specific update script for your agent." | |
| 662 | + ;; | |
| 663 | + *) | |
| 664 | + log_error "Unknown agent type '$agent_type'" | |
| 665 | + log_error "Expected: claude|gemini|copilot|cursor-agent|qwen|opencode|codex|windsurf|kilocode|auggie|roo|codebuddy|amp|shai|kiro-cli|agy|bob|qodercli|generic" | |
| 666 | + exit 1 | |
| 667 | + ;; | |
| 668 | + esac | |
| 669 | +} | |
| 670 | + | |
| 671 | +update_all_existing_agents() { | |
| 672 | + local found_agent=false | |
| 673 | + | |
| 674 | + # Check each possible agent file and update if it exists | |
| 675 | + if [[ -f "$CLAUDE_FILE" ]]; then | |
| 676 | + update_agent_file "$CLAUDE_FILE" "Claude Code" | |
| 677 | + found_agent=true | |
| 678 | + fi | |
| 679 | + | |
| 680 | + if [[ -f "$GEMINI_FILE" ]]; then | |
| 681 | + update_agent_file "$GEMINI_FILE" "Gemini CLI" | |
| 682 | + found_agent=true | |
| 683 | + fi | |
| 684 | + | |
| 685 | + if [[ -f "$COPILOT_FILE" ]]; then | |
| 686 | + update_agent_file "$COPILOT_FILE" "GitHub Copilot" | |
| 687 | + found_agent=true | |
| 688 | + fi | |
| 689 | + | |
| 690 | + if [[ -f "$CURSOR_FILE" ]]; then | |
| 691 | + update_agent_file "$CURSOR_FILE" "Cursor IDE" | |
| 692 | + found_agent=true | |
| 693 | + fi | |
| 694 | + | |
| 695 | + if [[ -f "$QWEN_FILE" ]]; then | |
| 696 | + update_agent_file "$QWEN_FILE" "Qwen Code" | |
| 697 | + found_agent=true | |
| 698 | + fi | |
| 699 | + | |
| 700 | + if [[ -f "$AGENTS_FILE" ]]; then | |
| 701 | + update_agent_file "$AGENTS_FILE" "Codex/opencode" | |
| 702 | + found_agent=true | |
| 703 | + fi | |
| 704 | + | |
| 705 | + if [[ -f "$WINDSURF_FILE" ]]; then | |
| 706 | + update_agent_file "$WINDSURF_FILE" "Windsurf" | |
| 707 | + found_agent=true | |
| 708 | + fi | |
| 709 | + | |
| 710 | + if [[ -f "$KILOCODE_FILE" ]]; then | |
| 711 | + update_agent_file "$KILOCODE_FILE" "Kilo Code" | |
| 712 | + found_agent=true | |
| 713 | + fi | |
| 714 | + | |
| 715 | + if [[ -f "$AUGGIE_FILE" ]]; then | |
| 716 | + update_agent_file "$AUGGIE_FILE" "Auggie CLI" | |
| 717 | + found_agent=true | |
| 718 | + fi | |
| 719 | + | |
| 720 | + if [[ -f "$ROO_FILE" ]]; then | |
| 721 | + update_agent_file "$ROO_FILE" "Roo Code" | |
| 722 | + found_agent=true | |
| 723 | + fi | |
| 724 | + | |
| 725 | + if [[ -f "$CODEBUDDY_FILE" ]]; then | |
| 726 | + update_agent_file "$CODEBUDDY_FILE" "CodeBuddy CLI" | |
| 727 | + found_agent=true | |
| 728 | + fi | |
| 729 | + | |
| 730 | + if [[ -f "$SHAI_FILE" ]]; then | |
| 731 | + update_agent_file "$SHAI_FILE" "SHAI" | |
| 732 | + found_agent=true | |
| 733 | + fi | |
| 734 | + | |
| 735 | + if [[ -f "$QODER_FILE" ]]; then | |
| 736 | + update_agent_file "$QODER_FILE" "Qoder CLI" | |
| 737 | + found_agent=true | |
| 738 | + fi | |
| 739 | + | |
| 740 | + if [[ -f "$KIRO_FILE" ]]; then | |
| 741 | + update_agent_file "$KIRO_FILE" "Kiro CLI" | |
| 742 | + found_agent=true | |
| 743 | + fi | |
| 744 | + | |
| 745 | + if [[ -f "$AGY_FILE" ]]; then | |
| 746 | + update_agent_file "$AGY_FILE" "Antigravity" | |
| 747 | + found_agent=true | |
| 748 | + fi | |
| 749 | + if [[ -f "$BOB_FILE" ]]; then | |
| 750 | + update_agent_file "$BOB_FILE" "IBM Bob" | |
| 751 | + found_agent=true | |
| 752 | + fi | |
| 753 | + | |
| 754 | + # If no agent files exist, create a default Claude file | |
| 755 | + if [[ "$found_agent" == false ]]; then | |
| 756 | + log_info "No existing agent files found, creating default Claude file..." | |
| 757 | + update_agent_file "$CLAUDE_FILE" "Claude Code" | |
| 758 | + fi | |
| 759 | +} | |
| 760 | +print_summary() { | |
| 761 | + echo | |
| 762 | + log_info "Summary of changes:" | |
| 763 | + | |
| 764 | + if [[ -n "$NEW_LANG" ]]; then | |
| 765 | + echo " - Added language: $NEW_LANG" | |
| 766 | + fi | |
| 767 | + | |
| 768 | + if [[ -n "$NEW_FRAMEWORK" ]]; then | |
| 769 | + echo " - Added framework: $NEW_FRAMEWORK" | |
| 770 | + fi | |
| 771 | + | |
| 772 | + if [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]]; then | |
| 773 | + echo " - Added database: $NEW_DB" | |
| 774 | + fi | |
| 775 | + | |
| 776 | + echo | |
| 777 | + | |
| 778 | + log_info "Usage: $0 [claude|gemini|copilot|cursor-agent|qwen|opencode|codex|windsurf|kilocode|auggie|roo|codebuddy|amp|shai|kiro-cli|agy|bob|qodercli]" | |
| 779 | +} | |
| 780 | + | |
| 781 | +#============================================================================== | |
| 782 | +# Main Execution | |
| 783 | +#============================================================================== | |
| 784 | + | |
| 785 | +main() { | |
| 786 | + # Validate environment before proceeding | |
| 787 | + validate_environment | |
| 788 | + | |
| 789 | + log_info "=== Updating agent context files for feature $CURRENT_BRANCH ===" | |
| 790 | + | |
| 791 | + # Parse the plan file to extract project information | |
| 792 | + if ! parse_plan_data "$NEW_PLAN"; then | |
| 793 | + log_error "Failed to parse plan data" | |
| 794 | + exit 1 | |
| 795 | + fi | |
| 796 | + | |
| 797 | + # Process based on agent type argument | |
| 798 | + local success=true | |
| 799 | + | |
| 800 | + if [[ -z "$AGENT_TYPE" ]]; then | |
| 801 | + # No specific agent provided - update all existing agent files | |
| 802 | + log_info "No agent specified, updating all existing agent files..." | |
| 803 | + if ! update_all_existing_agents; then | |
| 804 | + success=false | |
| 805 | + fi | |
| 806 | + else | |
| 807 | + # Specific agent provided - update only that agent | |
| 808 | + log_info "Updating specific agent: $AGENT_TYPE" | |
| 809 | + if ! update_specific_agent "$AGENT_TYPE"; then | |
| 810 | + success=false | |
| 811 | + fi | |
| 812 | + fi | |
| 813 | + | |
| 814 | + # Print summary | |
| 815 | + print_summary | |
| 816 | + | |
| 817 | + if [[ "$success" == true ]]; then | |
| 818 | + log_success "Agent context update completed successfully" | |
| 819 | + exit 0 | |
| 820 | + else | |
| 821 | + log_error "Agent context update completed with errors" | |
| 822 | + exit 1 | |
| 823 | + fi | |
| 824 | +} | |
| 825 | + | |
| 826 | +# Execute main function if script is run directly | |
| 827 | +if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then | |
| 828 | + main "$@" | |
| 829 | +fi |
A
.specify/templates/agent-file-template.md
+28
-0
@@ -0,0 +1,28 @@
| 1 | +# [PROJECT NAME] Development Guidelines | |
| 2 | + | |
| 3 | +Auto-generated from all feature plans. Last updated: [DATE] | |
| 4 | + | |
| 5 | +## Active Technologies | |
| 6 | + | |
| 7 | +[EXTRACTED FROM ALL PLAN.MD FILES] | |
| 8 | + | |
| 9 | +## Project Structure | |
| 10 | + | |
| 11 | +```text | |
| 12 | +[ACTUAL STRUCTURE FROM PLANS] | |
| 13 | +``` | |
| 14 | + | |
| 15 | +## Commands | |
| 16 | + | |
| 17 | +[ONLY COMMANDS FOR ACTIVE TECHNOLOGIES] | |
| 18 | + | |
| 19 | +## Code Style | |
| 20 | + | |
| 21 | +[LANGUAGE-SPECIFIC, ONLY FOR LANGUAGES IN USE] | |
| 22 | + | |
| 23 | +## Recent Changes | |
| 24 | + | |
| 25 | +[LAST 3 FEATURES AND WHAT THEY ADDED] | |
| 26 | + | |
| 27 | +<!-- MANUAL ADDITIONS START --> | |
| 28 | +<!-- MANUAL ADDITIONS END --> |
A
.specify/templates/checklist-template.md
+40
-0
@@ -0,0 +1,40 @@
| 1 | +# [CHECKLIST TYPE] Checklist: [FEATURE NAME] | |
| 2 | + | |
| 3 | +**Purpose**: [Brief description of what this checklist covers] | |
| 4 | +**Created**: [DATE] | |
| 5 | +**Feature**: [Link to spec.md or relevant documentation] | |
| 6 | + | |
| 7 | +**Note**: This checklist is generated by the `/speckit.checklist` command based on feature context and requirements. | |
| 8 | + | |
| 9 | +<!-- | |
| 10 | + ============================================================================ | |
| 11 | + IMPORTANT: The checklist items below are SAMPLE ITEMS for illustration only. | |
| 12 | + | |
| 13 | + The /speckit.checklist command MUST replace these with actual items based on: | |
| 14 | + - User's specific checklist request | |
| 15 | + - Feature requirements from spec.md | |
| 16 | + - Technical context from plan.md | |
| 17 | + - Implementation details from tasks.md | |
| 18 | + | |
| 19 | + DO NOT keep these sample items in the generated checklist file. | |
| 20 | + ============================================================================ | |
| 21 | +--> | |
| 22 | + | |
| 23 | +## [Category 1] | |
| 24 | + | |
| 25 | +- [ ] CHK001 First checklist item with clear action | |
| 26 | +- [ ] CHK002 Second checklist item | |
| 27 | +- [ ] CHK003 Third checklist item | |
| 28 | + | |
| 29 | +## [Category 2] | |
| 30 | + | |
| 31 | +- [ ] CHK004 Another category item | |
| 32 | +- [ ] CHK005 Item with specific criteria | |
| 33 | +- [ ] CHK006 Final item in this category | |
| 34 | + | |
| 35 | +## Notes | |
| 36 | + | |
| 37 | +- Check items off as completed: `[x]` | |
| 38 | +- Add comments or findings inline | |
| 39 | +- Link to relevant resources or documentation | |
| 40 | +- Items are numbered sequentially for easy reference |
A
.specify/templates/constitution-template.md
+50
-0
@@ -0,0 +1,50 @@
| 1 | +# [PROJECT_NAME] Constitution | |
| 2 | +<!-- Example: Spec Constitution, TaskFlow Constitution, etc. --> | |
| 3 | + | |
| 4 | +## Core Principles | |
| 5 | + | |
| 6 | +### [PRINCIPLE_1_NAME] | |
| 7 | +<!-- Example: I. Library-First --> | |
| 8 | +[PRINCIPLE_1_DESCRIPTION] | |
| 9 | +<!-- Example: Every feature starts as a standalone library; Libraries must be self-contained, independently testable, documented; Clear purpose required - no organizational-only libraries --> | |
| 10 | + | |
| 11 | +### [PRINCIPLE_2_NAME] | |
| 12 | +<!-- Example: II. CLI Interface --> | |
| 13 | +[PRINCIPLE_2_DESCRIPTION] | |
| 14 | +<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args → stdout, errors → stderr; Support JSON + human-readable formats --> | |
| 15 | + | |
| 16 | +### [PRINCIPLE_3_NAME] | |
| 17 | +<!-- Example: III. Test-First (NON-NEGOTIABLE) --> | |
| 18 | +[PRINCIPLE_3_DESCRIPTION] | |
| 19 | +<!-- Example: TDD mandatory: Tests written → User approved → Tests fail → Then implement; Red-Green-Refactor cycle strictly enforced --> | |
| 20 | + | |
| 21 | +### [PRINCIPLE_4_NAME] | |
| 22 | +<!-- Example: IV. Integration Testing --> | |
| 23 | +[PRINCIPLE_4_DESCRIPTION] | |
| 24 | +<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas --> | |
| 25 | + | |
| 26 | +### [PRINCIPLE_5_NAME] | |
| 27 | +<!-- Example: V. Observability, VI. Versioning & Breaking Changes, VII. Simplicity --> | |
| 28 | +[PRINCIPLE_5_DESCRIPTION] | |
| 29 | +<!-- Example: Text I/O ensures debuggability; Structured logging required; Or: MAJOR.MINOR.BUILD format; Or: Start simple, YAGNI principles --> | |
| 30 | + | |
| 31 | +## [SECTION_2_NAME] | |
| 32 | +<!-- Example: Additional Constraints, Security Requirements, Performance Standards, etc. --> | |
| 33 | + | |
| 34 | +[SECTION_2_CONTENT] | |
| 35 | +<!-- Example: Technology stack requirements, compliance standards, deployment policies, etc. --> | |
| 36 | + | |
| 37 | +## [SECTION_3_NAME] | |
| 38 | +<!-- Example: Development Workflow, Review Process, Quality Gates, etc. --> | |
| 39 | + | |
| 40 | +[SECTION_3_CONTENT] | |
| 41 | +<!-- Example: Code review requirements, testing gates, deployment approval process, etc. --> | |
| 42 | + | |
| 43 | +## Governance | |
| 44 | +<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan --> | |
| 45 | + | |
| 46 | +[GOVERNANCE_RULES] | |
| 47 | +<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance --> | |
| 48 | + | |
| 49 | +**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE] | |
| 50 | +<!-- Example: Version: 2.1.1 | Ratified: 2025-06-13 | Last Amended: 2025-07-16 --> |
A
.specify/templates/plan-template.md
+104
-0
@@ -0,0 +1,104 @@
| 1 | +# Implementation Plan: [FEATURE] | |
| 2 | + | |
| 3 | +**Branch**: `[###-feature-name]` | **Date**: [DATE] | **Spec**: [link] | |
| 4 | +**Input**: Feature specification from `/specs/[###-feature-name]/spec.md` | |
| 5 | + | |
| 6 | +**Note**: This template is filled in by the `/speckit.plan` command. See `.specify/templates/plan-template.md` for the execution workflow. | |
| 7 | + | |
| 8 | +## Summary | |
| 9 | + | |
| 10 | +[Extract from feature spec: primary requirement + technical approach from research] | |
| 11 | + | |
| 12 | +## Technical Context | |
| 13 | + | |
| 14 | +<!-- | |
| 15 | + ACTION REQUIRED: Replace the content in this section with the technical details | |
| 16 | + for the project. The structure here is presented in advisory capacity to guide | |
| 17 | + the iteration process. | |
| 18 | +--> | |
| 19 | + | |
| 20 | +**Language/Version**: [e.g., Python 3.11, Swift 5.9, Rust 1.75 or NEEDS CLARIFICATION] | |
| 21 | +**Primary Dependencies**: [e.g., FastAPI, UIKit, LLVM or NEEDS CLARIFICATION] | |
| 22 | +**Storage**: [if applicable, e.g., PostgreSQL, CoreData, files or N/A] | |
| 23 | +**Testing**: [e.g., pytest, XCTest, cargo test or NEEDS CLARIFICATION] | |
| 24 | +**Target Platform**: [e.g., Linux server, iOS 15+, WASM or NEEDS CLARIFICATION] | |
| 25 | +**Project Type**: [e.g., library/cli/web-service/mobile-app/compiler/desktop-app or NEEDS CLARIFICATION] | |
| 26 | +**Performance Goals**: [domain-specific, e.g., 1000 req/s, 10k lines/sec, 60 fps or NEEDS CLARIFICATION] | |
| 27 | +**Constraints**: [domain-specific, e.g., <200ms p95, <100MB memory, offline-capable or NEEDS CLARIFICATION] | |
| 28 | +**Scale/Scope**: [domain-specific, e.g., 10k users, 1M LOC, 50 screens or NEEDS CLARIFICATION] | |
| 29 | + | |
| 30 | +## Constitution Check | |
| 31 | + | |
| 32 | +*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.* | |
| 33 | + | |
| 34 | +[Gates determined based on constitution file] | |
| 35 | + | |
| 36 | +## Project Structure | |
| 37 | + | |
| 38 | +### Documentation (this feature) | |
| 39 | + | |
| 40 | +```text | |
| 41 | +specs/[###-feature]/ | |
| 42 | +├── plan.md # This file (/speckit.plan command output) | |
| 43 | +├── research.md # Phase 0 output (/speckit.plan command) | |
| 44 | +├── data-model.md # Phase 1 output (/speckit.plan command) | |
| 45 | +├── quickstart.md # Phase 1 output (/speckit.plan command) | |
| 46 | +├── contracts/ # Phase 1 output (/speckit.plan command) | |
| 47 | +└── tasks.md # Phase 2 output (/speckit.tasks command - NOT created by /speckit.plan) | |
| 48 | +``` | |
| 49 | + | |
| 50 | +### Source Code (repository root) | |
| 51 | +<!-- | |
| 52 | + ACTION REQUIRED: Replace the placeholder tree below with the concrete layout | |
| 53 | + for this feature. Delete unused options and expand the chosen structure with | |
| 54 | + real paths (e.g., apps/admin, packages/something). The delivered plan must | |
| 55 | + not include Option labels. | |
| 56 | +--> | |
| 57 | + | |
| 58 | +```text | |
| 59 | +# [REMOVE IF UNUSED] Option 1: Single project (DEFAULT) | |
| 60 | +src/ | |
| 61 | +├── models/ | |
| 62 | +├── services/ | |
| 63 | +├── cli/ | |
| 64 | +└── lib/ | |
| 65 | + | |
| 66 | +tests/ | |
| 67 | +├── contract/ | |
| 68 | +├── integration/ | |
| 69 | +└── unit/ | |
| 70 | + | |
| 71 | +# [REMOVE IF UNUSED] Option 2: Web application (when "frontend" + "backend" detected) | |
| 72 | +backend/ | |
| 73 | +├── src/ | |
| 74 | +│ ├── models/ | |
| 75 | +│ ├── services/ | |
| 76 | +│ └── api/ | |
| 77 | +└── tests/ | |
| 78 | + | |
| 79 | +frontend/ | |
| 80 | +├── src/ | |
| 81 | +│ ├── components/ | |
| 82 | +│ ├── pages/ | |
| 83 | +│ └── services/ | |
| 84 | +└── tests/ | |
| 85 | + | |
| 86 | +# [REMOVE IF UNUSED] Option 3: Mobile + API (when "iOS/Android" detected) | |
| 87 | +api/ | |
| 88 | +└── [same as backend above] | |
| 89 | + | |
| 90 | +ios/ or android/ | |
| 91 | +└── [platform-specific structure: feature modules, UI flows, platform tests] | |
| 92 | +``` | |
| 93 | + | |
| 94 | +**Structure Decision**: [Document the selected structure and reference the real | |
| 95 | +directories captured above] | |
| 96 | + | |
| 97 | +## Complexity Tracking | |
| 98 | + | |
| 99 | +> **Fill ONLY if Constitution Check has violations that must be justified** | |
| 100 | + | |
| 101 | +| Violation | Why Needed | Simpler Alternative Rejected Because | | |
| 102 | +|-----------|------------|-------------------------------------| | |
| 103 | +| [e.g., 4th project] | [current need] | [why 3 projects insufficient] | | |
| 104 | +| [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] | |
A
.specify/templates/spec-template.md
+115
-0
@@ -0,0 +1,115 @@
| 1 | +# Feature Specification: [FEATURE NAME] | |
| 2 | + | |
| 3 | +**Feature Branch**: `[###-feature-name]` | |
| 4 | +**Created**: [DATE] | |
| 5 | +**Status**: Draft | |
| 6 | +**Input**: User description: "$ARGUMENTS" | |
| 7 | + | |
| 8 | +## User Scenarios & Testing *(mandatory)* | |
| 9 | + | |
| 10 | +<!-- | |
| 11 | + IMPORTANT: User stories should be PRIORITIZED as user journeys ordered by importance. | |
| 12 | + Each user story/journey must be INDEPENDENTLY TESTABLE - meaning if you implement just ONE of them, | |
| 13 | + you should still have a viable MVP (Minimum Viable Product) that delivers value. | |
| 14 | + | |
| 15 | + Assign priorities (P1, P2, P3, etc.) to each story, where P1 is the most critical. | |
| 16 | + Think of each story as a standalone slice of functionality that can be: | |
| 17 | + - Developed independently | |
| 18 | + - Tested independently | |
| 19 | + - Deployed independently | |
| 20 | + - Demonstrated to users independently | |
| 21 | +--> | |
| 22 | + | |
| 23 | +### User Story 1 - [Brief Title] (Priority: P1) | |
| 24 | + | |
| 25 | +[Describe this user journey in plain language] | |
| 26 | + | |
| 27 | +**Why this priority**: [Explain the value and why it has this priority level] | |
| 28 | + | |
| 29 | +**Independent Test**: [Describe how this can be tested independently - e.g., "Can be fully tested by [specific action] and delivers [specific value]"] | |
| 30 | + | |
| 31 | +**Acceptance Scenarios**: | |
| 32 | + | |
| 33 | +1. **Given** [initial state], **When** [action], **Then** [expected outcome] | |
| 34 | +2. **Given** [initial state], **When** [action], **Then** [expected outcome] | |
| 35 | + | |
| 36 | +--- | |
| 37 | + | |
| 38 | +### User Story 2 - [Brief Title] (Priority: P2) | |
| 39 | + | |
| 40 | +[Describe this user journey in plain language] | |
| 41 | + | |
| 42 | +**Why this priority**: [Explain the value and why it has this priority level] | |
| 43 | + | |
| 44 | +**Independent Test**: [Describe how this can be tested independently] | |
| 45 | + | |
| 46 | +**Acceptance Scenarios**: | |
| 47 | + | |
| 48 | +1. **Given** [initial state], **When** [action], **Then** [expected outcome] | |
| 49 | + | |
| 50 | +--- | |
| 51 | + | |
| 52 | +### User Story 3 - [Brief Title] (Priority: P3) | |
| 53 | + | |
| 54 | +[Describe this user journey in plain language] | |
| 55 | + | |
| 56 | +**Why this priority**: [Explain the value and why it has this priority level] | |
| 57 | + | |
| 58 | +**Independent Test**: [Describe how this can be tested independently] | |
| 59 | + | |
| 60 | +**Acceptance Scenarios**: | |
| 61 | + | |
| 62 | +1. **Given** [initial state], **When** [action], **Then** [expected outcome] | |
| 63 | + | |
| 64 | +--- | |
| 65 | + | |
| 66 | +[Add more user stories as needed, each with an assigned priority] | |
| 67 | + | |
| 68 | +### Edge Cases | |
| 69 | + | |
| 70 | +<!-- | |
| 71 | + ACTION REQUIRED: The content in this section represents placeholders. | |
| 72 | + Fill them out with the right edge cases. | |
| 73 | +--> | |
| 74 | + | |
| 75 | +- What happens when [boundary condition]? | |
| 76 | +- How does system handle [error scenario]? | |
| 77 | + | |
| 78 | +## Requirements *(mandatory)* | |
| 79 | + | |
| 80 | +<!-- | |
| 81 | + ACTION REQUIRED: The content in this section represents placeholders. | |
| 82 | + Fill them out with the right functional requirements. | |
| 83 | +--> | |
| 84 | + | |
| 85 | +### Functional Requirements | |
| 86 | + | |
| 87 | +- **FR-001**: System MUST [specific capability, e.g., "allow users to create accounts"] | |
| 88 | +- **FR-002**: System MUST [specific capability, e.g., "validate email addresses"] | |
| 89 | +- **FR-003**: Users MUST be able to [key interaction, e.g., "reset their password"] | |
| 90 | +- **FR-004**: System MUST [data requirement, e.g., "persist user preferences"] | |
| 91 | +- **FR-005**: System MUST [behavior, e.g., "log all security events"] | |
| 92 | + | |
| 93 | +*Example of marking unclear requirements:* | |
| 94 | + | |
| 95 | +- **FR-006**: System MUST authenticate users via [NEEDS CLARIFICATION: auth method not specified - email/password, SSO, OAuth?] | |
| 96 | +- **FR-007**: System MUST retain user data for [NEEDS CLARIFICATION: retention period not specified] | |
| 97 | + | |
| 98 | +### Key Entities *(include if feature involves data)* | |
| 99 | + | |
| 100 | +- **[Entity 1]**: [What it represents, key attributes without implementation] | |
| 101 | +- **[Entity 2]**: [What it represents, relationships to other entities] | |
| 102 | + | |
| 103 | +## Success Criteria *(mandatory)* | |
| 104 | + | |
| 105 | +<!-- | |
| 106 | + ACTION REQUIRED: Define measurable success criteria. | |
| 107 | + These must be technology-agnostic and measurable. | |
| 108 | +--> | |
| 109 | + | |
| 110 | +### Measurable Outcomes | |
| 111 | + | |
| 112 | +- **SC-001**: [Measurable metric, e.g., "Users can complete account creation in under 2 minutes"] | |
| 113 | +- **SC-002**: [Measurable metric, e.g., "System handles 1000 concurrent users without degradation"] | |
| 114 | +- **SC-003**: [User satisfaction metric, e.g., "90% of users successfully complete primary task on first attempt"] | |
| 115 | +- **SC-004**: [Business metric, e.g., "Reduce support tickets related to [X] by 50%"] |
A
.specify/templates/tasks-template.md
+251
-0
@@ -0,0 +1,251 @@
| 1 | +--- | |
| 2 | + | |
| 3 | +description: "Task list template for feature implementation" | |
| 4 | +--- | |
| 5 | + | |
| 6 | +# Tasks: [FEATURE NAME] | |
| 7 | + | |
| 8 | +**Input**: Design documents from `/specs/[###-feature-name]/` | |
| 9 | +**Prerequisites**: plan.md (required), spec.md (required for user stories), research.md, data-model.md, contracts/ | |
| 10 | + | |
| 11 | +**Tests**: The examples below include test tasks. Tests are OPTIONAL - only include them if explicitly requested in the feature specification. | |
| 12 | + | |
| 13 | +**Organization**: Tasks are grouped by user story to enable independent implementation and testing of each story. | |
| 14 | + | |
| 15 | +## Format: `[ID] [P?] [Story] Description` | |
| 16 | + | |
| 17 | +- **[P]**: Can run in parallel (different files, no dependencies) | |
| 18 | +- **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3) | |
| 19 | +- Include exact file paths in descriptions | |
| 20 | + | |
| 21 | +## Path Conventions | |
| 22 | + | |
| 23 | +- **Single project**: `src/`, `tests/` at repository root | |
| 24 | +- **Web app**: `backend/src/`, `frontend/src/` | |
| 25 | +- **Mobile**: `api/src/`, `ios/src/` or `android/src/` | |
| 26 | +- Paths shown below assume single project - adjust based on plan.md structure | |
| 27 | + | |
| 28 | +<!-- | |
| 29 | + ============================================================================ | |
| 30 | + IMPORTANT: The tasks below are SAMPLE TASKS for illustration purposes only. | |
| 31 | + | |
| 32 | + The /speckit.tasks command MUST replace these with actual tasks based on: | |
| 33 | + - User stories from spec.md (with their priorities P1, P2, P3...) | |
| 34 | + - Feature requirements from plan.md | |
| 35 | + - Entities from data-model.md | |
| 36 | + - Endpoints from contracts/ | |
| 37 | + | |
| 38 | + Tasks MUST be organized by user story so each story can be: | |
| 39 | + - Implemented independently | |
| 40 | + - Tested independently | |
| 41 | + - Delivered as an MVP increment | |
| 42 | + | |
| 43 | + DO NOT keep these sample tasks in the generated tasks.md file. | |
| 44 | + ============================================================================ | |
| 45 | +--> | |
| 46 | + | |
| 47 | +## Phase 1: Setup (Shared Infrastructure) | |
| 48 | + | |
| 49 | +**Purpose**: Project initialization and basic structure | |
| 50 | + | |
| 51 | +- [ ] T001 Create project structure per implementation plan | |
| 52 | +- [ ] T002 Initialize [language] project with [framework] dependencies | |
| 53 | +- [ ] T003 [P] Configure linting and formatting tools | |
| 54 | + | |
| 55 | +--- | |
| 56 | + | |
| 57 | +## Phase 2: Foundational (Blocking Prerequisites) | |
| 58 | + | |
| 59 | +**Purpose**: Core infrastructure that MUST be complete before ANY user story can be implemented | |
| 60 | + | |
| 61 | +**⚠️ CRITICAL**: No user story work can begin until this phase is complete | |
| 62 | + | |
| 63 | +Examples of foundational tasks (adjust based on your project): | |
| 64 | + | |
| 65 | +- [ ] T004 Setup database schema and migrations framework | |
| 66 | +- [ ] T005 [P] Implement authentication/authorization framework | |
| 67 | +- [ ] T006 [P] Setup API routing and middleware structure | |
| 68 | +- [ ] T007 Create base models/entities that all stories depend on | |
| 69 | +- [ ] T008 Configure error handling and logging infrastructure | |
| 70 | +- [ ] T009 Setup environment configuration management | |
| 71 | + | |
| 72 | +**Checkpoint**: Foundation ready - user story implementation can now begin in parallel | |
| 73 | + | |
| 74 | +--- | |
| 75 | + | |
| 76 | +## Phase 3: User Story 1 - [Title] (Priority: P1) 🎯 MVP | |
| 77 | + | |
| 78 | +**Goal**: [Brief description of what this story delivers] | |
| 79 | + | |
| 80 | +**Independent Test**: [How to verify this story works on its own] | |
| 81 | + | |
| 82 | +### Tests for User Story 1 (OPTIONAL - only if tests requested) ⚠️ | |
| 83 | + | |
| 84 | +> **NOTE: Write these tests FIRST, ensure they FAIL before implementation** | |
| 85 | + | |
| 86 | +- [ ] T010 [P] [US1] Contract test for [endpoint] in tests/contract/test_[name].py | |
| 87 | +- [ ] T011 [P] [US1] Integration test for [user journey] in tests/integration/test_[name].py | |
| 88 | + | |
| 89 | +### Implementation for User Story 1 | |
| 90 | + | |
| 91 | +- [ ] T012 [P] [US1] Create [Entity1] model in src/models/[entity1].py | |
| 92 | +- [ ] T013 [P] [US1] Create [Entity2] model in src/models/[entity2].py | |
| 93 | +- [ ] T014 [US1] Implement [Service] in src/services/[service].py (depends on T012, T013) | |
| 94 | +- [ ] T015 [US1] Implement [endpoint/feature] in src/[location]/[file].py | |
| 95 | +- [ ] T016 [US1] Add validation and error handling | |
| 96 | +- [ ] T017 [US1] Add logging for user story 1 operations | |
| 97 | + | |
| 98 | +**Checkpoint**: At this point, User Story 1 should be fully functional and testable independently | |
| 99 | + | |
| 100 | +--- | |
| 101 | + | |
| 102 | +## Phase 4: User Story 2 - [Title] (Priority: P2) | |
| 103 | + | |
| 104 | +**Goal**: [Brief description of what this story delivers] | |
| 105 | + | |
| 106 | +**Independent Test**: [How to verify this story works on its own] | |
| 107 | + | |
| 108 | +### Tests for User Story 2 (OPTIONAL - only if tests requested) ⚠️ | |
| 109 | + | |
| 110 | +- [ ] T018 [P] [US2] Contract test for [endpoint] in tests/contract/test_[name].py | |
| 111 | +- [ ] T019 [P] [US2] Integration test for [user journey] in tests/integration/test_[name].py | |
| 112 | + | |
| 113 | +### Implementation for User Story 2 | |
| 114 | + | |
| 115 | +- [ ] T020 [P] [US2] Create [Entity] model in src/models/[entity].py | |
| 116 | +- [ ] T021 [US2] Implement [Service] in src/services/[service].py | |
| 117 | +- [ ] T022 [US2] Implement [endpoint/feature] in src/[location]/[file].py | |
| 118 | +- [ ] T023 [US2] Integrate with User Story 1 components (if needed) | |
| 119 | + | |
| 120 | +**Checkpoint**: At this point, User Stories 1 AND 2 should both work independently | |
| 121 | + | |
| 122 | +--- | |
| 123 | + | |
| 124 | +## Phase 5: User Story 3 - [Title] (Priority: P3) | |
| 125 | + | |
| 126 | +**Goal**: [Brief description of what this story delivers] | |
| 127 | + | |
| 128 | +**Independent Test**: [How to verify this story works on its own] | |
| 129 | + | |
| 130 | +### Tests for User Story 3 (OPTIONAL - only if tests requested) ⚠️ | |
| 131 | + | |
| 132 | +- [ ] T024 [P] [US3] Contract test for [endpoint] in tests/contract/test_[name].py | |
| 133 | +- [ ] T025 [P] [US3] Integration test for [user journey] in tests/integration/test_[name].py | |
| 134 | + | |
| 135 | +### Implementation for User Story 3 | |
| 136 | + | |
| 137 | +- [ ] T026 [P] [US3] Create [Entity] model in src/models/[entity].py | |
| 138 | +- [ ] T027 [US3] Implement [Service] in src/services/[service].py | |
| 139 | +- [ ] T028 [US3] Implement [endpoint/feature] in src/[location]/[file].py | |
| 140 | + | |
| 141 | +**Checkpoint**: All user stories should now be independently functional | |
| 142 | + | |
| 143 | +--- | |
| 144 | + | |
| 145 | +[Add more user story phases as needed, following the same pattern] | |
| 146 | + | |
| 147 | +--- | |
| 148 | + | |
| 149 | +## Phase N: Polish & Cross-Cutting Concerns | |
| 150 | + | |
| 151 | +**Purpose**: Improvements that affect multiple user stories | |
| 152 | + | |
| 153 | +- [ ] TXXX [P] Documentation updates in docs/ | |
| 154 | +- [ ] TXXX Code cleanup and refactoring | |
| 155 | +- [ ] TXXX Performance optimization across all stories | |
| 156 | +- [ ] TXXX [P] Additional unit tests (if requested) in tests/unit/ | |
| 157 | +- [ ] TXXX Security hardening | |
| 158 | +- [ ] TXXX Run quickstart.md validation | |
| 159 | + | |
| 160 | +--- | |
| 161 | + | |
| 162 | +## Dependencies & Execution Order | |
| 163 | + | |
| 164 | +### Phase Dependencies | |
| 165 | + | |
| 166 | +- **Setup (Phase 1)**: No dependencies - can start immediately | |
| 167 | +- **Foundational (Phase 2)**: Depends on Setup completion - BLOCKS all user stories | |
| 168 | +- **User Stories (Phase 3+)**: All depend on Foundational phase completion | |
| 169 | + - User stories can then proceed in parallel (if staffed) | |
| 170 | + - Or sequentially in priority order (P1 → P2 → P3) | |
| 171 | +- **Polish (Final Phase)**: Depends on all desired user stories being complete | |
| 172 | + | |
| 173 | +### User Story Dependencies | |
| 174 | + | |
| 175 | +- **User Story 1 (P1)**: Can start after Foundational (Phase 2) - No dependencies on other stories | |
| 176 | +- **User Story 2 (P2)**: Can start after Foundational (Phase 2) - May integrate with US1 but should be independently testable | |
| 177 | +- **User Story 3 (P3)**: Can start after Foundational (Phase 2) - May integrate with US1/US2 but should be independently testable | |
| 178 | + | |
| 179 | +### Within Each User Story | |
| 180 | + | |
| 181 | +- Tests (if included) MUST be written and FAIL before implementation | |
| 182 | +- Models before services | |
| 183 | +- Services before endpoints | |
| 184 | +- Core implementation before integration | |
| 185 | +- Story complete before moving to next priority | |
| 186 | + | |
| 187 | +### Parallel Opportunities | |
| 188 | + | |
| 189 | +- All Setup tasks marked [P] can run in parallel | |
| 190 | +- All Foundational tasks marked [P] can run in parallel (within Phase 2) | |
| 191 | +- Once Foundational phase completes, all user stories can start in parallel (if team capacity allows) | |
| 192 | +- All tests for a user story marked [P] can run in parallel | |
| 193 | +- Models within a story marked [P] can run in parallel | |
| 194 | +- Different user stories can be worked on in parallel by different team members | |
| 195 | + | |
| 196 | +--- | |
| 197 | + | |
| 198 | +## Parallel Example: User Story 1 | |
| 199 | + | |
| 200 | +```bash | |
| 201 | +# Launch all tests for User Story 1 together (if tests requested): | |
| 202 | +Task: "Contract test for [endpoint] in tests/contract/test_[name].py" | |
| 203 | +Task: "Integration test for [user journey] in tests/integration/test_[name].py" | |
| 204 | + | |
| 205 | +# Launch all models for User Story 1 together: | |
| 206 | +Task: "Create [Entity1] model in src/models/[entity1].py" | |
| 207 | +Task: "Create [Entity2] model in src/models/[entity2].py" | |
| 208 | +``` | |
| 209 | + | |
| 210 | +--- | |
| 211 | + | |
| 212 | +## Implementation Strategy | |
| 213 | + | |
| 214 | +### MVP First (User Story 1 Only) | |
| 215 | + | |
| 216 | +1. Complete Phase 1: Setup | |
| 217 | +2. Complete Phase 2: Foundational (CRITICAL - blocks all stories) | |
| 218 | +3. Complete Phase 3: User Story 1 | |
| 219 | +4. **STOP and VALIDATE**: Test User Story 1 independently | |
| 220 | +5. Deploy/demo if ready | |
| 221 | + | |
| 222 | +### Incremental Delivery | |
| 223 | + | |
| 224 | +1. Complete Setup + Foundational → Foundation ready | |
| 225 | +2. Add User Story 1 → Test independently → Deploy/Demo (MVP!) | |
| 226 | +3. Add User Story 2 → Test independently → Deploy/Demo | |
| 227 | +4. Add User Story 3 → Test independently → Deploy/Demo | |
| 228 | +5. Each story adds value without breaking previous stories | |
| 229 | + | |
| 230 | +### Parallel Team Strategy | |
| 231 | + | |
| 232 | +With multiple developers: | |
| 233 | + | |
| 234 | +1. Team completes Setup + Foundational together | |
| 235 | +2. Once Foundational is done: | |
| 236 | + - Developer A: User Story 1 | |
| 237 | + - Developer B: User Story 2 | |
| 238 | + - Developer C: User Story 3 | |
| 239 | +3. Stories complete and integrate independently | |
| 240 | + | |
| 241 | +--- | |
| 242 | + | |
| 243 | +## Notes | |
| 244 | + | |
| 245 | +- [P] tasks = different files, no dependencies | |
| 246 | +- [Story] label maps task to specific user story for traceability | |
| 247 | +- Each user story should be independently completable and testable | |
| 248 | +- Verify tests fail before implementing | |
| 249 | +- Commit after each task or logical group | |
| 250 | +- Stop at any checkpoint to validate story independently | |
| 251 | +- Avoid: vague tasks, same file conflicts, cross-story dependencies that break independence |
A
README.md
+13
-0
@@ -0,0 +1,13 @@
| 1 | +#RustWarden | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | +#Objectif | |
| 6 | +après reflexion sur le travail realiser dans Rustcloud sur la gestion des utilisateur je voudrai creer un portail generique de gestion des utilisateurs à reutiliser dans d'autre applications | |
| 7 | + | |
| 8 | +un framwork ou un boilerplate de site internet en rust avec gestion utilisateur et on ameliore avec Oauth OIDC Ldap | |
| 9 | + | |
| 10 | + | |
| 11 | +login password | |
| 12 | +verification du mail | |
| 13 | +etc.. |
A
SPECIFICATION.md
+1075
-0
@@ -0,0 +1,1075 @@
| 1 | +# Rustwarden — Spécification d'extraction du framework | |
| 2 | + | |
| 3 | +## 1. Vision du projet | |
| 4 | + | |
| 5 | +**Rustwarden** est un framework/boilerplate Rust réutilisable de gestion des utilisateurs, extrait du projet **rustcloud**. L'objectif est de fournir un socle complet et prêt à l'emploi pour tout projet web nécessitant : | |
| 6 | + | |
| 7 | +- Authentification (login/password, JWT, sessions) | |
| 8 | +- Gestion des utilisateurs (CRUD, profil, préférences) | |
| 9 | +- Système de rôles (RBAC) | |
| 10 | +- Vérification d'email | |
| 11 | +- Réinitialisation et changement de mot de passe | |
| 12 | +- Middleware d'authentification et d'autorisation | |
| 13 | +- Rate limiting | |
| 14 | +- Évolution future vers OAuth2, OIDC, LDAP | |
| 15 | + | |
| 16 | +--- | |
| 17 | + | |
| 18 | +## 2. Architecture cible | |
| 19 | + | |
| 20 | +``` | |
| 21 | +Rustwarden/ | |
| 22 | +├── Cargo.toml # Workspace + package principal | |
| 23 | +├── .env.sample # Variables d'environnement | |
| 24 | +├── package.json # Scripts build Tailwind CSS | |
| 25 | +├── tailwind.config.js # Config Tailwind + thème DaisyUI | |
| 26 | +├── README.md # Documentation | |
| 27 | +├── SPECIFICATION.md # Ce document | |
| 28 | +│ | |
| 29 | +├── static/ # Fichiers statiques servis par Axum | |
| 30 | +│ ├── css/ | |
| 31 | +│ │ ├── tailwind.src.css # Source Tailwind (import + thème DaisyUI) | |
| 32 | +│ │ ├── tailwind.css # CSS compilé (généré par npm run build:css) | |
| 33 | +│ │ └── custom.css # Styles personnalisés (variables, avatar, scrollbar) | |
| 34 | +│ ├── js/ | |
| 35 | +│ │ ├── htmx.min.js # HTMX (interactions sans rechargement) | |
| 36 | +│ │ └── alpine.min.js # Alpine.js (composants réactifs) | |
| 37 | +│ └── images/ | |
| 38 | +│ ├── favicon.svg # Favicon SVG | |
| 39 | +│ ├── apple-touch-icon.png # Icône Apple Touch | |
| 40 | +│ ├── logo.svg # Logo SVG | |
| 41 | +│ └── logo.png # Logo PNG | |
| 42 | +│ | |
| 43 | +├── migrations/ | |
| 44 | +│ └── src/ | |
| 45 | +│ ├── main.rs # Point d'entrée des migrations | |
| 46 | +│ ├── lib.rs # Registre des migrations | |
| 47 | +│ └── m20260305_000001_initial_schema.rs # Migration unique — schéma complet + RBAC | |
| 48 | +│ | |
| 49 | +├── src/ | |
| 50 | +│ ├── main.rs # Point d'entrée de l'application | |
| 51 | +│ ├── app_state.rs # État global de l'application | |
| 52 | +│ │ | |
| 53 | +│ ├── auth/ # Module d'authentification | |
| 54 | +│ │ ├── mod.rs | |
| 55 | +│ │ ├── session.rs # Gestion des sessions (Memory/Redis) | |
| 56 | +│ │ ├── jwt.rs # Service JWT (génération/validation) | |
| 57 | +│ │ ├── jwt_extractor.rs # Extraction JWT depuis requêtes | |
| 58 | +│ │ ├── handlers.rs # Handlers auth (login, register, etc.) | |
| 59 | +│ │ └── extractors.rs # Extracteur AuthUser | |
| 60 | +│ │ | |
| 61 | +│ ├── api/ | |
| 62 | +│ │ ├── routes.rs # Définition des routes | |
| 63 | +│ │ ├── middleware/ | |
| 64 | +│ │ │ ├── mod.rs | |
| 65 | +│ │ │ ├── auth_service.rs # Middleware auth (routes protégées) | |
| 66 | +│ │ │ ├── admin_service.rs # Middleware admin (vérification rôle) | |
| 67 | +│ │ │ ├── auth_required.rs # Helpers auth | |
| 68 | +│ │ │ ├── admin_helper.rs # Helpers admin | |
| 69 | +│ │ │ └── rate_limit.rs # Rate limiting | |
| 70 | +│ │ └── handlers/ | |
| 71 | +│ │ ├── login_handler.rs # Pages login/reset/verification | |
| 72 | +│ │ ├── user_handler.rs # API CRUD utilisateurs | |
| 73 | +│ │ ├── admin_handler.rs # Interface admin utilisateurs | |
| 74 | +│ │ └── settings_handler.rs # Profil, sessions, préférences | |
| 75 | +│ │ | |
| 76 | +│ ├── config/ | |
| 77 | +│ │ ├── mod.rs | |
| 78 | +│ │ ├── auth.rs # Configuration auth (JWT, sessions, etc.) | |
| 79 | +│ │ └── database.rs # Configuration base de données | |
| 80 | +│ │ | |
| 81 | +│ ├── models/ # Entités SeaORM | |
| 82 | +│ │ ├── mod.rs | |
| 83 | +│ │ ├── user.rs # Modèle User | |
| 84 | +│ │ ├── role.rs # Modèle Role | |
| 85 | +│ │ ├── user_role.rs # Table de liaison User↔Role | |
| 86 | +│ │ ├── refresh_token.rs # Refresh tokens | |
| 87 | +│ │ ├── jwt_blacklist.rs # Blacklist JWT | |
| 88 | +│ │ ├── user_preferences.rs # Préférences utilisateur | |
| 89 | +│ │ ├── password_reset_token.rs # Tokens de réinitialisation | |
| 90 | +│ │ ├── email_validation_token.rs # Tokens de validation email | |
| 91 | +│ │ └── password_change_request.rs # Demandes de changement password | |
| 92 | +│ │ | |
| 93 | +│ ├── services/ # Logique métier | |
| 94 | +│ │ ├── mod.rs | |
| 95 | +│ │ ├── auth_service.rs # Authentification (verify credentials) | |
| 96 | +│ │ ├── user_service.rs # CRUD utilisateurs | |
| 97 | +│ │ ├── role_service.rs # Gestion des rôles | |
| 98 | +│ │ ├── password_service.rs # Hash/validation bcrypt | |
| 99 | +│ │ ├── password_reset_service.rs # Reset password par email | |
| 100 | +│ │ ├── password_change_service.rs # Changement password avec confirm email | |
| 101 | +│ │ ├── jwt_blacklist_service.rs # Blacklist JWT au logout | |
| 102 | +│ │ ├── refresh_token_service.rs # Refresh tokens et rotation | |
| 103 | +│ │ ├── email_validation_service.rs # Validation email | |
| 104 | +│ │ └── auth_logging.rs # Logs d'authentification | |
| 105 | +│ │ | |
| 106 | +│ ├── templates/ # Code Rust des templates Askama | |
| 107 | +│ │ ├── mod.rs # Macro impl_template_response, LayoutContext | |
| 108 | +│ │ ├── email_templates.rs # Structs Askama pour les emails | |
| 109 | +│ │ └── helpers.rs # Contextes, breadcrumb, sidebar, CSRF, avatar | |
| 110 | +│ │ | |
| 111 | +│ └── bin/ # Utilitaires CLI | |
| 112 | +│ ├── seed.rs # Seeding de la base | |
| 113 | +│ ├── hash_password.rs # Hash un mot de passe | |
| 114 | +│ └── change_password.rs # Changement de mot de passe CLI | |
| 115 | +│ | |
| 116 | +└── templates/ # Templates HTML Askama | |
| 117 | + ├── base.html # Layout HTML de base (Tailwind/DaisyUI/HTMX/Alpine) | |
| 118 | + ├── base_with_theme.html # Snippet thème utilisateur | |
| 119 | + ├── login.html # Page login/register avec onglets | |
| 120 | + ├── home.html # Page d'accueil post-login | |
| 121 | + ├── profile.html # Page profil utilisateur | |
| 122 | + ├── email_verified.html # Page de confirmation email vérifié | |
| 123 | + ├── resend_verification.html # Page renvoi vérification | |
| 124 | + ├── reset_password.html # Page réinitialisation mot de passe | |
| 125 | + ├── settings.html # Page paramètres | |
| 126 | + ├── components/ | |
| 127 | + │ ├── header.html # En-tête avec logo et navigation | |
| 128 | + │ ├── navbar.html # Barre de navigation DaisyUI | |
| 129 | + │ ├── navigation.html # Liens de navigation (home, settings, admin) | |
| 130 | + │ ├── sidebar.html # Sidebar avec sections | |
| 131 | + │ ├── user_menu.html # Menu utilisateur (avatar, dropdown) | |
| 132 | + │ ├── breadcrumb.html # Fil d'Ariane | |
| 133 | + │ └── password_change_badge.html # Badge alerte changement password | |
| 134 | + ├── fragments/ | |
| 135 | + │ ├── user_menu_dropdown.html # Dropdown : profil, paramètres, déconnexion | |
| 136 | + │ └── form_message.html # Fragment messages succès/erreur | |
| 137 | + ├── admin/ | |
| 138 | + │ ├── dashboard.html # Dashboard admin (stats, liens) | |
| 139 | + │ ├── users_list.html # Liste utilisateurs (recherche, filtres, pagination) | |
| 140 | + │ ├── user_form.html # Formulaire création/édition utilisateur | |
| 141 | + │ └── errors.html # Page erreurs admin | |
| 142 | + ├── settings/ | |
| 143 | + │ ├── password.html # Formulaire changement mot de passe | |
| 144 | + │ ├── preferences.html # Préférences (thème, langue) | |
| 145 | + │ └── sessions.html # Sessions actives + révocation | |
| 146 | + ├── emails/ | |
| 147 | + │ ├── email_validation.html # Email validation adresse | |
| 148 | + │ ├── password_reset.html # Email réinitialisation password | |
| 149 | + │ ├── password_changed.html # Notification password changé | |
| 150 | + │ ├── password_change_confirmation.html # Confirmation changement password | |
| 151 | + │ ├── welcome.html # Email de bienvenue | |
| 152 | + │ ├── admin_new_user.html # Notification admin nouvel utilisateur | |
| 153 | + │ └── account_modified.html # Notification modification compte | |
| 154 | + └── errors/ | |
| 155 | + ├── 401.html # Non authentifié | |
| 156 | + ├── 403.html # Accès refusé | |
| 157 | + └── 500.html # Erreur serveur | |
| 158 | +``` | |
| 159 | + | |
| 160 | +--- | |
| 161 | + | |
| 162 | +## 3. Inventaire complet des éléments à copier depuis rustcloud | |
| 163 | + | |
| 164 | +### 3.1 Migration de base de données — UNIQUE ET CONSOLIDÉE | |
| 165 | + | |
| 166 | +Puisque Rustwarden est un projet neuf, les 11 migrations incrémentales de rustcloud sont **fusionnées en une seule migration initiale** qui crée le schéma complet avec le RBAC dès le départ. | |
| 167 | + | |
| 168 | +**Fichiers à créer :** | |
| 169 | + | |
| 170 | +| Fichier | Rôle | | |
| 171 | +|---|---| | |
| 172 | +| `migrations/src/main.rs` | Point d'entrée du binaire `migrate` | | |
| 173 | +| `migrations/src/lib.rs` | Registre des migrations (une seule entrée) | | |
| 174 | +| `migrations/src/m20260305_000001_initial_schema.rs` | **Migration unique — schéma complet** | | |
| 175 | + | |
| 176 | +**Fichiers source rustcloud à consulter** (pour en extraire et fusionner la logique) : | |
| 177 | + | |
| 178 | +| Migration rustcloud | Intégrée dans | | |
| 179 | +|---|---| | |
| 180 | +| `m20241209_000001_create_users_table` | Table `users` (avec `last_login_at/ip`, `email_verified/at`, `password_changed_at` déjà inclus) | | |
| 181 | +| `m20241209_000002_create_roles_table` | Table `roles` | | |
| 182 | +| `m20241209_000003_create_user_roles_table` | Table `user_roles` | | |
| 183 | +| `m20241209_000004_create_refresh_tokens_table` | Table `refresh_tokens` | | |
| 184 | +| `m20241211_000005_create_jwt_blacklist_table` | Table `jwt_blacklist` | | |
| 185 | +| `m20241211_000006_create_user_preferences_table` | Table `user_preferences` | | |
| 186 | +| `m20241211_000008_add_last_login_to_users` | ⟶ Fusionné dans la table `users` | | |
| 187 | +| `m20241214_000010_create_password_reset_tokens_table` | Table `password_reset_tokens` | | |
| 188 | +| `m20241214_000011_create_email_validation_tokens_table` | Table `email_validation_tokens` | | |
| 189 | +| `m20241214_000012_add_email_verified_to_users` | ⟶ Fusionné dans la table `users` | | |
| 190 | +| `m20251213_000021_create_password_change_requests_table` | Table `password_change_requests` | | |
| 191 | + | |
| 192 | +**Migrations rustcloud EXCLUES** (domaine métier) : | |
| 193 | +- `m20250127_000018_create_organisations_table` — hors périmètre | |
| 194 | +- `m20250127_000019_create_organisation_members_table` — hors périmètre | |
| 195 | +- `m20250127_000020_create_shares_table` — hors périmètre | |
| 196 | + | |
| 197 | +**Schéma SQL consolidé** de la migration unique `m20260305_000001_initial_schema` : | |
| 198 | + | |
| 199 | +```sql | |
| 200 | +-- ============================================= | |
| 201 | +-- Rustwarden — Migration initiale | |
| 202 | +-- Schéma complet : utilisateurs, RBAC, auth | |
| 203 | +-- ============================================= | |
| 204 | + | |
| 205 | +-- 1. Table des utilisateurs (fusion de 3 migrations rustcloud) | |
| 206 | +CREATE TABLE users ( | |
| 207 | + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), | |
| 208 | + username VARCHAR(64) NOT NULL UNIQUE, | |
| 209 | + email VARCHAR(255) NOT NULL UNIQUE, | |
| 210 | + password_hash VARCHAR(255) NOT NULL, | |
| 211 | + must_change_password BOOLEAN NOT NULL DEFAULT FALSE, | |
| 212 | + last_login_at TIMESTAMPTZ, | |
| 213 | + last_login_ip VARCHAR(45), | |
| 214 | + password_changed_at TIMESTAMPTZ, | |
| 215 | + email_verified BOOLEAN NOT NULL DEFAULT FALSE, | |
| 216 | + email_verified_at TIMESTAMPTZ, | |
| 217 | + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), | |
| 218 | + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() | |
| 219 | +); | |
| 220 | + | |
| 221 | +-- 2. Table des rôles | |
| 222 | +CREATE TABLE roles ( | |
| 223 | + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), | |
| 224 | + name VARCHAR(64) NOT NULL UNIQUE, | |
| 225 | + description TEXT, | |
| 226 | + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), | |
| 227 | + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() | |
| 228 | +); | |
| 229 | + | |
| 230 | +-- 3. Table de liaison utilisateurs ↔ rôles (RBAC) | |
| 231 | +CREATE TABLE user_roles ( | |
| 232 | + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, | |
| 233 | + role_id UUID NOT NULL REFERENCES roles(id) ON DELETE CASCADE, | |
| 234 | + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), | |
| 235 | + PRIMARY KEY (user_id, role_id) | |
| 236 | +); | |
| 237 | + | |
| 238 | +-- 4. Refresh tokens (rotation de tokens JWT) | |
| 239 | +CREATE TABLE refresh_tokens ( | |
| 240 | + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), | |
| 241 | + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, | |
| 242 | + token VARCHAR(255) NOT NULL UNIQUE, | |
| 243 | + expires_at TIMESTAMPTZ NOT NULL, | |
| 244 | + revoked BOOLEAN NOT NULL DEFAULT FALSE, | |
| 245 | + revoked_at TIMESTAMPTZ, | |
| 246 | + replaced_by UUID, | |
| 247 | + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() | |
| 248 | +); | |
| 249 | + | |
| 250 | +-- 5. Blacklist JWT (tokens invalidés au logout) | |
| 251 | +CREATE TABLE jwt_blacklist ( | |
| 252 | + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), | |
| 253 | + token_hash VARCHAR(255) NOT NULL UNIQUE, | |
| 254 | + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, | |
| 255 | + expires_at TIMESTAMPTZ NOT NULL, | |
| 256 | + revoked_at TIMESTAMPTZ, | |
| 257 | + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() | |
| 258 | +); | |
| 259 | + | |
| 260 | +-- 6. Préférences utilisateur | |
| 261 | +CREATE TABLE user_preferences ( | |
| 262 | + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), | |
| 263 | + user_id UUID NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE, | |
| 264 | + theme VARCHAR(16) NOT NULL DEFAULT 'auto', | |
| 265 | + language VARCHAR(8) NOT NULL DEFAULT 'fr', | |
| 266 | + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), | |
| 267 | + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() | |
| 268 | +); | |
| 269 | + | |
| 270 | +-- 7. Tokens de réinitialisation de mot de passe | |
| 271 | +CREATE TABLE password_reset_tokens ( | |
| 272 | + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), | |
| 273 | + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, | |
| 274 | + token_hash VARCHAR(255) NOT NULL UNIQUE, | |
| 275 | + expires_at TIMESTAMPTZ NOT NULL, | |
| 276 | + used_at TIMESTAMPTZ, | |
| 277 | + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() | |
| 278 | +); | |
| 279 | + | |
| 280 | +-- 8. Tokens de validation d'email | |
| 281 | +CREATE TABLE email_validation_tokens ( | |
| 282 | + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), | |
| 283 | + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, | |
| 284 | + token_hash VARCHAR(255) NOT NULL UNIQUE, | |
| 285 | + expires_at TIMESTAMPTZ NOT NULL, | |
| 286 | + used_at TIMESTAMPTZ, | |
| 287 | + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() | |
| 288 | +); | |
| 289 | + | |
| 290 | +-- 9. Demandes de changement de mot de passe (avec confirmation email) | |
| 291 | +CREATE TABLE password_change_requests ( | |
| 292 | + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), | |
| 293 | + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, | |
| 294 | + token_hash VARCHAR(255) NOT NULL UNIQUE, | |
| 295 | + new_password_hash VARCHAR(255) NOT NULL, | |
| 296 | + expires_at TIMESTAMPTZ NOT NULL, | |
| 297 | + confirmed BOOLEAN NOT NULL DEFAULT FALSE, | |
| 298 | + used_at TIMESTAMPTZ, | |
| 299 | + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() | |
| 300 | +); | |
| 301 | + | |
| 302 | +-- ============================================= | |
| 303 | +-- Index pour les performances | |
| 304 | +-- ============================================= | |
| 305 | +CREATE INDEX idx_refresh_tokens_user_id ON refresh_tokens(user_id); | |
| 306 | +CREATE INDEX idx_refresh_tokens_token ON refresh_tokens(token); | |
| 307 | +CREATE INDEX idx_jwt_blacklist_token_hash ON jwt_blacklist(token_hash); | |
| 308 | +CREATE INDEX idx_jwt_blacklist_expires_at ON jwt_blacklist(expires_at); | |
| 309 | +CREATE INDEX idx_password_reset_tokens_user_id ON password_reset_tokens(user_id); | |
| 310 | +CREATE INDEX idx_email_validation_tokens_user_id ON email_validation_tokens(user_id); | |
| 311 | +CREATE INDEX idx_password_change_requests_user_id ON password_change_requests(user_id); | |
| 312 | + | |
| 313 | +-- ============================================= | |
| 314 | +-- Seed RBAC : rôles par défaut | |
| 315 | +-- ============================================= | |
| 316 | +INSERT INTO roles (id, name, description) VALUES | |
| 317 | + (gen_random_uuid(), 'admin', 'Administrateur avec accès complet'), | |
| 318 | + (gen_random_uuid(), 'user', 'Utilisateur standard'); | |
| 319 | +``` | |
| 320 | + | |
| 321 | +> **Note** : Le seed RBAC (insertion des rôles `admin` et `user`) est inclus directement dans la migration pour garantir que les rôles de base existent toujours. Le seed de l'utilisateur admin reste dans `src/bin/seed.rs` car il dépend de variables d'environnement (mot de passe, email). | |
| 322 | + | |
| 323 | +### 3.2 Modèles SeaORM (COPIER + ADAPTER) | |
| 324 | + | |
| 325 | +| Fichier source | Action | Modifications | | |
| 326 | +|---|---|---| | |
| 327 | +| `src/models/user.rs` | Copier | Supprimer les relations avec organisations/shares | | |
| 328 | +| `src/models/role.rs` | Copier tel quel | Aucune | | |
| 329 | +| `src/models/user_role.rs` | Copier tel quel | Aucune | | |
| 330 | +| `src/models/refresh_token.rs` | Copier tel quel | Aucune | | |
| 331 | +| `src/models/jwt_blacklist.rs` | Copier tel quel | Aucune | | |
| 332 | +| `src/models/user_preferences.rs` | Copier tel quel | Aucune | | |
| 333 | +| `src/models/password_reset_token.rs` | Copier tel quel | Aucune | | |
| 334 | +| `src/models/email_validation_token.rs` | Copier tel quel | Aucune | | |
| 335 | +| `src/models/password_change_request.rs` | Copier tel quel | Aucune | | |
| 336 | + | |
| 337 | +**Modèles à NE PAS copier** : | |
| 338 | +- Tout modèle lié à organisation, share, files, todo, apps | |
| 339 | + | |
| 340 | +### 3.3 Module Auth (COPIER + ADAPTER) | |
| 341 | + | |
| 342 | +| Fichier source | Action | Modifications | | |
| 343 | +|---|---|---| | |
| 344 | +| `src/auth/mod.rs` | Copier | Supprimer les exports liés au domaine métier | | |
| 345 | +| `src/auth/session.rs` | Copier tel quel | Aucune — déjà générique | | |
| 346 | +| `src/auth/jwt.rs` | Copier | Renommer issuer `rustcloud` → `rustwarden` | | |
| 347 | +| `src/auth/jwt_extractor.rs` | Copier tel quel | Aucune | | |
| 348 | +| `src/auth/handlers.rs` | Copier | Supprimer les redirections vers `/home` rustcloud, rendre configurable | | |
| 349 | +| `src/auth/extractors.rs` | Copier tel quel | Aucune — déjà générique | | |
| 350 | + | |
| 351 | +### 3.4 Services (COPIER + ADAPTER) | |
| 352 | + | |
| 353 | +| Fichier source | Action | Modifications | | |
| 354 | +|---|---|---| | |
| 355 | +| `src/services/auth_service.rs` | Copier | Supprimer les dépendances vers le domaine métier | | |
| 356 | +| `src/services/user_service.rs` | Copier | Retirer les fonctions liées aux organisations/shares, garder uniquement CRUD user + rôles | | |
| 357 | +| `src/services/role_service.rs` | Copier tel quel | Aucune | | |
| 358 | +| `src/services/password_service.rs` | Copier tel quel | Aucune | | |
| 359 | +| `src/services/password_reset_service.rs` | Copier tel quel | Aucune | | |
| 360 | +| `src/services/password_change_service.rs` | Copier tel quel | Aucune | | |
| 361 | +| `src/services/jwt_blacklist_service.rs` | Copier tel quel | Aucune | | |
| 362 | +| `src/services/refresh_token_service.rs` | Copier tel quel | Aucune | | |
| 363 | +| `src/services/email_validation_service.rs` | Copier tel quel | Aucune | | |
| 364 | +| `src/services/auth_logging.rs` | Copier tel quel | Aucune | | |
| 365 | + | |
| 366 | +### 3.5 Middleware (COPIER + ADAPTER) | |
| 367 | + | |
| 368 | +| Fichier source | Action | Modifications | | |
| 369 | +|---|---|---| | |
| 370 | +| `src/api/middleware/auth_service.rs` | Copier | Rendre les routes protégées **configurables** au lieu d'un hardcodé `/home`, `/settings`, etc. | | |
| 371 | +| `src/api/middleware/admin_service.rs` | Copier | Rendre les routes admin configurables | | |
| 372 | +| `src/api/middleware/auth_required.rs` | Copier tel quel | Aucune | | |
| 373 | +| `src/api/middleware/admin_helper.rs` | Copier tel quel | Aucune | | |
| 374 | +| `src/api/middleware/rate_limit.rs` | Copier tel quel | Aucune | | |
| 375 | + | |
| 376 | +### 3.6 Configuration (COPIER + ADAPTER) | |
| 377 | + | |
| 378 | +| Fichier source | Action | Modifications | | |
| 379 | +|---|---|---| | |
| 380 | +| `src/config/auth.rs` | Copier | Renommer `rustcloud` → `rustwarden` dans les valeurs par défaut | | |
| 381 | +| `env.sample` | Copier | Simplifier, retirer les variables spécifiques au domaine métier | | |
| 382 | + | |
| 383 | +### 3.7 Handlers / Routes API (COPIER + ADAPTER) | |
| 384 | + | |
| 385 | +| Fichier source | Action | Modifications | | |
| 386 | +|---|---|---| | |
| 387 | +| `src/api/routes.rs` | Copier | **Épurer** : garder uniquement les routes auth, user, admin, settings. Supprimer files, shares, todo, apps, organisations | | |
| 388 | +| `src/api/handlers/login_handler.rs` | Copier | Adapter les templates | | |
| 389 | +| `src/api/handlers/user_handler.rs` | Copier | Garder uniquement le CRUD user | | |
| 390 | +| `src/api/handlers/admin_handler.rs` | Copier | Retirer la gestion d'organisations/apps/settings domaine | | |
| 391 | +| `src/api/handlers/settings_handler.rs` | Copier | Garder profil, password, sessions, préférences | | |
| 392 | + | |
| 393 | +### 3.8 Utilitaires CLI (COPIER + ADAPTER) | |
| 394 | + | |
| 395 | +| Fichier source | Action | Modifications | | |
| 396 | +|---|---|---| | |
| 397 | +| `src/bin/seed.rs` | Copier | Adapter les données de seed, simplifier | | |
| 398 | +| `src/bin/hash_password.rs` | Copier tel quel | Aucune | | |
| 399 | +| `src/bin/change_password.rs` | Copier tel quel | Aucune | | |
| 400 | + | |
| 401 | +### 3.9 Code Rust des templates — `src/templates/` (COPIER + ADAPTER) | |
| 402 | + | |
| 403 | +| Fichier source | Action | Modifications | | |
| 404 | +|---|---|---| | |
| 405 | +| `src/templates/mod.rs` | Copier + adapter | Macro `impl_template_response`, `LayoutContext` — renommer RustCloud → RustWarden, adapter les DTOs | | |
| 406 | +| `src/templates/email_templates.rs` | Copier + adapter | Structs Askama pour tous les emails (reset, validation, welcome, etc.) — renommer le branding | | |
| 407 | +| `src/templates/helpers.rs` | Copier + adapter | Contexte de base (session, claims), breadcrumb, sidebar, navigation, CSRF, initiales, couleur avatar — adapter les chemins et références | | |
| 408 | +| `src/templates/helpers/sharing_helpers.rs` | **NE PAS COPIER** | Spécifique au domaine métier (organisations, partages) | | |
| 409 | + | |
| 410 | +### 3.10 Templates HTML — `templates/` (COPIER + ADAPTER) | |
| 411 | + | |
| 412 | +#### Layout et base | |
| 413 | + | |
| 414 | +| Fichier source | Action | Modifications | | |
| 415 | +|---|---|---| | |
| 416 | +| `templates/base.html` | Copier + adapter | Layout HTML de base (Tailwind/DaisyUI, HTMX, Alpine.js) — renommer RustCloud → RustWarden | | |
| 417 | +| `templates/base_with_theme.html` | **Copier tel quel** | Snippet thème utilisateur — déjà générique | | |
| 418 | + | |
| 419 | +#### Pages publiques (auth) | |
| 420 | + | |
| 421 | +| Fichier source | Action | Modifications | | |
| 422 | +|---|---|---| | |
| 423 | +| `templates/login.html` | Copier + adapter | Page login/register avec onglets, i18n — adapter le branding | | |
| 424 | +| `templates/resend_verification.html` | Copier + adapter | Page renvoi de vérification — adapter le branding | | |
| 425 | +| `templates/reset_password.html` | Copier + adapter | Page réinitialisation mot de passe — adapter le branding | | |
| 426 | +| `templates/email_verified.html` | Copier + adapter | Page confirmation email vérifié — adapter le branding | | |
| 427 | + | |
| 428 | +#### Pages utilisateur | |
| 429 | + | |
| 430 | +| Fichier source | Action | Modifications | | |
| 431 | +|---|---|---| | |
| 432 | +| `templates/home.html` | Copier + **réécrire** | Page d'accueil post-login — contenu spécifique rustcloud à remplacer par un dashboard Rustwarden | | |
| 433 | +| `templates/profile.html` | Copier + adapter | Page profil utilisateur — adapter le branding | | |
| 434 | +| `templates/settings.html` | Copier + adapter | Page paramètres — retirer les entrées spécifiques au domaine | | |
| 435 | +| `templates/settings/password.html` | Copier + adapter | Formulaire changement mot de passe — adapter le branding | | |
| 436 | +| `templates/settings/preferences.html` | Copier + adapter | Préférences (thème, langue) — adapter le branding | | |
| 437 | +| `templates/settings/sessions.html` | Copier + adapter | Sessions actives + révocation — adapter le branding | | |
| 438 | + | |
| 439 | +#### Composants réutilisables | |
| 440 | + | |
| 441 | +| Fichier source | Action | Modifications | | |
| 442 | +|---|---|---| | |
| 443 | +| `templates/components/header.html` | Copier + adapter | En-tête avec logo et navigation — adapter branding et liens | | |
| 444 | +| `templates/components/navbar.html` | Copier + adapter | Barre de navigation DaisyUI — adapter les liens | | |
| 445 | +| `templates/components/navigation.html` | Copier + adapter | Liens de navigation — **retirer** "Fichiers" et liens domaine, garder home/settings/admin | | |
| 446 | +| `templates/components/sidebar.html` | **Copier tel quel** | Sidebar avec sections — déjà générique | | |
| 447 | +| `templates/components/user_menu.html` | **Copier tel quel** | Menu utilisateur (avatar, dropdown) — déjà générique | | |
| 448 | +| `templates/components/breadcrumb.html` | **Copier tel quel** | Fil d'Ariane DaisyUI — déjà générique | | |
| 449 | +| `templates/components/password_change_badge.html` | **Copier tel quel** | Badge alerte changement password — déjà générique | | |
| 450 | + | |
| 451 | +#### Fragments HTMX | |
| 452 | + | |
| 453 | +| Fichier source | Action | Modifications | | |
| 454 | +|---|---|---| | |
| 455 | +| `templates/fragments/user_menu_dropdown.html` | **Copier tel quel** | Dropdown profil/paramètres/déconnexion — déjà générique | | |
| 456 | +| `templates/fragments/form_message.html` | **Copier tel quel** | Fragment messages succès/erreur — déjà générique | | |
| 457 | + | |
| 458 | +#### Admin | |
| 459 | + | |
| 460 | +| Fichier source | Action | Modifications | | |
| 461 | +|---|---|---| | |
| 462 | +| `templates/admin/dashboard.html` | Copier + adapter | Dashboard admin — **retirer** les sections organisations/apps | | |
| 463 | +| `templates/admin/users_list.html` | Copier + adapter | Liste utilisateurs — adapter le branding | | |
| 464 | +| `templates/admin/user_form.html` | Copier + adapter | Formulaire création/édition — adapter le branding | | |
| 465 | +| `templates/admin/errors.html` | Copier + adapter | Page erreurs admin — adapter le branding | | |
| 466 | +| `templates/admin/settings.html` | Copier + adapter | Paramètres admin — retirer les paramètres domaine | | |
| 467 | + | |
| 468 | +#### Emails | |
| 469 | + | |
| 470 | +| Fichier source | Action | Modifications | | |
| 471 | +|---|---|---| | |
| 472 | +| `templates/emails/email_validation.html` | Copier + adapter | Validation email — renommer RustCloud → RustWarden | | |
| 473 | +| `templates/emails/password_reset.html` | Copier + adapter | Réinitialisation password — renommer | | |
| 474 | +| `templates/emails/password_changed.html` | Copier + adapter | Notification password changé — renommer | | |
| 475 | +| `templates/emails/password_change_confirmation.html` | Copier + adapter | Confirmation changement password — renommer | | |
| 476 | +| `templates/emails/welcome.html` | Copier + adapter | Email de bienvenue — renommer | | |
| 477 | +| `templates/emails/admin_new_user.html` | Copier + adapter | Notification admin nouvel utilisateur — renommer | | |
| 478 | +| `templates/emails/account_modified.html` | Copier + adapter | Notification modification compte — renommer | | |
| 479 | + | |
| 480 | +#### Pages d'erreur | |
| 481 | + | |
| 482 | +| Fichier source | Action | Modifications | | |
| 483 | +|---|---|---| | |
| 484 | +| `templates/errors/401.html` | Copier + adapter | Non authentifié — adapter le branding | | |
| 485 | +| `templates/errors/403.html` | Copier + adapter | Accès refusé — adapter le branding | | |
| 486 | +| `templates/errors/500.html` | Copier + adapter | Erreur serveur — adapter le branding | | |
| 487 | + | |
| 488 | +#### Templates à NE PAS copier (domaine métier rustcloud) | |
| 489 | + | |
| 490 | +| Fichier | Raison | | |
| 491 | +|---|---| | |
| 492 | +| `templates/admin/organisation_form.html` | Spécifique organisations | | |
| 493 | +| `templates/admin/organisation_members.html` | Spécifique organisations | | |
| 494 | +| `templates/admin/organisations_list.html` | Spécifique organisations | | |
| 495 | +| `templates/admin/organisations_list_rows.html` | Spécifique organisations | | |
| 496 | +| `templates/admin/apps_list.html` | Spécifique apps modulaires | | |
| 497 | +| `templates/components/organisation_selector.html` | Spécifique organisations | | |
| 498 | +| `templates/components/permissions_selector.html` | Spécifique partage | | |
| 499 | +| `templates/components/share_button.html` | Spécifique partage | | |
| 500 | +| `templates/components/share_list_item.html` | Spécifique partage | | |
| 501 | +| `templates/fragments/member_row.html` | Spécifique organisations | | |
| 502 | +| `templates/fragments/organisation_row.html` | Spécifique organisations | | |
| 503 | +| `templates/sharing/permissions_customize.html` | Spécifique partage | | |
| 504 | +| `templates/sharing/share_modal.html` | Spécifique partage | | |
| 505 | +| `templates/sharing/shares_received.html` | Spécifique partage | | |
| 506 | +| `templates/test.html` | Page de test | | |
| 507 | +| `templates/test_base.html` | Page de test | | |
| 508 | + | |
| 509 | +### 3.11 Fichiers statiques — `static/` (COPIER + ADAPTER) | |
| 510 | + | |
| 511 | +#### CSS | |
| 512 | + | |
| 513 | +| Fichier source | Taille | Action | Modifications | | |
| 514 | +|---|---|---|---| | |
| 515 | +| `static/css/tailwind.src.css` | 2,2 Ko | Copier + adapter | Fichier source Tailwind 4 + DaisyUI 5 — renommer le thème `rustcloud` → `rustwarden` | | |
| 516 | +| `static/css/tailwind.css` | 297 Ko | **Regénérer** | Fichier compilé — ne pas copier, le regénérer avec `npm run build:css` | | |
| 517 | +| `static/css/custom.css` | 1,4 Ko | Copier + adapter | Variables CSS (`--rc-primary`, etc.), couleurs avatars, scrollbar — renommer le préfixe `--rc-` → `--rw-` | | |
| 518 | + | |
| 519 | +#### JavaScript | |
| 520 | + | |
| 521 | +| Fichier source | Taille | Action | Modifications | | |
| 522 | +|---|---|---|---| | |
| 523 | +| `static/js/htmx.min.js` | 47 Ko | **Copier tel quel** | Librairie HTMX utilisée dans base.html et login.html | | |
| 524 | +| `static/js/alpine.min.js` | 43 Ko | **Copier tel quel** | Librairie Alpine.js pour les composants réactifs (dropdowns, onglets, etc.) | | |
| 525 | + | |
| 526 | +#### Images | |
| 527 | + | |
| 528 | +| Fichier source | Taille | Action | Modifications | | |
| 529 | +|---|---|---|---| | |
| 530 | +| `static/images/favicon.svg` | 4,3 Ko | **Remplacer** | Créer un nouveau favicon pour Rustwarden | | |
| 531 | +| `static/images/apple-touch-icon.png` | 2,4 Ko | **Remplacer** | Créer une nouvelle icône Apple Touch | | |
| 532 | +| `static/images/logo.svg` | 26 Ko | **Remplacer** | Créer un nouveau logo SVG Rustwarden | | |
| 533 | +| `static/images/logo.png` | 19 Ko | **Remplacer** | Créer un nouveau logo PNG Rustwarden | | |
| 534 | + | |
| 535 | +#### Fichier à NE PAS copier | |
| 536 | + | |
| 537 | +| Fichier | Raison | | |
| 538 | +|---|---| | |
| 539 | +| `static/test.txt` | Fichier de test, inutile | | |
| 540 | + | |
| 541 | +### 3.12 Configuration frontend (COPIER + ADAPTER) | |
| 542 | + | |
| 543 | +| Fichier source | Action | Modifications | | |
| 544 | +|---|---|---| | |
| 545 | +| `package.json` | Copier + adapter | Renommer `rustcloud` → `rustwarden`, garder les scripts `build:css` / `build:css:watch` / `build:css:min` | | |
| 546 | +| `tailwind.config.js` | Copier + adapter | Renommer le thème DaisyUI `rustcloud` → `rustwarden`, adapter les couleurs primaire/secondaire | | |
| 547 | + | |
| 548 | +**Configuration Tailwind adaptée pour Rustwarden :** | |
| 549 | + | |
| 550 | +```js | |
| 551 | +// tailwind.config.js | |
| 552 | +module.exports = { | |
| 553 | + content: ["./templates/**/*.html"], | |
| 554 | + theme: { | |
| 555 | + extend: { | |
| 556 | + colors: { | |
| 557 | + 'rustwarden': { | |
| 558 | + 'blue': '#3b82f6', // Couleur primaire à définir | |
| 559 | + 'rust': '#f97316', // Couleur accent à définir | |
| 560 | + } | |
| 561 | + } | |
| 562 | + }, | |
| 563 | + }, | |
| 564 | + plugins: [require('daisyui')], | |
| 565 | + daisyui: { | |
| 566 | + themes: [ | |
| 567 | + { | |
| 568 | + rustwarden: { | |
| 569 | + "primary": "#3b82f6", | |
| 570 | + "secondary": "#1e293b", | |
| 571 | + "accent": "#10b981", | |
| 572 | + "neutral": "#f5f5f5", | |
| 573 | + "base-100": "#ffffff", | |
| 574 | + "info": "#3b82f6", | |
| 575 | + "success": "#10b981", | |
| 576 | + "warning": "#f59e0b", | |
| 577 | + "error": "#ef4444", | |
| 578 | + }, | |
| 579 | + }, | |
| 580 | + "light", | |
| 581 | + "dark", | |
| 582 | + ], | |
| 583 | + }, | |
| 584 | +} | |
| 585 | +``` | |
| 586 | + | |
| 587 | +**Commande de build CSS :** | |
| 588 | + | |
| 589 | +```bash | |
| 590 | +npm install # Installer Tailwind + DaisyUI | |
| 591 | +npm run build:css # Compiler le CSS | |
| 592 | +npm run build:css:watch # Mode watch (développement) | |
| 593 | +npm run build:css:min # Compiler + minifier (production) | |
| 594 | +``` | |
| 595 | + | |
| 596 | +> **Bugs à corriger** (hérités de rustcloud) : | |
| 597 | +> - `templates/base.html` référence `/static/images/favicon.png` qui n'existe pas → utiliser `favicon.svg` | |
| 598 | +> - `templates/email_verified.html` référence `output.css` au lieu de `tailwind.css` → corriger | |
| 599 | + | |
| 600 | +### 3.13 Fichiers à NE PAS copier (résumé global) | |
| 601 | + | |
| 602 | +| Catégorie | Exemples | | |
| 603 | +|---|---| | |
| 604 | +| Apps modulaires | `crates/apps/files/`, `crates/apps/todo/` | | |
| 605 | +| Core métier | `crates/rustcloud-core/` (sauf `sharing/permissions.rs` si on veut le système de permissions bitmask) | | |
| 606 | +| SDK | `crates/rustcloud-app-sdk/` | | |
| 607 | +| i18n spécifique | Fichiers de traduction spécifiques au domaine | | |
| 608 | +| WebDAV | `crates/apps/files/src/webdav/` | | |
| 609 | +| Organisations | Tout ce qui touche aux organisations | | |
| 610 | +| Partages | Tout ce qui touche aux shares | | |
| 611 | + | |
| 612 | +--- | |
| 613 | + | |
| 614 | +## 4. Modifications structurelles à effectuer | |
| 615 | + | |
| 616 | +### 4.1 Cargo.toml — Nouveau fichier | |
| 617 | + | |
| 618 | +```toml | |
| 619 | +[package] | |
| 620 | +name = "rustwarden" | |
| 621 | +version = "0.1.0" | |
| 622 | +edition = "2021" | |
| 623 | +default-run = "rustwarden" | |
| 624 | + | |
| 625 | +[dependencies] | |
| 626 | +# Web framework | |
| 627 | +axum = { version = "0.8", features = ["macros"] } | |
| 628 | +tokio = { version = "1", features = ["full"] } | |
| 629 | +async-trait = "0.1" | |
| 630 | +# Serialization | |
| 631 | +serde = { version = "1.0", features = ["derive"] } | |
| 632 | +serde_json = "1.0" | |
| 633 | +# Middleware | |
| 634 | +tower = { version = "0.5", features = ["limit", "util"] } | |
| 635 | +tower-http = { version = "0.6", features = ["cors", "trace", "limit", "fs"] } | |
| 636 | +# Templates | |
| 637 | +askama = "0.14" | |
| 638 | +# Logging | |
| 639 | +tracing = "0.1" | |
| 640 | +tracing-subscriber = { version = "0.3", features = ["env-filter"] } | |
| 641 | +# Env | |
| 642 | +dotenvy = "0.15" | |
| 643 | +# Database ORM | |
| 644 | +sea-orm = { version = "2.0.0-rc.20", features = ["sqlx-postgres", "runtime-tokio-native-tls", "macros"] } | |
| 645 | +sea-orm-migration = { version = "2.0.0-rc.20", features = ["sqlx-postgres", "runtime-tokio-native-tls"] } | |
| 646 | +# Password hashing | |
| 647 | +bcrypt = "0.15" | |
| 648 | +# Validation | |
| 649 | +validator = { version = "0.20", features = ["derive"] } | |
| 650 | +# UUID & Datetime | |
| 651 | +uuid = { version = "1.0", features = ["v4", "serde"] } | |
| 652 | +chrono = { version = "0.4", features = ["serde"] } | |
| 653 | +time = { version = "0.3", features = ["macros", "serde"] } | |
| 654 | +# Error handling | |
| 655 | +thiserror = "1.0" | |
| 656 | +anyhow = "1.0" | |
| 657 | +# Authentication — JWT & Sessions | |
| 658 | +jsonwebtoken = "9.3" | |
| 659 | +axum-login = "0.18" | |
| 660 | +tower-sessions = "0.14" | |
| 661 | +tower-sessions-seaorm-store = "0.1.1" | |
| 662 | +tower-sessions-redis-store = { version = "0.14", optional = true } | |
| 663 | +tower-csrf = "0.1" | |
| 664 | +axum-extra = { version = "0.9", features = ["cookie"] } | |
| 665 | +rand = { version = "0.8", features = ["std"] } | |
| 666 | +# JWT Blacklist | |
| 667 | +sha2 = "0.10" | |
| 668 | +base64 = "0.22" | |
| 669 | +hex = "0.4" | |
| 670 | ||
| 671 | +lettre = { version = "0.11", features = ["tokio1-native-tls", "builder"] } | |
| 672 | + | |
| 673 | +[features] | |
| 674 | +default = [] | |
| 675 | +redis-session = ["tower-sessions-redis-store"] | |
| 676 | + | |
| 677 | +[[bin]] | |
| 678 | +name = "migrate" | |
| 679 | +path = "migrations/src/main.rs" | |
| 680 | + | |
| 681 | +[[bin]] | |
| 682 | +name = "hash_password" | |
| 683 | +path = "src/bin/hash_password.rs" | |
| 684 | + | |
| 685 | +[[bin]] | |
| 686 | +name = "seed" | |
| 687 | +path = "src/bin/seed.rs" | |
| 688 | + | |
| 689 | +[[bin]] | |
| 690 | +name = "change_password" | |
| 691 | +path = "src/bin/change_password.rs" | |
| 692 | +``` | |
| 693 | + | |
| 694 | +### 4.2 Renommages globaux | |
| 695 | + | |
| 696 | +| Ancien | Nouveau | | |
| 697 | +|---|---| | |
| 698 | +| `rustcloud` | `rustwarden` | | |
| 699 | +| `RustCloud` | `RustWarden` | | |
| 700 | +| `RUSTCLOUD` | `RUSTWARDEN` | | |
| 701 | + | |
| 702 | +À appliquer dans tous les fichiers copiés (noms de crates, imports, commentaires, issuer JWT, noms de cookies, etc.). | |
| 703 | + | |
| 704 | +### 4.3 Rendre les routes protégées configurables | |
| 705 | + | |
| 706 | +Actuellement dans rustcloud, les routes protégées sont hardcodées dans `AuthService` : | |
| 707 | + | |
| 708 | +```rust | |
| 709 | +// Ancien (hardcodé dans rustcloud) | |
| 710 | +let protected_paths = ["/home", "/settings", "/test-base", "/profil", "/apps/", "/shares"]; | |
| 711 | +``` | |
| 712 | + | |
| 713 | +**Modification** : les rendre configurables via la structure `AuthConfig` : | |
| 714 | + | |
| 715 | +```rust | |
| 716 | +// Nouveau (configurable dans rustwarden) | |
| 717 | +pub struct AuthConfig { | |
| 718 | + // ... champs existants ... | |
| 719 | + pub protected_paths: Vec<String>, | |
| 720 | + pub admin_paths: Vec<String>, | |
| 721 | + pub public_paths: Vec<String>, | |
| 722 | +} | |
| 723 | +``` | |
| 724 | + | |
| 725 | +### 4.4 Supprimer les dépendances au domaine métier | |
| 726 | + | |
| 727 | +Dans `user_service.rs` et `auth_service.rs`, retirer : | |
| 728 | +- Toute référence aux organisations | |
| 729 | +- Toute référence aux shares/partages | |
| 730 | +- Toute référence aux apps modulaires | |
| 731 | +- Les événements spécifiques (UserCreatedEvent lié au EventBus de rustcloud) | |
| 732 | + | |
| 733 | +### 4.5 Simplifier `main.rs` | |
| 734 | + | |
| 735 | +Le `main.rs` de Rustwarden doit être épuré : | |
| 736 | +- Garder : connexion DB, migrations, session layer, auth middleware, admin middleware, rate limiting | |
| 737 | +- Retirer : chargement des apps, EventBus, WebDAV, organisations, i18n complexe | |
| 738 | + | |
| 739 | +--- | |
| 740 | + | |
| 741 | +## 5. Schéma de base de données Rustwarden | |
| 742 | + | |
| 743 | +``` | |
| 744 | +┌─────────────────────────┐ | |
| 745 | +│ users │ | |
| 746 | +├─────────────────────────┤ | |
| 747 | +│ id UUID PK │ | |
| 748 | +│ username VARCHAR(64) │ UNIQUE | |
| 749 | +│ email VARCHAR(255) │ UNIQUE | |
| 750 | +│ password_hash VARCHAR │ | |
| 751 | +│ must_change_password BOOL│ | |
| 752 | +│ last_login_at TIMESTAMP │ | |
| 753 | +│ last_login_ip VARCHAR │ | |
| 754 | +│ password_changed_at TS │ | |
| 755 | +│ email_verified BOOL │ | |
| 756 | +│ email_verified_at TS │ | |
| 757 | +│ created_at TIMESTAMP │ | |
| 758 | +│ updated_at TIMESTAMP │ | |
| 759 | +└──────────┬──────────────┘ | |
| 760 | + │ | |
| 761 | + ┌─────┼──────────────────────────────────┐ | |
| 762 | + │ │ │ | |
| 763 | + ▼ ▼ ▼ | |
| 764 | +┌──────────────────┐ ┌──────────────────┐ ┌──────────────────────┐ | |
| 765 | +│ user_roles │ │ roles │ │ user_preferences │ | |
| 766 | +├──────────────────┤ ├──────────────────┤ ├──────────────────────┤ | |
| 767 | +│ user_id FK │──│ id UUID PK │ │ id UUID PK │ | |
| 768 | +│ role_id FK │ │ name UNIQUE │ │ user_id FK UNIQUE │ | |
| 769 | +│ created_at │ │ description │ │ theme ENUM │ | |
| 770 | +│ (PK composite) │ │ created_at │ │ language ENUM │ | |
| 771 | +└──────────────────┘ │ updated_at │ │ created_at │ | |
| 772 | + └──────────────────┘ │ updated_at │ | |
| 773 | + └──────────────────────┘ | |
| 774 | + │ | |
| 775 | + ├──────────────────────────────────────────────────────┐ | |
| 776 | + │ │ │ | |
| 777 | + ▼ ▼ ▼ | |
| 778 | +┌────────────────────┐ ┌────────────────────────┐ ┌─────────────────────────┐ | |
| 779 | +│ refresh_token │ │ jwt_blacklist │ │ password_reset_tokens │ | |
| 780 | +├────────────────────┤ ├────────────────────────┤ ├─────────────────────────┤ | |
| 781 | +│ id UUID PK │ │ id UUID PK │ │ id UUID PK │ | |
| 782 | +│ user_id FK │ │ token_hash UNIQUE │ │ user_id FK │ | |
| 783 | +│ token UNIQUE │ │ user_id FK │ │ token_hash UNIQUE │ | |
| 784 | +│ expires_at │ │ expires_at │ │ expires_at │ | |
| 785 | +│ revoked BOOL │ │ revoked_at │ │ used_at │ | |
| 786 | +│ revoked_at │ │ created_at │ │ created_at │ | |
| 787 | +│ replaced_by │ └────────────────────────┘ └─────────────────────────┘ | |
| 788 | +│ created_at │ | |
| 789 | +└────────────────────┘ | |
| 790 | + ┌──────────────────────────┐ ┌─────────────────────────────┐ | |
| 791 | + │ email_validation_tokens │ │ password_change_requests │ | |
| 792 | + ├──────────────────────────┤ ├─────────────────────────────┤ | |
| 793 | + │ id UUID PK │ │ id UUID PK │ | |
| 794 | + │ user_id FK │ │ user_id FK │ | |
| 795 | + │ token_hash UNIQUE │ │ token_hash UNIQUE │ | |
| 796 | + │ expires_at │ │ new_password_hash │ | |
| 797 | + │ used_at │ │ expires_at │ | |
| 798 | + │ created_at │ │ confirmed / used_at │ | |
| 799 | + └──────────────────────────┘ │ created_at │ | |
| 800 | + └─────────────────────────────┘ | |
| 801 | +``` | |
| 802 | + | |
| 803 | +--- | |
| 804 | + | |
| 805 | +## 6. API REST — Endpoints Rustwarden | |
| 806 | + | |
| 807 | +### 6.1 Authentification (`/api/v1/auth`) | |
| 808 | + | |
| 809 | +| Méthode | Endpoint | Description | Auth requise | | |
| 810 | +|---|---|---|---| | |
| 811 | +| POST | `/api/v1/auth/login` | Connexion (retourne JWT + refresh token) | Non | | |
| 812 | +| POST | `/api/v1/auth/register` | Inscription | Non | | |
| 813 | +| POST | `/api/v1/auth/logout` | Déconnexion (blacklist JWT) | Oui | | |
| 814 | +| POST | `/api/v1/auth/refresh` | Rafraîchir le token JWT | Non (refresh token) | | |
| 815 | +| GET | `/api/v1/auth/me` | Utilisateur courant | Oui | | |
| 816 | +| POST | `/api/v1/auth/forgot-password` | Demande de reset password | Non | | |
| 817 | +| POST | `/api/v1/auth/reset-password` | Réinitialiser le mot de passe | Non (token) | | |
| 818 | +| GET | `/api/v1/auth/verify-email/{token}` | Vérifier l'email | Non (token) | | |
| 819 | +| POST | `/api/v1/auth/resend-verification` | Renvoyer l'email de vérification | Oui | | |
| 820 | +| POST | `/api/v1/auth/resend-verification/by-username` | Renvoyer par username | Non | | |
| 821 | + | |
| 822 | +### 6.2 Gestion utilisateurs (`/api/v1/users`) | |
| 823 | + | |
| 824 | +| Méthode | Endpoint | Description | Auth requise | | |
| 825 | +|---|---|---|---| | |
| 826 | +| GET | `/api/v1/users` | Lister les utilisateurs | Admin | | |
| 827 | +| POST | `/api/v1/users` | Créer un utilisateur | Admin | | |
| 828 | + | |
| 829 | +### 6.3 Administration (`/admin`) | |
| 830 | + | |
| 831 | +| Méthode | Endpoint | Description | Auth requise | | |
| 832 | +|---|---|---|---| | |
| 833 | +| GET | `/admin` | Dashboard admin | Admin | | |
| 834 | +| GET | `/admin/users` | Liste des utilisateurs | Admin | | |
| 835 | +| GET | `/admin/users/create` | Formulaire création | Admin | | |
| 836 | +| POST | `/admin/users` | Créer un utilisateur | Admin | | |
| 837 | +| GET | `/admin/users/{id}` | Formulaire édition | Admin | | |
| 838 | +| PUT | `/admin/users/{id}` | Modifier un utilisateur | Admin | | |
| 839 | +| DELETE | `/admin/users/{id}` | Supprimer un utilisateur | Admin | | |
| 840 | +| POST | `/admin/users/{id}/reset-password` | Reset password (admin) | Admin | | |
| 841 | +| POST | `/admin/users/{id}/reset-password-email` | Reset password par email | Admin | | |
| 842 | + | |
| 843 | +### 6.4 Paramètres utilisateur (`/settings`) | |
| 844 | + | |
| 845 | +| Méthode | Endpoint | Description | Auth requise | | |
| 846 | +|---|---|---|---| | |
| 847 | +| GET | `/settings` | Page paramètres | Oui | | |
| 848 | +| GET | `/profile` | Page profil | Oui | | |
| 849 | +| PUT | `/profile` | Modifier profil | Oui | | |
| 850 | +| GET | `/settings/password` | Page mot de passe | Oui | | |
| 851 | +| PUT | `/settings/password` | Changer mot de passe | Oui | | |
| 852 | +| DELETE | `/settings/password/pending` | Annuler changement en cours | Oui | | |
| 853 | +| GET | `/settings/sessions` | Sessions actives | Oui | | |
| 854 | +| DELETE | `/settings/sessions/{id}` | Révoquer une session | Oui | | |
| 855 | +| GET | `/settings/preferences` | Préférences | Oui | | |
| 856 | +| PUT | `/settings/preferences` | Modifier préférences | Oui | | |
| 857 | +| GET | `/confirm-password-change` | Confirmer changement password | Non (token) | | |
| 858 | + | |
| 859 | +### 6.5 Pages publiques | |
| 860 | + | |
| 861 | +| Méthode | Endpoint | Description | | |
| 862 | +|---|---|---| | |
| 863 | +| GET | `/login` | Page de connexion | | |
| 864 | +| GET | `/resend-verification` | Page de renvoi de vérification | | |
| 865 | +| GET | `/reset-password` | Page de réinitialisation | | |
| 866 | + | |
| 867 | +--- | |
| 868 | + | |
| 869 | +## 7. Stack technique | |
| 870 | + | |
| 871 | +| Composant | Technologie | Version | | |
| 872 | +|---|---|---| | |
| 873 | +| Langage | Rust | 1.91+ | | |
| 874 | +| Framework web | Axum | 0.8 | | |
| 875 | +| ORM | SeaORM | 2.0.0-rc.20 | | |
| 876 | +| Base de données | PostgreSQL | 14+ | | |
| 877 | +| Runtime async | Tokio | 1.x | | |
| 878 | +| JWT | jsonwebtoken | 10.3.0 | | |
| 879 | +| Hashing passwords | bcrypt | 0.15 | | |
| 880 | +| Sessions | tower-sessions | 0.14 | | |
| 881 | +| Sessions store | tower-sessions-seaorm-store | 0.1.1 | | |
| 882 | +| Sessions Redis (opt.) | tower-sessions-redis-store | 0.16 | | |
| 883 | +| CSRF | tower-csrf | 0.1 | | |
| 884 | +| Templates | Askama | 0.15.4 | | |
| 885 | +| Email | Lettre | 0.11.19 | | |
| 886 | +| Validation | validator | 0.20 | | |
| 887 | +| Rate limiting | Custom (tower middleware) | — | | |
| 888 | + | |
| 889 | +--- | |
| 890 | + | |
| 891 | +## 8. Variables d'environnement | |
| 892 | + | |
| 893 | +```env | |
| 894 | +# Base de données | |
| 895 | +DATABASE_URL=postgres://rustwarden_user:password@localhost:5432/rustwarden | |
| 896 | + | |
| 897 | +# Serveur | |
| 898 | +SERVER_HOST=0.0.0.0 | |
| 899 | +SERVER_PORT=3000 | |
| 900 | + | |
| 901 | +# Logging | |
| 902 | +RUST_LOG=debug | |
| 903 | + | |
| 904 | +# JWT | |
| 905 | +JWT_SECRET=<min 32 caractères> | |
| 906 | +JWT_EXPIRATION_MINUTES=15 | |
| 907 | +JWT_ISSUER=rustwarden | |
| 908 | + | |
| 909 | +# Refresh tokens | |
| 910 | +REFRESH_TOKEN_EXPIRATION_DAYS=7 | |
| 911 | + | |
| 912 | +# Sessions | |
| 913 | +SESSION_SECRET=<min 64 caractères> | |
| 914 | +SESSION_TIMEOUT_MINUTES=30 | |
| 915 | +SESSION_BACKEND=memory # memory | seaorm | redis | |
| 916 | + | |
| 917 | +# Redis (si SESSION_BACKEND=redis) | |
| 918 | +REDIS_URL=redis://localhost:6379 | |
| 919 | + | |
| 920 | +# Rate Limiting | |
| 921 | +RATE_LIMIT_LOGIN_PER_MINUTE=5 | |
| 922 | +RATE_LIMIT_REFRESH_PER_MINUTE=10 | |
| 923 | +RATE_LIMIT_GENERAL_PER_MINUTE=100 | |
| 924 | + | |
| 925 | +# Cookies | |
| 926 | +COOKIE_SECURE=false # true en production | |
| 927 | +COOKIE_SAME_SITE=Lax # Lax | Strict | |
| 928 | + | |
| 929 | +# Admin initial | |
| 930 | +ADMIN_USERNAME=admin | |
| 931 | +ADMIN_EMAIL=admin@localhost | |
| 932 | +ADMIN_PASSWORD=ChangeMe123! | |
| 933 | + | |
| 934 | +# Email SMTP | |
| 935 | +SMTP_HOST=localhost | |
| 936 | +SMTP_PORT=587 | |
| 937 | +SMTP_USERNAME= | |
| 938 | +SMTP_PASSWORD= | |
| 939 | +SMTP_FROM=noreply@rustwarden.local | |
| 940 | +``` | |
| 941 | + | |
| 942 | +--- | |
| 943 | + | |
| 944 | +## 9. Fonctionnalités du framework — Détail | |
| 945 | + | |
| 946 | +### 9.1 Authentification JWT | |
| 947 | +- Algorithme HS256 | |
| 948 | +- Claims : `sub` (user_id), `username`, `roles`, `exp`, `iat`, `iss` | |
| 949 | +- Extraction depuis header `Authorization: Bearer <token>` OU cookie `jwt_token` | |
| 950 | +- Blacklist au logout (hash SHA256 stocké en base) | |
| 951 | +- Refresh token avec rotation (ancien token révoqué, nouveau créé) | |
| 952 | + | |
| 953 | +### 9.2 Sessions | |
| 954 | +- Backends interchangeables : Memory (dev), SeaORM (prod), Redis (haute dispo) | |
| 955 | +- Données de session : `user_id`, `username`, `roles` | |
| 956 | +- Cookies : HttpOnly, Secure (configurable), SameSite (Lax/Strict) | |
| 957 | + | |
| 958 | +### 9.3 RBAC (Role-Based Access Control) | |
| 959 | +- Rôles nommés (admin, user, etc.) | |
| 960 | +- Table de liaison many-to-many `user_roles` | |
| 961 | +- Extracteur `AuthUser` avec méthodes : `has_role()`, `has_any_role()`, `has_all_roles()` | |
| 962 | +- Middleware `AdminService` : vérifie le rôle "admin" | |
| 963 | + | |
| 964 | +### 9.4 Gestion des mots de passe | |
| 965 | +- Hash bcrypt | |
| 966 | +- Réinitialisation par email (token à usage unique avec expiration) | |
| 967 | +- Changement avec confirmation par email (double validation) | |
| 968 | +- Flag `must_change_password` pour forcer le changement à la prochaine connexion | |
| 969 | + | |
| 970 | +### 9.5 Vérification email | |
| 971 | +- Token envoyé par email à l'inscription | |
| 972 | +- Endpoint de vérification par token | |
| 973 | +- Renvoi de l'email de vérification (par auth ou par username) | |
| 974 | +- Champs `email_verified` et `email_verified_at` | |
| 975 | + | |
| 976 | +### 9.6 Rate Limiting | |
| 977 | +- Par endpoint (login, refresh, admin, general) | |
| 978 | +- Configurable via variables d'environnement | |
| 979 | +- Implémenté en middleware Tower | |
| 980 | + | |
| 981 | +### 9.7 Middleware d'authentification | |
| 982 | +- `AuthService` : protège les routes nécessitant une connexion | |
| 983 | +- `AdminService` : protège les routes nécessitant le rôle admin | |
| 984 | +- Chaîne : `Request → AdminService → AuthService → SessionLayer → Router` | |
| 985 | +- Redirection vers `/login?redirect=...` si non authentifié | |
| 986 | + | |
| 987 | +--- | |
| 988 | + | |
| 989 | +## 10. Plan d'implémentation par phases | |
| 990 | + | |
| 991 | +### Phase 1 — Socle (Fondations) | |
| 992 | +1. Initialiser le projet Cargo | |
| 993 | +2. Copier et adapter le `Cargo.toml` | |
| 994 | +3. Créer la migration unique consolidée `m20260305_000001_initial_schema.rs` (fusion des 11 migrations rustcloud + seed RBAC) | |
| 995 | +4. Créer `migrations/src/main.rs` et `migrations/src/lib.rs` | |
| 996 | +5. Copier tous les modèles SeaORM | |
| 997 | +6. Copier le module `config/` | |
| 998 | +7. Copier `env.sample` | |
| 999 | +8. Vérifier la compilation et tester `cargo run --bin migrate` | |
| 1000 | + | |
| 1001 | +### Phase 2 — Services | |
| 1002 | +1. Copier `services/password_service.rs` (aucune dépendance) | |
| 1003 | +2. Copier `services/auth_service.rs` (dépend de user model + password) | |
| 1004 | +3. Copier `services/user_service.rs` (épurer les dépendances métier) | |
| 1005 | +4. Copier `services/role_service.rs` | |
| 1006 | +5. Copier les services JWT, refresh token, blacklist | |
| 1007 | +6. Copier les services email, reset password, password change | |
| 1008 | +7. Copier `services/auth_logging.rs` | |
| 1009 | + | |
| 1010 | +### Phase 3 — Auth & Middleware | |
| 1011 | +1. Copier le module `auth/` complet | |
| 1012 | +2. Copier le module `api/middleware/` | |
| 1013 | +3. Rendre les routes protégées configurables | |
| 1014 | +4. Tester la chaîne d'authentification | |
| 1015 | + | |
| 1016 | +### Phase 4 — Handlers & Routes | |
| 1017 | +1. Copier les handlers auth (login, register, etc.) | |
| 1018 | +2. Copier les handlers admin (CRUD users) | |
| 1019 | +3. Copier les handlers settings (profil, password, sessions, preferences) | |
| 1020 | +4. Copier et adapter `api/routes.rs` | |
| 1021 | +5. Créer un `main.rs` simplifié | |
| 1022 | + | |
| 1023 | +### Phase 5 — Templates & UI | |
| 1024 | +1. Copier les templates login/register/reset | |
| 1025 | +2. Copier les templates admin | |
| 1026 | +3. Copier les templates settings | |
| 1027 | +4. Adapter le branding (rustcloud → rustwarden) | |
| 1028 | +5. Nettoyer la navigation (retirer les liens vers les fonctionnalités métier) | |
| 1029 | + | |
| 1030 | +### Phase 6 — CLI & Seed | |
| 1031 | +1. Copier les binaires utilitaires | |
| 1032 | +2. Adapter le seed pour Rustwarden | |
| 1033 | +3. Tester le flux complet : seed → login → admin → settings | |
| 1034 | + | |
| 1035 | +### Phase 7 — Évolutions futures (post-MVP) | |
| 1036 | +1. OAuth2 / OpenID Connect (login via Google, GitHub, etc.) | |
| 1037 | +2. LDAP / Active Directory | |
| 1038 | +3. 2FA (TOTP / WebAuthn) | |
| 1039 | +4. Audit log complet | |
| 1040 | +5. API keys pour applications tierces | |
| 1041 | +6. Système de permissions granulaire (bitmask, inspiré de `SharePermissions`) | |
| 1042 | + | |
| 1043 | +--- | |
| 1044 | + | |
| 1045 | +## 11. Critères de validation | |
| 1046 | + | |
| 1047 | +Le framework Rustwarden sera considéré comme fonctionnel quand : | |
| 1048 | + | |
| 1049 | +- [ ] `cargo run --bin migrate` crée toutes les tables | |
| 1050 | +- [ ] `cargo run --bin seed` crée l'utilisateur admin et les rôles | |
| 1051 | +- [ ] `cargo run` démarre le serveur sur le port configuré | |
| 1052 | +- [ ] La page `/login` s'affiche correctement | |
| 1053 | +- [ ] Le login/logout fonctionne (JWT + cookie) | |
| 1054 | +- [ ] Le refresh token fonctionne | |
| 1055 | +- [ ] L'inscription crée un utilisateur et envoie un email de vérification | |
| 1056 | +- [ ] La réinitialisation de mot de passe fonctionne par email | |
| 1057 | +- [ ] L'admin peut lister, créer, éditer, supprimer des utilisateurs | |
| 1058 | +- [ ] Le middleware bloque l'accès aux routes protégées sans auth | |
| 1059 | +- [ ] Le middleware admin bloque l'accès sans rôle admin | |
| 1060 | +- [ ] Le rate limiting fonctionne sur `/api/v1/auth/login` | |
| 1061 | +- [ ] Les préférences utilisateur (thème, langue) sont sauvegardées | |
| 1062 | +- [ ] La gestion des sessions actives fonctionne (liste, révocation) | |
| 1063 | + | |
| 1064 | +--- | |
| 1065 | + | |
| 1066 | +## 12. Ressources de test existantes | |
| 1067 | + | |
| 1068 | +Le projet rustcloud dispose de deux suites de tests réutilisables : | |
| 1069 | + | |
| 1070 | +| Projet | Type | Chemin | | |
| 1071 | +|---|---|---| | |
| 1072 | +| `sele_rustcloud` | Tests E2E Selenium (Python/pytest) | `/home/monsieurb/Documents/devel/specKit/sele_rustcloud` | | |
| 1073 | +| `Bruno_rustcloud` | Collection API Bruno | `/home/monsieurb/Documents/devel/specKit/Bruno_rustcloud` | | |
| 1074 | + | |
| 1075 | +Ces suites pourront être adaptées pour Rustwarden en modifiant les URLs et les données de seed. |
A
constitution.md
+149
-0
@@ -0,0 +1,149 @@
| 1 | +<!-- | |
| 2 | +Sync Impact Report: | |
| 3 | +- Version change: 0.5.1 → 0.5.2 | |
| 4 | +- Modified principles: None | |
| 5 | +- Added sections: "Development Environment" dans Technical Constraints - Usage de Docker pour PostgreSQL en développement | |
| 6 | +- Removed sections: None | |
| 7 | +- Templates requiring updates: | |
| 8 | + ✅ spec-template.md (no changes needed - already references constitution) | |
| 9 | + ✅ plan-template.md (no changes needed - already references constitution) | |
| 10 | + ✅ tasks-template.md (no changes needed - already references constitution) | |
| 11 | + ✅ commands/constitution.md (no changes needed) | |
| 12 | +- Follow-up TODOs: None | |
| 13 | +--> | |
| 14 | + | |
| 15 | +# Rustwarden Constitution | |
| 16 | + | |
| 17 | +## Core Principles | |
| 18 | + | |
| 19 | +### I. Qualité de Code | |
| 20 | + | |
| 21 | +Toutes les fonctions publiques DOIVENT être documentées avec `///` (doc comments Rust). Le code DOIT respecter les bonnes pratiques Rust (clippy warnings = 0). Les structures de données DOIVENT utiliser `#[derive(Debug, Clone)]` où approprié. La gestion d'erreurs DOIT utiliser `Result<T, E>` avec des types d'erreur explicites. | |
| 22 | + | |
| 23 | +**Rationale**: La documentation et la qualité du code facilitent la maintenance, la collaboration et réduisent les bugs. Rust offre des outils puissants (clippy, rustfmt) qui doivent être utilisés. | |
| 24 | + | |
| 25 | +### II. Architecture Axum et SeaORM | |
| 26 | + | |
| 27 | +Toutes les routes HTTP DOIVENT être définies avec Axum uniquement (`axum::Router`). Toutes les interactions avec la base de données DOIVENT passer par SeaORM (aucun raw SQL autorisé). Les migrations DOIVENT être gérées via le système de migrations SeaORM (`migrations/src/`). Le serveur DOIT utiliser Tokio comme runtime async (requis par Axum). | |
| 28 | + | |
| 29 | +**Documentation SeaORM** (amendement v0.4.1): Toutes les interactions avec la base de données DOIVENT être implémentées en référence à la [documentation officielle SeaORM](https://www.sea-ql.org/SeaORM/docs/index/). Avant d'implémenter une nouvelle fonctionnalité de base de données (requêtes, relations, transactions, etc.), la documentation SeaORM DOIT être consultée pour garantir l'utilisation des bonnes pratiques et des patterns recommandés. Les exemples de code et les patterns documentés dans la documentation SeaORM DOIVENT être privilégiés par rapport aux approches personnalisées. | |
| 30 | + | |
| 31 | +**Implémentation obligatoire des handlers serveur** (amendement v0.5.0): TOUJOURS implémenter les handlers serveur pour que l'API soit fonctionnelle. Les handlers stub (retournant `501 Not Implemented`) sont INTERDITS dans le code de production. Chaque route définie DOIT avoir un handler complet qui : | |
| 32 | +- Injecte l'état nécessaire (`State<DatabaseConnection>`, `Extension<Claims>`, etc.) | |
| 33 | +- Utilise les services métier appropriés | |
| 34 | +- Retourne des réponses fonctionnelles avec données réelles | |
| 35 | +- Gère les erreurs de manière appropriée | |
| 36 | + | |
| 37 | +Les handlers stub sont uniquement autorisés temporairement pendant le développement incrémental, mais DOIVENT être remplacés par des implémentations complètes avant que la feature soit considérée comme terminée. Toute documentation d'API (OpenAPI, guides, exemples) qui référence un endpoint DOIT correspondre à un handler serveur fonctionnel. | |
| 38 | + | |
| 39 | +**Rationale**: Axum et SeaORM sont les frameworks standard pour Rust, offrant sécurité, performance et maintenabilité. L'utilisation exclusive de ces outils garantit la cohérence de l'architecture. La documentation officielle SeaORM contient les meilleures pratiques, les patterns recommandés et les solutions aux problèmes courants. En s'y référant systématiquement, on évite les erreurs d'implémentation, on améliore la maintenabilité et on garantit la compatibilité avec les futures versions de SeaORM. L'implémentation complète des handlers serveur est essentielle pour que l'API soit réellement utilisable par les clients. Des handlers stub créent une fausse impression de fonctionnalité et empêchent les tests d'intégration réels. Cette règle garantit que toute documentation d'API correspond à une implémentation fonctionnelle, évitant les frustrations des développeurs clients. | |
| 40 | + | |
| 41 | +### III. Développement Incrémental | |
| 42 | + | |
| 43 | +Chaque fonctionnalité DOIT être complète et testée avant de passer à la suivante. L'architecture DOIT être modulaire (structure de dossiers claire, séparation des responsabilités). Les user stories DOIVENT être indépendantes et testables individuellement. | |
| 44 | + | |
| 45 | +**Rationale**: Le développement incrémental permet de livrer de la valeur rapidement, facilite les tests et réduit la complexité. Chaque étape doit être validée avant de continuer. | |
| 46 | + | |
| 47 | +### IV. Sécurité par Défaut | |
| 48 | + | |
| 49 | +Tous les secrets DOIVENT être stockés dans des variables d'environnement, JAMAIS dans le code. La validation et la sanitization des entrées utilisateur DOIVENT être effectuées systématiquement. L'authentification et l'autorisation RBAC DOIVENT être implémentées pour toutes les routes protégées. | |
| 50 | + | |
| 51 | +**JWT Authentication Standard** (amendement v0.3.1): Le système DOIT extraire et vérifier les JWT tokens depuis le header `Authorization` au format `Bearer <token>`. Cette extraction DOIT être la méthode principale pour l'authentification API. Les cookies HttpOnly peuvent être utilisés comme méthode alternative pour les clients web, mais le header Authorization a priorité pour permettre aux clients API de surcharger l'authentification par cookie. | |
| 52 | + | |
| 53 | +**Conformité ANSSI Rust** (amendement v0.4.0): Le code DOIT respecter les recommandations du [Guide ANSSI pour le développement sécurisé en Rust](https://anssi-fr.github.io/rust-guide/). Spécifiquement : | |
| 54 | +- Le code DOIT compiler avec `#![deny(warnings)]` activé (ou au minimum `#![warn(warnings)]`) | |
| 55 | +- Toute utilisation de `unsafe` DOIT être justifiée et documentée avec un commentaire `// SAFETY:` expliquant pourquoi `unsafe` est nécessaire et quels invariants doivent être respectés | |
| 56 | +- Les `unwrap()` et `expect()` sont INTERDITS dans le code de production (sauf dans les tests unitaires). Toutes les erreurs DOIVENT être gérées explicitement avec `Result<T, E>` et l'opérateur `?` | |
| 57 | +- L'utilisation de `std::mem::uninitialized` est INTERDITE (dépréciée). L'utilisation de `std::mem::MaybeUninit` DOIT être justifiée pour chaque cas d'usage | |
| 58 | +- Les outils `cargo-audit` et `cargo-outdated` DOIVENT être exécutés régulièrement. Les vulnérabilités détectées DOIVENT être corrigées avant chaque release | |
| 59 | +- Toutes les considérations de sécurité, invariants et garanties DOIVENT être documentées | |
| 60 | + | |
| 61 | +Voir `docs/ANSSI_COMPLIANCE_REPORT.md` pour le rapport de conformité détaillé et les actions prioritaires. | |
| 62 | + | |
| 63 | +**Rationale**: La sécurité est critique pour un système cloud. Les secrets dans le code sont une vulnérabilité majeure. La validation des entrées prévient les attaques par injection. L'authentification JWT via header Authorization est le standard de l'industrie pour les APIs REST et permet une authentification stateless sécurisée. Les guidelines ANSSI représentent les meilleures pratiques pour le développement sécurisé en Rust. Leur respect garantit que les garanties de sécurité offertes par Rust ne sont pas invalidées par une utilisation incorrecte du langage. | |
| 64 | + | |
| 65 | +### V. Tests et Validation Continue | |
| 66 | + | |
| 67 | +Tous les composants DOIVENT avoir des tests unitaires et d'intégration. La couverture de tests DOIT être > 80% (objectif > 90% pour les composants critiques). Les tests DOIVENT être exécutés avant chaque commit (`cargo test`). Les tests DOIVENT suivre les bonnes pratiques Rust (structure `#[cfg(test)]`, tests d'intégration dans `tests/integration/`). | |
| 68 | + | |
| 69 | +**Rationale**: Les tests garantissent la qualité et la fiabilité du code. Une couverture élevée réduit les régressions et facilite les refactorings. L'exécution automatique des tests avant commit maintient la qualité du codebase. | |
| 70 | + | |
| 71 | +## Technical Constraints | |
| 72 | + | |
| 73 | +### Framework Requirements | |
| 74 | + | |
| 75 | +- **Rust Version**: Rust 1.91.1+ (Edition 2024) - **IMPORTANT**: Version minimale requise pour Axum/SeaORM | |
| 76 | +- **Web Framework**: Axum 0.8.7+ (dernière version stable) | |
| 77 | +- **ORM**: SeaORM 2.0.x+ (requis pour toutes les interactions DB) | |
| 78 | +- **Runtime**: Tokio 1.x (requis par Axum) | |
| 79 | +- **Database**: PostgreSQL 18+ (recommandé) | |
| 80 | + | |
| 81 | +### Development Environment | |
| 82 | + | |
| 83 | +**Docker pour Base de Données** (amendement v0.5.2): En développement, la base de données PostgreSQL DOIT être lancée via Docker depuis le dossier `database/` à la racine du projet. Le développeur DOIT utiliser le fichier `database/docker-compose.yml` pour démarrer la base de données. La base de données est lancée et gérée par le développeur (pas automatiquement par le système). Cette configuration garantit un environnement de développement cohérent et isolé, facilite le partage de configuration entre développeurs, et permet un reset rapide de la base de données pour les tests. | |
| 84 | + | |
| 85 | +**Rationale**: L'utilisation de Docker pour PostgreSQL en développement standardise l'environnement de développement, évite les conflits de versions entre développeurs, et simplifie la configuration initiale. Le développeur garde le contrôle sur le démarrage/arrêt de la base de données, permettant une meilleure gestion des ressources et une flexibilité dans le workflow de développement. | |
| 86 | + | |
| 87 | +### Code Quality Requirements | |
| 88 | + | |
| 89 | +- Toutes les fonctions publiques DOIVENT avoir une documentation `///` | |
| 90 | +- `cargo clippy -- -D warnings` DOIT passer sans erreur | |
| 91 | +- `cargo fmt` DOIT être appliqué avant chaque commit | |
| 92 | +- Les erreurs DOIVENT utiliser des types explicites (`Result<T, AppError>`) | |
| 93 | +- `#![deny(warnings)]` DOIT être activé dans `src/lib.rs` ou `src/main.rs` (conformité ANSSI) | |
| 94 | +- Les `unwrap()` et `expect()` sont INTERDITS dans le code de production (conformité ANSSI) | |
| 95 | +- Toute utilisation de `unsafe` DOIT être documentée avec `// SAFETY:` (conformité ANSSI) | |
| 96 | + | |
| 97 | +### Testing Requirements | |
| 98 | + | |
| 99 | +- Tests unitaires dans le même fichier avec `#[cfg(test)]` ou dans `tests/unit/` | |
| 100 | +- Tests d'intégration dans `tests/integration/` | |
| 101 | +- Tests de contrat dans `tests/contract/` | |
| 102 | +- Couverture > 80% (objectif > 90% pour auth, security, core services) | |
| 103 | + | |
| 104 | +### Security Requirements | |
| 105 | + | |
| 106 | +- Pas de secrets hardcodés (variables d'environnement uniquement) | |
| 107 | +- Validation de toutes les entrées utilisateur | |
| 108 | +- Hashing des mots de passe (bcrypt, jamais en clair) | |
| 109 | +- JWT tokens: extraction depuis header `Authorization: Bearer <token>` (priorité 1) | |
| 110 | +- Cookies HttpOnly pour les clients web (fallback, priorité 2) | |
| 111 | +- Rate limiting sur les endpoints d'authentification | |
| 112 | +- Logging de tous les événements d'authentification (succès et échecs) | |
| 113 | +- Conformité aux guidelines ANSSI Rust (voir `docs/ANSSI_COMPLIANCE_REPORT.md`) | |
| 114 | +- Code `unsafe` minimisé et documenté avec `// SAFETY:` | |
| 115 | +- Gestion d'erreurs explicite (pas de panics en production) | |
| 116 | + | |
| 117 | +## Development Workflow | |
| 118 | + | |
| 119 | +### Code Review Process | |
| 120 | + | |
| 121 | +Toutes les pull requests DOIVENT être revues avant merge. Les reviewers DOIVENT vérifier la conformité avec cette constitution. Les violations constitutionnelles DOIVENT être corrigées avant merge. | |
| 122 | + | |
| 123 | +### Quality Gates | |
| 124 | + | |
| 125 | +- ✅ `cargo build` passe sans erreur | |
| 126 | +- ✅ `cargo test` passe (tous les tests) | |
| 127 | +- ✅ `cargo clippy -- -D warnings` passe | |
| 128 | +- ✅ `cargo fmt --check` passe | |
| 129 | +- ✅ Couverture de tests > 80% | |
| 130 | +- ✅ Documentation complète (`cargo doc` génère sans warnings) | |
| 131 | +- ✅ `cargo audit` ne signale pas de vulnérabilités (avant release, conformité ANSSI) | |
| 132 | +- ✅ `cargo outdated` a été vérifié (avant release, conformité ANSSI) | |
| 133 | +- ✅ Aucun `unwrap()`/`expect()` dans le code de production (sauf tests, conformité ANSSI) | |
| 134 | +- ✅ Tous les blocs `unsafe` sont documentés avec `// SAFETY:` (conformité ANSSI) | |
| 135 | + | |
| 136 | +### Testing Strategy | |
| 137 | + | |
| 138 | +1. **TDD recommandé**: Écrire les tests avant l'implémentation pour les nouvelles fonctionnalités | |
| 139 | +2. **Tests unitaires**: Pour chaque fonction publique, tester les cas normaux et d'erreur | |
| 140 | +3. **Tests d'intégration**: Pour chaque endpoint API, tester les scénarios complets | |
| 141 | +4. **Tests de contrat**: Pour chaque endpoint public, valider le format de réponse | |
| 142 | + | |
| 143 | +## Governance | |
| 144 | + | |
| 145 | +Cette constitution prévaut sur toutes les autres pratiques du projet. Les amendements nécessitent une documentation, une approbation et un plan de migration si nécessaire. | |
| 146 | + | |
| 147 | +**Version**: 0.5.2 | **Ratified**: 2025-12-09 | **Last Amended**: 2025-01-29 | |
| 148 | + | |
| 149 | +**Compliance**: Toutes les PRs et reviews DOIVENT vérifier la conformité avec cette constitution. La complexité DOIT être justifiée. Utiliser les templates dans `.specify/templates/` pour la documentation des features. |
A
database/docker-compose.yml
+19
-0
@@ -0,0 +1,19 @@
| 1 | +services: | |
| 2 | + | |
| 3 | + db: | |
| 4 | + image: postgres:18-trixie | |
| 5 | + shm_size: 1g | |
| 6 | + volumes: | |
| 7 | + - ./data/postgres_data:/var/lib/postgresql/18/docker | |
| 8 | + environment: | |
| 9 | + # If you need to create multiple database you can add coma separated databases eg gis,data | |
| 10 | + - POSTGRES_DB=${POSTGRES_DB:-database} | |
| 11 | + - POSTGRES_USER=${POSTGRES_USER:-user} | |
| 12 | + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-pass3ord} | |
| 13 | + - ALLOW_IP_RANGE=${ALLOW_IP_RANGE:-0.0.0.0/0} | |
| 14 | + # Add extensions you need to be enabled by default in the DB. Default are the five specified below | |
| 15 | + ports: | |
| 16 | + - 5432:5432 | |
| 17 | + restart: unless-stopped | |
| 18 | + healthcheck: | |
| 19 | + test: "exit 0" |
A
database/env.sample
+8
-0
@@ -0,0 +1,8 @@
| 1 | +## environment file for docker-compose and builders | |
| 2 | + | |
| 3 | +COMPOSE_PROJECT_NAME=postgres-rustcloud | |
| 4 | +POSTGRES_DB=rustcloud | |
| 5 | +POSTGRES_USER=eric | |
| 6 | +POSTGRES_PASSWORD=natmin170 | |
| 7 | +ALLOW_IP_RANGE=0.0.0.0/0 | |
| 8 | + |
A
docs/ANSSI_COMPLIANCE_REPORT.md
+470
-0
@@ -0,0 +1,470 @@
| 1 | +# Rapport de Conformité ANSSI - RustCloud | |
| 2 | + | |
| 3 | +> **Date** : 2025 | |
| 4 | +> **Projet** : RustCloud | |
| 5 | +> **Référence** : [Guide ANSSI Rust](https://anssi-fr.github.io/rust-guide/) | |
| 6 | + | |
| 7 | +## Résumé Exécutif | |
| 8 | + | |
| 9 | +Ce rapport analyse la conformité du code source de RustCloud aux recommandations du guide ANSSI pour le développement sécurisé en Rust. L'analyse couvre les fichiers du dossier `src/`. | |
| 10 | + | |
| 11 | +### Score Global de Conformité | |
| 12 | + | |
| 13 | +- ✅ **Conforme** : 75% | |
| 14 | +- ⚠️ **Améliorations recommandées** : 20% | |
| 15 | +- ❌ **Non conforme** : 5% | |
| 16 | + | |
| 17 | +--- | |
| 18 | + | |
| 19 | +## 1. Utilisation des Outils de l'Écosystème Rust | |
| 20 | + | |
| 21 | +### 1.1 Gestion des Dépendances | |
| 22 | + | |
| 23 | +#### ✅ Règle LIBS-OUTDATED - CONFORME | |
| 24 | +**Statut** : À vérifier manuellement | |
| 25 | + | |
| 26 | +- Le projet utilise `Cargo.toml` pour la gestion des dépendances | |
| 27 | +- **Recommandation** : Intégrer `cargo-outdated` dans le pipeline CI/CD | |
| 28 | +- **Action requise** : Ajouter une vérification périodique des dépendances obsolètes | |
| 29 | + | |
| 30 | +#### ✅ Règle LIBS-AUDIT - CONFORME | |
| 31 | +**Statut** : À vérifier manuellement | |
| 32 | + | |
| 33 | +- **Recommandation** : Intégrer `cargo-audit` dans le pipeline CI/CD | |
| 34 | +- **Action requise** : Ajouter `cargo audit` avant chaque release | |
| 35 | + | |
| 36 | +### 1.2 Compilation et Build | |
| 37 | + | |
| 38 | +#### ❌ Règle BUILD-WARNINGS - NON CONFORME | |
| 39 | +**Statut** : Le code ne refuse pas les warnings à la compilation | |
| 40 | + | |
| 41 | +**Problème identifié** : | |
| 42 | +- Aucun `#![deny(warnings)]` trouvé dans les fichiers `src/lib.rs` ou `src/main.rs` | |
| 43 | +- Les warnings de compilation ne sont pas traités comme des erreurs | |
| 44 | + | |
| 45 | +**Fichiers concernés** : | |
| 46 | +- `src/lib.rs` | |
| 47 | +- `src/main.rs` | |
| 48 | + | |
| 49 | +**Recommandation** : | |
| 50 | +```rust | |
| 51 | +// À ajouter en haut de src/lib.rs ou src/main.rs | |
| 52 | +#![deny(warnings)] | |
| 53 | +``` | |
| 54 | + | |
| 55 | +**Action requise** : Ajouter `#![deny(warnings)]` ou au minimum `#![warn(warnings)]` | |
| 56 | + | |
| 57 | +--- | |
| 58 | + | |
| 59 | +## 2. Gestion de la Mémoire | |
| 60 | + | |
| 61 | +### 2.1 Mémoire Non Initialisée | |
| 62 | + | |
| 63 | +#### ✅ Règle MEM-UNINIT - CONFORME | |
| 64 | +**Statut** : Aucune utilisation de `std::mem::uninitialized` détectée | |
| 65 | + | |
| 66 | +- Aucune utilisation de la fonction dépréciée `std::mem::uninitialized` | |
| 67 | +- ✅ Conforme | |
| 68 | + | |
| 69 | +#### ✅ Règle MEM-MAYBEUNINIT - CONFORME | |
| 70 | +**Statut** : Aucune utilisation de `std::mem::MaybeUninit` détectée | |
| 71 | + | |
| 72 | +- Aucune utilisation de `MaybeUninit` dans le code | |
| 73 | +- ✅ Conforme | |
| 74 | + | |
| 75 | +### 2.2 Fuites de Mémoire | |
| 76 | + | |
| 77 | +#### ✅ Avertissement MEM-FORGET - CONFORME | |
| 78 | +**Statut** : Aucune utilisation de `std::mem::forget` détectée | |
| 79 | + | |
| 80 | +- ✅ Conforme | |
| 81 | + | |
| 82 | +### 2.3 Pointeurs Bruts | |
| 83 | + | |
| 84 | +#### ✅ Règle MEM-RAW-PTR - CONFORME | |
| 85 | +**Statut** : Aucun pointeur brut (`*const T`, `*mut T`) détecté | |
| 86 | + | |
| 87 | +- Aucune utilisation de pointeurs bruts dans le code | |
| 88 | +- ✅ Conforme | |
| 89 | + | |
| 90 | +--- | |
| 91 | + | |
| 92 | +## 3. Code Unsafe | |
| 93 | + | |
| 94 | +### 3.1 Utilisation du Mot-clé `unsafe` | |
| 95 | + | |
| 96 | +#### ⚠️ Règle UNSAFE-JUSTIFY - AMÉLIORATION RECOMMANDÉE | |
| 97 | +**Statut** : Code `unsafe` présent mais documentation insuffisante | |
| 98 | + | |
| 99 | +**Utilisations détectées** : | |
| 100 | +- `src/config/admin.rs` : 6 occurrences (lignes 178, 193, 206, 216, 222, 235) | |
| 101 | +- `src/config/app.rs` : 2 occurrences (lignes 193, 204) | |
| 102 | + | |
| 103 | +**Analyse** : | |
| 104 | +- Toutes les utilisations de `unsafe` sont dans des **tests unitaires** | |
| 105 | +- Utilisation pour manipuler les variables d'environnement (`std::env::set_var`, `std::env::remove_var`) | |
| 106 | +- **Justification** : Nécessaire pour isoler les tests et éviter les interférences entre tests | |
| 107 | + | |
| 108 | +**Problèmes identifiés** : | |
| 109 | +1. ❌ Aucune documentation expliquant pourquoi `unsafe` est nécessaire | |
| 110 | +2. ❌ Aucun commentaire justifiant l'utilisation dans les tests | |
| 111 | + | |
| 112 | +**Recommandations** : | |
| 113 | + | |
| 114 | +```rust | |
| 115 | +// Exemple de documentation recommandée | |
| 116 | +#[test] | |
| 117 | +fn test_from_env_with_variables() { | |
| 118 | + // SAFETY: std::env::set_var/remove_var sont marqués unsafe car ils modifient | |
| 119 | + // l'état global de l'environnement. Dans les tests, c'est acceptable car : | |
| 120 | + // 1. Les tests s'exécutent de manière séquentielle | |
| 121 | + // 2. Chaque test nettoie après lui-même | |
| 122 | + // 3. L'isolation est garantie par le framework de test | |
| 123 | + unsafe { | |
| 124 | + std::env::set_var("ADMIN_USERNAME", "testadmin"); | |
| 125 | + std::env::set_var("ADMIN_EMAIL", "test@example.com"); | |
| 126 | + std::env::set_var("ADMIN_PASSWORD", "testpass123"); | |
| 127 | + } | |
| 128 | + // ... reste du test | |
| 129 | +} | |
| 130 | +``` | |
| 131 | + | |
| 132 | +**Action requise** : Documenter toutes les utilisations de `unsafe` avec des commentaires `// SAFETY:` | |
| 133 | + | |
| 134 | +#### ✅ Règle UNSAFE-MINIMIZE - CONFORME | |
| 135 | +**Statut** : Utilisation minimale de `unsafe` | |
| 136 | + | |
| 137 | +- Seulement 8 occurrences, toutes dans des tests | |
| 138 | +- Aucune utilisation dans le code de production | |
| 139 | +- ✅ Conforme | |
| 140 | + | |
| 141 | +#### ⚠️ Recommandation UNSAFE-REVIEW - AMÉLIORATION RECOMMANDÉE | |
| 142 | +**Statut** : Code review nécessaire | |
| 143 | + | |
| 144 | +- **Action requise** : S'assurer que le code `unsafe` dans les tests a été revu | |
| 145 | +- **Recommandation** : Ajouter une checklist de review pour le code `unsafe` | |
| 146 | + | |
| 147 | +--- | |
| 148 | + | |
| 149 | +## 4. Foreign Function Interface (FFI) | |
| 150 | + | |
| 151 | +### 4.1 Consistance des Types | |
| 152 | + | |
| 153 | +#### ✅ Règle FFI-TYPES - CONFORME | |
| 154 | +**Statut** : Aucune utilisation de FFI détectée | |
| 155 | + | |
| 156 | +- Aucune interface FFI dans le code analysé | |
| 157 | +- ✅ Conforme (N/A) | |
| 158 | + | |
| 159 | +--- | |
| 160 | + | |
| 161 | +## 5. Gestion des Erreurs | |
| 162 | + | |
| 163 | +### 5.1 Types de Résultat | |
| 164 | + | |
| 165 | +#### ⚠️ Recommandation ERR-RESULT - AMÉLIORATION RECOMMANDÉE | |
| 166 | +**Statut** : Utilisation excessive de `unwrap()` et `expect()` | |
| 167 | + | |
| 168 | +**Utilisations détectées** : 51 occurrences de `unwrap()` et `expect()` | |
| 169 | + | |
| 170 | +**Analyse par contexte** : | |
| 171 | + | |
| 172 | +#### ✅ Acceptable (Tests uniquement) - 30 occurrences | |
| 173 | +Ces utilisations sont **acceptables** car elles sont dans des tests unitaires : | |
| 174 | + | |
| 175 | +- `src/i18n/service.rs` : lignes 217, 229 (tests) | |
| 176 | +- `src/i18n/loader.rs` : ligne 380 (test) | |
| 177 | +- `src/i18n/helpers.rs` : lignes 236, 301 (tests) | |
| 178 | +- `src/templates/helpers.rs` : lignes 471, 475, 491, 495, 508 (tests) | |
| 179 | +- `src/templates/mod.rs` : lignes 205, 210 (tests) | |
| 180 | +- `src/services/password_service.rs` : lignes 199, 202, 205 (tests) | |
| 181 | +- `src/api/middleware/update_last_login.rs` : lignes 128, 130, 139, 141 (tests) | |
| 182 | +- `src/config/auth.rs` : ligne 127 (exemple de documentation) | |
| 183 | +- `src/auth/session.rs` : lignes 90, 142, 148, 208, 211 (exemples de documentation) | |
| 184 | +- `src/auth/jwt.rs` : lignes 112, 121, 193, 251, 309 (exemples de documentation) | |
| 185 | + | |
| 186 | +#### ⚠️ À améliorer (Code de production) - 21 occurrences | |
| 187 | + | |
| 188 | +**Fichiers concernés** : | |
| 189 | + | |
| 190 | +1. **`src/main.rs`** (lignes 510, 516) - ⚠️ **CRITIQUE** | |
| 191 | + ```rust | |
| 192 | + let listener = tokio::net::TcpListener::bind(&address) | |
| 193 | + .await | |
| 194 | + .expect("Failed to bind to address"); | |
| 195 | + | |
| 196 | + axum::serve(listener, app) | |
| 197 | + .await | |
| 198 | + .expect("Server failed to start"); | |
| 199 | + ``` | |
| 200 | + **Problème** : Utilisation de `expect()` au démarrage du serveur | |
| 201 | + **Recommandation** : Gérer l'erreur proprement avec un message d'erreur structuré | |
| 202 | + **Impact** : Élevé - Le serveur ne peut pas démarrer si le port est occupé | |
| 203 | + | |
| 204 | +2. **`src/api/handlers/admin_handler.rs`** (lignes 594, 595) | |
| 205 | + ```rust | |
| 206 | + has_search: search.is_some() && !search.as_ref().unwrap().is_empty(), | |
| 207 | + has_role_filter: role_filter.is_some() && !role_filter.as_ref().unwrap().is_empty(), | |
| 208 | + ``` | |
| 209 | + **Problème** : `unwrap()` après `is_some()` - peut paniquer | |
| 210 | + **Recommandation** : Utiliser `if let Some(ref s) = search` ou `map_or(false, |s| !s.is_empty())` | |
| 211 | + **Impact** : Moyen - Panic possible si le code change | |
| 212 | + | |
| 213 | +3. **`src/services/email_queue_service.rs`** (ligne 235) | |
| 214 | + ```rust | |
| 215 | + email_active.attempts = Set(email_active.attempts.unwrap() + 1); | |
| 216 | + ``` | |
| 217 | + **Problème** : `unwrap()` sur une valeur potentiellement None | |
| 218 | + **Recommandation** : Utiliser `unwrap_or(0)` ou gérer le cas None explicitement | |
| 219 | + **Impact** : Moyen - Panic si attempts est None | |
| 220 | + | |
| 221 | +4. **`src/config/email.rs`** (ligne 262) | |
| 222 | + ```rust | |
| 223 | + imap_host.as_ref().unwrap(), | |
| 224 | + ``` | |
| 225 | + **Problème** : `unwrap()` sans vérification préalable | |
| 226 | + **Recommandation** : Vérifier que `imap_host` est Some avant utilisation | |
| 227 | + **Impact** : Moyen - Panic si imap_host est None | |
| 228 | + | |
| 229 | +5. **`src/services/password_reset_service.rs`** (lignes 295, 301) | |
| 230 | + ```rust | |
| 231 | + .unwrap() | |
| 232 | + .retain(|&time| time.duration_since(UNIX_EPOCH).unwrap().as_secs() > one_hour_ago); | |
| 233 | + ``` | |
| 234 | + **Problème** : Double `unwrap()` enchaîné | |
| 235 | + **Recommandation** : Utiliser `?` pour propager les erreurs ou gérer explicitement | |
| 236 | + **Impact** : Moyen - Panic possible | |
| 237 | + | |
| 238 | +6. **`src/services/email_validation_service.rs`** (lignes 359, 365) | |
| 239 | + ```rust | |
| 240 | + .unwrap() | |
| 241 | + .retain(|&time| time.duration_since(UNIX_EPOCH).unwrap().as_secs() > one_hour_ago); | |
| 242 | + ``` | |
| 243 | + **Problème** : Même pattern que password_reset_service | |
| 244 | + **Recommandation** : Même correction | |
| 245 | + **Impact** : Moyen | |
| 246 | + | |
| 247 | +7. **`src/api/handlers/template_test.rs`** (ligne 86) | |
| 248 | + ```rust | |
| 249 | + let rendered = template.render().expect("Template should render"); | |
| 250 | + ``` | |
| 251 | + **Problème** : `expect()` dans un handler (même si c'est un handler de test) | |
| 252 | + **Recommandation** : Retourner une erreur HTTP appropriée | |
| 253 | + **Impact** : Faible - Handler de test uniquement | |
| 254 | + | |
| 255 | +**Recommandations générales** : | |
| 256 | + | |
| 257 | +1. **Remplacer `unwrap()` par une gestion d'erreur appropriée** : | |
| 258 | + ```rust | |
| 259 | + // ❌ MAUVAIS | |
| 260 | + let value = option.unwrap(); | |
| 261 | + | |
| 262 | + // ✅ BON | |
| 263 | + let value = option.ok_or(MyError::MissingValue)?; | |
| 264 | + // ou | |
| 265 | + let value = option.unwrap_or(default_value); | |
| 266 | + ``` | |
| 267 | + | |
| 268 | +2. **Utiliser l'opérateur `?` pour propager les erreurs** : | |
| 269 | + ```rust | |
| 270 | + // ❌ MAUVAIS | |
| 271 | + let result = operation().unwrap(); | |
| 272 | + | |
| 273 | + // ✅ BON | |
| 274 | + let result = operation()?; | |
| 275 | + ``` | |
| 276 | + | |
| 277 | +3. **Pour les cas où une valeur ne peut pas être None** : | |
| 278 | + ```rust | |
| 279 | + // ✅ BON (avec documentation) | |
| 280 | + // SAFETY: This value is guaranteed to be Some at this point | |
| 281 | + // because it's set in the initialization phase | |
| 282 | + let value = option.expect("Value should be initialized"); | |
| 283 | + ``` | |
| 284 | + | |
| 285 | +#### ❌ Règle ERR-PANIC - PARTIELLEMENT NON CONFORME | |
| 286 | +**Statut** : Utilisation de panics dans le code de production | |
| 287 | + | |
| 288 | +**Problèmes identifiés** : | |
| 289 | +- 21 utilisations de `unwrap()`/`expect()` dans le code de production | |
| 290 | +- Certaines peuvent causer des panics en production | |
| 291 | + | |
| 292 | +**Action requise** : Remplacer toutes les utilisations de `unwrap()`/`expect()` dans le code de production par une gestion d'erreur appropriée | |
| 293 | + | |
| 294 | +--- | |
| 295 | + | |
| 296 | +## 6. Concurrence et Parallélisme | |
| 297 | + | |
| 298 | +### 6.1 Partage de Données | |
| 299 | + | |
| 300 | +#### ✅ Règle CONC-SHARED - CONFORME | |
| 301 | +**Statut** : Utilisation appropriée des types de synchronisation | |
| 302 | + | |
| 303 | +- Utilisation de `Arc<T>` pour le partage de données | |
| 304 | +- Utilisation de `Mutex` et autres primitives de synchronisation appropriées | |
| 305 | +- ✅ Conforme (analyse basée sur la structure du code) | |
| 306 | + | |
| 307 | +--- | |
| 308 | + | |
| 309 | +## 7. Entrées/Sorties et Validation | |
| 310 | + | |
| 311 | +### 7.1 Validation des Entrées | |
| 312 | + | |
| 313 | +#### ✅ Règle IO-VALIDATE - CONFORME | |
| 314 | +**Statut** : Validation des entrées utilisateur présente | |
| 315 | + | |
| 316 | +- Utilisation de `validator` pour la validation | |
| 317 | +- Validation dans `AdminConfig::validate()` | |
| 318 | +- ✅ Conforme | |
| 319 | + | |
| 320 | +### 7.2 Parsing et Désérialisation | |
| 321 | + | |
| 322 | +#### ✅ Recommandation IO-PARSE - CONFORME | |
| 323 | +**Statut** : Utilisation de bibliothèques bien testées | |
| 324 | + | |
| 325 | +- Utilisation de `serde` pour la sérialisation/désérialisation | |
| 326 | +- ✅ Conforme | |
| 327 | + | |
| 328 | +--- | |
| 329 | + | |
| 330 | +## 8. Cryptographie et Sécurité | |
| 331 | + | |
| 332 | +### 8.1 Génération de Nombres Aléatoires | |
| 333 | + | |
| 334 | +#### ✅ Règle CRYPTO-RNG - CONFORME | |
| 335 | +**Statut** : Utilisation appropriée des RNG | |
| 336 | + | |
| 337 | +- Utilisation de `rand` pour la génération de nombres aléatoires | |
| 338 | +- Utilisation de `jsonwebtoken` pour les tokens JWT | |
| 339 | +- ✅ Conforme | |
| 340 | + | |
| 341 | +### 8.2 Gestion des Secrets | |
| 342 | + | |
| 343 | +#### ✅ Règle CRYPTO-SECRETS - CONFORME | |
| 344 | +**Statut** : Pas de logging de secrets détecté | |
| 345 | + | |
| 346 | +- Les secrets ne sont pas loggés dans le code analysé | |
| 347 | +- ✅ Conforme | |
| 348 | + | |
| 349 | +--- | |
| 350 | + | |
| 351 | +## 9. Tests et Vérification | |
| 352 | + | |
| 353 | +### 9.1 Tests Unitaires | |
| 354 | + | |
| 355 | +#### ✅ Recommandation TEST-UNIT - CONFORME | |
| 356 | +**Statut** : Tests unitaires présents | |
| 357 | + | |
| 358 | +- Tests unitaires présents dans la plupart des modules | |
| 359 | +- ✅ Conforme | |
| 360 | + | |
| 361 | +### 9.2 Tests d'Intégration | |
| 362 | + | |
| 363 | +#### ✅ Recommandation TEST-INTEGRATION - CONFORME | |
| 364 | +**Statut** : Tests d'intégration présents | |
| 365 | + | |
| 366 | +- Dossier `tests/` avec des tests d'intégration | |
| 367 | +- ✅ Conforme | |
| 368 | + | |
| 369 | +--- | |
| 370 | + | |
| 371 | +## 10. Documentation et Maintenabilité | |
| 372 | + | |
| 373 | +### 10.1 Documentation du Code | |
| 374 | + | |
| 375 | +#### ✅ Recommandation DOC-CODE - CONFORME | |
| 376 | +**Statut** : Documentation présente | |
| 377 | + | |
| 378 | +- Documentation Rustdoc présente sur les fonctions publiques | |
| 379 | +- Exemples d'utilisation dans la documentation | |
| 380 | +- ✅ Conforme | |
| 381 | + | |
| 382 | +### 10.2 Documentation de Sécurité | |
| 383 | + | |
| 384 | +#### ⚠️ Règle DOC-SECURITY - AMÉLIORATION RECOMMANDÉE | |
| 385 | +**Statut** : Documentation de sécurité insuffisante pour le code `unsafe` | |
| 386 | + | |
| 387 | +**Problèmes identifiés** : | |
| 388 | +- Code `unsafe` non documenté dans les tests | |
| 389 | +- Aucune documentation des invariants de sécurité | |
| 390 | + | |
| 391 | +**Action requise** : Ajouter des commentaires `// SAFETY:` pour toutes les utilisations de `unsafe` | |
| 392 | + | |
| 393 | +--- | |
| 394 | + | |
| 395 | +## Plan d'Action Prioritaire | |
| 396 | + | |
| 397 | +### 🔴 Priorité Haute (Sécurité) | |
| 398 | + | |
| 399 | +1. **Ajouter `#![deny(warnings)]`** dans `src/lib.rs` ou `src/main.rs` | |
| 400 | + - **Fichier** : `src/lib.rs` ou `src/main.rs` | |
| 401 | + - **Impact** : Empêche les warnings de compilation | |
| 402 | + | |
| 403 | +2. **Remplacer `expect()` dans `src/main.rs`** (démarrage du serveur) | |
| 404 | + - **Fichier** : `src/main.rs` lignes 510, 516 | |
| 405 | + - **Impact** : Améliore la gestion d'erreur au démarrage | |
| 406 | + | |
| 407 | +### 🟡 Priorité Moyenne (Robustesse) | |
| 408 | + | |
| 409 | +3. **Documenter le code `unsafe` dans les tests** | |
| 410 | + - **Fichiers** : `src/config/admin.rs`, `src/config/app.rs` | |
| 411 | + - **Impact** : Améliore la maintenabilité | |
| 412 | + | |
| 413 | +4. **Remplacer `unwrap()` dans le code de production** | |
| 414 | + - **Fichiers** : | |
| 415 | + - `src/api/handlers/admin_handler.rs` | |
| 416 | + - `src/services/email_queue_service.rs` | |
| 417 | + - `src/config/email.rs` | |
| 418 | + - `src/services/password_reset_service.rs` | |
| 419 | + - `src/services/email_validation_service.rs` | |
| 420 | + - **Impact** : Réduit le risque de panics en production | |
| 421 | + | |
| 422 | +### 🟢 Priorité Basse (Amélioration continue) | |
| 423 | + | |
| 424 | +5. **Intégrer `cargo-audit` dans le CI/CD** | |
| 425 | + - **Impact** : Détection automatique des vulnérabilités | |
| 426 | + | |
| 427 | +6. **Intégrer `cargo-outdated` dans le CI/CD** | |
| 428 | + - **Impact** : Suivi des dépendances obsolètes | |
| 429 | + | |
| 430 | +--- | |
| 431 | + | |
| 432 | +## Checklist de Conformité | |
| 433 | + | |
| 434 | +### Avant chaque Commit | |
| 435 | + | |
| 436 | +- [x] Le code compile sans avertissements (⚠️ à améliorer : ajouter `#![deny(warnings)]`) | |
| 437 | +- [x] `cargo clippy` ne signale pas de problèmes | |
| 438 | +- [x] Tous les tests passent | |
| 439 | +- [ ] Le code `unsafe` est documenté et justifié (⚠️ à améliorer) | |
| 440 | +- [ ] Les dépendances sont à jour ou justifiées (⚠️ à vérifier manuellement) | |
| 441 | + | |
| 442 | +### Avant chaque Release | |
| 443 | + | |
| 444 | +- [ ] `cargo audit` ne signale pas de vulnérabilités (⚠️ à intégrer) | |
| 445 | +- [ ] `cargo outdated` a été vérifié (⚠️ à intégrer) | |
| 446 | +- [x] Tous les tests d'intégration passent | |
| 447 | +- [x] La documentation est à jour | |
| 448 | +- [ ] Le code a été revu par un pair (⚠️ à vérifier) | |
| 449 | +- [x] Les secrets ne sont pas dans le code source | |
| 450 | +- [x] Les builds de production utilisent les optimisations | |
| 451 | + | |
| 452 | +--- | |
| 453 | + | |
| 454 | +## Conclusion | |
| 455 | + | |
| 456 | +Le code de RustCloud présente un **bon niveau de conformité** aux recommandations ANSSI. Les principaux points à améliorer sont : | |
| 457 | + | |
| 458 | +1. **Gestion des erreurs** : Remplacer les `unwrap()`/`expect()` dans le code de production | |
| 459 | +2. **Documentation du code `unsafe`** : Ajouter des commentaires justificatifs | |
| 460 | +3. **Configuration de compilation** : Ajouter `#![deny(warnings)]` | |
| 461 | +4. **Intégration d'outils** : Ajouter `cargo-audit` et `cargo-outdated` au CI/CD | |
| 462 | + | |
| 463 | +Le code est globalement **sécurisé** et suit les bonnes pratiques Rust. Les améliorations recommandées sont principalement des **améliorations de robustesse** et de **maintenabilité**. | |
| 464 | + | |
| 465 | +--- | |
| 466 | + | |
| 467 | +**Prochaine révision recommandée** : Après implémentation des actions prioritaires | |
| 468 | + | |
| 469 | + | |
| 470 | + |
A
docs/CSS_STYLE_GUIDE.md
+277
-0
@@ -0,0 +1,277 @@
| 1 | +# Guide de Style CSS - DaisyUI/Tailwind CSS | |
| 2 | + | |
| 3 | +**Basé sur**: [daisyUI llms.txt](https://daisyui.com/llms.txt) | |
| 4 | +**Version**: DaisyUI 5.5.14, Tailwind CSS 4.1.18 | |
| 5 | +**Date**: 2025-12-13 | |
| 6 | + | |
| 7 | +## Principes Généraux | |
| 8 | + | |
| 9 | +1. **Utiliser les classes daisyUI** pour les composants UI | |
| 10 | +2. **Utiliser les classes Tailwind CSS** pour les utilitaires et personnalisations | |
| 11 | +3. **Éviter le CSS personnalisé** - utiliser les classes daisyUI/Tailwind uniquement | |
| 12 | +4. **Utiliser les couleurs sémantiques daisyUI** (`primary`, `base-100`, etc.) plutôt que les couleurs Tailwind directes | |
| 13 | +5. **Layout responsive** - utiliser les préfixes responsive (`sm:`, `md:`, `lg:`) pour `flex` et `grid` | |
| 14 | + | |
| 15 | +## Règles d'Utilisation | |
| 16 | + | |
| 17 | +### 1. Classes daisyUI vs Tailwind CSS | |
| 18 | + | |
| 19 | +- **Composants**: Utiliser les classes daisyUI (`btn`, `card`, `alert`, etc.) | |
| 20 | +- **Personnalisation**: Utiliser les classes Tailwind CSS (`px-4`, `mb-6`, etc.) | |
| 21 | +- **Override**: Si nécessaire, utiliser `!` à la fin d'une classe Tailwind (ex: `btn bg-red-500!`) | |
| 22 | + | |
| 23 | +### 2. Couleurs | |
| 24 | + | |
| 25 | +**Utiliser les couleurs sémantiques daisyUI**: | |
| 26 | +- `primary`, `primary-content` | |
| 27 | +- `secondary`, `secondary-content` | |
| 28 | +- `accent`, `accent-content` | |
| 29 | +- `base-100`, `base-200`, `base-300`, `base-content` | |
| 30 | +- `info`, `info-content` | |
| 31 | +- `success`, `success-content` | |
| 32 | +- `warning`, `warning-content` | |
| 33 | +- `error`, `error-content` | |
| 34 | + | |
| 35 | +**Éviter**: | |
| 36 | +- ❌ `text-gray-800` (ne fonctionne pas bien avec les thèmes sombres) | |
| 37 | +- ✅ `text-base-content` (s'adapte automatiquement au thème) | |
| 38 | + | |
| 39 | +### 3. Espacements | |
| 40 | + | |
| 41 | +**Classes standardisées**: | |
| 42 | +- Padding: `p-4`, `px-4`, `py-4`, `pt-4`, `pb-4`, `pl-4`, `pr-4` | |
| 43 | +- Margin: `m-4`, `mx-4`, `my-4`, `mt-4`, `mb-4`, `ml-4`, `mr-4` | |
| 44 | +- Gap: `gap-4`, `gap-6`, `gap-8` | |
| 45 | +- Espacements communs: `4`, `6`, `8`, `12`, `16` | |
| 46 | + | |
| 47 | +### 4. Typographie | |
| 48 | + | |
| 49 | +**Classes standardisées**: | |
| 50 | +- Tailles: `text-sm`, `text-base`, `text-lg`, `text-xl`, `text-2xl`, `text-3xl` | |
| 51 | +- Poids: `font-normal`, `font-medium`, `font-semibold`, `font-bold` | |
| 52 | +- Couleurs: `text-base-content`, `text-base-content/70`, `text-primary`, `text-error` | |
| 53 | + | |
| 54 | +## Composants DaisyUI Standardisés | |
| 55 | + | |
| 56 | +### Boutons (`btn`) | |
| 57 | + | |
| 58 | +```html | |
| 59 | +<!-- Bouton primaire --> | |
| 60 | +<button class="btn btn-primary">Action</button> | |
| 61 | + | |
| 62 | +<!-- Bouton outline --> | |
| 63 | +<button class="btn btn-outline btn-primary">Action</button> | |
| 64 | + | |
| 65 | +<!-- Bouton ghost --> | |
| 66 | +<button class="btn btn-ghost">Action</button> | |
| 67 | + | |
| 68 | +<!-- Bouton avec taille --> | |
| 69 | +<button class="btn btn-primary btn-sm">Petit</button> | |
| 70 | +<button class="btn btn-primary btn-lg">Grand</button> | |
| 71 | +``` | |
| 72 | + | |
| 73 | +**Classes disponibles**: | |
| 74 | +- Couleurs: `btn-primary`, `btn-secondary`, `btn-accent`, `btn-info`, `btn-success`, `btn-warning`, `btn-error` | |
| 75 | +- Styles: `btn-outline`, `btn-ghost`, `btn-link` | |
| 76 | +- Tailles: `btn-xs`, `btn-sm`, `btn-md`, `btn-lg`, `btn-xl` | |
| 77 | +- Modificateurs: `btn-wide`, `btn-block`, `btn-square`, `btn-circle` | |
| 78 | + | |
| 79 | +### Cartes (`card`) | |
| 80 | + | |
| 81 | +```html | |
| 82 | +<div class="card bg-base-100 shadow-xl"> | |
| 83 | + <div class="card-body"> | |
| 84 | + <h2 class="card-title">Titre</h2> | |
| 85 | + <p>Contenu</p> | |
| 86 | + <div class="card-actions"> | |
| 87 | + <button class="btn btn-primary">Action</button> | |
| 88 | + </div> | |
| 89 | + </div> | |
| 90 | +</div> | |
| 91 | +``` | |
| 92 | + | |
| 93 | +**Classes disponibles**: | |
| 94 | +- Part: `card-title`, `card-body`, `card-actions` | |
| 95 | +- Style: `card-border`, `card-dash` | |
| 96 | +- Modificateurs: `card-side`, `image-full` | |
| 97 | +- Tailles: `card-xs`, `card-sm`, `card-md`, `card-lg`, `card-xl` | |
| 98 | + | |
| 99 | +### Formulaires | |
| 100 | + | |
| 101 | +#### Input | |
| 102 | + | |
| 103 | +```html | |
| 104 | +<div class="form-control"> | |
| 105 | + <label class="label"> | |
| 106 | + <span class="label-text">Label</span> | |
| 107 | + </label> | |
| 108 | + <input type="text" class="input input-bordered w-full" /> | |
| 109 | + <label class="label"> | |
| 110 | + <span class="label-text-alt">Texte d'aide</span> | |
| 111 | + </label> | |
| 112 | +</div> | |
| 113 | +``` | |
| 114 | + | |
| 115 | +**Classes disponibles**: | |
| 116 | +- `input`, `input-bordered`, `input-ghost` | |
| 117 | +- Tailles: `input-xs`, `input-sm`, `input-md`, `input-lg` | |
| 118 | +- États: `input-error`, `input-success`, `input-warning`, `input-info` | |
| 119 | + | |
| 120 | +#### Select | |
| 121 | + | |
| 122 | +```html | |
| 123 | +<select class="select select-bordered w-full"> | |
| 124 | + <option>Option 1</option> | |
| 125 | +</select> | |
| 126 | +``` | |
| 127 | + | |
| 128 | +#### Textarea | |
| 129 | + | |
| 130 | +```html | |
| 131 | +<textarea class="textarea textarea-bordered w-full"></textarea> | |
| 132 | +``` | |
| 133 | + | |
| 134 | +### Alertes (`alert`) | |
| 135 | + | |
| 136 | +```html | |
| 137 | +<div role="alert" class="alert alert-info"> | |
| 138 | + <svg>...</svg> | |
| 139 | + <span>Message informatif</span> | |
| 140 | +</div> | |
| 141 | +``` | |
| 142 | + | |
| 143 | +**Classes disponibles**: | |
| 144 | +- Couleurs: `alert-info`, `alert-success`, `alert-warning`, `alert-error` | |
| 145 | +- Styles: `alert-outline`, `alert-dash`, `alert-soft` | |
| 146 | + | |
| 147 | +### Badges (`badge`) | |
| 148 | + | |
| 149 | +```html | |
| 150 | +<span class="badge badge-primary">Badge</span> | |
| 151 | +<span class="badge badge-outline badge-primary">Outline</span> | |
| 152 | +``` | |
| 153 | + | |
| 154 | +**Classes disponibles**: | |
| 155 | +- Couleurs: `badge-primary`, `badge-secondary`, `badge-accent`, `badge-info`, `badge-success`, `badge-warning`, `badge-error` | |
| 156 | +- Styles: `badge-outline`, `badge-dash`, `badge-soft`, `badge-ghost` | |
| 157 | +- Tailles: `badge-xs`, `badge-sm`, `badge-md`, `badge-lg`, `badge-xl` | |
| 158 | + | |
| 159 | +### Navigation (`navbar`) | |
| 160 | + | |
| 161 | +```html | |
| 162 | +<nav class="navbar bg-base-200 border-b border-base-300"> | |
| 163 | + <div class="navbar-start">...</div> | |
| 164 | + <div class="navbar-center">...</div> | |
| 165 | + <div class="navbar-end">...</div> | |
| 166 | +</nav> | |
| 167 | +``` | |
| 168 | + | |
| 169 | +### Breadcrumbs | |
| 170 | + | |
| 171 | +```html | |
| 172 | +<div class="text-sm breadcrumbs"> | |
| 173 | + <ul> | |
| 174 | + <li><a href="/">Accueil</a></li> | |
| 175 | + <li>Page actuelle</li> | |
| 176 | + </ul> | |
| 177 | +</div> | |
| 178 | +``` | |
| 179 | + | |
| 180 | +### Tables | |
| 181 | + | |
| 182 | +```html | |
| 183 | +<table class="table table-zebra"> | |
| 184 | + <thead> | |
| 185 | + <tr> | |
| 186 | + <th>Colonne 1</th> | |
| 187 | + </tr> | |
| 188 | + </thead> | |
| 189 | + <tbody> | |
| 190 | + <tr> | |
| 191 | + <td>Donnée</td> | |
| 192 | + </tr> | |
| 193 | + </tbody> | |
| 194 | +</table> | |
| 195 | +``` | |
| 196 | + | |
| 197 | +**Classes disponibles**: | |
| 198 | +- `table`, `table-zebra`, `table-pin-rows`, `table-pin-cols` | |
| 199 | + | |
| 200 | +## Layout et Grilles | |
| 201 | + | |
| 202 | +### Container | |
| 203 | + | |
| 204 | +```html | |
| 205 | +<div class="container mx-auto px-4 py-6"> | |
| 206 | + <!-- Contenu --> | |
| 207 | +</div> | |
| 208 | +``` | |
| 209 | + | |
| 210 | +### Grille Responsive | |
| 211 | + | |
| 212 | +```html | |
| 213 | +<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"> | |
| 214 | + <!-- Items --> | |
| 215 | +</div> | |
| 216 | +``` | |
| 217 | + | |
| 218 | +### Flexbox Responsive | |
| 219 | + | |
| 220 | +```html | |
| 221 | +<div class="flex flex-col md:flex-row gap-4"> | |
| 222 | + <!-- Items --> | |
| 223 | +</div> | |
| 224 | +``` | |
| 225 | + | |
| 226 | +## États et Modificateurs | |
| 227 | + | |
| 228 | +### États de chargement | |
| 229 | + | |
| 230 | +```html | |
| 231 | +<button class="btn btn-primary" disabled> | |
| 232 | + <span class="loading loading-spinner"></span> | |
| 233 | + Chargement... | |
| 234 | +</button> | |
| 235 | +``` | |
| 236 | + | |
| 237 | +### États vides | |
| 238 | + | |
| 239 | +```html | |
| 240 | +<div class="card bg-base-100 shadow-xl"> | |
| 241 | + <div class="card-body text-center"> | |
| 242 | + <svg class="w-16 h-16 mx-auto text-base-content/30">...</svg> | |
| 243 | + <p class="text-base-content/70">Aucun élément</p> | |
| 244 | + </div> | |
| 245 | +</div> | |
| 246 | +``` | |
| 247 | + | |
| 248 | +### États d'erreur | |
| 249 | + | |
| 250 | +```html | |
| 251 | +<div role="alert" class="alert alert-error"> | |
| 252 | + <svg>...</svg> | |
| 253 | + <span>Message d'erreur</span> | |
| 254 | +</div> | |
| 255 | +``` | |
| 256 | + | |
| 257 | +## Checklist d'Uniformisation | |
| 258 | + | |
| 259 | +Pour chaque template, vérifier: | |
| 260 | + | |
| 261 | +- [ ] Utilise les couleurs sémantiques daisyUI (`primary`, `base-100`, etc.) | |
| 262 | +- [ ] Utilise les classes daisyUI pour les composants (`btn`, `card`, `alert`, etc.) | |
| 263 | +- [ ] Utilise les espacements standardisés (`p-4`, `mb-6`, `gap-6`, etc.) | |
| 264 | +- [ ] Utilise les classes Tailwind responsive (`md:`, `lg:`) pour les layouts | |
| 265 | +- [ ] N'utilise pas de CSS personnalisé (sauf si absolument nécessaire) | |
| 266 | +- [ ] Les formulaires utilisent `form-control`, `input input-bordered`, etc. | |
| 267 | +- [ ] Les boutons utilisent les classes `btn` avec modificateurs appropriés | |
| 268 | +- [ ] Les cartes utilisent `card`, `card-body`, `card-title`, `card-actions` | |
| 269 | +- [ ] Les alertes utilisent `alert` avec couleurs sémantiques | |
| 270 | +- [ ] Les badges utilisent `badge` avec couleurs sémantiques | |
| 271 | + | |
| 272 | +## Références | |
| 273 | + | |
| 274 | +- [daisyUI Documentation](https://daisyui.com) | |
| 275 | +- [Tailwind CSS Documentation](https://tailwindcss.com) | |
| 276 | +- [daisyUI llms.txt Reference](./DAISYUI_LLMS_REFERENCE.txt) | |
| 277 | + |
GitRust