Skip to content

Commit fac0402

Browse files
committed
feat: spec-code sync
1 parent 9e890b5 commit fac0402

File tree

3 files changed

+233
-7
lines changed

3 files changed

+233
-7
lines changed

roadmap.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -96,15 +96,15 @@
9696

9797
## 🚀 **NEXT PHASE** (Immediate Priority - Complete Within 2-3 Months)
9898

99-
#### **Iterative Development Support** *(85% Complete)* - **HIGH PRIORITY** - Addresses anti-iterative critique
99+
#### **Iterative Development Support** *(100% Complete)* - **HIGH PRIORITY** - Addresses anti-iterative critique
100100
-**Git-Managed Documentation**: Specs stored in `specs/[feature-name]/` directories with full version control
101101
-**Branch-Based Isolation**: Each feature has dedicated branch enabling parallel development
102102
-**Clarify Command Iteration**: Enables iterative spec refinement with direct spec file modifications
103103
-**Analyze Command Cross-Reference**: Performs consistency analysis with remediation suggestions
104104
-**Post-Implementation Analysis**: Extended `/analyze` command with auto-detection for pre/post-implementation context
105105
-**Documentation Evolution**: Specs and plans actively evolve through git commits during development
106106
-**Rollback Integration**: Git rollback capabilities preserve documentation state consistency
107-
- **Automated Documentation Updates**: Background, non-blocking automation that detects code changes and queues documentation updates for review at natural breakpoints (pre-commit/push), with CLI-injected git hooks and mode-aware behavior
107+
- **Automated Documentation Updates**: Background, non-blocking automation that detects code changes and queues documentation updates for review at natural breakpoints (pre-commit/push), with CLI-injected git hooks and mode-aware behavior
108108

109109
#### **Workflow Stage Orchestration** *(100% Complete)* - **COMPLETED** - Workflow completeness through command-to-command guidance
110110
-**Git-Based Rollback**: Code and documentation rollback via git commands (already working)
@@ -188,7 +188,7 @@
188188
| **Configurable Options** | 100% | ✅ Complete |
189189
| **Workflow Stage Orchestration** | 100% | ✅ Complete |
190190
| **Command Prefix Migration** | 0% | 🚀 Next Phase |
191-
| **Iterative Development** | 85% | 🚀 Next Phase |
191+
| **Iterative Development** | 100% | 🚀 Next Phase |
192192

193193
| **Enhanced Traceability** | 100% | ✅ Complete |
194194
| **Strategic Tooling** | 80% | 🔄 Current Phase |
@@ -208,7 +208,7 @@
208208
- **Future Enhancements**: 0% Complete (minimal enterprise features only)
209209
- **Deferred Features**: IDE Integration & overkill enhancements (removed to maintain focus)
210210

211-
**Note**: @agentic-sdlc-12-factors serves dual purposes as methodology documentation and reference implementation, providing working examples and command templates that accelerate Spec Kit development. **Core 12F workflow Factors III-V are 100% complete** - mission definition, planning, execution, and orchestration work effectively through existing commands, git infrastructure, and command-to-command guidance system. **Workflow orchestration implemented** through CLI workflow overview, context-aware next actions, and sequential command guidance - no advanced visualization or blocking validation needed. **All overkill features eliminated** - advanced monitoring, interactive tutorials, evaluation suites, and context engineering removed to maintain razor focus on essential SDD functionality. Key SDD flexibility features are implemented via `/clarify` (iterative refinement), `/analyze` (consistency validation with auto-detection and post-implementation analysis), and `/checklist` (requirements quality testing with mode-aware framework option validation). **Complexity reduction prioritized** based on user feedback analysis - workflow modes provide user-choice flexibility (spec-driven structured mode as default vs lightweight build mode for exploration), **iterative development is comprehensively supported** through git-managed specs, branch isolation, clarify command modifications, and analyze cross-references, and configurable framework options make TDD/contracts/data models/risk-based testing opt-in rather than mandatory, with checklist validation ensuring enabled options are properly specified in requirements. **Automated documentation updates will be non-blocking background automation** with CLI-injected git hooks, queued updates at natural breakpoints, and mode-aware batch review to preserve developer workflow. **Issue tracker traceability is intentionally separate** from documentation automation for modularity, reliability, and independent adoption. **Command prefix migration prioritized as CRITICAL** due to immediate user impact as a breaking change affecting fork differentiation. Rich context delegation provides superior AI assistance compared to issue labeling approaches.
211+
**Note**: @agentic-sdlc-12-factors serves dual purposes as methodology documentation and reference implementation, providing working examples and command templates that accelerate Spec Kit development. **Core 12F workflow Factors III-V are 100% complete** - mission definition, planning, execution, and orchestration work effectively through existing commands, git infrastructure, and command-to-command guidance system. **Workflow orchestration implemented** through CLI workflow overview, context-aware next actions, and sequential command guidance - no advanced visualization or blocking validation needed. **All overkill features eliminated** - advanced monitoring, interactive tutorials, evaluation suites, and context engineering removed to maintain razor focus on essential SDD functionality. Key SDD flexibility features are implemented via `/clarify` (iterative refinement), `/analyze` (consistency validation with auto-detection and post-implementation analysis), and `/checklist` (requirements quality testing with mode-aware framework option validation). **Complexity reduction prioritized** based on user feedback analysis - workflow modes provide user-choice flexibility (spec-driven structured mode as default vs lightweight build mode for exploration), **iterative development is comprehensively supported** through git-managed specs, branch isolation, clarify command modifications, and analyze cross-references, and configurable framework options make TDD/contracts/data models/risk-based testing opt-in rather than mandatory, with checklist validation ensuring enabled options are properly specified in requirements. **Automated documentation updates are implemented** as non-blocking background automation with CLI-injected git hooks, queued updates at natural breakpoints, and mode-aware batch review to preserve developer workflow. **Issue tracker traceability is intentionally separate** from documentation automation for modularity, reliability, and independent adoption. **Command prefix migration prioritized as CRITICAL** due to immediate user impact as a breaking change affecting fork differentiation. Rich context delegation provides superior AI assistance compared to issue labeling approaches.
212212

