Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 17:51:59 +08:00
commit 38e80921c8
89 changed files with 20480 additions and 0 deletions

View File

@@ -0,0 +1,484 @@
---
name: plugin-slash-command
description: Generate new Navigator slash commands following project conventions. Use when user says "add slash command", "create command", "new /nav command", or "add /nav:[name] command".
allowed-tools: Read, Write, Edit, Grep, Glob, Bash
version: 1.0.0
---
# Navigator Slash Command Generator
Generate new slash commands for the Navigator plugin following established conventions and patterns.
## When to Invoke
Auto-invoke when user says:
- "Add a slash command for..."
- "Create a new /nav:[name] command"
- "Generate slash command..."
- "Add /nav:[feature] command"
- "New Navigator command for..."
## What This Does
1. Asks for command details (name, purpose, complexity)
2. Analyzes existing commands for pattern matching
3. Generates command markdown file with proper structure
4. Validates YAML frontmatter and formatting
5. Shows usage example
## Execution Steps
### Step 1: Gather Command Requirements
Ask user:
- **Command name** (kebab-case, without /nav: prefix)
- Example: "marker", "compact", "update-doc"
- **Command purpose** (one sentence description)
- Example: "Create context markers to save conversation state"
- **Command complexity**:
- Simple: Single action, minimal steps (e.g., marker)
- Medium: Multiple steps, some logic (e.g., compact)
- Complex: Multi-phase execution, integrations (e.g., init, start)
- **User-facing or internal**?
- User-facing: Part of standard Navigator workflow
- Internal: For plugin development/maintenance
### Step 2: Analyze Similar Commands
Use Task agent to find similar commands:
```
"Find existing Navigator commands similar to [purpose]:
- Commands in commands/*.md
- Similar complexity level
- Common structure patterns
- Return 2-3 best examples"
```
**What to extract from examples**:
- Section structure (What This Does, When to Use, etc.)
- Tone and style (conversational, 2nd person)
- Emoji usage patterns
- Example format
- Troubleshooting patterns
### Step 3: Design Command Structure
Based on complexity level:
**Simple commands**:
```
- YAML frontmatter (description)
- Title
- What This Does (2-3 sentences)
- Usage (basic syntax + examples)
- When to Use (2-3 scenarios)
- Expected Output
- Troubleshooting (2-3 common issues)
- Closing statement
```
**Medium commands**:
```
- YAML frontmatter
- Title + overview
- What This Does (detailed explanation)
- When to Use (5-6 scenarios with examples)
- Usage / Execution Steps
- Output Format
- Integration notes (if applicable)
- Troubleshooting (4-5 issues)
- Best Practices
- Closing statement
```
**Complex commands**:
```
- YAML frontmatter
- Title + comprehensive overview
- What This Does (with comparisons)
- Execution Plan (multi-step)
- Pre-flight checks
- Step-by-step implementation
- Validation steps
- Integration with PM tools (if applicable)
- Success criteria
- Troubleshooting (comprehensive)
- Edge cases
- Performance notes
- Closing statement
```
### Step 4: Generate Command File
**Use predefined function**: `functions/command_generator.py`
```python
# Generates command markdown following Navigator conventions
generate_command(
name="[command-name]",
description="[one-line purpose]",
complexity="simple|medium|complex",
sections={
"what_this_does": "...",
"when_to_use": [...],
"usage": "...",
"execution_steps": [...],
"troubleshooting": [...]
}
)
```
**File location**: `commands/[command-name].md`
**Structure**:
1. YAML frontmatter with description
2. Title (# Command Name - Navigator Context)
3. Overview paragraph (what user is doing)
4. Content sections (based on complexity)
5. Closing statement (emoji + key takeaway)
### Step 5: Validate Generated Command
**Use predefined function**: `functions/command_validator.py`
Checks:
- [ ] YAML frontmatter is valid
- [ ] Description field exists and is clear
- [ ] Markdown structure is correct
- [ ] All sections have content
- [ ] Code blocks are properly formatted
- [ ] Examples are realistic
- [ ] Troubleshooting addresses real issues
- [ ] Tone matches Navigator style (conversational, helpful)
- [ ] Emoji usage is consistent with other commands
- [ ] File name matches command name (kebab-case)
### Step 6: Show Usage Example
Display:
```
✅ Slash Command Created: /nav:[command-name]
File: commands/[command-name].md
Lines: [count]
Complexity: [simple/medium/complex]
Try it:
/nav:[command-name]
What it does:
[brief description]
Next steps:
1. Test the command manually
2. Update plugin documentation if public-facing
3. Add to CLAUDE.md command list if needed
```
---
## Example Workflows
### Example 1: Simple Command
**User**: "Add a slash command for showing Navigator version"
**Execution**:
1. **Gather requirements**:
```
Name: version
Purpose: Display current Navigator plugin version
Complexity: Simple
Type: User-facing
```
2. **Analyze similar** (via Task agent):
```
Found similar: marker.md (simple, informational)
Pattern: Short description → Usage → When to use → Output
```
3. **Design structure**:
```
- Frontmatter
- Title: "Navigator Version Info"
- What This Does: 1 paragraph
- Usage: Basic syntax
- When to Use: 2-3 scenarios
- Output Format: Example
- Closing statement
```
4. **Generate**: `commands/version.md`
```markdown
---
description: Display Navigator plugin version and system info
---
# Navigator Version Info
Check which version of Navigator you're running.
## What This Does
Displays the current Navigator plugin version, Claude Code version, and system configuration.
## Usage
```bash
/nav:version
```
## When to Use
**Reporting issues**:
- Include version info in bug reports
- Help maintainers reproduce issues
**Checking updates**:
- See if you're on latest version
- Compare with marketplace version
**System diagnostics**:
- Verify plugin installed correctly
- Check configuration loaded
## Output Format
```
Navigator Plugin
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Version: 2.2.0
Installed: /Users/you/.claude/plugins/jitd
Config: .agent/.nav-config.json
System:
- Claude Code: 1.5.0
- Project: /Users/you/project
- Platform: darwin
```
**Keep your Navigator up to date for latest features** 🚀
```
5. **Validate**: ✅ All checks pass
6. **Show usage**:
```
✅ Slash Command Created: /nav:version
File: commands/version.md
Lines: 45
Complexity: Simple
Try it: /nav:version
```
### Example 2: Medium Command
**User**: "Create a command for archiving old task documentation"
**Execution**:
1. **Gather requirements**:
```
Name: archive-tasks
Purpose: Move completed tasks to archive directory
Complexity: Medium (file operations, validation)
Type: User-facing
```
2. **Analyze similar**:
```
Found: markers.md (file management, user selection)
Found: compact.md (multi-step process)
Pattern: Overview → Execution Plan → Steps → Validation
```
3. **Design structure**:
```
- Frontmatter
- Title + overview
- What This Does (comparison with manual approach)
- When to Use (5 scenarios)
- Execution Plan (Step 1-4)
- Output Format
- Troubleshooting (4 issues)
- Best Practices
- Closing
```
4. **Generate**: `commands/archive-tasks.md` (full content)
5. **Validate**: ✅ All checks pass
6. **Show usage**: Command ready to use
---
## Output Format
**After generating command, show**:
```
✅ Slash Command Created: /nav:[name]
Structure:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📄 commands/[name].md
Sections:
✅ YAML frontmatter
✅ Title and overview
✅ What This Does
✅ When to Use ([N] scenarios)
✅ Usage / Execution Plan
✅ [Additional sections based on complexity]
✅ Troubleshooting
✅ Closing statement
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Command: /nav:[name]
Purpose: [brief description]
Lines: [count]
Test it:
/nav:[name]
Documentation:
- Add to README.md if user-facing
- Update CLAUDE.md command list
- Add to plugin.json if needed
```
---
## Best Practices
### Command Naming
- Use kebab-case (marker, update-doc, archive-tasks)
- Be specific but concise (not too generic, not too verbose)
- Match feature purpose (nav:compact for compacting)
- Avoid abbreviations unless very common
### Description Writing
- One sentence, clear purpose
- Action-oriented ("Create", "Display", "Update")
- Mention key benefit or what it does
- Under 100 characters
### Content Structure
- Start with user perspective ("You are...")
- Use 2nd person ("your task", "you can")
- Include realistic examples
- Show expected output
- Address common issues in troubleshooting
### Tone and Style
- Conversational and helpful
- Use emojis for visual markers (✅❌📖🚀)
- Bold key terms and actions
- Code blocks for all commands/output
- Bullet lists for readability
### Examples Quality
- Real-world scenarios (not toy examples)
- Show before/after when relevant
- Include expected output
- Cover common use cases
- Demonstrate Navigator benefits
### Troubleshooting Section
- Address real issues users might encounter
- Provide specific solutions (not generic advice)
- Include verification commands
- Link to related docs if helpful
---
## Common Command Patterns
### Informational Commands
**Pattern**: Simple structure, quick output
**Examples**: version, status, list
**Sections**: Description → Usage → Output
### Action Commands
**Pattern**: Execute something, show result
**Examples**: marker, compact, archive
**Sections**: Description → Execution → Validation → Result
### Setup/Configuration Commands
**Pattern**: Multi-step process, checks
**Examples**: init, migrate, setup
**Sections**: Pre-flight → Steps → Validation → Troubleshooting
### Management Commands
**Pattern**: User selection, operations, feedback
**Examples**: markers (list/load), tasks (list/select)
**Sections**: Overview → Modes → Operations → Results
---
## Troubleshooting
### Generated Command Too Short
**Problem**: Command content is sparse, missing sections
**Solutions**:
1. Increase complexity level (simple → medium)
2. Add more scenarios to "When to Use"
3. Expand troubleshooting section (more common issues)
4. Add Best Practices section
5. Include more examples
### Command Doesn't Match Navigator Style
**Problem**: Tone or structure feels off
**Solutions**:
1. Re-analyze example commands (marker.md, compact.md)
2. Check emoji usage (should match existing patterns)
3. Verify 2nd person perspective ("You are...")
4. Ensure conversational tone (not technical manual)
5. Add personality to closing statement
### YAML Validation Fails
**Problem**: Invalid frontmatter
**Solutions**:
1. Check YAML syntax (proper indentation)
2. Ensure `description` field exists
3. Verify no special characters break parsing
4. Test with: `python -c "import yaml; yaml.safe_load(open('commands/[name].md').read().split('---')[1])"`
### Examples Are Too Generic
**Problem**: Examples don't feel realistic
**Solutions**:
1. Base examples on actual Navigator usage
2. Use real file paths (not /path/to/file)
3. Show actual output format (not [output here])
4. Include context (why user would run this)
---
## Success Criteria
**This skill succeeds when**:
- [ ] Generated command file is syntactically valid
- [ ] YAML frontmatter passes validation
- [ ] All required sections present
- [ ] Tone matches Navigator style (conversational, helpful)
- [ ] Examples are realistic and useful
- [ ] Troubleshooting addresses real issues
- [ ] Command can be invoked in Claude Code
- [ ] Minimal manual editing needed (<10% of content)
---
**The plugin-slash-command skill automates Navigator command creation, ensuring consistency and saving development time** 🔧

View File

@@ -0,0 +1,456 @@
---
description: Smart context compact - preserve essential Navigator markers and documentation context
---
# Navigator Smart Compact
You are performing a context-optimized compact operation that preserves essential Navigator documentation markers.
## What This Does
**Regular `/compact`**: Clears all conversation history, loses context
**Navigator `/nav:compact`**:
- Generates a **context marker** (snapshot of where you are)
- Saves marker to `.agent/.context-markers/`
- Shows you exactly how to resume
- Clears conversation history
- You restore context in your next session by reading the marker
**The Magic**: Context markers compress your entire session (50+ messages, 130k tokens) into a focused summary (3k tokens) that captures only what matters: current task, decisions made, next steps.
## How Context Markers Work
Think of it like save points in a video game:
```
Before Compact:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
You: "Help me implement auth"
Claude: [50 messages of implementation]
You: "Now add OAuth"
Claude: [20 messages of OAuth work]
Total: 130k tokens, approaching limit
After /nav:compact:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ Marker saved: .agent/.context-markers/2025-10-12.md
Contains:
- Task: TASK-45 (auth + OAuth)
- Status: OAuth integrated, needs testing
- Decisions: Using passport.js, JWT tokens
- Next: Write tests for OAuth flow
- 3k tokens
Next session:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
You: Read @.agent/.context-markers/2025-10-12.md
Claude: *knows exactly where you left off*
You: "Write the OAuth tests"
Claude: *continues seamlessly*
```
**You never lose progress. The knowledge is preserved, just compressed.**
## When to Use
### ✅ Good Times to Compact
**After isolated sub-tasks**:
- Just finished documentation update
- Created SOP for solved issue
- Archived feature implementation plan
- Completed debugging session
**Before context switches**:
- Switching from feature A to feature B
- Moving from debugging to new feature
- Starting new sprint/milestone
- After research phase, before implementation
**Token optimization**:
- Approaching 70% token usage
- Long conversation with repeated info
- After multiple /nav:update-doc operations
### ❌ Bad Times to Compact
**In middle of work**:
- Feature half-implemented
- Debugging complex issue
- Multiple related sub-tasks pending
**Context still needed**:
- Next sub-task depends on current conversation
- Need to reference recent decisions
- Team discussion ongoing
## Compact Process
### Step 1: Identify Essential Context
Scan conversation for:
**Must preserve**:
- Current task ID (TASK-XX)
- Active feature/epic name
- Key technical decisions made
- Unresolved blockers/questions
- Next steps planned
**Can clear**:
- Completed sub-tasks details
- Resolved debugging sessions
- Documentation already written
- Exploratory research (if documented)
### Step 2: Generate Context Marker
Create compact marker to preserve essentials:
```markdown
# Navigator Context Marker (Post-Compact)
**Session**: [Date/Time]
**Navigator**: .agent/DEVELOPMENT-README.md
## Active Work
- **Task**: TASK-XX - [Feature Name]
- **Status**: [Phase/Progress]
- **Location**: [File/component being worked on]
## Recent Decisions
- [Decision 1]
- [Decision 2]
## Documentation State
- **Task docs**: [List updated docs]
- **System docs**: [List updated docs]
- **SOPs**: [List created SOPs]
## Next Steps
1. [Next action]
2. [Following action]
## Blockers
- [Blocker 1 if any]
## Don't Load Again (Already Documented)
- [Doc 1] - Already in .agent/
- [Doc 2] - Already in .agent/
---
Load this context marker after compacting to resume efficiently.
```
### Step 3: Save Context Marker
**IMPORTANT**: You MUST save the marker where the user can access it after compact.
**Recommended**: Save to `.agent/.context-markers/` directory
```bash
# Create directory if doesn't exist
mkdir -p .agent/.context-markers
# Save with timestamp
Write(
file_path: ".agent/.context-markers/2025-10-12-143022-compact.md"
content: [context marker from Step 2]
)
```
### Step 3.5: Mark as Active Marker
**NEW**: Create `.active` file to enable automatic resume
```bash
# Create .active file pointing to this marker
echo "2025-10-12-143022-compact.md" > .agent/.context-markers/.active
```
**This enables**: `/nav:start` will auto-detect and load this marker
**Show user the saved location**:
```
✅ Context marker saved and marked as active:
.agent/.context-markers/2025-10-12-143022-compact.md
This marker will be auto-loaded on next session start.
```
**Alternative locations**:
**Option 2**: Append to current task doc (if task exists)
```
Append to: .agent/tasks/TASK-XX-feature.md
## Session Notes
### Compact Point - [Date]
[Context marker content]
After compact: Read @.agent/tasks/TASK-XX-feature.md
```
**Option 3**: User clipboard (if no task doc yet)
```
⚠️ No task doc exists yet.
Copy this marker and paste it in your next session:
[Show marker content]
Or save it manually before compacting.
```
### Step 4: Show Resume Instructions
**CRITICAL**: Tell the user exactly how to resume.
```
╔══════════════════════════════════════════════════════╗
║ ║
║ 🔄 Ready to Compact ║
║ ║
╚══════════════════════════════════════════════════════╝
✅ Context marker created and marked as active:
.agent/.context-markers/2025-10-12-143022-compact.md
TO RESUME AFTER COMPACT:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Simply run: /nav:start
This will automatically:
• Load navigator (.agent/DEVELOPMENT-README.md)
• Detect active marker
• Restore your context (~3k tokens)
• Load current task (if applicable)
All in one command. No manual steps needed.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Proceed with compact? Type 'yes' to continue.
```
**Wait for confirmation before compacting**.
### Step 5: Perform Compact
**Only after user confirms**, execute Claude Code's `/compact` command.
### Step 6: Post-Compact Resume (For User's Next Session)
**Immediately after compact**:
1. **Load navigator** (always):
```
Read .agent/DEVELOPMENT-README.md (~2k tokens)
```
2. **Load context marker**:
```
Read context marker from Step 2
```
3. **Load active task doc** (if exists):
```
Read .agent/tasks/TASK-XX-feature.md (~3k tokens)
```
4. **Resume work**: Continue where left off
**Total tokens loaded**: ~7k (vs 60k+ if keeping full conversation)
## Compact Strategies
### Aggressive (Compact Often)
**When**: Token-constrained, switching tasks frequently
**Trigger**:
- After every sub-task
- Before every new task
- Every 50% token usage
**Trade-off**: More compacts, less context continuity
**Best for**: Multiple short tasks, exploratory work
### Conservative (Compact Rarely)
**When**: Deep work on single feature, need context continuity
**Trigger**:
- After major milestones only
- When reaching 70%+ tokens
- Between unrelated epics
**Trade-off**: Fewer compacts, more token usage
**Best for**: Complex features, long debugging sessions
### Manual (User Decides)
**When**: User knows when to compact
**Trigger**: User runs `/nav:compact` explicitly
**Trade-off**: Full control, requires judgment
**Best for**: Experienced users, custom workflows
## Configuration
Set in `.agent/.nav-config.json`:
```json
{
"compact_strategy": "conservative",
"compact_trigger_percent": 70,
"save_context_markers": true,
"context_marker_location": ".agent/.context-markers/"
}
```
## Example Compact Scenarios
### Scenario 1: Feature Complete
```
Before Compact:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Tokens: 65% (130k used)
Conversation: 50+ messages
Feature TASK-123 complete
Docs updated
Tests passing
Action: /nav:compact
Reason: Feature done, docs archived, ready for next task
After Compact:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Tokens: 5% (10k used)
- Navigator loaded (2k)
- Context marker (3k)
- Ready for TASK-124
Savings: 120k tokens freed (60% of budget)
```
### Scenario 2: Research → Implementation
```
Before Compact:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Tokens: 45% (90k used)
Research: Explored 5 different approaches
Decision: Chose approach #3
Key findings: Documented in SOP
Action: /nav:compact
Reason: Research done, documented, time to implement
After Compact:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Tokens: 7% (14k used)
- Navigator (2k)
- Task doc with decision (3k)
- Relevant SOP (2k)
- Implementation ready
Savings: 76k tokens freed
```
### Scenario 3: Multi-Task Day
```
Morning:
- TASK-101: Bug fix (15k tokens)
- /nav:compact
- TASK-102: New feature (25k tokens)
- /nav:compact
Afternoon:
- TASK-103: Integration (20k tokens)
- /nav:compact
- TASK-104: Documentation (10k tokens)
Total work: 4 tasks
Peak usage: 25k tokens (12.5%)
Without compact: Would hit 70k+ (35%), slower responses
Benefit: Maintained fast responses all day
```
## Compact Checklist
Before running `/nav:compact`:
- [ ] Current task completed or at good stopping point
- [ ] Important decisions documented (task doc or SOP)
- [ ] No unresolved blockers requiring conversation context
- [ ] Ready to switch tasks or take break
- [ ] Context marker generated (if needed)
After running `/nav:compact`:
- [ ] Load navigator (.agent/DEVELOPMENT-README.md)
- [ ] Load context marker (if saved)
- [ ] Load active task doc (if continuing work)
- [ ] Verify ready to continue
## Advanced: Auto-Compact
**Future enhancement**: Automatically compact based on triggers
```json
{
"auto_compact": {
"enabled": false,
"triggers": {
"token_percent": 70,
"after_update_doc": true,
"between_tasks": true
},
"require_confirmation": true
}
}
```
When trigger hit:
```
⚠️ Navigator Auto-Compact Suggested
Reason: Token usage at 71%
Action: Run /nav:compact to free 60k+ tokens
Compact now? [Y/n]:
```
## Metrics
Track compact efficiency:
**Before Compact**:
- Tokens used: 130k (65%)
- Message count: 50+
- Time: 2 hours
**After Compact**:
- Tokens used: 10k (5%)
- Context preserved: Task doc + decision markers
- Ready for: Next task immediately
**Savings**:
- 120k tokens freed
- 60% of budget reclaimed
- Fast responses restored
---
**Remember**: Navigator compact preserves what matters (documented knowledge) and clears what doesn't (conversation history). This keeps your context lean and your sessions productive.

View File

@@ -0,0 +1,642 @@
---
description: Create context markers on-demand - save your progress anytime
---
# Navigator Marker - Save Points for Your Conversation
Create context markers during work to capture your current state. Think of it as **git commits for your AI conversation**.
---
## What This Does
Creates a snapshot of your current work state that you can restore later.
**Traditional approach**: Work until compact, lose intermediate context
**With markers**:
- Save progress anytime
- Multiple markers per session
- Resume from any point
- Safety nets before risky changes
---
## When to Use
### ✅ Perfect Times for Markers
**Before taking breaks**:
```
You: "Implemented auth flow, going to lunch"
You: /nav:marker lunch-break
Result: Resume perfectly after lunch
```
**Before exploring approaches**:
```
You: /nav:marker before-refactor
You: "Let's try refactoring X"
*doesn't work*
You: Read @.agent/.context-markers/before-refactor.md
Result: Back to known good state
```
**During long features**:
```
Day 1: Core implementation → /nav:marker day1-core
Day 2: Add integrations → /nav:marker day2-integrations
Day 3: Tests & polish → /nav:marker day3-complete
Result: Checkpoints throughout multi-day work
```
**Before risky changes**:
```
You: "About to refactor entire routing system"
You: /nav:marker pre-routing-refactor
Result: Safety net if things go wrong
```
**End of day**:
```
You: /nav:marker eod-2025-10-12
Result: Tomorrow starts with perfect context
```
**After important decisions**:
```
You: "We decided to use PostgreSQL instead of MongoDB"
You: /nav:marker architecture-decision
Result: Decision captured with full context
```
---
## Usage
### Basic Usage
```bash
/nav:marker
```
Creates marker with auto-generated name: `marker-2025-10-12-143022.md`
### Named Markers
```bash
/nav:marker before-refactor
/nav:marker lunch-break
/nav:marker pre-deployment
/nav:marker day1-complete
```
Creates marker with your name: `before-refactor-2025-10-12-143022.md`
### With Description
```bash
/nav:marker oauth-working "OAuth flow implemented and tested"
```
Adds description to marker content.
---
## Marker Creation Process
### Step 1: Analyze Current State
Scan conversation for:
**Active work**:
- Current task/feature
- Files being modified
- What's implemented
- What's remaining
**Recent context**:
- Technical decisions made
- Approaches tried (successful and failed)
- Dependencies added
- Blockers encountered
**Next steps**:
- What you planned to do next
- Open questions
- Ideas to explore
### Step 2: Generate Marker Content
Create comprehensive marker:
```markdown
# Navigator Context Marker: [Name]
**Created**: 2025-10-12 14:30:22
**Type**: On-demand marker
**Navigator**: .agent/DEVELOPMENT-README.md
---
## 📍 Current Location
**Task**: TASK-123 - Implement OAuth authentication
**Phase**: Integration complete, testing pending
**Files**:
- src/auth/oauth.ts (implemented)
- src/routes/auth.ts (updated)
- tests/auth.test.ts (needs work)
**Progress**: 70% complete
---
## 🎯 What's Done
- ✅ OAuth flow implemented with passport.js
- ✅ JWT token generation working
- ✅ Login/logout endpoints created
- ✅ Session management configured
- ✅ Google OAuth provider integrated
---
## 🔧 Technical Decisions
**OAuth Library**: Chose passport.js over next-auth
- Reason: More control over flow, simpler for our use case
- Trade-off: More manual config, but cleaner integration
**Token Strategy**: JWT in httpOnly cookies
- Reason: XSS protection, no localStorage needed
- Expiration: 7 days, refresh token pattern
**Session Store**: Redis
- Reason: Fast, scalable, easy invalidation
- Config: TTL matches JWT expiration
---
## ⚠️ Challenges & Solutions
**Challenge**: CORS issues with OAuth callback
**Solution**: Added credentials: 'include' and proper CORS headers
**File**: src/middleware/cors.ts
**Challenge**: Token not persisting across requests
**Solution**: Missing httpOnly flag in cookie options
**File**: src/auth/tokens.ts:45
---
## 📝 Next Steps
1. Write comprehensive tests for OAuth flow
- Happy path: successful login
- Error cases: invalid tokens, expired sessions
- Edge cases: concurrent logins, token refresh
2. Add error handling for failed OAuth
- Network errors
- Provider downtime
- Invalid credentials
3. Document OAuth setup in README
- Environment variables needed
- Provider setup instructions
- Local development flow
---
## 🔗 Related Documentation
**Already documented**:
- .agent/system/auth-architecture.md - Auth system design
- .agent/sops/integrations/oauth-setup.md - OAuth provider config
**Needs documentation**:
- Testing strategy for OAuth
- Production deployment checklist
---
## 💡 Ideas to Explore
- Add more OAuth providers (GitHub, Twitter)
- Implement OAuth scope management
- Add "Sign in with" UI component library
- Consider magic link as alternative auth method
---
## 🚫 Don't Load Again
These are already documented, don't reload:
- .agent/tasks/TASK-123-oauth-auth.md
- .agent/system/auth-architecture.md
- Previous markers (if any)
---
## 🔄 Restore Instructions
To resume from this marker:
1. Read this marker:
```
Read @.agent/.context-markers/oauth-working-2025-10-12-143022.md
```
2. Continue with: "Write tests for OAuth flow"
**Context restored in ~3k tokens instead of replaying 130k token conversation.**
---
Generated by: /nav:marker oauth-working
```
### Step 3: Save Marker
**Create directory if needed**:
```bash
mkdir -p .agent/.context-markers
```
**Save with naming convention**:
```
Format: [user-name]-YYYY-MM-DD-HHMMSS.md
Example: oauth-working-2025-10-12-143022.md
```
**Write marker**:
```
Write(
file_path: ".agent/.context-markers/oauth-working-2025-10-12-143022.md"
content: [marker content from Step 2]
)
```
### Step 4: Confirm to User
Show clear confirmation:
```
✅ Marker saved!
📍 Location: .agent/.context-markers/oauth-working-2025-10-12-143022.md
🔄 To restore this state later:
Read @.agent/.context-markers/oauth-working-2025-10-12-143022.md
💾 Marker size: ~3k tokens
📊 Current session: ~85k tokens
Tip: You can continue working or use /nav:compact to free up space.
```
---
## Advanced Features
### List All Markers
```bash
/nav:marker list
```
Shows all available markers:
```
📍 Available Context Markers
Recent markers (last 7 days):
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. oauth-working-2025-10-12-143022.md
Created: 2 hours ago
Task: TASK-123 - OAuth authentication
Size: 3.2k tokens
2. before-refactor-2025-10-12-091500.md
Created: 7 hours ago
Task: TASK-122 - Routing refactor
Size: 2.8k tokens
3. day1-complete-2025-10-11-170000.md
Created: yesterday
Task: TASK-121 - User dashboard
Size: 3.5k tokens
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Total: 3 markers | Combined size: 9.5k tokens
To restore: Read @.agent/.context-markers/[filename]
To clean up: /nav:marker clean
```
### Clean Old Markers
```bash
/nav:marker clean
```
Interactive cleanup:
```
🧹 Marker Cleanup
Found 15 markers older than 7 days:
- [list with dates and sizes]
Keep only:
1. Last 7 days (recommended)
2. Last 30 days
3. Keep all, just show me
4. Custom selection
Choice [1-4]:
```
### Compare Markers
```bash
/nav:marker diff oauth-working before-refactor
```
Shows what changed between two markers:
```
📊 Marker Comparison
From: before-refactor (7 hours ago)
To: oauth-working (2 hours ago)
Changes:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Tasks:
- Completed: TASK-122 (routing refactor)
+ Started: TASK-123 (OAuth auth)
Files Modified:
+ src/auth/oauth.ts (new)
+ src/auth/tokens.ts (new)
~ src/routes/auth.ts (modified)
Decisions Made:
+ Using passport.js for OAuth
+ JWT in httpOnly cookies
+ Redis for session storage
Progress: 30% → 70% (task)
```
---
## Marker Strategies
### Checkpoint Strategy
Create markers at natural checkpoints:
```
Feature Planning:
/nav:marker planning-complete
Core Implementation:
/nav:marker core-working
Integration:
/nav:marker integration-done
Testing:
/nav:marker tests-passing
Ready for Review:
/nav:marker ready-for-pr
```
**Benefit**: Clear progression, easy to resume at any stage
### Daily Markers
End each day with a marker:
```bash
/nav:marker eod-2025-10-12 "Finished OAuth, need tests tomorrow"
```
**Benefit**: Perfect context on Monday for Friday's work
### Experiment Markers
Before trying new approaches:
```bash
/nav:marker before-experiment
# Try risky refactor
# Doesn't work?
# Restore from marker, try different approach
```
**Benefit**: Safe exploration, easy rollback
### Decision Markers
After important decisions:
```bash
/nav:marker architecture-decision "Chose PostgreSQL over MongoDB"
```
**Benefit**: Capture why decisions were made with full context
---
## Marker Best Practices
### ✅ Do
- Create markers before breaks (lunch, end of day)
- Name markers descriptively (`oauth-working` not `marker-1`)
- Add descriptions for important markers
- Clean up old markers monthly
- Use markers as conversation save points
### ❌ Don't
- Don't create markers every 5 minutes (too granular)
- Don't use generic names (`test`, `stuff`, `work`)
- Don't forget to clean up (markers accumulate)
- Don't rely solely on markers (still commit code!)
---
## Integration with Navigator Workflow
### Markers + Compact
```
Work on feature → /nav:marker feature-done
Continue to polish → Token usage high
/nav:compact
Result: Marker preserved, conversation cleared
```
**Benefit**: Markers survive compacts
### Markers + Tasks
```
Start task → Load task doc
Make progress → /nav:marker progress-update
Complete → /nav:update-doc feature TASK-XX
```
**Benefit**: Markers complement task documentation
### Markers + SOPs
```
Hit bug → Debug → Solve
/nav:marker bug-solved "Fixed CORS issue with OAuth"
/nav:update-doc sop debugging cors-oauth-fix
```
**Benefit**: Markers capture point-in-time, SOPs capture solution
---
## Technical Implementation
### Marker Storage
```
.agent/.context-markers/
├── oauth-working-2025-10-12-143022.md
├── before-refactor-2025-10-12-091500.md
├── day1-complete-2025-10-11-170000.md
└── .gitkeep
```
**Naming**: `[name]-YYYY-MM-DD-HHMMSS.md`
**Size**: ~3k tokens each
**Git**: Ignored by default (in .gitignore)
### Marker Format
**Required sections**:
- Current Location (task, files, progress)
- What's Done (achievements)
- Technical Decisions (with rationale)
- Next Steps (what's remaining)
- Restore Instructions (how to resume)
**Optional sections**:
- Challenges & Solutions
- Ideas to Explore
- Related Documentation
---
## Examples
### Example 1: End of Day Marker
```bash
You: "Finished implementing user settings page, need to add tests tomorrow"
You: /nav:marker eod-settings-done
Result:
✅ Marker saved: .agent/.context-markers/eod-settings-done-2025-10-12-170000.md
Tomorrow: Read @.agent/.context-markers/eod-settings-done-2025-10-12-170000.md
```
### Example 2: Before Risky Change
```bash
You: "Current routing works. About to refactor to use new router"
You: /nav:marker before-routing-refactor
You: "Refactor the routing system to use express-router"
*After testing...*
You: "The refactor broke auth. Let me restore"
You: Read @.agent/.context-markers/before-routing-refactor.md
You: "Take different approach - migrate gradually"
```
### Example 3: Multi-Day Feature
```bash
Monday:
You: /nav:marker day1-foundation "Built database models and API structure"
Tuesday:
You: Read @.agent/.context-markers/day1-foundation.md
You: *continues work*
You: /nav:marker day2-integration "Integrated with frontend, working on auth"
Wednesday:
You: Read @.agent/.context-markers/day2-integration.md
You: *continues work*
You: /nav:marker day3-complete "Feature complete, tests passing"
```
---
## Success Metrics
**Without markers**:
- Resume after break: 5-10 min re-explaining context
- Session restart: Lose all context
- Risky changes: No safety net
- Multi-day work: Fragmented understanding
**With markers**:
- Resume after break: 30 seconds (read marker)
- Session restart: Full context restored
- Risky changes: Rollback point available
- Multi-day work: Continuous context thread
**Token efficiency**:
- Marker: 3k tokens to restore full context
- Re-explaining: 20-30k tokens of back-and-forth
- **Savings**: 85-90% fewer tokens to resume
---
## Future Enhancements
**Auto-markers**:
```json
{
"auto_marker": {
"on_task_complete": true,
"on_break_detected": true,
"every_n_hours": 2
}
}
```
**Marker search**:
```bash
/nav:marker search "OAuth"
# Returns all markers mentioning OAuth
```
**Marker merge**:
```bash
/nav:marker merge day1 day2 day3 → feature-complete
# Combines multiple markers into one
```
---
**Markers transform your AI workflow from stateless to stateful. Never lose context again.** 🎯

View File

@@ -0,0 +1,430 @@
#!/usr/bin/env python3
"""
Command Generator - Generate Navigator slash command markdown files
Generates properly structured command files following Navigator conventions.
"""
from typing import Dict, List, Optional
from datetime import datetime
def generate_command(
name: str,
description: str,
complexity: str = "medium",
sections: Optional[Dict] = None
) -> str:
"""
Generate complete Navigator command markdown file.
Args:
name: Command name (kebab-case, without /nav: prefix)
description: One-line purpose description
complexity: Command complexity level ("simple", "medium", "complex")
sections: Dictionary of section content (optional, uses templates if not provided)
Returns:
Complete markdown content for the command file
Example:
>>> content = generate_command(
... name="example",
... description="Example command for testing",
... complexity="simple"
... )
>>> "---" in content and "description:" in content
True
"""
if sections is None:
sections = {}
# Validate inputs
valid, error = validate_command_name(name)
if not valid:
raise ValueError(f"Invalid command name: {error}")
if complexity not in ["simple", "medium", "complex"]:
raise ValueError(f"Complexity must be 'simple', 'medium', or 'complex', got: {complexity}")
# Generate frontmatter
frontmatter = f"""---
description: {description}
---"""
# Generate title
title = f"# {format_title(name)}"
# Generate content based on complexity
if complexity == "simple":
content = generate_simple_command(name, description, sections)
elif complexity == "medium":
content = generate_medium_command(name, description, sections)
else: # complex
content = generate_complex_command(name, description, sections)
# Combine all parts
return f"{frontmatter}\n\n{title}\n\n{content}"
def generate_simple_command(name: str, description: str, sections: Dict) -> str:
"""Generate content for a simple command."""
what_this_does = sections.get("what_this_does", f"[Explain what /nav:{name} does in 2-3 sentences]")
usage = sections.get("usage", f"/nav:{name}")
when_to_use = sections.get("when_to_use", [
"Scenario 1",
"Scenario 2",
"Scenario 3"
])
output_format = sections.get("output_format", "[Example output]")
troubleshooting = sections.get("troubleshooting", {
"Issue 1": "Solution 1",
"Issue 2": "Solution 2"
})
# Build when_to_use section
when_to_use_content = "\n\n".join([
f"**{scenario}**:\n```\n[Example]\n```" for scenario in when_to_use
])
# Build troubleshooting section
troubleshooting_content = "\n\n".join([
f"### {issue}\n\n**Problem**: [Description]\n\n**Solution**:\n{solution}"
for issue, solution in troubleshooting.items()
])
return f"""## What This Does
{what_this_does}
---
## Usage
```bash
{usage}
```
---
## When to Use
{when_to_use_content}
---
## Output Format
```
{output_format}
```
---
## Troubleshooting
{troubleshooting_content}
---
**[Closing statement about the command]** 🚀"""
def generate_medium_command(name: str, description: str, sections: Dict) -> str:
"""Generate content for a medium complexity command."""
overview = sections.get("overview", f"You are using Navigator's `/nav:{name}` command.\n\n[Explain context and purpose]")
what_this_does = sections.get("what_this_does", "[Detailed explanation with comparisons]")
when_to_use = sections.get("when_to_use", [f"Scenario {i+1}" for i in range(5)])
execution_steps = sections.get("execution_steps", [f"Step {i+1}" for i in range(3)])
troubleshooting = sections.get("troubleshooting", {f"Issue {i+1}": f"Solution {i+1}" for i in range(4)})
# Build when_to_use section
when_to_use_content = "\n\n".join([
f"**{scenario}**:\n```\n[Example]\n```" for scenario in when_to_use
])
# Build execution steps
execution_content = "\n\n".join([
f"### {step}\n\n[Instructions for this step]\n\n**Expected outcome**: [What happens]"
for step in execution_steps
])
# Build troubleshooting
troubleshooting_content = "\n\n".join([
f"### {issue}\n\n**Problem**: [Description]\n\n**Solutions**:\n1. {solution}\n2. [Additional solution]\n3. [Additional solution]"
for issue, solution in troubleshooting.items()
])
return f"""{overview}
---
## What This Does
{what_this_does}
---
## When to Use
{when_to_use_content}
---
## Execution Steps
{execution_content}
---
## Output Format
```
[Expected output format]
```
---
## Best Practices
- [Best practice 1]
- [Best practice 2]
- [Best practice 3]
---
## Troubleshooting
{troubleshooting_content}
---
**[Closing statement emphasizing key benefit]** 🚀"""
def generate_complex_command(name: str, description: str, sections: Dict) -> str:
"""Generate content for a complex command."""
return f"""You are executing the `/nav:{name}` command.
[Comprehensive overview explaining the command's role in Navigator workflow]
---
## What This Does
[Detailed explanation with comparisons to alternative approaches]
**Traditional approach**: [Manual process]
**With `/nav:{name}`**:
- [Benefit 1]
- [Benefit 2]
- [Benefit 3]
---
## EXECUTION PLAN
You will execute these steps in order. Each step has explicit outcomes.
---
### Step 1: Pre-Flight Checks
[Validation and preparation steps]
**Checks**:
- [ ] Check 1
- [ ] Check 2
- [ ] Check 3
---
### Step 2: [Main Operation]
[Detailed implementation instructions]
**Process**:
1. [Substep 1]
2. [Substep 2]
3. [Substep 3]
**Expected outcome**: [What should happen]
---
### Step 3: Validation
[Verification steps]
**Verify**:
- [ ] Verification 1
- [ ] Verification 2
- [ ] Verification 3
---
### Step 4: Completion
[Finalization and user feedback]
**Show summary**:
```
✅ [Success message]
[Summary of what was accomplished]
```
---
## Integration Notes
[How this command integrates with other Navigator features or external tools]
---
## Success Criteria
**This command succeeds when**:
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] Criterion 3
- [ ] Criterion 4
---
## Troubleshooting
### Common Issue 1
**Error**: [Error message or symptom]
**Solution**:
[Detailed solution with commands]
### Common Issue 2
**Error**: [Error message or symptom]
**Solution**:
[Detailed solution]
### Edge Case 1
**Scenario**: [When this happens]
**Handling**:
[How to handle this case]
---
## Performance Notes
[Any performance considerations, optimization tips, or scalability notes]
---
**[Comprehensive closing statement]** 🚀"""
def validate_command_name(name: str) -> tuple[bool, Optional[str]]:
"""
Validate command name follows Navigator conventions.
Args:
name: Command name to validate
Returns:
Tuple of (is_valid, error_message)
Example:
>>> validate_command_name("my-command")
(True, None)
>>> validate_command_name("MyCommand")
(False, 'Command name must be kebab-case')
"""
import re
if not name:
return False, "Command name cannot be empty"
if not re.match(r'^[a-z][a-z0-9]*(-[a-z0-9]+)*$', name):
return False, "Command name must be kebab-case (lowercase, hyphens only)"
if len(name) > 50:
return False, "Command name too long (max 50 characters)"
# Reserved names
reserved = ["help", "clear", "reset"]
if name in reserved:
return False, f"Command name '{name}' is reserved"
return True, None
def format_title(name: str) -> str:
"""
Format command name as title.
Args:
name: Command name (kebab-case)
Returns:
Formatted title string
Example:
>>> format_title("update-doc")
'Update Doc - Navigator'
>>> format_title("marker")
'Marker - Navigator'
"""
# Convert kebab-case to Title Case
title = name.replace('-', ' ').title()
# Add Navigator branding
return f"{title} - Navigator"
def generate_description(name: str, purpose: str) -> str:
"""
Generate command description for YAML frontmatter.
Args:
name: Command name
purpose: Brief purpose statement
Returns:
Formatted description (under 100 chars)
Example:
>>> desc = generate_description("marker", "save conversation state")
>>> len(desc) < 100
True
"""
# Ensure it starts with a verb and is concise
if len(purpose) > 90:
purpose = purpose[:87] + "..."
return purpose
if __name__ == "__main__":
# Example usage
print("Generating simple command...")
simple = generate_command(
name="example",
description="Example command for demonstration",
complexity="simple"
)
print("\n" + "=" * 50)
print(simple[:500] + "...")
print("=" * 50)
# Validate names
test_names = ["my-command", "MyCommand", "my_command", "valid-name-123"]
print("\nValidation Tests:")
for name in test_names:
valid, error = validate_command_name(name)
status = "" if valid else ""
print(f"{status} {name}: {error or 'Valid'}")

View File

@@ -0,0 +1,323 @@
#!/usr/bin/env python3
"""
Command Validator - Validate Navigator slash command files
Validates command markdown files follow Navigator conventions and standards.
"""
import re
from typing import List, Tuple, Optional
from pathlib import Path
def validate_command_file(file_path: str) -> Tuple[bool, List[str]]:
"""
Validate complete command markdown file.
Args:
file_path: Path to command .md file
Returns:
Tuple of (is_valid, list_of_errors)
Example:
>>> valid, errors = validate_command_file("commands/marker.md")
>>> valid or len(errors) > 0
True
"""
errors = []
# Check file exists
path = Path(file_path)
if not path.exists():
return False, [f"File not found: {file_path}"]
# Read content
try:
content = path.read_text()
except Exception as e:
return False, [f"Cannot read file: {e}"]
# Validate sections
errors.extend(validate_frontmatter(content))
errors.extend(validate_structure(content))
errors.extend(validate_formatting(content))
errors.extend(validate_style(content))
return len(errors) == 0, errors
def validate_frontmatter(content: str) -> List[str]:
"""
Validate YAML frontmatter.
Args:
content: File content
Returns:
List of errors (empty if valid)
"""
errors = []
# Check frontmatter exists
if not content.startswith("---"):
errors.append("Missing YAML frontmatter (must start with '---')")
return errors
# Extract frontmatter
parts = content.split("---", 2)
if len(parts) < 3:
errors.append("Invalid frontmatter structure (must be surrounded by '---')")
return errors
frontmatter = parts[1].strip()
# Check description field
if "description:" not in frontmatter:
errors.append("Missing 'description' field in frontmatter")
else:
# Extract description value
desc_match = re.search(r'description:\s*(.+)', frontmatter)
if desc_match:
desc = desc_match.group(1).strip()
if not desc:
errors.append("Description field is empty")
elif len(desc) > 150:
errors.append(f"Description too long ({len(desc)} chars, max 150)")
else:
errors.append("Cannot parse description field")
# Check for invalid fields (Navigator commands use minimal frontmatter)
valid_fields = ["description", "author", "version", "deprecated"]
for line in frontmatter.split("\n"):
if ":" in line:
field = line.split(":")[0].strip()
if field and field not in valid_fields:
errors.append(f"Unexpected frontmatter field: '{field}'")
return errors
def validate_structure(content: str) -> List[str]:
"""
Validate document structure and required sections.
Args:
content: File content
Returns:
List of errors (empty if valid)
"""
errors = []
# Extract markdown body (after frontmatter)
parts = content.split("---", 2)
if len(parts) < 3:
return ["Cannot extract markdown body"]
body = parts[2].strip()
# Check for title (# heading)
if not body.startswith("#"):
errors.append("Missing main title (must start with # heading)")
else:
title_match = re.match(r'^#\s+(.+)$', body.split("\n")[0])
if not title_match:
errors.append("Invalid title format")
else:
title = title_match.group(1)
# Navigator commands typically end with " - Navigator" or context
if "navigator" not in title.lower() and "jitd" not in title.lower():
errors.append(f"Title should include Navigator branding: '{title}'")
# Check for required sections (vary by complexity, so we check for minimum)
required_keywords = ["what", "usage", "when"]
for keyword in required_keywords:
if keyword.lower() not in body.lower():
errors.append(f"Missing section with '{keyword}' (recommended sections: What This Does, Usage, When to Use)")
# Check for code blocks (commands should have examples)
if "```" not in body:
errors.append("No code blocks found (commands should include examples)")
# Check for closing statement
last_line = body.strip().split("\n")[-1]
if not last_line.startswith("**") or not last_line.endswith("**"):
errors.append("Missing closing statement (should be bold text at end)")
return errors
def validate_formatting(content: str) -> List[str]:
"""
Validate markdown formatting and syntax.
Args:
content: File content
Returns:
List of errors (empty if valid)
"""
errors = []
# Check for proper heading hierarchy
headings = re.findall(r'^(#{1,6})\s+(.+)$', content, re.MULTILINE)
prev_level = 0
for heading, text in headings:
level = len(heading)
if level > prev_level + 1:
errors.append(f"Heading hierarchy skip: {heading} {text} (jumped from h{prev_level} to h{level})")
prev_level = level
# Check for unclosed code blocks
code_block_count = content.count("```")
if code_block_count % 2 != 0:
errors.append(f"Unclosed code block (found {code_block_count} backticks, must be even)")
# Check for proper list formatting
lines = content.split("\n")
in_list = False
for i, line in enumerate(lines, 1):
if re.match(r'^\s*[-*+]\s+', line):
in_list = True
# Check indentation consistency
if not re.match(r'^( |\t)?[-*+]\s+\S', line):
errors.append(f"Line {i}: Improper list item format (needs space after bullet)")
elif in_list and line.strip() and not line.startswith(" ") and not line.startswith("\t"):
in_list = False
# Check for broken links (markdown links with empty href)
broken_links = re.findall(r'\[([^\]]+)\]\(\s*\)', content)
if broken_links:
errors.append(f"Broken markdown links found: {broken_links}")
return errors
def validate_style(content: str) -> List[str]:
"""
Validate Navigator style conventions.
Args:
content: File content
Returns:
List of errors (empty if valid)
"""
errors = []
# Check for 2nd person perspective (Navigator style)
first_person = ["I am", "I will", "I have", "we are", "we will", "we have"]
for phrase in first_person:
if phrase.lower() in content.lower():
errors.append(f"Use 2nd person perspective ('you are') not 1st person ('{phrase}')")
# Check emoji usage (Navigator commands use emojis sparingly)
# Common Navigator emojis: ✅ ❌ 📖 🚀 ⚠️ 💡 🔹
emoji_count = len(re.findall(r'[\U0001F300-\U0001F9FF]', content))
if emoji_count > 15:
errors.append(f"Too many emojis ({emoji_count} found, keep under 15 for professionalism)")
# Check for proper bash/shell syntax in code blocks
bash_blocks = re.findall(r'```(?:bash|shell|sh)\n(.*?)\n```', content, re.DOTALL)
for block in bash_blocks:
if "$(" in block and not re.search(r'\)\s*$', block, re.MULTILINE):
errors.append("Potential unclosed command substitution in bash block")
# Check for Navigator command references (should use /nav: prefix)
nav_cmds = re.findall(r'`/(?:jitd|nav):([a-z-]+)`', content)
jitd_cmds = re.findall(r'`/jitd:([a-z-]+)`', content)
if len(jitd_cmds) > len(nav_cmds) * 0.5: # More than 50% use old prefix
errors.append("Prefer /nav: prefix over /jitd: (for consistency)")
return errors
def validate_example_realism(content: str) -> List[str]:
"""
Check if examples are realistic (not placeholders).
Args:
content: File content
Returns:
List of warnings (empty if examples look good)
"""
warnings = []
# Check for common placeholder patterns
placeholders = [
r'\[.*?\]', # [placeholder]
r'<.*?>', # <placeholder>
r'\.\.\.+', # ...
r'TODO',
r'FIXME',
r'XXX',
]
code_blocks = re.findall(r'```.*?\n(.*?)\n```', content, re.DOTALL)
for block in code_blocks:
for pattern in placeholders:
if re.search(pattern, block):
warnings.append(f"Code block contains placeholder-like content: {pattern}")
break # One warning per block
return warnings
def quick_validate(file_path: str) -> bool:
"""
Quick validation check (returns only boolean).
Args:
file_path: Path to command file
Returns:
True if valid, False otherwise
"""
valid, _ = validate_command_file(file_path)
return valid
def print_validation_report(file_path: str):
"""
Print formatted validation report.
Args:
file_path: Path to command file
"""
valid, errors = validate_command_file(file_path)
print(f"\n{'='*60}")
print(f"Validation Report: {Path(file_path).name}")
print(f"{'='*60}\n")
if valid:
print("✅ All validations passed!")
print("\nFile is ready to use.")
else:
print(f"❌ Found {len(errors)} issue(s):\n")
for i, error in enumerate(errors, 1):
print(f"{i}. {error}")
print("\n" + "="*60)
print("Fix these issues before using the command.")
print()
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Usage: python command_validator.py <command-file.md>")
print("\nExample:")
print(" python command_validator.py commands/marker.md")
sys.exit(1)
file_path = sys.argv[1]
print_validation_report(file_path)
# Exit with error code if validation failed
if not quick_validate(file_path):
sys.exit(1)

View File

@@ -0,0 +1,124 @@
---
description: ${DESCRIPTION}
---
# ${TITLE} - Navigator
${OVERVIEW_PARAGRAPH}
---
## What This Does
${WHAT_THIS_DOES_CONTENT}
---
## When to Use
### ✅ Perfect Times
**${SCENARIO_1_TITLE}**:
```
${SCENARIO_1_EXAMPLE}
```
**${SCENARIO_2_TITLE}**:
```
${SCENARIO_2_EXAMPLE}
```
**${SCENARIO_3_TITLE}**:
```
${SCENARIO_3_EXAMPLE}
```
---
## Usage
### Basic Usage
```bash
/nav:${COMMAND_NAME}
```
${BASIC_USAGE_DESCRIPTION}
### With Options
```bash
/nav:${COMMAND_NAME} ${OPTION_1}
/nav:${COMMAND_NAME} ${OPTION_2} "${OPTIONAL_ARG}"
```
${OPTIONS_DESCRIPTION}
---
## Execution Steps
### Step 1: ${STEP_1_NAME}
${STEP_1_INSTRUCTIONS}
**Expected outcome**: ${STEP_1_OUTCOME}
### Step 2: ${STEP_2_NAME}
${STEP_2_INSTRUCTIONS}
**Expected outcome**: ${STEP_2_OUTCOME}
### Step 3: ${STEP_3_NAME}
${STEP_3_INSTRUCTIONS}
**Expected outcome**: ${STEP_3_OUTCOME}
---
## Output Format
```
${OUTPUT_EXAMPLE}
```
---
## Best Practices
- **${BEST_PRACTICE_1_TITLE}**: ${BEST_PRACTICE_1_DESCRIPTION}
- **${BEST_PRACTICE_2_TITLE}**: ${BEST_PRACTICE_2_DESCRIPTION}
- **${BEST_PRACTICE_3_TITLE}**: ${BEST_PRACTICE_3_DESCRIPTION}
---
## Troubleshooting
### ${ISSUE_1_TITLE}
**Error**: ${ISSUE_1_ERROR_MESSAGE}
**Solution**:
${ISSUE_1_SOLUTION}
### ${ISSUE_2_TITLE}
**Error**: ${ISSUE_2_ERROR_MESSAGE}
**Solution**:
${ISSUE_2_SOLUTION}
### ${ISSUE_3_TITLE}
**Problem**: ${ISSUE_3_DESCRIPTION}
**Fix**:
```bash
${ISSUE_3_FIX_COMMAND}
```
---
**${CLOSING_STATEMENT}** 🚀