Skip to content

Commit 864b28a

Browse files
authored
chore: merge dev branch updates (v0.20.5) (#60)
* feat: v0.13.2 - Add --install-deps option and enhance contract workflow (#42) * feat: AI IDE contract enhancement workflow and critical bug fixes (v0.13.0) - Added generate contracts-prompt command for AI IDE integration - Added generate contracts-apply with comprehensive 6-step validation - Fixed AttributeError in sync.py, import_cmd.py, enforce.py (71 test failures resolved) - Renamed --apply all to --apply all-contracts for clarity - Bundle-specific prompt storage (.specfact/projects/<bundle>/prompts/) - Enhanced error messages and validation feedback - Updated documentation (commands, directory structure, IDE integration) - Updated internal implementation plans Version bump: 0.12.1 → 0.13.0 * feat: v0.13.2 - Add --install-deps option and enhance contract workflow - Add specfact init --install-deps option for streamlined setup - Enhance contracts-apply with automatic code quality checks - Optimize test execution in contracts-apply (scoped pytest runs) - Strengthen LLM abort conditions in generated prompts - Clarify contract application requirements (ALL eligible functions) - Update documentation for new features - Bump version to 0.13.2 and sync across all files * fix: v0.13.3 - Improve data model detection in contract analysis - Fix false positives for Pydantic data model files - Properly distinguish between class methods and module-level functions - Add support for common helper methods (compute_summary, update_summary, etc.) - Increase E2E test timeouts from 5s to 20s for slow tests - Files like models/plan.py and models/protocol.py now correctly identified as data models * feat: Add /specfact.07-contracts slash command for contract enhancement workflow - New sequential workflow: analyze contracts → generate prompts → apply contracts - Processes files one at a time for careful review - Supports user selection of files to enhance - Includes validation and confirmation steps - Updated documentation with new slash command * docs: Update prompt validation checklist with specfact.07-contracts * docs: Update prompt validation checklist to match actual prompt structure - Updated required sections to match actual format: - User Input (with ) - Purpose - Parameters (organized by groups) - Workflow - CLI Enforcement - Expected Output - Common Patterns - Context (with {ARGS}) - Removed outdated sections (CRITICAL, Wait States, Goal, Operating Constraints) - Updated wait state validation to reflect actual structure * fix: Update prompt validation tool to match actual prompt structure - Updated required sections to match actual format: - User Input, Purpose, Parameters, Workflow, CLI Enforcement, Expected Output, Common Patterns, Context - Removed outdated sections (CRITICAL, Wait States, Goal, Operating Constraints) - Made CLI enforcement rule matching flexible (multiple variants) - Updated dual-stack workflow markers to be flexible - Added specfact.07-contracts to CLI_COMMANDS mapping - Updated wait state validation to check for User Input section and - All 9 prompts now pass validation * fix: Resolve prompt validation warnings - Added 'Use CLI output as grounding' to specfact.07-contracts.md - Added explicit CLI enforcement rules to specfact.validate.md - Added enrichment report location to specfact.01-import.md workflow - All 9 prompts now pass validation with 0 errors and 0 warnings * Update prompts and validation * feat: Include specfact.07-contracts in init command - Added specfact.07-contracts to SPECFACT_COMMANDS list in ide_setup.py - Updated VS Code settings example in ide-integration.md to include new prompt - New contract enhancement workflow prompt will now be copied during init * Fix ruff linter errors * fix: Update test_validate_structure to match new prompt structure - Updated test to use new required sections (User Input, Purpose, Parameters, Workflow, CLI Enforcement, Expected Output, Common Patterns, Context) - Test now matches actual prompt structure used in resources/prompts/ - All prompt validation tests passing * Add missing contracts to analyze agent2 --------- Co-authored-by: Dominikus Nold <[email protected]> * feat: implement Phase 4.11 Dual-Stack Enrichment Pattern (#43) - Add dual-stack workflow documentation to all 10 prompt templates - Enhance CLI enforcement rules with CLI vs LLM capabilities - Create validation utilities (cli_first_validator.py) with 4 functions - Add comprehensive tests (23 test cases, all passing) - Create end-user guide (docs/guides/dual-stack-enrichment.md) - Create technical specification (docs/technical/dual-stack-pattern.md) - Fix test timeouts for 12 integration/e2e tests (add @pytest.mark.timeout(20)) - Update .cursor/commands/ prompts with dual-stack pattern Implements: - CLI-first principle enforcement - Standard validation loop pattern documentation - Three-phase workflow (CLI Grounding → LLM Enrichment → CLI Artifact Creation) - .specfact/ folder protection validation - Format consistency validation All success criteria met for Phase 4.11. Future enhancements (metadata injection, code generation workflow, plan enrichment workflow) are deferred to future phases. Closes: Phase 4.11 implementation Co-authored-by: Dominikus Nold <[email protected]> * feat: Phase 4.9 (Quick Start) and Phase 4.10 (CI Performance) Optimization (#44) * feat: implement Phase 4.9 (Quick Start) and Phase 4.10 (CI Performance) - Phase 4.9: Quick Start Optimization - Add incremental results callback to CodeAnalyzer for real-time feature discovery - Implement _suggest_next_steps() function with contextual next commands - Add early feedback mechanism showing first value within < 60 seconds - Enhance progress indicators with incremental updates every 5 features - Create comprehensive e2e tests (6 tests, all passing) - Phase 4.10: CI Performance Optimization - Create performance monitoring utility (src/specfact_cli/utils/performance.py) - Integrate performance tracking into import command with threshold-based detection - Add performance report display (non-CI mode only) for interactive feedback - Track all major operations: analyze_codebase, extract_relationships, etc. - Create comprehensive unit tests (8 tests, all passing) - Create comprehensive e2e tests (6 tests, all passing) Files: - src/specfact_cli/analyzers/code_analyzer.py - Added incremental callback support - src/specfact_cli/commands/import_cmd.py - Added next steps suggestions and performance tracking - src/specfact_cli/utils/performance.py - New performance monitoring utility - tests/unit/utils/test_performance.py - Unit tests (8 tests) - tests/e2e/test_quick_start_performance_e2e.py - E2E tests (6 tests) All tests passing. Documentation updated in internal repo. * chore: bump version to 0.14.0 and update changelog - Bump version from 0.13.3 to 0.14.0 (minor version for new features) - Sync version across pyproject.toml, src/__init__.py, and src/specfact_cli/__init__.py - Add comprehensive changelog entry for Phase 4.9 and 4.10 features --------- Co-authored-by: Dominikus Nold <[email protected]> * feat: Natural UX Flow - Phases 4.1-4.5 Complete (#45) * feat: implement Phases 4.1-4.5 - Natural UX Flow enhancements - Phase 4.1: Context Detection System - Auto-detect project type, language, framework, specs, and configuration - Smart defaults based on detected context - Comprehensive test coverage (8 unit + 3 E2E tests) - Phase 4.2: Progressive Disclosure - Hide advanced options by default - Reveal via --help-advanced flag - Custom ProgressiveDisclosureGroup for Typer - Test coverage (6 unit + 2 E2E tests) - Phase 4.3: Intelligent Suggestions & Template-Driven Quality - Context-aware command suggestions - Error-specific fix suggestions - Template system for specification quality - Feature, implementation plan, and contract extraction templates - Test coverage (10 unit + 6 E2E tests) - Phase 4.4: Enhanced Watch Mode - Hash-based change detection (SHA256) - Dependency tracking for incremental processing - LZ4 compression for cache (optional) - Persistent hash cache across sessions - Test coverage (9 unit + 2 E2E tests) - Phase 4.5: Unified Progress Display - Verified consistent n/m format across all commands - Rich Progress integration with timing information - Documentation Updates - New UX Features guide (guides/ux-features.md) - Updated command reference with --help-advanced - Updated workflows guide with watch mode enhancements - Updated first-steps guide with context detection info - Plan Status Updates - Marked Phases 4.1-4.5 as COMPLETE in internal plan - Updated progress percentages and status All tests passing (228 total, 61 new tests for these phases) * chore: bump version to 0.14.1 - Natural UX Flow Phases 4.1-4.5 - Phase 4.1: Context Detection System - Phase 4.2: Progressive Disclosure (--help-advanced) - Phase 4.3: Intelligent Suggestions & Template-Driven Quality - Phase 4.4: Enhanced Watch Mode (hash-based detection) - Phase 4.5: Unified Progress Display Added comprehensive documentation and 61 new tests (all passing) * chore: bump version to 0.14.2 - Update version in src/__init__.py, pyproject.toml, setup.py - Add changelog entry for 0.14.2 - Document Phase 4.2 Progressive Disclosure final implementation - Fix internal plan status inconsistencies and improve readability --------- Co-authored-by: Dominikus Nold <[email protected]> * chore: bump version to 0.15.0 - Phase 8.5: Bundle-Specific Artifact Organization completed - Fixed atomic bundle saves to preserve reports/ and logs/ directories - Removed legacy directories (plans/, gates/results/) from ensure_structure() - Migrated active bundle config to global config.yaml - Removed GWT patterns from ControlFlowAnalyzer - Added comprehensive tests for ControlFlowAnalyzer - Updated all documentation to reflect bundle-specific artifact organization - Fixed integration tests for new directory structure - Fixed progress bar UI in import from-code command BREAKING CHANGE: Report paths, SDD manifests, and task files now use bundle-specific locations * fix: remove duplicate 'First value' and 'Themes detected' messages from import command - Removed intermediate console.print messages that duplicated progress bar information - Progress bar already shows feature count in description - Final summary provides complete information (features, themes, stories) - Cleaner output without redundant messages * Fix formatting * fix: recognize simplified acceptance criteria format and add --output-questions option - Fixed ambiguity scanner to recognize simplified format (e.g., 'Must verify X works correctly (see contract examples)') as valid - Added --output-questions option to save questions directly to file, avoiding complex JSON parsing - Enhanced CLI enforcement warnings in prompt documentation - Updated version to 0.15.1 * Improve review prompt, add cleanup script * fix(plan): integrate INTERACTION_UX answers and improve coverage display - Add INTERACTION_UX category to integration logic in _integrate_clarification - Fix unclear findings count to accurately reflect findings that can generate questions - Improve coverage summary display: show '143 Partial' when all unclear, '5/143 Partial' when partially clarified - Fix format errors: remove unused question_id variable assignments - Bump version to 0.15.5 * chore: add findings.json to .gitignore * feat: Project Bundle Phase 5-6 - Persona Workflows & OpenAPI Enforcement (v0.16.1) (#46) * chore: bump version to 0.16.0 - Fixed contract generation path resolution for bundle-specific locations - Improved error handling for invalid personas with --list-personas flag - Fixed sdd_path possibly unbound errors in generate command - Enhanced persona workflow UX with optional --persona and better error messages - Fixed SDD discovery to correctly identify bundle-specific SDDs - Fixed contract generator logic errors - Updated all tests to use bundle-specific paths - Added comprehensive changelog entry for v0.16.0 * feat: complete Phase 5.1.6 - Developer & Architect template enhancements (v0.16.1) - Enhanced Developer template with task breakdown, technical design, code mappings, sprint context, and Definition of Done - Enhanced Architect template with architectural decisions, NFRs, protocols/state machines, contracts, risk assessment, and deployment architecture - Fixed Markdown linting issues (MD012, MD024, MD036) in persona templates - Fixed data model alignment issues in persona exporter (feature.constraints handling) - Enhanced context preparation to include protocols and contracts from bundle directory - Updated documentation to emphasize persona-based workflows and agile team integration - Added comprehensive Agile/Scrum Workflows guide - Added project export/import command documentation - Updated READMEs to position SpecFact as team collaboration tool for agile/scrum teams - Bumped version to 0.16.1 and updated CHANGELOG All three persona templates (Product Owner, Developer, Architect) are now production-ready and aligned with real-world agile/scrum expectations. * Add defaults for linter --------- Co-authored-by: Dominikus Nold <[email protected]> * feat: implement Phase 5.3 lock enforcement with E2E tests - Add lock enforcement to project import command - Implement check_sections_locked_for_persona() helper - Add comprehensive E2E integration tests (5 tests, all passing) - Fix Markdown parser to handle *(mandatory)* markers - Disable agile validation in test mode for simpler test scenarios - Add lock workflow documentation to agile-scrum-workflows guide - Add lock command documentation to command reference - Fix template path resolution for development and installed scenarios - Update version to 0.16.2 Phase 5.3 (Lock Enforcement) complete: - Lock/unlock commands working - Import operations respect locks - Persona validation against locks - Real-world scenarios tested and working * feat: Add contract verify command and improve mock server reliability (Phase 6.4) (#48) * feat: implement Phase 6 OpenAPI Contract Enforcement - Phase 6.1: Add contract index to manifest for fast lookup - Phase 6.2: Implement contract serve and test commands - contract serve: Launch Specmatic mock server for contract testing - contract test: Generate Specmatic test suites from contracts - Phase 6.3: SDD Integration (already complete) - plan harden extracts OpenAPI contracts automatically - enforce sdd validates OpenAPI coverage percentage - Add comprehensive integration tests (8 tests, all passing) - Update end user documentation with contract command reference - Update internal plans to mark Phase 6 as complete - Fix enum serialization in manifest save (use model_dump(mode='json')) All tests passing, coverage maintained at 80%+ * feat: add contract verify command and improve mock server reliability - Add contract verify command (Phase 6.4) - all-in-one verification workflow - Improve mock server process management with port polling and better error handling - Add automatic example generation from OpenAPI schema - Fix path handling issues in contract commands (relative_to errors) - Fix exit code handling in contract test command - Update documentation with simplified workflow guide - Add comprehensive integration tests (4 tests for contract verify) - Update UI/UX consistency across all contract commands Closes: Phase 6.4 Contract Verify implementation Version: 0.16.2 → 0.16.3 * sync version * Fix unit test * fix: reorder contract checks and mock Specmatic in tests - Move Specmatic availability check after contract validation in contract test command - This ensures 'no contract' errors are shown before Specmatic errors - Add mocks for Specmatic availability in verify command tests - Mock generate_specmatic_examples in verify tests to avoid async issues - All 3 previously failing tests now pass Fixes: - test_test_contract_no_contract: Now checks contract before Specmatic - test_verify_contract_skip_mock: Mocks Specmatic availability - test_verify_contract_all_contracts: Mocks Specmatic availability and example generation * applied format * fix: resolve type errors for optional output_dir parameter - Add check to set default output_dir if None before using it - Ensures output_dir is always Path type when calling relative_to() and path operations - Fixes basedpyright errors at lines 1174 and 1191 Fixes: - reportOptionalMemberAccess: 'relative_to' is not a known attribute of 'None' - reportOptionalOperand: Operator '/' not supported for 'None' --------- Co-authored-by: Dominikus Nold <[email protected]> * Adding project version commands * chore: release 0.17.0 with warn CI version check * chore: remove run command per bridge plan * Update changelog * test: add version command integration coverage * Update getting started syntax * docs: v0.18.0 - update README positioning, deprecation messaging - Add Current Version section clarifying 0.x = analysis/enforcement - Add AI IDE Bridge documentation with workflow examples - Update implement command docstrings with deprecation warnings - Bump version to 0.18.0 across all version files - Update CHANGELOG with v0.18.0 documentation changes * docs: add AI IDE bridge workflow to getting-started and docs index - Add gap analysis and fix-prompt workflow to first-steps.md - Add 'Using AI IDEs?' section to docs/README.md - Update primary goal messaging to 'analyze → find gaps → enforce' * feat: restore bridge commands (fix-prompt, test-prompt) from stash * test: v0.19.0 - add bridge command tests and migration guide - Add 6 integration tests for fix-prompt and test-prompt commands - Add migration guide for upgrading from v0.16.x to v0.19.x - Bump version to 0.19.0 across all version files - Update CHANGELOG with v0.19.0 test coverage improvements * Add fixes on formatting * docs: improve Jekyll GitHub Pages integration with navigation and styling - Add YAML front matter to all documentation pages for proper Jekyll rendering - Implement left-side navigation sidebar for better UX - Fix CSS styling issues (white-on-white text, code block backgrounds) - Add custom default layout with two-column docs layout - Configure proper permalinks for all documentation pages - Fix Rouge syntax highlighting for code blocks with light theme - Ensure proper CSS asset generation and loading - Add responsive design for mobile devices * chore: prepare v0.20.0 LTS release - Update version to 0.20.0 in pyproject.toml, setup.py, and all __init__.py files - Add comprehensive v0.20.0 LTS release notes to CHANGELOG.md - Add LTS designation to README.md - Update migration guide to v0.20.0 LTS - Mark v0.20.0 as Long-Term Stable release This release marks the stabilization of SpecFact CLI's core analysis and enforcement capabilities, positioning the tool for public promotion and early adopter usage. * fix: Add external repository support for repro command (v0.20.1) (#52) * fix: add external repository support for repro command (0.20.1) - Add environment manager detection (hatch, poetry, uv, pip) - Make all validation tools optional with clear messaging - Add dynamic source directory detection - Update documentation for external repo support - Add comprehensive test coverage (25 new tests) Fixes critical design issue where repro command only worked on SpecFact CLI's own codebase. Now works on external repositories without requiring SpecFact CLI adoption. Closes: External repository support issue Reference: CRITICAL_DESIGN_ISSUE_EXTERNAL_REPO_SUPPORT.md * fix: add external repository support for generate commands (0.20.1) - Fix generate contracts-apply: use dynamic source/test detection - Fix generate test-prompt: use dynamic source directory detection - Add test directory detection utilities (detect_test_directories, find_test_files_for_source) - Use environment detection for Python/pytest invocations - Add comprehensive tests (6 new tests for test detection utilities) Completes external repository support fixes identified in analysis. All generate commands now work on external repositories. * test: add comprehensive tests for repro setup and init environment warning - Add 15 integration tests for repro setup command covering: - pyproject.toml creation and updates with CrossHair config - Environment manager detection (hatch, poetry, uv, pip) - Source directory detection (src/, lib/, package name) - CrossHair tool availability checking and installation - Error handling and user guidance - Add 5 e2e tests for init command environment manager warning: - Warning display when no environment manager detected - No warning when hatch/poetry/pip/uv detected - Update CHANGELOG.md with new features and test coverage improvements All tests passing (20/20) * feat: align init --install-deps with environment manager detection - Update init --install-deps to use build_tool_command for environment-aware installation - Automatically detect and use hatch, poetry, uv, or pip based on project configuration - Show detected environment manager message and command being used - Provide environment-specific installation guidance on errors - Add 5-minute timeout for package installation - Track environment manager in telemetry - Update help text to reflect environment manager awareness - Update CHANGELOG.md with improvements This ensures consistent behavior with repro setup command and proper integration with different Python project management tools. --------- Co-authored-by: Dominikus Nold <[email protected]> * feat: add automatic GitHub release creation after PyPI publishing - Add generate-release-notes.sh script to extract release notes from CHANGELOG.md - Add create-github-release.sh script to create GitHub releases with release notes - Add create-release job to workflow that runs after successful PyPI publishing - Release is only created when: - PyPI publishing succeeds (published=true) - Push to main branch - Version is newer than PyPI version - Release notes are automatically extracted from CHANGELOG.md for the version - Release includes proper title and formatted release notes This automates the release process so that every successful PyPI publication automatically creates a corresponding GitHub release with release notes. * fix: sidecar template code quality improvements (v0.20.5) (#58) * fix: update sidecar templates and bump patch version * fix: sidecar template code quality improvements (v0.20.5) - Fixed formatting and linting issues in sidecar template files - Removed unused imports and whitespace issues - Combined nested if statements to reduce complexity (SIM102) - Replaced for loop with any() expression (SIM110) - Fixed exception chaining with proper 'from None' syntax - Updated version to 0.20.5 in all version files - Updated CHANGELOG.md with formatting fixes documentation --------- Co-authored-by: Dominikus Nold <[email protected]> --------- Co-authored-by: Dominikus Nold <[email protected]>
1 parent 404af63 commit 864b28a

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+4840
-250
lines changed

.cursor/commands/specfact.01-import.md

Lines changed: 155 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,20 @@ Import codebase → plan bundle. CLI extracts routes/schemas/relationships/contr
2121

2222
## Workflow
2323

24-
1. **Execute CLI**: `specfact import from-code [<bundle>] --repo <path> [options]`
24+
1. **Execute CLI**: `specfact [GLOBAL OPTIONS] import from-code [<bundle>] --repo <path> [options]`
2525
- CLI extracts: routes (FastAPI/Flask/Django), schemas (Pydantic), relationships, contracts (OpenAPI scaffolds), source tracking
2626
- Uses active plan if bundle not specified
27+
- Note: `--no-interactive` is a global option and must appear before the subcommand (e.g., `specfact --no-interactive import from-code ...`).
2728
- **Auto-enrichment enabled by default**: Automatically enhances vague acceptance criteria, incomplete requirements, and generic tasks using PlanEnricher (same logic as `plan review --auto-enrich`)
2829
- Use `--no-enrich-for-speckit` to disable auto-enrichment
30+
- **Contract extraction**: OpenAPI contracts are extracted automatically **only** for features with `source_tracking.implementation_files` and detectable API endpoints (FastAPI/Flask patterns). For enrichment-added features or Django apps, use `specfact contract init` after enrichment (see Phase 4)
2931

30-
2. **LLM Enrichment** (if `--enrichment` provided):
31-
- Read `.specfact/projects/<bundle>/enrichment_context.md`
32-
- Enrich: business context, "why" reasoning, missing acceptance criteria
33-
- Validate: contracts vs code, feature/story alignment
34-
- Save enrichment report to `.specfact/projects/<bundle-name>/reports/enrichment/` (bundle-specific, Phase 8.5, if created)
32+
2. **LLM Enrichment** (Copilot-only, before applying `--enrichment`):
33+
- Read CLI artifacts: `.specfact/projects/<bundle>/enrichment_context.md`, feature YAMLs, contract scaffolds, and brownfield reports
34+
- Scan the codebase within `--entry-point` (and adjacent modules) to identify missing features, dependencies, and behavior; do **not** rely solely on AST-derived YAML
35+
- Compare code findings vs CLI artifacts, then add missing features/stories, reasoning, and acceptance criteria (each added feature must include at least one story)
36+
- Save the enrichment report to `.specfact/projects/<bundle-name>/reports/enrichment/<bundle-name>-<timestamp>.enrichment.md` (bundle-specific, Phase 8.5)
37+
- **CRITICAL**: Follow the exact enrichment report format (see "Enrichment Report Format" section below) to ensure successful parsing
3538

3639
3. **Present**: Bundle location, report path, summary (features/stories/contracts/relationships)
3740

@@ -42,7 +45,7 @@ Import codebase → plan bundle. CLI extracts routes/schemas/relationships/contr
4245
**Rules:**
4346

4447
- Execute CLI first - never create artifacts directly
45-
- Use `--no-interactive` flag in CI/CD environments
48+
- Use the global `--no-interactive` flag in CI/CD environments (must appear before the subcommand)
4649
- Never modify `.specfact/` directly
4750
- Use CLI output as grounding for validation
4851
- Code generation requires LLM (only via AI IDE slash prompts, not CLI-only)
@@ -55,7 +58,7 @@ When in copilot mode, follow this three-phase workflow:
5558

5659
```bash
5760
# Execute CLI to get structured output
58-
specfact import from-code [<bundle>] --repo <path> --no-interactive
61+
specfact --no-interactive import from-code [<bundle>] --repo <path>
5962
```
6063

6164
**Capture**:
@@ -71,10 +74,10 @@ specfact import from-code [<bundle>] --repo <path> --no-interactive
7174
**What to do**:
7275

7376
- Read CLI-generated artifacts (use file reading tools for display only)
74-
- Research codebase for additional context
75-
- Identify missing features/stories
76-
- Suggest confidence adjustments
77-
- Extract business context
77+
- Scan the codebase within `--entry-point` for missing features/behavior and compare against CLI artifacts
78+
- Identify missing features/stories and add reasoning/acceptance criteria (no direct edits to `.specfact/`)
79+
- Suggest confidence adjustments and extract business context
80+
- **CRITICAL**: Generate enrichment report in the exact format specified below (see "Enrichment Report Format" section)
7881

7982
**What NOT to do**:
8083

@@ -83,20 +86,159 @@ specfact import from-code [<bundle>] --repo <path> --no-interactive
8386
- ❌ Bypass CLI validation
8487
- ❌ Write to `.specfact/` folder directly (always use CLI)
8588
- ❌ Use direct file manipulation tools for writing (use CLI commands)
89+
- ❌ Deviate from the enrichment report format (will cause parsing failures)
8690

8791
**Output**: Generate enrichment report (Markdown) saved to `.specfact/projects/<bundle-name>/reports/enrichment/` (bundle-specific, Phase 8.5)
8892

93+
**Enrichment Report Format** (REQUIRED for successful parsing):
94+
95+
The enrichment parser expects a specific Markdown format. Follow this structure exactly:
96+
97+
```markdown
98+
# [Bundle Name] Enrichment Report
99+
100+
**Date**: YYYY-MM-DDTHH:MM:SS
101+
**Bundle**: <bundle-name>
102+
103+
---
104+
105+
## Missing Features
106+
107+
1. **Feature Title** (Key: FEATURE-XXX)
108+
- Confidence: 0.85
109+
- Outcomes: outcome1, outcome2, outcome3
110+
- Stories:
111+
1. Story title here
112+
- Acceptance: criterion1, criterion2, criterion3
113+
2. Another story title
114+
- Acceptance: criterion1, criterion2
115+
116+
2. **Another Feature** (Key: FEATURE-YYY)
117+
- Confidence: 0.80
118+
- Outcomes: outcome1, outcome2
119+
- Stories:
120+
1. Story title
121+
- Acceptance: criterion1, criterion2, criterion3
122+
123+
## Confidence Adjustments
124+
125+
- FEATURE-EXISTING-KEY: 0.90 (reason: improved understanding after code review)
126+
127+
## Business Context
128+
129+
- Priority: High priority feature for core functionality
130+
- Constraint: Must support both REST and GraphQL APIs
131+
- Risk: Potential performance issues with large datasets
132+
```
133+
134+
**Format Requirements**:
135+
136+
1. **Section Header**: Must use `## Missing Features` (case-insensitive, but prefer this exact format)
137+
2. **Feature Format**:
138+
- Numbered list: `1. **Feature Title** (Key: FEATURE-XXX)`
139+
- **Bold title** is required (use `**Title**`)
140+
- **Key in parentheses**: `(Key: FEATURE-XXX)` - must be uppercase, alphanumeric with hyphens/underscores
141+
- Fields on separate lines with `-` prefix:
142+
- `- Confidence: 0.85` (float between 0.0-1.0)
143+
- `- Outcomes: comma-separated or line-separated list`
144+
- `- Stories:` (required - each feature must have at least one story)
145+
3. **Stories Format**:
146+
- Numbered list under `Stories:` section: `1. Story title`
147+
- **Indentation**: Stories must be indented (2-4 spaces) under the feature
148+
- **Acceptance Criteria**: `- Acceptance: criterion1, criterion2, criterion3`
149+
- Can be comma-separated on one line
150+
- Or multi-line (each criterion on new line)
151+
- Must start with `- Acceptance:`
152+
4. **Optional Sections**:
153+
- `## Confidence Adjustments`: List existing features with confidence updates
154+
- `## Business Context`: Priorities, constraints, risks (bullet points)
155+
5. **File Naming**: `<bundle-name>-<timestamp>.enrichment.md` (e.g., `djangogoat-2025-12-23T23-50-00.enrichment.md`)
156+
157+
**Example** (working format):
158+
159+
```markdown
160+
## Missing Features
161+
162+
1. **User Authentication** (Key: FEATURE-USER-AUTHENTICATION)
163+
- Confidence: 0.85
164+
- Outcomes: User registration, login, profile management
165+
- Stories:
166+
1. User can sign up for new account
167+
- Acceptance: sign_up view processes POST requests, creates User automatically, user is logged in after signup, redirects to profile page
168+
2. User can log in with credentials
169+
- Acceptance: log_in view authenticates username/password, on success user is logged in and redirected, on failure error message is displayed
170+
```
171+
172+
**Common Mistakes to Avoid**:
173+
174+
- ❌ Missing `(Key: FEATURE-XXX)` - parser needs this to identify features
175+
- ❌ Missing `Stories:` section - every feature must have at least one story
176+
- ❌ Stories not indented - parser expects indented numbered lists
177+
- ❌ Missing `- Acceptance:` prefix - acceptance criteria won't be parsed
178+
- ❌ Using bullet points (`-`) instead of numbers (`1.`) for stories
179+
- ❌ Feature title not in bold (`**Title**`) - parser may not extract title correctly
180+
89181
### Phase 3: CLI Artifact Creation (REQUIRED)
90182

91183
```bash
92184
# Use enrichment to update plan via CLI
93-
specfact import from-code [<bundle>] --repo <path> --enrichment <enrichment-report> --no-interactive
185+
specfact --no-interactive import from-code [<bundle>] --repo <path> --enrichment <enrichment-report>
94186
```
95187

96188
**Result**: Final artifacts are CLI-generated with validated enrichments
97189

98190
**Note**: If code generation is needed, use the validation loop pattern (see [CLI Enforcement Rules](./shared/cli-enforcement.md#standard-validation-loop-pattern-for-llm-generated-code))
99191

192+
### Phase 4: OpenAPI Contract Generation (REQUIRED for Sidecar Validation)
193+
194+
**When contracts are generated automatically:**
195+
196+
The `import from-code` command attempts to extract OpenAPI contracts automatically, but **only if**:
197+
198+
1. Features have `source_tracking.implementation_files` (AST-detected features)
199+
2. The OpenAPI extractor finds API endpoints (FastAPI/Flask patterns like `@app.get`, `@router.post`, `@app.route`)
200+
201+
**When contracts are NOT generated:**
202+
203+
Contracts are **NOT** generated automatically when:
204+
205+
- Features were added via enrichment (no `source_tracking.implementation_files`)
206+
- Django applications (Django `path()` patterns are not detected by the extractor)
207+
- Features without API endpoints (models, utilities, middleware, etc.)
208+
- Framework SDKs or libraries without web endpoints
209+
210+
**How to generate contracts manually:**
211+
212+
For features that need OpenAPI contracts (e.g., for sidecar validation with CrossHair), use:
213+
214+
```bash
215+
# Generate contract for a single feature
216+
specfact --no-interactive contract init --bundle <bundle-name> --feature <FEATURE_KEY> --repo <path>
217+
218+
# Example: Generate contracts for all enrichment-added features
219+
specfact --no-interactive contract init --bundle djangogoat-validation --feature FEATURE-USER-AUTHENTICATION --repo .
220+
specfact --no-interactive contract init --bundle djangogoat-validation --feature FEATURE-NOTES-MANAGEMENT --repo .
221+
# ... repeat for each feature that needs a contract
222+
```
223+
224+
**When to apply contract generation:**
225+
226+
- **After Phase 3** (enrichment applied): Check which features have contracts in `.specfact/projects/<bundle>/contracts/`
227+
- **Before sidecar validation**: All features that will be analyzed by CrossHair/Specmatic need OpenAPI contracts
228+
- **For Django apps**: Always generate contracts manually after enrichment, as Django URL patterns are not auto-detected
229+
230+
**Verification:**
231+
232+
```bash
233+
# Check which features have contracts
234+
ls .specfact/projects/<bundle>/contracts/*.yaml
235+
236+
# Compare with total features
237+
ls .specfact/projects/<bundle>/features/*.yaml
238+
```
239+
240+
If the contract count is less than the feature count, generate missing contracts using `contract init`.
241+
100242
## Expected Output
101243

102244
**Success**: Bundle location, report path, summary (features/stories/contracts/relationships)

.cursor/commands/specfact.02-plan.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,9 @@ specfact plan <operation> [--bundle <name>] [options] --no-interactive
103103
**What to do**:
104104

105105
- Read CLI-generated artifacts (use file reading tools for display only)
106-
- Research codebase for additional context
106+
- Use CLI artifacts as the source of truth for keys/structure/metadata
107+
- Scan codebase only if asked to align the plan with implementation or to add missing features
108+
- When scanning, compare findings against CLI artifacts and propose updates via CLI commands
107109
- Identify missing features/stories
108110
- Suggest confidence adjustments
109111
- Extract business context

.cursor/commands/specfact.03-review.md

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,9 @@ For these cases, use the **export-to-file → LLM reasoning → import-from-file
131131

132132
**CRITICAL**: Always use `/tmp/` for temporary artifacts to avoid polluting the codebase. Never create temporary files in the project root.
133133

134+
**CRITICAL**: Question IDs are generated per run and can change if you re-run review.
135+
**Do not** re-run `plan review` between exporting questions and applying answers. Always answer using the exact exported questions file for that session.
136+
134137
**Note**: The `--max-questions` parameter (default: 5) limits the number of questions per session, not the total number of available questions. If there are more questions available, you may need to run the review multiple times to answer all questions. Each session will ask different questions (avoiding duplicates from previous sessions).
135138

136139
**Export questions to file for LLM reasoning:**
@@ -393,6 +396,11 @@ specfact plan review [<bundle-name>] --list-questions --output-questions /tmp/qu
393396

394397
**What to do**:
395398

399+
0. **Grounding rule**:
400+
- Treat CLI-exported questions as the source of truth; consult codebase/docs only to answer them (do not invent new artifacts)
401+
- **Feature/Story Completeness note**: Answers here are clarifications only. They do **NOT** create stories.
402+
For missing stories, use `specfact plan add-story` (or `plan update-story --batch-updates` if stories already exist).
403+
396404
1. **Read exported questions file** (`/tmp/questions.json`):
397405
- Review all questions and their categories
398406
- Identify questions requiring code/feature analysis
@@ -601,6 +609,102 @@ Create one with: specfact plan init legacy-api
601609
- Use `plan update-idea` to update idea fields directly
602610
- If bundle needs regeneration, use `import from-code --enrichment`
603611

612+
**Note on OpenAPI Contracts:**
613+
614+
After applying enrichment or review updates, check if features need OpenAPI contracts for sidecar validation:
615+
616+
- Features added via enrichment typically don't have contracts (no `source_tracking`)
617+
- Django applications require manual contract generation (Django URL patterns not auto-detected)
618+
- Use `specfact contract init --bundle <bundle> --feature <FEATURE_KEY>` to generate contracts for features that need them
619+
620+
**Enrichment Report Format** (for `import from-code --enrichment`):
621+
622+
When generating enrichment reports for use with `import from-code --enrichment`, follow this exact format:
623+
624+
```markdown
625+
# [Bundle Name] Enrichment Report
626+
627+
**Date**: YYYY-MM-DDTHH:MM:SS
628+
**Bundle**: <bundle-name>
629+
630+
---
631+
632+
## Missing Features
633+
634+
1. **Feature Title** (Key: FEATURE-XXX)
635+
- Confidence: 0.85
636+
- Outcomes: outcome1, outcome2, outcome3
637+
- Stories:
638+
1. Story title here
639+
- Acceptance: criterion1, criterion2, criterion3
640+
2. Another story title
641+
- Acceptance: criterion1, criterion2
642+
643+
2. **Another Feature** (Key: FEATURE-YYY)
644+
- Confidence: 0.80
645+
- Outcomes: outcome1, outcome2
646+
- Stories:
647+
1. Story title
648+
- Acceptance: criterion1, criterion2, criterion3
649+
650+
## Confidence Adjustments
651+
652+
- FEATURE-EXISTING-KEY: 0.90 (reason: improved understanding after code review)
653+
654+
## Business Context
655+
656+
- Priority: High priority feature for core functionality
657+
- Constraint: Must support both REST and GraphQL APIs
658+
- Risk: Potential performance issues with large datasets
659+
```
660+
661+
**Format Requirements**:
662+
663+
1. **Section Header**: Must use `## Missing Features` (case-insensitive, but prefer this exact format)
664+
2. **Feature Format**:
665+
- Numbered list: `1. **Feature Title** (Key: FEATURE-XXX)`
666+
- **Bold title** is required (use `**Title**`)
667+
- **Key in parentheses**: `(Key: FEATURE-XXX)` - must be uppercase, alphanumeric with hyphens/underscores
668+
- Fields on separate lines with `-` prefix:
669+
- `- Confidence: 0.85` (float between 0.0-1.0)
670+
- `- Outcomes: comma-separated or line-separated list`
671+
- `- Stories:` (required - each feature must have at least one story)
672+
3. **Stories Format**:
673+
- Numbered list under `Stories:` section: `1. Story title`
674+
- **Indentation**: Stories must be indented (2-4 spaces) under the feature
675+
- **Acceptance Criteria**: `- Acceptance: criterion1, criterion2, criterion3`
676+
- Can be comma-separated on one line
677+
- Or multi-line (each criterion on new line)
678+
- Must start with `- Acceptance:`
679+
4. **Optional Sections**:
680+
- `## Confidence Adjustments`: List existing features with confidence updates
681+
- `## Business Context`: Priorities, constraints, risks (bullet points)
682+
5. **File Naming**: `<bundle-name>-<timestamp>.enrichment.md` (e.g., `djangogoat-2025-12-23T23-50-00.enrichment.md`)
683+
684+
**Example** (working format):
685+
686+
```markdown
687+
## Missing Features
688+
689+
1. **User Authentication** (Key: FEATURE-USER-AUTHENTICATION)
690+
- Confidence: 0.85
691+
- Outcomes: User registration, login, profile management
692+
- Stories:
693+
1. User can sign up for new account
694+
- Acceptance: sign_up view processes POST requests, creates User automatically, user is logged in after signup, redirects to profile page
695+
2. User can log in with credentials
696+
- Acceptance: log_in view authenticates username/password, on success user is logged in and redirected, on failure error message is displayed
697+
```
698+
699+
**Common Mistakes to Avoid**:
700+
701+
- ❌ Missing `(Key: FEATURE-XXX)` - parser needs this to identify features
702+
- ❌ Missing `Stories:` section - every feature must have at least one story
703+
- ❌ Stories not indented - parser expects indented numbered lists
704+
- ❌ Missing `- Acceptance:` prefix - acceptance criteria won't be parsed
705+
- ❌ Using bullet points (`-`) instead of numbers (`1.`) for stories
706+
- ❌ Feature title not in bold (`**Title**`) - parser may not extract title correctly
707+
604708
## Context
605709

606710
{ARGS}

.cursor/commands/specfact.04-sdd.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ specfact plan harden [<bundle-name>] [--sdd <path>] --no-interactive
8686
**What to do**:
8787

8888
- Read CLI-generated SDD (use file reading tools for display only)
89+
- Treat CLI SDD as the source of truth; scan codebase only to enrich WHY/WHAT/HOW context
8990
- Research codebase for additional context
9091
- Suggest improvements to WHY/WHAT/HOW sections
9192

.cursor/commands/specfact.05-enforce.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ specfact enforce sdd [<bundle-name>] [--sdd <path>] --no-interactive
9090
**What to do**:
9191

9292
- Read CLI-generated validation report (use file reading tools for display only)
93+
- Treat the CLI report as the source of truth; scan codebase only to explain deviations or propose fixes
9394
- Research codebase for context on deviations
9495
- Suggest fixes for validation failures
9596

.cursor/commands/specfact.06-sync.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ specfact sync bridge --adapter <adapter> --repo <path> [options] --no-interactiv
9393
**What to do**:
9494

9595
- Read CLI-generated sync results (use file reading tools for display only)
96+
- Treat CLI sync output as the source of truth; scan codebase only to explain conflicts
9697
- Research codebase for context on conflicts
9798
- Suggest resolution strategies
9899

.cursor/commands/specfact.compare.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ specfact plan compare [--bundle <name>] [options] --no-interactive
9090
**What to do**:
9191

9292
- Read CLI-generated comparison report (use file reading tools for display only)
93+
- Treat the comparison report as the source of truth; scan codebase only to explain or confirm deviations
9394
- Research codebase for context on deviations
9495
- Suggest fixes for missing features or mismatches
9596

.cursor/commands/specfact.validate.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ specfact repro --repo <path> [options] --no-interactive
9292
**What to do**:
9393

9494
- Read CLI-generated validation report (use file reading tools for display only)
95+
- Treat the validation report as the source of truth; scan codebase only to explain failures
9596
- Research codebase for context on failures
9697
- Suggest fixes for validation failures
9798

0 commit comments

Comments
 (0)