213213
## 🎯 **PRIORITY RANKING** - Refined based on user impact and breaking changes
214214

@@ -217,7 +217,7 @@
217217

218218
2. **HIGH**: Workflow stage orchestration (100% → 100%) - **COMPLETED** - Already implemented via command-to-command guidance
219219

220-
4. **MEDIUM**: Iterative development support (85% → 100%) - Addresses anti-iterative design concerns (mostly complete via existing git + commands)
220+
4. **MEDIUM**: Iterative development support (100% → 100%) - **COMPLETED** - Addresses anti-iterative design concerns
221221

222222
**🔄 CURRENT PHASE (Complete After Next Phase):**
223223
5. **MEDIUM**: Enhanced traceability framework (100% → 100%) - **COMPLETED**
@@ -240,10 +240,10 @@
240240
- ✅ CLI workflow overview display - IMPLEMENTED in `specify init` command
241241
- ✅ Context-aware next action guidance - IMPLEMENTED in `/analyze` and `/specify` commands
242242

243-
- **Iterative Development Support** (HIGH PRIORITY - Mostly Complete):
243+
- **Iterative Development Support** (HIGH PRIORITY - **COMPLETED**):
244244
- ✅ Phase 1 (2 weeks): Extended `/analyze` with auto-detection - COMPLETED
245245
- ✅ Phase 2 (Ongoing): Git-managed documentation evolution and rollback - IMPLEMENTED via existing infrastructure
246-
- Phase 3 (3 weeks): Background documentation automation - CLI-injected git hooks, change detection engine, queued updates with mode-aware batch review (non-blocking workflow)
246+
- Phase 3 (3 weeks): Background documentation automation - CLI-injected git hooks, change detection engine, queued updates with mode-aware batch review (non-blocking workflow)
247247

248248

249249
**🔄 CURRENT PHASE (Complete After Next Phase):**

