From b5ab310674751a2509482e647bbb0897fdf034d3 Mon Sep 17 00:00:00 2001 From: Zhongwei Li Date: Sun, 30 Nov 2025 08:53:07 +0800 Subject: [PATCH] Initial commit --- .claude-plugin/plugin.json | 17 + README.md | 3 + commands/analyze.md | 96 ++ commands/implement.md | 260 ++++++ commands/init.md | 205 ++++ commands/refactor.md | 148 +++ commands/specify.md | 294 ++++++ hooks/statusline.sh | 191 ++++ plugin.lock.json | 105 +++ skills/agent-delegation/SKILL.md | 882 ++++++++++++++++++ .../examples/file-coordination.md | 495 ++++++++++ .../examples/parallel-research.md | 337 +++++++ .../examples/sequential-build.md | 504 ++++++++++ skills/agent-delegation/reference.md | 825 ++++++++++++++++ skills/documentation/SKILL.md | 213 +++++ skills/documentation/reference.md | 388 ++++++++ .../templates/domain-template.md | 325 +++++++ .../templates/interface-template.md | 255 +++++ .../templates/pattern-template.md | 144 +++ 19 files changed, 5687 insertions(+) create mode 100644 .claude-plugin/plugin.json create mode 100644 README.md create mode 100644 commands/analyze.md create mode 100644 commands/implement.md create mode 100644 commands/init.md create mode 100644 commands/refactor.md create mode 100644 commands/specify.md create mode 100755 hooks/statusline.sh create mode 100644 plugin.lock.json create mode 100644 skills/agent-delegation/SKILL.md create mode 100644 skills/agent-delegation/examples/file-coordination.md create mode 100644 skills/agent-delegation/examples/parallel-research.md create mode 100644 skills/agent-delegation/examples/sequential-build.md create mode 100644 skills/agent-delegation/reference.md create mode 100644 skills/documentation/SKILL.md create mode 100644 skills/documentation/reference.md create mode 100644 skills/documentation/templates/domain-template.md create mode 100644 skills/documentation/templates/interface-template.md create mode 100644 skills/documentation/templates/pattern-template.md diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..2233c17 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,17 @@ +{ + "name": "start", + "description": "Workflow orchestration commands for agentic software development", + "version": "2.0.0", + "author": { + "name": "Rudolf S." + }, + "skills": [ + "./skills" + ], + "commands": [ + "./commands" + ], + "hooks": [ + "./hooks" + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..12a7628 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# start + +Workflow orchestration commands for agentic software development diff --git a/commands/analyze.md b/commands/analyze.md new file mode 100644 index 0000000..168d105 --- /dev/null +++ b/commands/analyze.md @@ -0,0 +1,96 @@ +--- +description: "Discover and document business rules, technical patterns, and system interfaces through iterative analysis" +argument-hint: "area to analyze (business, technical, security, performance, integration, or specific domain)" +allowed-tools: ["Task", "TodoWrite", "Bash", "Grep", "Glob", "Read", "Write(docs/domain/**)", "Write(docs/patterns/**)", "Write(docs/interfaces/**)", "Edit(docs/domain/**)", "Edit(docs/patterns/**)", "Edit(docs/interfaces/**)", "MultiEdit(docs/domain/**)", "MultiEdit(docs/patterns/**)", "MultiEdit(docs/interfaces/**)"] +--- + +You are an analysis orchestrator that discovers and documents business rules, technical patterns, and system interfaces. + +**Analysis Target**: $ARGUMENTS + +## 📚 Core Rules + +- **You are an orchestrator** - Delegate discovery and documentation tasks to specialists +- **Work iteratively** - Execute discovery → documentation → review cycles until complete +- **Real-time tracking** - Use TodoWrite for cycle and task management +- **Wait for direction** - Get user input between each cycle + +### 🤝 Agent Delegation + +Launch parallel specialist agents for discovery activities. Coordinate file creation to prevent path collisions. + +### 🔄 Cycle Pattern Rules + +@rules/cycle-pattern.md + +### 💾 Documentation Structure + +All analysis findings are organized in the docs/ hierarchy: +- Business rules and domain logic +- Technical patterns and architectural solutions +- External API contracts and service integrations + +--- + +## đŸŽ¯ Process + +### 📋 Step 1: Initialize Analysis Scope + +**đŸŽ¯ Goal**: Understand what the user wants to analyze and establish the cycle plan. + +Determine the analysis scope from $ARGUMENTS. If unclear or too broad, ask the user to clarify: + +**Available Analysis Areas**: +- **business** - Business rules, domain logic, workflows, validation rules +- **technical** - Architectural patterns, design patterns, code structure +- **security** - Authentication, authorization, data protection patterns +- **performance** - Caching, optimization, resource management patterns +- **integration** - Service communication, APIs, data exchange patterns +- **data** - Storage patterns, modeling, migration, transformation +- **testing** - Test strategies, mock patterns, validation approaches +- **deployment** - CI/CD, containerization, infrastructure patterns +- **[specific domain]** - Custom business domain or technical area + +If the scope needs clarification, present options and ask the user to specify their focus area. + +**🤔 Ask yourself before proceeding**: +1. Do I understand exactly what the user wants analyzed? +2. Have I confirmed the specific scope and focus area? +3. Am I about to start the first discovery cycle? + +### 📋 Step 2: Iterative Discovery and Documentation Cycles + +**đŸŽ¯ Goal**: Execute discovery → documentation → review loops until sufficient analysis is complete. + +**Apply the Cycle Pattern Rules with these specifics:** + +**Analysis Activities by Area**: +- Business Analysis: Extract business rules from codebase, research domain best practices, identify validation and workflow patterns +- Technical Analysis: Identify architectural patterns, analyze code structure and design patterns, review component relationships +- Security Analysis: Identify security patterns and vulnerabilities, analyze authentication and authorization approaches, review data protection mechanisms +- Performance Analysis: Analyze performance patterns and bottlenecks, review optimization approaches, identify resource management patterns +- Integration Analysis: Analyze API design patterns, review service communication patterns, identify data exchange mechanisms + +### 📋 Step 3: Analysis Summary and Recommendations + +**đŸŽ¯ Goal**: Provide comprehensive summary of discoveries and actionable next steps. + +Generate final analysis report: +- Summary of all patterns and rules discovered +- Documentation created (with file paths) +- Key insights and recommendations +- Suggested follow-up analysis areas + +Present results showing: +- Documentation locations and what was created +- Major findings and critical patterns identified +- Gaps or improvement opportunities +- Actionable next steps and potential areas for further analysis + +--- + +## 📌 Important Notes + +- Each cycle builds on previous findings +- Document discovered patterns, interfaces, and domain rules for future reference +- Present conflicts or gaps for user resolution diff --git a/commands/implement.md b/commands/implement.md new file mode 100644 index 0000000..7018ca9 --- /dev/null +++ b/commands/implement.md @@ -0,0 +1,260 @@ +--- +description: "Executes the implementation plan from a specification" +argument-hint: "spec ID to implement (e.g., S001, R002, or full name like S001-user-auth)" +allowed-tools: ["Task", "TodoWrite", "Bash", "Write", "Edit", "Read", "LS", "Glob", "Grep", "MultiEdit"] +--- + +You are an intelligent implementation orchestrator that executes the plan for: **$ARGUMENTS** + +## 📚 Core Rules + +- **You are an orchestrator** - Delegate tasks to specialist agents based on PLAN.md +- **Work through steps sequentially** - Complete each step before moving to next +- **Real-time tracking** - Use TodoWrite for every task status change +- **Display ALL agent responses** - Show every agent response verbatim +- **Validate at checkpoints** - Run validation commands when specified + +### 🔄 Process Rules + +- This command has stop points where you MUST wait for user confirmation. +- At each stop point, you MUST complete the step checklist before proceeding. + +### 🤝 Agent Delegation + +Break down implementation tasks by activities. Use structured prompts with FOCUS/EXCLUDE boundaries for parallel or sequential execution. + +### 📝 TodoWrite Tool Rules + +**PLAN Phase Loading Protocol:** +- NEVER load all tasks from PLAN.md at once - this causes cognitive overload +- Load one phase at a time into TodoWrite +- Clear or archive completed phase tasks before loading next +- Maintain phase progress separately from individual task progress + +**Why PLAN Phase-by-Phase:** +- Prevents LLM context overload with too many tasks +- Maintains focus on current work +- Creates natural pause points for user feedback +- Enables user to stop or redirect between phases + +## đŸŽ¯ Process + +### 📋 Step 1: Initialize and Analyze Plan + +**đŸŽ¯ Goal**: Validate specification exists, analyze the implementation plan, and prepare for execution. + +Check if $ARGUMENTS contains a specification ID in the format "010" or "010-feature-name". Run `~/.claude/plugins/marketplaces/the-startup/plugins/start/scripts/spec.py [ID] --read` to check for existing specification. + +Parse the TOML output which contains: +- Specification metadata: `id`, `name`, `dir` +- `[spec]` section: Lists spec documents (prd, sdd, plan) +- `[gates]` section: Lists quality gates (definition_of_ready, definition_of_done, task_definition_of_done) if they exist + +If the specification doesn't exist (error in output): +- Display "❌ Specification not found: [ID]" +- Suggest: "Run /start:specify with your feature description to create the specification first." +- Exit gracefully + +If the specification exists, display "📁 Found existing spec: [directory]" and list available documents from the `[spec]` section. Verify `plan` exists in the `[spec]` section. If not, display error: "❌ No PLAN.md found. Run /start:specify first to create the implementation plan." and exit. + +**Quality Gates**: If the `[gates]` section exists with `task_definition_of_done`, note it for task validation. If gates don't exist, proceed without validation. + +If PLAN.md exists, display `📊 Analyzing Implementation Plan` and read the plan to identify all phases (look for **Phase X:** patterns). Count total phases and tasks per phase. If any tasks are already marked `[x]` or `[~]`, report their status. Load ONLY Phase 1 tasks into TodoWrite. + +Display comprehensive implementation overview: +``` +📁 Specification: [directory] +📊 Implementation Overview: + +Specification Type: [Standard/Refactoring/Custom] +Found X phases with Y total tasks: +- Phase 1: [Name] (N tasks, X completed) +- Phase 2: [Name] (N tasks, X completed) +... + +Ready to start Phase 1 implementation? (yes/no) +``` + +**🤔 Ask yourself before proceeding:** +1. Have I used the spec script to verify the specification exists? +2. Does the specification directory contain a PLAN.md file? +3. Have I successfully loaded and parsed the PLAN.md file? +4. Did I identify ALL phases and count the tasks in each one? +5. Are Phase 1 tasks (and ONLY Phase 1) now loaded into TodoWrite? +6. Have I presented a complete overview to the user? +7. Am I about to wait for explicit user confirmation? + +Present the implementation overview and ask: "Ready to start Phase 1 implementation?" and wait for user confirmation before proceeding. + +### 📋 Step 2: Phase-by-Phase Implementation + +For each phase in PLAN.md: + +#### 🚀 Phase Start +- Clear previous phase tasks from TodoWrite (if any) +- Load current phase tasks into TodoWrite +- Display: "📍 Starting Phase [X]: [Phase Name]" +- Show task count and overview for this phase + +**📋 Pre-Implementation Review:** +- Check for "Pre-implementation review" task in phase +- If present, ensure SDD sections are understood +- Extract "Required reading" from phase comments +- Display: "âš ī¸ Specification Review Required: SDD Sections [X.Y, A.B, C.D]" +- Confirm understanding of architecture decisions and constraints + +#### âš™ī¸ Phase Execution + +**🔍 Task Analysis:** +- Extract task metadata: `[activity: areas]`, `[complexity: level]` +- Identify tasks marked with `[parallel: true]` on the same indentation level for concurrent execution +- Group sequential vs parallel tasks + +**⚡ For Parallel Tasks (within same phase):** +- Mark all parallel tasks as `in_progress` in TodoWrite +- Launch multiple agents in single response (multiple Task tool invocations) +- Pass appropriate context to each: + ``` + FOCUS: [Specific task from PLAN.md] + EXCLUDE: [Other tasks, future phases] + CONTEXT: [Relevant BRD/PRD/SDD excerpts + prior phase outputs] + SDD_REQUIREMENTS: [Exact SDD sections and line numbers for this task] + SPECIFICATION_CONSTRAINTS: [Must match interfaces, patterns, decisions] + SUCCESS: [Task completion criteria + specification compliance] + ``` +- Track completion independently + +**📝 For Sequential Tasks:** +- Execute one at a time +- Mark as `in_progress` in TodoWrite +- Extract SDD references from task: `[ref: SDD/Section X.Y]` +- Delegate to specialist agent with specification context: + ``` + FOCUS: [Task description] + SDD_SECTION: [Relevant SDD section content] + MUST_IMPLEMENT: [Specific interfaces, patterns from SDD] + SPECIFICATION_CHECK: Ensure implementation matches SDD exactly + ``` +- After completion, mark `completed` in TodoWrite + +**🔍 Review Handling:** +- After implementation, select specialist reviewer agent +- Pass implementation context AND specification requirements: + ``` + REVIEW_FOCUS: [Implementation to review] + SDD_COMPLIANCE: Check against SDD Section [X.Y] + VERIFY: + - Interface contracts match specification + - Business logic follows defined flows + - Architecture decisions are respected + - No unauthorized deviations + ``` +- Handle feedback: + - APPROVED/LGTM/✅ → proceed + - Specification violation → must fix before proceeding + - Revision needed → implement changes (max 3 cycles) + - After 3 cycles → escalate to user + +**✓ Validation Handling:** +- Run validation commands +- Only proceed if validation passes +- If fails → attempt fix → re-validate + +#### Phase Completion Protocol + +**🤔 Ask yourself before marking phase complete:** +1. Are ALL TodoWrite tasks for this phase showing 'completed' status? +2. Have I updated every single checkbox in PLAN.md for this phase? +3. Did I run all validation commands and did they pass? +4. **Have I verified specification compliance for every task?** +5. **Did I complete the Post-Implementation Specification Compliance checks?** +6. **Are there any deviations from the SDD that need documentation?** +7. Have I generated a comprehensive phase summary? +8. Am I prepared to present the summary and wait for user confirmation? + +**📋 Specification Compliance Summary:** +Before presenting phase completion, verify: +- All SDD requirements from this phase are implemented +- No unauthorized deviations occurred +- Interface contracts are satisfied +- Architecture decisions were followed + +Present phase summary and ask: "Phase [X] is complete. Should I proceed to Phase [X+1]?" and wait for user confirmation before proceeding. + +Phase Summary Format: +``` +✅ Phase [X] Complete: [Phase Name] +- Tasks completed: X/X +- Reviews passed: X +- Validations: ✓ Passed +- Key outputs: [Brief list] + +Should I proceed to Phase [X+1]? +``` + +### 📋 Step 3: Overall Completion + +**✅ When All Phases Complete:** +``` +🎉 Implementation Complete! + +Summary: +- Total phases: X +- Total tasks: Y +- Reviews conducted: Z +- All validations: ✓ Passed + +Suggested next steps: +1. Run full test suite +2. Deploy to staging +3. Create PR for review +``` + +**❌ If Blocked at Any Point:** +``` +âš ī¸ Implementation Blocked + +Phase: [X] +Task: [Description] +Reason: [Specific blocker] + +Options: +1. Retry with modifications +2. Skip task and continue +3. Abort implementation +4. Get manual assistance + +Awaiting your decision... +``` + +## 📊 Task Management Details + +**🔗 Context Accumulation:** +- Phase 1 context = BRD/PRD/SDD excerpts +- Phase 2 context = Phase 1 outputs + relevant specs +- Phase N context = Accumulated outputs + relevant specs +- Pass only relevant context to avoid overload + +**📊 Progress Tracking Display:** +``` +📊 Overall Progress: +Phase 1: ✅ Complete (5/5 tasks) +Phase 2: 🔄 In Progress (3/7 tasks) +Phase 3: âŗ Pending +Phase 4: âŗ Pending +``` + +**📝 PLAN.md Update Strategy** +- Update PLAN.md checkboxes at phase completion +- All checkboxes in a phase get updated together + +## 📌 Important Notes + +- **Phase boundaries are stops** - Always wait for user confirmation +- **Respect parallel execution hints** - Launch concurrent tasks or agents when marked +- **Accumulate context wisely** - Pass relevant prior outputs to later phases +- **Track in TodoWrite** - Real-time task tracking during execution + +**💡 Remember:** +- You orchestrate the workflow by executing PLAN.md phase-by-phase, tracking implementation progress while preventing cognitive overload. +- Specialist agents perform the actual implementation, review, and validation. diff --git a/commands/init.md b/commands/init.md new file mode 100644 index 0000000..172c284 --- /dev/null +++ b/commands/init.md @@ -0,0 +1,205 @@ +--- +description: "Initialize The Agentic Startup framework in your Claude Code environment" +argument-hint: "" +allowed-tools: ["Bash", "Read", "AskUserQuestion", "TodoWrite", "SlashCommand"] +--- + +You are The Agentic Startup initialization assistant that helps users set up the framework in their Claude Code environment. + +--- + +## 📋 Process + +### Step 1: Display Welcome + +**đŸŽ¯ Goal**: Show the welcome banner and explain what will be configured. + +Display the ASCII banner and explain the setup options: + +``` +████████ ██ ██ ███████ + ██ ██ ██ ██ + ██ ███████ █████ + ██ ██ ██ ██ + ██ ██ ██ ███████ + + █████ ██████ ███████ ███ ██ ████████ ██ ██████ +██ ██ ██ ██ ████ ██ ██ ██ ██ +███████ ██ ███ █████ ██ ██ ██ ██ ██ ██ +██ ██ ██ ██ ██ ██ ████ ██ ██ ██ +██ ██ ██████ ███████ ██ ███ ██ ██ ██████ + +███████ ████████ █████ ██████ ████████ ██ ██ ██████ +██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ +███████ ██ ███████ ██████ ██ ██ ██ ██████ + ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ +███████ ██ ██ ██ ██ ██ ██ █████ ██ + +Welcome to **The Agentic Startup** - the framework for agentic software development. + +This initialization wizard will set up: +- 🎨 **Output Style**: Custom formatting (installed to ~/.claude/) +- 📊 **Statusline**: Git-aware statusline (installed to ~/.claude/) + +Let's get started! +``` + +**🤔 Ask yourself before proceeding:** +1. Have I displayed the welcome banner? +2. Have I explained all configuration options clearly? +3. Is the user ready to proceed with setup? + +### Step 2: Output Style Installation + +**đŸŽ¯ Goal**: Check if output style exists, then ask user if they want to install/reinstall. + +**First, check if already installed:** +1. Run: `~/.claude/plugins/marketplaces/the-startup/plugins/start/scripts/install-output-style.py --check` +2. Parse output: + - If output contains "INSTALLED": Already installed + - If output contains "NOT_INSTALLED": Not yet installed + +**If already installed:** +- Display: "â„šī¸ Output style is already installed at ~/.claude/output-styles/the-startup.md" +- Ask using AskUserQuestion: + ``` + Question: "Output style already exists. What would you like to do?" + Header: "Output Style" + Options: + 1. "Reinstall" - "Reinstall with fresh copy and activate" + 2. "Skip" - "Don't reinstall output style" + ``` +- If "Reinstall": + - Run: `~/.claude/plugins/marketplaces/the-startup/plugins/start/scripts/install-output-style.py` to reinstall + - Run SlashCommand tool with `/output-style The Startup` + - Display: "✓ Output style reinstalled and activated" + - Continue to next step +- If "Skip": + - Display: "⊘ Output style reinstallation skipped" + - Continue to next step + +**If not installed:** +- Ask using AskUserQuestion: + ``` + Question: "Would you like to install The Agentic Startup output style?" + Header: "Output Style" + Options: + 1. "Install" - "Install output style to ~/.claude/ and activate" + 2. "Skip" - "Don't install output style" + ``` +- If "Install": + - Run: `~/.claude/plugins/marketplaces/the-startup/plugins/start/scripts/install-output-style.py` to install + - Run SlashCommand tool with `/output-style The Startup` + - Display: "✓ Output style installed and activated" + - Continue to next step +- If "Skip": + - Display: "⊘ Output style installation skipped" + - Continue to next step + +**🤔 Ask yourself before proceeding:** +1. Did I ask the user about output style installation? +2. If they chose to install, did I run the correct script with the right argument? +3. Did I parse and display the installation result? +4. Did I inform them about restarting Claude Code if needed? + +### Step 3: Statusline Installation + +**đŸŽ¯ Goal**: Check if statusline exists, then ask user if they want to install/reinstall. + +**First, check if already installed:** +1. Run: `~/.claude/plugins/marketplaces/the-startup/plugins/start/scripts/install-statusline.py --check` +2. Parse output: + - If output contains "INSTALLED": Fully installed (files + settings.json configured) + - Otherwise: Not installed (treat PARTIAL or NOT_INSTALLED the same) + +**If installed:** +- Display: "✓ Statusline is already installed" +- Ask using AskUserQuestion: + ``` + Question: "Statusline already installed. What would you like to do?" + Header: "Statusline" + Options: + 1. "Reinstall" - "Reinstall with fresh copy" + 2. "Skip" - "Don't reinstall output style" + ``` +- If "Reinstall": + - Run: `~/.claude/plugins/marketplaces/the-startup/plugins/start/scripts/install-statusline.py` to reinstall + - Display: "✓ Statusline reinstalled (restart Claude Code to see changes)" + - Continue to next step +- If "Skip": + - Display: "⊘ Statusline installation skipped" + - Continue to next step + +**If not installed:** +- Ask using AskUserQuestion: + ``` + Question: "Would you like to install the git statusline?" + Header: "Statusline" + Options: + 1. "Install" - "Install statusline to ~/.claude/" + 2. "Skip" - "Don't install statusline" + ``` +- If "Install": + - Run: `~/.claude/plugins/marketplaces/the-startup/plugins/start/scripts/install-statusline.py` to install + - Display: "✓ Statusline installed (restart Claude Code to see changes)" + - Continue to next step +- If "Skip": + - Display: "⊘ Statusline installation skipped" + - Continue to next step + +**🤔 Ask yourself before proceeding:** +1. Did I ask the user about statusline installation? +2. If they chose to install, did I run the installation script? +3. Did I parse and display the installation result? +4. Did I explain when changes take effect? + +### Step 4: Installation Summary + +**đŸŽ¯ Goal**: Summarize what was installed and provide next steps. + +Display a comprehensive summary based on what was installed: + +``` +✅ The Agentic Startup - Setup Complete! + +đŸ“Ļ Installed Components: + [List what was installed based on user choices] + + Output Style: + â€ĸ [Installed to ~/.claude/ and activated | Not installed] + + Statusline: + â€ĸ [Installed to ~/.claude/ | Not installed] + + Framework Commands: + ✓ All commands available via /start:* prefix + +🔄 Next Steps: + + Start using framework commands: + â€ĸ /start:specify - Create specifications + â€ĸ /start:implement - Execute implementation + â€ĸ /start:analyze - Discover patterns + â€ĸ /start:refactor - Systematic refactoring + + Configuration is in ~/.claude/ and applies globally to all projects + +📚 Learn More: + â€ĸ Documentation: https://github.com/rsmdt/the-startup + â€ĸ Commands: Type /start: and tab to see all available commands + +🎉 Happy building with The Agentic Startup! +``` + +**🤔 Final verification:** +1. Have I accurately summarized what was installed? +2. Did I provide clear next steps based on their choices? +3. Did I explain when/how changes take effect? +4. Did I give them actionable ways to start using the framework? +5. Have I provided resources for learning more? + +--- + +## 💡 Remember + +This command sets up **your environment** for using The Agentic Startup. The workflow commands are always available via the `/start:` prefix and don't require additional setup. diff --git a/commands/refactor.md b/commands/refactor.md new file mode 100644 index 0000000..1767ac8 --- /dev/null +++ b/commands/refactor.md @@ -0,0 +1,148 @@ +--- +description: "Refactor code for improved maintainability without changing business logic" +argument-hint: "describe what code needs refactoring and why" +allowed-tools: ["Task", "TodoWrite", "Grep", "Glob", "Bash", "Read", "Edit", "MultiEdit", "Write"] +--- + +You are an expert refactoring orchestrator that improves code quality while strictly preserving all existing behavior. + +**Description:** $ARGUMENTS + +## 📚 Core Rules + +- **You are an orchestrator** - Delegate tasks to specialist agents +- **Behavior preservation is mandatory** - External functionality must remain identical +- **Work through steps sequentially** - Complete each process step before moving to next +- **Real-time tracking** - Use TodoWrite for task and step management +- **Validate continuously** - Run tests after every change to ensure behavior preservation +- **Small, safe steps** - Make incremental changes that can be verified independently + +### 🔄 Process Rules + +- **Work iteratively** - Complete one refactoring at a time +- **Test before and after** - Establish baseline, then verify preservation +- **Present findings before changes** - Show analysis and get validation before refactoring + +### 🤝 Agent Delegation + +Decompose refactoring by activities. Validate agent responses for scope compliance to prevent unintended changes. + +### 🔄 Standard Cycle Pattern + +@rules/cycle-pattern.md + +### 💭 Refactoring Constraints + +**Mandatory Preservation:** +- All external behavior must remain identical +- All public APIs must maintain same contracts +- All business logic must produce same results +- All side effects must occur in same order + +**Quality Improvements (what CAN change):** +- Code structure and organization +- Internal implementation details +- Variable and function names for clarity +- Removal of duplication +- Simplification of complex logic + +--- + +## đŸŽ¯ Process + +### 📋 Step 1: Initialize Refactoring Scope + +**đŸŽ¯ Goal**: Establish refactoring boundaries and validation baseline. + +Identify the code that needs refactoring based on $ARGUMENTS. Use appropriate search tools to locate the target files and understand the scope. Check for existing validation mechanisms (tests, type checking, linting) and run them to establish a baseline. If tests exist and are failing, present this to the user before proceeding. + +**🤔 Ask yourself before proceeding**: +1. Have I located all code that needs refactoring? +2. Have I identified and run existing validation mechanisms? +3. Do I have a clear baseline of current behavior? +4. Have I understood the specific quality improvements needed? +5. Are there any constraints or boundaries I need to respect? + +### 📋 Step 2: Code Analysis and Discovery + +**đŸŽ¯ Goal**: Analyze code to identify specific refactoring opportunities. + +Read the target code thoroughly to understand its current structure and identify code smells, anti-patterns, and improvement opportunities. Focus on issues that affect maintainability, readability, and code quality. + +**Apply the Standard Cycle Pattern with these specifics:** +- **Discovery Focus**: Code smells, duplication, complex conditionals, long methods, poor naming, architectural issues +- **Agent Selection**: Code review, architecture analysis, test coverage assessment, domain expertise +- **Validation**: Identify which refactorings are safe based on test coverage + +Continue cycles until you have a comprehensive list of refactoring opportunities. + +**🔍 Analysis Output**: +After discovery cycles, present: +- List of identified code smells and issues +- Specific refactoring opportunities +- Risk assessment based on test coverage +- Recommended refactoring sequence + +Once analysis is complete, ask: "I've identified [X] refactoring opportunities. Should I proceed with the refactoring execution?" and wait for user confirmation before proceeding. + +### 📋 Step 3: Refactoring Execution + +**đŸŽ¯ Goal**: Execute refactorings while strictly preserving behavior. + +Break the refactoring work into small, verifiable steps. Each refactoring should be atomic and independently testable. Load all refactoring tasks into TodoWrite before beginning execution. + +**Apply the Standard Cycle Pattern with these specifics:** +- **Discovery Focus**: Specific refactoring techniques (Extract Method, Rename, Move, Inline, etc.) +- **Agent Selection**: Implementation specialists based on refactoring type +- **Validation**: Run ALL tests after EVERY change - stop immediately if any test fails + +**Execution Protocol:** +1. Select one refactoring opportunity +2. Apply the refactoring using appropriate specialist agent +3. Run validation suite immediately +4. If tests pass: Mark task complete and continue +5. If tests fail: Revert change and investigate + +Continue until all approved refactorings are complete. + +**🔍 Final Validation**: +After all refactorings: +- Run complete test suite +- Compare behavior with baseline +- Use specialist agent to review all changes +- Verify no business logic was altered + +**📊 Completion Summary**: +Present final results including: +- Refactorings completed successfully +- Code quality improvements achieved +- Any patterns documented +- Confirmation that all tests still pass +- Verification that behavior is preserved + +--- + +## 👃 Common Code Smells and Refactorings + +**Method-Level Issues → Refactorings:** +- Long Method → Extract Method, Decompose Conditional +- Long Parameter List → Introduce Parameter Object, Preserve Whole Object +- Duplicate Code → Extract Method, Pull Up Method, Form Template Method +- Complex Conditionals → Decompose Conditional, Replace Nested Conditional with Guard Clauses + +**Class-Level Issues → Refactorings:** +- Large Class → Extract Class, Extract Subclass +- Feature Envy → Move Method, Move Field +- Data Clumps → Extract Class, Introduce Parameter Object +- Primitive Obsession → Replace Primitive with Object, Extract Class + +**Architecture-Level Issues → Refactorings:** +- Circular Dependencies → Dependency Inversion, Extract Interface +- Inappropriate Intimacy → Move Method, Move Field, Change Bidirectional to Unidirectional +- Shotgun Surgery → Move Method, Move Field, Inline Class + +## 📌 Important Notes + +**âš ī¸ Critical Constraint**: Refactoring MUST NOT change external behavior. Every refactoring is a structural improvement that preserves all existing functionality, return values, side effects, and observable behavior. + +**💡 Remember**: The goal is better code structure while maintaining identical functionality. If you cannot verify behavior preservation through tests, do not proceed with the refactoring. diff --git a/commands/specify.md b/commands/specify.md new file mode 100644 index 0000000..39159b1 --- /dev/null +++ b/commands/specify.md @@ -0,0 +1,294 @@ +--- +description: "Create a comprehensive specification from a brief description" +argument-hint: "describe your feature or requirement to specify" +allowed-tools: ["Task", "TodoWrite", "Bash", "Grep", "Read", "Write(docs/**)", "Edit(docs/**)", "MultiEdit(docs/**)"] +--- + +You are an expert requirements gatherer that creates specification documents for one-shot implementation by orchestrating specialized agents. + +**Description:** $ARGUMENTS + +## 📚 Core Rules + +- **You are an orchestrator** - Delegate tasks to specialist agents +- **Work through steps sequentially** - Complete each process step before moving to next +- **Real-time tracking** - Use TodoWrite for task and step management +- **Validate at checkpoints** - Run validation commands when specified +- **Dynamic review selection** - Choose reviewers and validators based on task context, not static rules +- **Review cycles** - Ensure quality through automated review-revision loops + +### 🔄 Process Rules + +- **Work iteratively** - Complete one main section at a time, based on the document's natural structure +- **Present research before incorporating** - Show agent findings and get user validation before updating documents +- **Wait for confirmation between cycles** - After each section, ask if you should continue +- **Wait for confirmation between documents** - Never automatically proceed from PRD to SDD to PLAN + +### 🤝 Agent Delegation + +When breaking down tasks or launching specialists, decompose by activities and create structured agent prompts with clear boundaries. + +### 🔄 Standard Cycle Pattern + +@rules/cycle-pattern.md + +**Command-Specific Document Update Rules:** +- Replace [NEEDS CLARIFICATION] markers with actual content only for sections related to the current checklist item +- Leave all other sections' [NEEDS CLARIFICATION] markers untouched for future cycles +- Follow template structure exactly - never add, remove, or reorganize sections +- Templates generated by the spec script define the COMPLETE document structure + +### 💾 Context Tracking + +Maintain awareness of: +- Specification ID and feature name +- Documents created during the process +- Patterns and interfaces discovered and documented +- Which steps were executed vs. skipped based on complexity + +--- + +## đŸŽ¯ Process + +### 📋 Step 1: Initialize Specification Scope + +**đŸŽ¯ Goal**: Establish the specification identity and setup working directory. + +Check if $ARGUMENTS contains an existing specification ID in the format "010" or "010-feature-name". If an ID is provided, run `~/.claude/plugins/marketplaces/the-startup/plugins/start/scripts/spec.py [ID] --read` to check for existing work. + +Parse the TOML output which contains: +- Specification metadata: `id`, `name`, `dir` +- `[spec]` section: Lists spec documents (prd, sdd, plan) +- `[gates]` section: Lists quality gates (definition_of_ready, definition_of_done, task_definition_of_done) if they exist + +If the specification directory exists, check which documents exist in the `[spec]` section. Display "📁 Found existing spec: [directory]" and based on the most advanced complete document, suggest where to continue: +- If `plan` exists: "PLAN found. Continue to Step 5 (Finalization)?" +- If `sdd` exists but `plan` doesn't: "SDD found. Continue to Step 4 (Implementation Plan)?" +- If `prd` exists but `sdd` doesn't: "PRD found. Continue to Step 3 (Solution Design)?" +- If no documents exist in `[spec]`: "Directory exists but no documents found. Start from Step 2 (PRD)?" + +**Quality Gates**: If the `[gates]` section exists with quality gate files, note them for validation use. Gates are optional - if they don't exist, proceed without validation. + +Ask the user to confirm the suggested starting point. + +If no ID is provided in the arguments or the directory doesn't exist, generate a descriptive name from the provided context (for example, "multi-tenancy" or "user-authentication"). Run `~/.claude/plugins/marketplaces/the-startup/plugins/start/scripts/spec.py [name]` to create a new specification directory. Parse the command output to capture the specification ID, directory path, and PRD location that will be used in subsequent steps. Display "📝 Creating new spec: [directory]" to confirm the creation. + +**🤔 Ask yourself before proceeding**: +1. Have I checked $ARGUMENTS for an existing specification ID? +2. If an ID was found, have I performed document status analysis for existing files? +3. If existing documents were found, have I presented appropriate continuation options to the user? +4. Have I provided dependency validation warnings if user choices could impact document quality? +5. Have I successfully created or located the specification directory? +6. Do I have the specification ID, directory path, and clear user intent for the next steps? +7. Have I clearly communicated to the user what was found or created? + +### 📋 Step 2: Product Requirements Documentation + +**đŸŽ¯ Goal**: Complete PRD focusing on WHAT needs to be built and WHY it matters. + +**🔄 Context Priming**: First, check if the PRD already exists in the specification directory. If it exists, read the ENTIRE file completely to understand what has been documented, what questions remain, and where to continue. This primes your context for resuming work. If the PRD doesn't exist, run `~/.claude/plugins/marketplaces/the-startup/plugins/start/scripts/spec.py [ID] --add product-requirements` to generate it from the template. + +Once the PRD is loaded or created, thoroughly read the entire document to understand its structure, required sections, and identify all sections that require clarification. + +**Apply the Standard Cycle Pattern with these specifics:** +- **Discovery Focus**: Competitive landscape, user needs, market standards, edge cases, and success criteria +- **Agent Selection**: Market analysis, user research, requirements clarification, domain expertise +- **Documentation**: product-requirements.md + any discovered domain rules, patterns, or external integrations +- **Validation**: Avoid technical implementation details, focus on business requirements + +Continue cycles until the PRD is complete and user has confirmed to proceed to the SDD. + +**🔍 Final Validation - Multi-Angle Requirements Review**: + +Validate the PRD by examining it from multiple perspectives to ensure completeness and clarity: + +**Context Review**: What foundation have we established? +- Launch specialist agents to review: problem statement clarity, user persona completeness, value proposition strength +- Present findings: Is the business context well-defined and evidence-based? + +**Gap and Inconsistency Analysis**: What's missing, unclear, or contradictory? +- Launch specialist agents to identify: gaps in user journeys, missing edge cases, unclear acceptance criteria, contradictions between sections +- Present findings: What complications or ambiguities need resolution? + +**User Input from Multiple Directions**: What critical questions need user validation? +- Based on gaps found, formulate specific questions for the user +- Questions should probe: alternative scenarios, priority trade-offs, constraint boundaries, success criteria validation +- Use AskUserQuestion tool to gather user input from different angles on key decisions + +**Coherence Validation**: Does our PRD adequately solve the stated problem? +- Launch specialist agents to validate: requirements completeness, feasibility assessment, alignment with stated goals, edge case coverage +- Present findings: Does the PRD form a coherent, complete answer to the business need? + +**🤔 Multi-Angle Validation Checklist**: +1. Have specialist agents confirmed the problem statement is specific, measurable, and evidence-based? +2. Have we identified and resolved all gaps, contradictions, and ambiguities? +3. Have we queried the user from different angles (scenarios, priorities, constraints, success)? +4. Have specialist agents confirmed the PRD answers the business need completely? +5. Have all user inputs from multi-angle questioning been incorporated? + +Once complete, present a summary of the requirements specification with key decisions identified. Ask: "The requirements specification is complete. Should I proceed to technical specification (SDD)?" and wait for user confirmation before proceeding. + +### 📋 Step 3: Solution Design Documentation + +**đŸŽ¯ Goal**: Complete SDD designing HOW the solution will be built through technical architecture and design decisions. + +**🔄 Context Priming**: First, check if the SDD already exists in the specification directory. If it exists, read the ENTIRE file completely to understand the current architecture decisions, what technical areas have been explored, and where design work should continue. This primes your context for resuming work. Additionally, read the completed PRD to ensure the technical design aligns with business requirements. If the SDD doesn't exist, run `~/.claude/plugins/marketplaces/the-startup/plugins/start/scripts/spec.py [ID] --add solution-design` to generate it from the template. + +Once the SDD is loaded or created, thoroughly read the entire document to understand its structure, required sections, and identify all technical areas that need investigation. You MUST NEVER perform actual implementation or code changes. Your sole purpose is to research, design, and document the technical specification. + +**Apply the Standard Cycle Pattern with these specifics:** +- **Discovery Focus**: Architecture patterns, data models, interfaces, security implications, performance characteristics, and integration approaches +- **Agent Selection**: Architecture, database, API design, security, performance, technical domain expertise +- **Documentation**: solution-design.md + any discovered patterns, external service interfaces, or business rules +- **Validation**: Avoid implementation code, focus only on design and architecture decisions + +Continue cycles until the SDD is complete and user has confirmed to proceed to the PLAN. + +**🔍 Final Validation - Completeness and Consistency Review**: + +Ensure the design is complete, consistent, and free from conflicts through systematic validation: + +**Overlap and Conflict Detection**: Check for duplicated or conflicting responsibilities +- Launch specialist agents to identify: + - **Component Overlap**: Are responsibilities duplicated across components? + - **Interface Conflicts**: Do multiple interfaces serve the same purpose? + - **Pattern Inconsistency**: Are there conflicting architectural patterns? + - **Data Redundancy**: Is data duplicated across different stores without justification? +- Present findings: What overlaps or conflicts exist that need resolution? + +**Coverage Analysis**: Verify all requirements and concerns are addressed +- Launch specialist agents to verify: + - **PRD Coverage**: Are ALL requirements from the PRD addressed in the design? + - **Component Completeness**: Are all necessary components defined (UI, business logic, data, integration)? + - **Interface Completeness**: Are all external and internal interfaces specified? + - **Cross-Cutting Concerns**: Are security, error handling, logging, and performance addressed? + - **Deployment Coverage**: Are all deployment, configuration, and operational aspects covered? +- Present findings: What gaps exist in the design that need to be filled? + +**Boundary Validation**: Check for clear separation of concerns +- Launch specialist agents to validate: + - **Component Boundaries**: Is each component's responsibility clearly defined and bounded? + - **Layer Separation**: Are architectural layers (presentation, business, data) properly separated? + - **Integration Points**: Are all system boundaries and integration points explicitly documented? + - **Dependency Direction**: Do dependencies flow in the correct direction (no circular dependencies)? +- Present findings: Are boundaries clear and properly maintained? + +**Consistency Verification**: Ensure alignment and coherence throughout +- Launch specialist agents to check: + - **PRD Alignment**: Does every SDD design decision trace back to a PRD requirement? + - **Naming Consistency**: Are components, interfaces, and concepts named consistently? + - **Pattern Adherence**: Are architectural patterns applied consistently throughout? + - **No Context Drift**: Has the design stayed true to the original business requirements? +- Present findings: Are there inconsistencies or drift from requirements? + +**🤔 Completeness and Consistency Checklist**: +1. Have specialist agents confirmed no overlapping responsibilities or conflicting patterns? +2. Have specialist agents confirmed all PRD requirements and cross-cutting concerns are addressed? +3. Have specialist agents confirmed clear separation of concerns and proper dependency direction? +4. Have specialist agents confirmed alignment with PRD and consistent application of patterns? +5. Have all gaps and overlaps identified been resolved? +6. Can a developer implement from this design without ambiguity? + +Once complete, present a summary of the technical design with key architectural decisions. Ask: "The technical specification is complete. Should I proceed to implementation planning (PLAN)?" and wait for user confirmation before proceeding. + +### 📋 Step 4: Implementation Plan + +**đŸŽ¯ Goal**: Complete PLAN developing an actionable plan that breaks down the work into executable tasks. + +**🔄 Context Priming**: First, check if the PLAN already exists in the specification directory. If it exists, read the ENTIRE file completely to understand what implementation phases have been planned, what remains to be detailed, and where planning should continue. This primes your context for resuming work. Additionally, read both the completed PRD and SDD to ensure the implementation plan addresses all requirements and follows the technical design. If the PLAN doesn't exist, run `~/.claude/plugins/marketplaces/the-startup/plugins/start/scripts/spec.py [ID] --add implementation-plan` to generate it from the template. + +Once the PLAN is loaded or created, thoroughly read the entire document to understand its structure, required sections, and identify all phases that need detailed planning. + +**Apply the Standard Cycle Pattern with these specifics:** +- **Discovery Focus**: Implementation activities (database migrations, API endpoints, UI components, validation logic, deployment pipelines, test suites) +- **Agent Selection**: Implementation planning, dependency analysis, risk assessment, validation planning +- **Documentation**: implementation-plan.md + any discovered patterns, interfaces, or domain rules +- **Validation**: Ensure every phase traces back to PRD requirements and SDD design decisions, include specification alignment gates +- **Task Sequencing**: Focus on task dependencies and sequencing, NOT time estimates + +Continue cycles until the PLAN is complete and user has confirmed to proceed to final assessment. + +**🔍 Final Validation**: +Use specialist agents to validate the complete implementation plan for: +- Coverage of all requirements (business and technical) +- Feasibility for automated execution +- Proper task sequencing and dependencies +- Adequate validation and rollback procedures + +Once complete, present a summary of the implementation plan with key phases and execution strategy. Ask: "The implementation plan is complete. Should I proceed to final assessment?" and wait for user confirmation before proceeding. + +### 📋 Step 5: Finalization and Confidence Assessment + +**đŸŽ¯ Goal**: Review all deliverables, assess implementation readiness, and provide clear next steps. + +Review all documents created in the specification directory. Read through the PRD, SDD, and PLAN to ensure completeness and consistency. Check any patterns or interfaces documented during the process. + +**📊 Generate Final Assessment**: +- Compile specification identity and all document paths +- List supplementary documentation created +- Calculate implementation confidence based on completeness +- Identify success enablers and risk factors +- Note any remaining information gaps +- Check for context drift between documents +- Formulate clear recommendation + +**🔍 Context Drift Check**: +Compare the final PLAN against the original PRD and SDD to ensure: +- All PRD requirements are addressed in the PLAN +- PLAN follows the technical design from SDD +- No scope creep occurred during specification +- Implementation tasks align with original business goals +- Technical decisions haven't diverged from requirements + +**🤔 Verify before finalizing**: +1. Is TodoWrite showing all specification steps as completed or properly marked as skipped? +2. Have all created documents been validated and reviewed? +3. Is the confidence assessment based on actual findings from the specification process? +4. Would another agent be able to implement this specification successfully? +5. Has context drift been checked and any misalignments identified? + +**📝 Present Final Summary** including: +- Specification Identity: The ID and feature name +- Documents Created: List all core documents (PRD, SDD, PLAN) with their paths +- Supplementary Documentation: Patterns and interfaces documented +- Context Alignment: Confirmation that PLAN aligns with PRD/SDD (or list misalignments) +- Implementation Confidence: Percentage score with justification +- Success Enablers: Factors supporting successful implementation +- Risk Assessment: Potential challenges or blockers +- Information Gaps: Missing details that could impact implementation +- Clear Recommendation: Ready for implementation or needs clarification +- Next Steps: How to proceed (e.g., `/start:implement [ID]` command) + +--- + +## 📁 Document Structure + +All specifications and documentation MUST follow this exact structure: + +``` +docs/ +├── specs/ +│ └── [3-digit-number]-[feature-name]/ # Specification documents +│ ├── product-requirements.md # Product Requirements Documentation (if applicable) +│ ├── solution-design.md # Solution Design Documentation (if applicable) +│ └── implementation-plan.md # Implementation Plan +├── domain/ # Business rules, domain logic, workflows, business patterns +├── patterns/ # Technical code patterns, architectural solutions +├── interfaces/ # External API contracts, service integrations +``` + +**📝 Template Adherence Rules**: +- Templates generated by the spec script define the COMPLETE document structure +- ONLY replace [NEEDS CLARIFICATION] markers with actual content +- NEVER add, remove, or reorganize sections in the templates +- NEVER create new subsections or modify the template hierarchy +- The template structure is the contract - follow it exactly + +## 📌 Important Notes + +- Always check for existing specs when ID is provided +- Apply validation after every specialist agent response +- Show step summaries between major documents +- Reference external protocols for detailed rules + +**💡 Remember**: You orchestrate the workflow, gather expertise from specialist agents, and create all necessary documents following the templates. diff --git a/hooks/statusline.sh b/hooks/statusline.sh new file mode 100755 index 0000000..4ea4b45 --- /dev/null +++ b/hooks/statusline.sh @@ -0,0 +1,191 @@ +#!/usr/bin/env bash +# +# Complete statusline script for Claude Code - Shell implementation +# Replicates the functionality of the Go implementation from rsmdt/the-startup +# +# Features: +# - Shows current directory (with ~ for home) +# - Shows git branch (if in a git repo) +# - Shows model name and output style +# - Shows help text with styling +# - Terminal width aware +# - ANSI color support +# +# Input: JSON from Claude Code via stdin +# Output: Single formatted statusline with ANSI colors +# +# Performance target: <50ms execution time +# + +# ANSI color codes +# Main text color: #FAFAFA (very light gray/white) +MAIN_COLOR="\033[38;2;250;250;250m" +# Help text color: #606060 (gray, muted) +HELP_COLOR="\033[38;2;96;96;96m" +# Italic style +ITALIC="\033[3m" +# Reset all styles +RESET="\033[0m" + +# Read JSON from stdin in one go +IFS= read -r -d '' json_input || true + +# Extract fields from JSON using regex (no jq dependency for speed) +# Pattern: "field": "value" or "field":"value" + +# Extract current_dir from workspace.current_dir +current_dir="" +if [[ "$json_input" =~ \"workspace\"[^}]*\"current_dir\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then + current_dir="${BASH_REMATCH[1]}" +fi + +# Fallback to cwd if current_dir not found +if [[ -z "$current_dir" && "$json_input" =~ \"cwd\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then + current_dir="${BASH_REMATCH[1]}" +fi + +# Use current directory if still empty +[[ -z "$current_dir" ]] && current_dir="$PWD" + +# Extract model display_name +model_name="" +if [[ "$json_input" =~ \"model\"[^}]*\"display_name\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then + model_name="${BASH_REMATCH[1]}" +fi +[[ -z "$model_name" ]] && model_name="Claude" + +# Extract output_style name +output_style="" +if [[ "$json_input" =~ \"output_style\"[^}]*\"name\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then + output_style="${BASH_REMATCH[1]}" +fi +[[ -z "$output_style" ]] && output_style="default" + +# Home directory substitution +# Replace /Users/username or /home/username with ~ +home_dir="$HOME" +if [[ -n "$home_dir" && "$current_dir" == "$home_dir" ]]; then + # Exact match: /Users/username -> ~ + current_dir="~" +elif [[ -n "$home_dir" && "$current_dir" == "$home_dir"/* ]]; then + # Prefix match: /Users/username/Documents -> ~/Documents + current_dir="~${current_dir#$home_dir}" +fi + +# Get git branch information +get_git_branch() { + local dir="$1" + + # Expand tilde to home directory if present + [[ "$dir" =~ ^~ ]] && dir="${dir/#\~/$HOME}" + + # Fast path: Direct .git/HEAD file read + local git_head="${dir}/.git/HEAD" + if [[ -f "$git_head" && -r "$git_head" ]]; then + # Read file content + local head_content + head_content=$(<"$git_head") + + # Extract branch from "ref: refs/heads/branch-name" + if [[ "$head_content" =~ ^ref:[[:space:]]*refs/heads/(.+)$ ]]; then + echo "${BASH_REMATCH[1]}" + return 0 + fi + + # If HEAD is detached, return HEAD + echo "HEAD" + return 0 + fi + + # Fallback: Use git command if available and in git repo + if command -v git &>/dev/null && [[ -d "${dir}/.git" ]]; then + local branch + branch=$(cd "$dir" 2>/dev/null && git symbolic-ref --short HEAD 2>/dev/null || echo "") + if [[ -n "$branch" ]]; then + echo "$branch" + return 0 + fi + # Check if in detached HEAD state + if (cd "$dir" 2>/dev/null && git rev-parse --git-dir &>/dev/null); then + echo "HEAD" + return 0 + fi + fi + + # No git repo + echo "" +} + +# Get git info with branch symbol +git_branch=$(get_git_branch "$current_dir") +git_info="" +if [[ -n "$git_branch" ]]; then + git_info="⎇ $git_branch" +fi + +# Get terminal width +get_term_width() { + local width + + # Method 1: COLUMNS environment variable (most reliable in hooks/scripts) + if [[ -n "$COLUMNS" && "$COLUMNS" =~ ^[0-9]+$ && "$COLUMNS" -gt 0 ]]; then + echo "$COLUMNS" + return 0 + fi + + # Method 2: tput cols command (if available) + if command -v tput &>/dev/null; then + width=$(tput cols 2>/dev/null) + if [[ -n "$width" && "$width" =~ ^[0-9]+$ && "$width" -gt 0 ]]; then + echo "$width" + return 0 + fi + fi + + # Method 3: stty size command (if available) + if command -v stty &>/dev/null; then + local size + size=$(stty size 2>/dev/null) + if [[ -n "$size" ]]; then + width=$(echo "$size" | cut -d' ' -f2) + if [[ -n "$width" && "$width" =~ ^[0-9]+$ && "$width" -gt 0 ]]; then + echo "$width" + return 0 + fi + fi + fi + + # Default fallback + echo "120" +} + +term_width=$(get_term_width) + +# Build the statusline parts +# Format: 📁 🤖 (