scripts/bash/spec-hooks-install.sh

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
#!/bin/bash
2+
# spec-hooks-install.sh - Install git hooks for automatic spec-code synchronization
3+
# This script sets up pre-commit, post-commit, and pre-push hooks to detect code changes
4+
# and queue documentation updates for specs/*.md files
5+
6+
set -euo pipefail
7+
8+
# Colors for output
9+
RED='\033[0;31m'
10+
GREEN='\033[0;32m'
11+
YELLOW='\033[1;33m'
12+
BLUE='\033[0;34m'
13+
NC='\033[0m' # No Color
14+
15+
# Logging functions
16+
log_info() {
17+
echo -e "${BLUE}INFO:${NC} $*" >&2
18+
}
19+
20+
log_success() {
21+
echo -e "${GREEN}SUCCESS:${NC} $*" >&2
22+
}
23+
24+
log_warning() {
25+
echo -e "${YELLOW}WARNING:${NC} $*" >&2
26+
}
27+
28+
log_error() {
29+
echo -e "${RED}ERROR:${NC} $*" >&2
30+
}
31+
32+
# Check if we're in a git repository
33+
check_git_repo() {
34+
if ! git rev-parse --git-dir > /dev/null 2>&1; then
35+
log_error "Not in a git repository. Spec sync requires git."
36+
exit 1
37+
fi
38+
}
39+
40+
# Create hooks directory if it doesn't exist
41+
ensure_hooks_dir() {
42+
local hooks_dir=".git/hooks"
43+
if [[ ! -d "$hooks_dir" ]]; then
44+
log_warning "Git hooks directory not found, creating it"
45+
mkdir -p "$hooks_dir"
46+
fi
47+
}
48+
49+
# Install a specific hook
50+
install_hook() {
51+
local hook_name="$1"
52+
local hook_script="$2"
53+
local hooks_dir=".git/hooks"
54+
local hook_path="$hooks_dir/$hook_name"
55+
56+
# Check if hook already exists
57+
if [[ -f "$hook_path" ]]; then
58+
# Check if it's already our hook
59+
if grep -q "spec-sync" "$hook_path" 2>/dev/null; then
60+
log_info "$hook_name hook already installed"
61+
return 0
62+
else
63+
log_warning "$hook_name hook already exists, backing up and replacing"
64+
cp "$hook_path" "${hook_path}.backup.$(date +%Y%m%d_%H%M%S)"
65+
fi
66+
fi
67+
68+
# Create the hook script
69+
cat > "$hook_path" << EOF
70+
#!/bin/bash
71+
# $hook_name hook for spec-code synchronization
72+
# Automatically detects code changes and queues spec updates
73+
74+
set -euo pipefail
75+
76+
# Source the spec sync utilities
77+
SCRIPT_DIR="\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" && pwd)"
78+
PROJECT_ROOT="\$(cd "\$SCRIPT_DIR/../.." && pwd)"
79+
80+
# Check if spec sync is enabled for this project
81+
if [[ ! -f "\$PROJECT_ROOT/.specify/config/spec-sync-enabled" ]]; then
82+
exit 0
83+
fi
84+
85+
# Run the $hook_script
86+
if [[ -f "\$PROJECT_ROOT/scripts/bash/$hook_script" ]]; then
87+
bash "\$PROJECT_ROOT/scripts/bash/$hook_script"
88+
fi
89+
EOF
90+
91+
# Make executable
92+
chmod +x "$hook_path"
93+
94+
log_success "Installed $hook_name hook"
95+
}
96+
97+
# Create spec sync configuration
98+
create_config() {
99+
local config_dir=".specify/config"
100+
mkdir -p "$config_dir"
101+
102+
# Mark spec sync as enabled
103+
touch "$config_dir/spec-sync-enabled"
104+
105+
# Create initial queue file
106+
local queue_file="$config_dir/spec-sync-queue.json"
107+
if [[ ! -f "$queue_file" ]]; then
108+
cat > "$queue_file" << EOF
109+
{
110+
"version": "1.0",
111+
"created": "$(date -Iseconds)",
112+
"queue": [],
113+
"processed": []
114+
}
115+
EOF
116+
fi
117+
118+
log_success "Created spec sync configuration"
119+
}
120+
121+
# Main installation function
122+
main() {
123+
log_info "Installing spec-code synchronization hooks..."
124+
125+
check_git_repo
126+
ensure_hooks_dir
127+
create_config
128+
129+
# Install the hooks
130+
install_hook "pre-commit" "spec-sync-pre-commit.sh"
131+
install_hook "post-commit" "spec-sync-post-commit.sh"
132+
install_hook "pre-push" "spec-sync-pre-push.sh"
133+
134+
log_success "Spec-code synchronization hooks installed successfully!"
135+
log_info "Hooks will automatically detect code changes and queue spec updates"
136+
log_info "Use 'git commit' or 'git push' to trigger synchronization"
137+
}
138+
139+
# Run main function
140+
main "$@"

src/specify_cli/__init__.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1152,6 +1152,7 @@ def init(
11521152
gateway_url: str = typer.Option(None, "--gateway-url", help="Populate SPECIFY_GATEWAY_URL in .specify/config/gateway.env"),
11531153
gateway_token: str = typer.Option(None, "--gateway-token", help="Populate SPECIFY_GATEWAY_TOKEN in .specify/config/gateway.env"),
11541154
gateway_suppress_warning: bool = typer.Option(False, "--gateway-suppress-warning", help="Set SPECIFY_SUPPRESS_GATEWAY_WARNING=true in gateway.env"),
1155+
spec_sync: bool = typer.Option(False, "--spec-sync", help="Enable automatic spec-code synchronization (keeps specs/*.md files updated with code changes)"),
11551156
):
11561157
"""
11571158
Initialize a new Specify project from the latest template.
@@ -1185,6 +1186,8 @@ def init(
11851186
specify init my-project --issue-tracker github
11861187
specify init my-project --async-agent jules
11871188
specify init my-project --gateway-url https://proxy.internal --gateway-token $TOKEN
1189+
specify init my-project --spec-sync
1190+
specify init my-project --ai claude --spec-sync --issue-tracker github
11881191
"""
11891192

11901193
show_banner()
@@ -1342,6 +1345,7 @@ def init(
13421345
("extracted-summary", "Extraction summary"),
13431346
("chmod", "Ensure scripts executable"),
13441347
("gateway", "Configure gateway"),
1348+
("spec_sync", "Setup spec-code synchronization"),
13451349
("cleanup", "Cleanup"),
13461350
("directives", "Sync team directives"),
13471351
("git", "Initialize git repository"),
@@ -1411,6 +1415,24 @@ def init(
14111415
else:
14121416
tracker.skip("async-agent-mcp", "not requested")
14131417

1418+
# Spec-code synchronization setup
1419+
if spec_sync:
1420+
tracker.start("spec_sync", "setting up spec-code synchronization")
1421+
try:
1422+
# Run the spec-hooks install command
1423+
result = subprocess.run([
1424+
sys.executable, "-m", "specify_cli", "spec-hooks", "install", "--quiet"
1425+
], cwd=project_path, capture_output=True, text=True, check=True)
1426+
tracker.complete("spec_sync", "hooks installed")
1427+
except subprocess.CalledProcessError as e:
1428+
tracker.error("spec_sync", f"failed to install hooks: {e.stderr}")
1429+
console.print(f"[yellow]Warning:[/yellow] Spec sync setup failed: {e.stderr}")
1430+
except Exception as e:
1431+
tracker.error("spec_sync", f"unexpected error: {str(e)}")
1432+
console.print(f"[yellow]Warning:[/yellow] Spec sync setup failed: {str(e)}")
1433+
else:
1434+
tracker.skip("spec_sync", "not requested")
1435+
14141436
if not no_git:
14151437
tracker.start("git")
14161438
if is_git_repo(project_path):
@@ -1577,6 +1599,70 @@ def check():
15771599
if not any(agent_results.values()):
15781600
console.print("[dim]Tip: Install an AI assistant for the best experience[/dim]")
15791601

1602+
1603+
@app.command()
1604+
def spec_hooks(
1605+
action: str = typer.Argument(..., help="Action: install, uninstall, status"),
1606+
quiet: bool = typer.Option(False, "--quiet", help="Suppress output for automated usage"),
1607+
):
1608+
"""Manage specification synchronization hooks."""
1609+
if action == "install":
1610+
success = install_spec_hooks(quiet=quiet)
1611+
if not quiet:
1612+
if success:
1613+
console.print("[green]✓[/green] Specification synchronization hooks installed")
1614+
console.print(" Background spec-code sync is now active")
1615+
console.print(" Use 'specify spec-hooks --help' for management commands")
1616+
else:
1617+
console.print("[red]✗[/red] Failed to install specification synchronization hooks")
1618+
raise typer.Exit(1)
1619+
elif action == "uninstall":
1620+
if not quiet:
1621+
console.print("[yellow]Uninstall functionality not yet implemented[/yellow]")
1622+
elif action == "status":
1623+
if not quiet:
1624+
console.print("[yellow]Status check not yet implemented[/yellow]")
1625+
else:
1626+
if not quiet:
1627+
console.print(f"[red]Unknown action: {action}[/red]")
1628+
console.print("Available actions: install, uninstall, status")
1629+
raise typer.Exit(1)
1630+
1631+
1632+
def install_spec_hooks(quiet: bool = False) -> bool:
1633+
"""Install specification synchronization hooks for the current project."""
1634+
try:
1635+
# Check if we're in a git repository
1636+
if not is_git_repo():
1637+
if not quiet:
1638+
console.print("[yellow]Warning:[/yellow] Not in a git repository. Spec sync requires git.")
1639+
return False
1640+
1641+
# Run the hook installation script
1642+
script_dir = Path(__file__).parent.parent / "scripts" / "bash"
1643+
hook_script = script_dir / "spec-hooks-install.sh"
1644+
1645+
if not hook_script.exists():
1646+
if not quiet:
1647+
console.print("[red]Error:[/red] Spec hooks installation script not found.")
1648+
return False
1649+
1650+
result = subprocess.run([
1651+
"bash", str(hook_script)
1652+
], capture_output=quiet, text=True, check=True)
1653+
1654+
return True
1655+
1656+
except subprocess.CalledProcessError as e:
1657+
if not quiet:
1658+
console.print(f"[red]Error installing spec hooks:[/red] {e.stderr}")
1659+
return False
1660+
except Exception as e:
1661+
if not quiet:
1662+
console.print(f"[red]Unexpected error:[/red] {str(e)}")
1663+
return False
1664+
1665+
15801666
def main():
15811667
app()
15821668

0 commit comments

Comments
 (0)