Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:50:12 +08:00
commit d16c5de665
29 changed files with 4788 additions and 0 deletions

510
commands/configure.md Normal file
View File

@@ -0,0 +1,510 @@
---
name: configure
description: Generate or update project-level plugin configuration with smart migration
version: 2.0.0
---
# Configure Plugin Settings
This command helps you set up `.claude/super-claude-config.json` for customizing plugin behavior (skills and hooks).
## What This Does
Creates or updates `.claude/super-claude-config.json` with configuration for:
- **Skills** - Auto-activation triggers, enable/disable
- **Hooks** - Behavior customization (protected branches, timeouts, etc.)
- **All installed plugins** - Unified configuration in one file
## Your Task
Execute this workflow intelligently based on what configuration files exist:
### Step 1: Detect Existing Configuration
Check for these files:
- **New format**: `.claude/super-claude-config.json`
- **Legacy format**: `.claude/skills/skill-rules.json`
### Step 2: Determine Strategy (Smart Routing)
**CASE 1: No configuration files exist (Clean Slate)**
- Generate `.claude/super-claude-config.json` from all plugin defaults
- No questions needed, just create it
- Skip to Step 4 (Generation)
**CASE 2: Only legacy config exists**
Use AskUserQuestion:
```json
{
"questions": [
{
"question": "Found legacy skill-rules.json configuration. How should we handle it?",
"header": "Migration",
"multiSelect": false,
"options": [
{
"label": "Migrate to new format",
"description": "Convert to super-claude-config.json and create backup (.bak file)"
},
{
"label": "Keep legacy format",
"description": "Create new config separately (both will work, legacy shows deprecation warning)"
}
]
}
]
}
```
Actions based on answer:
- **"Migrate to new format"**: Follow Migration workflow (Step 3a)
- **"Keep legacy format"**: Generate new config only, don't touch legacy (Step 4)
**CASE 3: Only new config exists**
Check if new plugin defaults are available:
```typescript
// Pseudo-code logic
const current = loadJson('.claude/super-claude-config.json');
const allPluginDefaults = discoverPluginDefaults(); // from plugins/*/super-claude-config.json
const newAdditions = computeNewAdditions(current, allPluginDefaults);
if (newAdditions.isEmpty()) {
// No updates needed
console.log('✓ Configuration is up to date (all plugins configured)');
return;
}
```
If new defaults found, use AskUserQuestion:
```json
{
"questions": [
{
"question": "Found ${count} new configuration options. Add them to your config?",
"header": "Update",
"multiSelect": false,
"options": [
{
"label": "Add new defaults",
"description": "Add ${summary} while preserving all your customizations"
},
{
"label": "Skip for now",
"description": "Don't update (you can run /workflow:configure again later)"
}
]
}
]
}
```
Actions based on answer:
- **"Add new defaults"**: Merge new defaults (Step 3b)
- **"Skip for now"**: Exit without changes
**CASE 4: Both configs exist**
Use AskUserQuestion:
```json
{
"questions": [
{
"question": "Both legacy and new configuration files exist. What should we do?",
"header": "Conflict",
"multiSelect": false,
"options": [
{
"label": "Merge into new config",
"description": "Import legacy overrides into super-claude-config.json (creates backup)"
},
{
"label": "Update new config only",
"description": "Ignore legacy file and just update super-claude-config.json"
},
{
"label": "Keep both separate",
"description": "Don't merge (both will be loaded, legacy shows deprecation warning)"
}
]
}
]
}
```
Actions based on answer:
- **"Merge into new config"**: Migration + merge workflow (Step 3a)
- **"Update new config only"**: Update new config, ignore legacy (Step 3b)
- **"Keep both separate"**: Exit without changes
### Step 3a: Migration Workflow
**Convert legacy skill-rules.json to new format:**
```typescript
function migrateLegacyConfig(legacyPath: string): ProjectConfig {
const legacy = JSON.parse(fs.readFileSync(legacyPath, 'utf8'));
const migrated: ProjectConfig = {};
// Legacy format has:
// - plugin.namespace (e.g., "meta")
// - skills.{skillName}
// - overrides.disabled (array of "namespace/skillName")
const namespace = legacy.plugin.namespace;
if (!migrated[namespace]) {
migrated[namespace] = { skills: {}, hooks: {} };
}
// Convert disabled skills
if (legacy.overrides?.disabled) {
for (const fullName of legacy.overrides.disabled) {
const [ns, skillName] = fullName.split('/');
if (ns === namespace) {
migrated[namespace].skills[skillName] = { enabled: false };
}
}
}
// Convert skill overrides (if any custom triggers, priorities, etc.)
for (const [skillName, skillData] of Object.entries(legacy.skills || {})) {
if (!migrated[namespace].skills[skillName]) {
migrated[namespace].skills[skillName] = {};
}
// Preserve custom triggers if they exist
if (skillData.promptTriggers) {
migrated[namespace].skills[skillName].triggers = {
keywords: skillData.promptTriggers.keywords || [],
patterns: skillData.promptTriggers.intentPatterns || [],
};
}
}
return migrated;
}
```
**Workflow:**
1. Read `.claude/skills/skill-rules.json`
2. Convert to new format using migration logic above
3. Create backup: `cp .claude/skills/skill-rules.json .claude/skills/skill-rules.json.bak`
4. Load all plugin defaults
5. Deep merge: `plugin defaults → migrated overrides → existing new config (if any)`
6. Write to `.claude/super-claude-config.json`
### Step 3b: Update Existing Config
**Add only NEW plugins/hooks while preserving ALL user customizations:**
```typescript
function addNewDefaults(
current: ProjectConfig,
allDefaults: Record<string, PluginConfig>,
): ProjectConfig {
const result = { ...current };
for (const [pluginName, pluginDefaults] of Object.entries(allDefaults)) {
if (!result[pluginName]) {
// Brand new plugin - add entire config
result[pluginName] = {
skills: pluginDefaults.skills || {},
hooks: pluginDefaults.hooks || {},
};
} else {
// Existing plugin - add only NEW skills/hooks
// Add new skills
if (pluginDefaults.skills) {
result[pluginName].skills = result[pluginName].skills || {};
for (const [skillName, skillConfig] of Object.entries(
pluginDefaults.skills,
)) {
if (!result[pluginName].skills[skillName]) {
// Only add if doesn't exist (preserve user customizations)
result[pluginName].skills[skillName] = skillConfig;
}
}
}
// Add new hooks
if (pluginDefaults.hooks) {
result[pluginName].hooks = result[pluginName].hooks || {};
for (const [hookName, hookConfig] of Object.entries(
pluginDefaults.hooks,
)) {
if (!result[pluginName].hooks[hookName]) {
// Only add if doesn't exist (preserve user customizations)
result[pluginName].hooks[hookName] = hookConfig;
}
}
}
}
}
return result;
}
```
### Step 4: Generate Configuration
**Discover all plugin defaults:**
1. Find all `plugins/*/super-claude-config.json` files in the repository
2. Extract `skills` and `hooks` from each plugin's config
3. Build a map of plugin-name → { skills, hooks }
**Generate the configuration file:**
Use this EXACT template structure - do NOT modify the `$schema` path or repo URL:
```json
{
"$schema": "../../.claude-plugin/super-claude-config.schema.json",
"_comment": [
"Super Claude Plugin Configuration",
"",
"This file controls plugin behavior for this project.",
"Configuration priority: this file > plugin defaults > environment variables",
"",
"Common customizations:",
" • Disable a skill: Set 'enabled': false",
" • Change protected branches: Modify workflow.hooks.gitCommitGuard.protectedBranches",
" • Add branch prefixes: Modify workflow.hooks.branchNameValidator.allowedPrefixes",
" • Customize triggers: Add/modify 'keywords' or 'patterns' arrays",
"",
"Changes take effect immediately (no restart needed).",
"Documentation: https://github.com/jbabin91/super-claude"
],
"workflow": {
"skills": {},
"hooks": {}
},
"meta": {
"skills": {},
"hooks": {}
}
}
```
**CRITICAL: Merge discovered defaults into this template structure:**
1. For each plugin discovered, add a top-level key with that plugin's name
2. Populate `skills` and `hooks` from the discovered defaults
3. Keep the `$schema` and `_comment` exactly as shown above
4. Format with Prettier using these rules:
- **NO blank lines between object properties**
- 2-space indentation
- Double quotes for strings
- Trailing commas where allowed
**Example after merging (if testing plugin discovered):**
```json
{
"$schema": "../../.claude-plugin/super-claude-config.schema.json",
"_comment": [
"Super Claude Plugin Configuration",
"",
"This file controls plugin behavior for this project.",
"Configuration priority: this file > plugin defaults > environment variables",
"",
"Common customizations:",
" • Disable a skill: Set 'enabled': false",
" • Change protected branches: Modify workflow.hooks.gitCommitGuard.protectedBranches",
" • Add branch prefixes: Modify workflow.hooks.branchNameValidator.allowedPrefixes",
" • Customize triggers: Add/modify 'keywords' or 'patterns' arrays",
"",
"Changes take effect immediately (no restart needed).",
"Documentation: https://github.com/jbabin91/super-claude"
],
"workflow": {
"skills": {},
"hooks": {
"gitCommitGuard": {
"enabled": false,
"protectedBranches": ["main", "master"],
"bypassEnvVar": "SKIP_COMMIT_GUARD"
},
"branchNameValidator": {
"enabled": false,
"allowedPrefixes": [
"feat",
"fix",
"chore",
"docs",
"test",
"refactor",
"perf",
"build",
"ci",
"revert",
"style"
],
"allowedBranches": ["main", "master", "develop"]
},
"typeChecker": {
"enabled": true,
"timeout": 2000
},
"sessionChecklist": {
"enabled": true
}
}
},
"meta": {
"skills": {
"skill-creator": {
"enabled": true,
"triggers": {
"keywords": ["create skill", "new skill", "skill development"],
"patterns": ["(create|add|generate|build).*?skill"]
}
},
"hook-creator": {
"enabled": true,
"triggers": {
"keywords": ["create hook", "new hook", "hook development"],
"patterns": ["(create|add|generate|build).*?hook"]
}
}
},
"hooks": {}
},
"testing": {
"skills": {
"test-runner": {
"enabled": true,
"triggers": {
"keywords": ["run tests", "test"],
"patterns": ["(run|execute).*?tests?"]
}
}
},
"hooks": {}
}
}
```
### Step 5: Show Summary
Provide clear feedback based on what was done:
**For clean slate generation:**
```txt
✓ Created .claude/super-claude-config.json
Configured ${pluginCount} plugins:
• workflow (${skillCount} skills, ${hookCount} hooks)
• meta (${skillCount} skills, ${hookCount} hooks)
...
Next steps:
1. Open .claude/super-claude-config.json
2. Customize settings for your project
3. Changes take effect immediately (no restart needed)
Common customizations:
• Disable skill: Set "enabled": false
• Change protected branches: Modify workflow.hooks.gitCommitGuard.protectedBranches
• Add branch prefixes: Modify workflow.hooks.branchNameValidator.allowedPrefixes
Documentation: See docs/guides/plugin-configuration.md
```
**For migration:**
```txt
✓ Migrated legacy configuration
Actions taken:
• Created backup: .claude/skills/skill-rules.json.bak
• Migrated overrides → .claude/super-claude-config.json
• Merged with plugin defaults
Your customizations were preserved:
- meta/skill-creator: disabled
- Custom triggers for hook-creator
You can safely delete .claude/skills/skill-rules.json after verification.
The new config will be loaded automatically.
```
**For update:**
```txt
✓ Updated .claude/super-claude-config.json
Added new defaults:
+ Plugin: testing (3 skills, 2 hooks)
+ Hook: workflow/sessionChecklist
+ Hook: workflow/typeChecker
Your existing customizations were preserved:
- workflow/gitCommitGuard.protectedBranches: ["main", "production"]
- meta/skill-creator.enabled: false
```
**For up-to-date:**
```txt
✓ Configuration is up to date
All ${pluginCount} installed plugins are configured.
No new defaults available.
To reset to plugin defaults: Delete .claude/super-claude-config.json and run this command again.
```
## Error Handling
1. **Cannot create .claude/ directory**
- Check permissions
- Suggest: `chmod +w .claude`
2. **Plugin defaults not found**
- List plugins with missing configs
- Suggest: Check plugin installation
3. **Invalid JSON in existing config**
- Show parse error
- Offer to backup and regenerate
4. **File write fails**
- Show specific error
- Check disk space and permissions
## Important Notes
- **Always preserve user customizations** - Never overwrite unless user explicitly confirms
- **Create backups** - Always create `.bak` files before modifying
- **Deep merge strategy** - User values always win over defaults
- **Idempotent** - Safe to run multiple times
- **No restart needed** - Config loader reads on every hook execution
## Testing Checklist
After implementation, verify:
- [ ] Clean slate generation works
- [ ] Legacy migration creates backup
- [ ] Update adds only new defaults
- [ ] Conflict resolution offers all choices
- [ ] User customizations are never lost
- [ ] AskUserQuestion shows clear options
- [ ] Summary messages are accurate
- [ ] Generated JSON is valid and formatted

View File

@@ -0,0 +1,160 @@
---
name: generate-skill-rules
description: Generate skill-rules.json entries from SKILL.md YAML frontmatter (for maintainers)
version: 1.0.0
---
# Generate Skill Rules
This command parses YAML frontmatter from SKILL.md files and generates `skill-rules.json` entries for the auto-activation system.
## Usage
```sh
/generate-skill-rules [options]
```
## What It Does
1. Scans for SKILL.md files in the specified directory
2. Parses YAML frontmatter to extract trigger information
3. Converts to skill-rules.json format
4. Outputs generated JSON to stdout or writes to file
## Options
- **--plugin** - Plugin directory to scan (default: current directory)
- **--namespace** - Plugin namespace (required if --write)
- **--write** - Write directly to skill-rules.json
- **--dry-run** - Output to stdout without writing (default)
## Examples
### Preview Generated Rules
```sh
/generate-skill-rules --plugin plugins/tanstack-tools --namespace tanstack
```
### Write to skill-rules.json
```sh
/generate-skill-rules --plugin plugins/api-tools --namespace api --write
```
## Instructions for Claude
When this command is invoked:
1. **Locate SKILL.md Files**
```sh
find {plugin-dir}/skills -name "SKILL.md" -type f
```
2. **Parse Each SKILL.md**
- Read YAML frontmatter (between `---` delimiters)
- Extract these fields:
- `name` → skill ID
- `description` → skill description
- `category` → determines skill type
- `triggers.keywords` → promptTriggers.keywords
- `triggers.patterns` → promptTriggers.intentPatterns
- `priority` (if present) → priority field
3. **Map Fields to skill-rules.json Schema**
```json
{
"plugin": {
"name": "{extracted-from-plugin-json}",
"version": "{extracted-from-plugin-json}",
"namespace": "{from-cli-arg-or-plugin-json}"
},
"skills": {
"{skill-name}": {
"type": "domain",
"enforcement": "suggest",
"priority": "{from-yaml-or-default-high}",
"description": "{from-yaml}",
"promptTriggers": {
"keywords": ["{from-yaml-triggers-keywords}"],
"intentPatterns": ["{from-yaml-triggers-patterns}"]
}
}
}
}
```
4. **Handle Edge Cases**
- Skills without triggers → create empty arrays
- Skills without priority → default to "high"
- Skills with category "guardrail" → type: "guardrail"
- All other categories → type: "domain"
5. **Validation**
- Check namespace is valid (lowercase, no spaces)
- Ensure skill names are kebab-case
- Validate regex patterns are valid
- Warn about missing required fields
6. **Output Format**
- **Dry run**: Print formatted JSON to stdout with guidance
- **Write mode**: Create/update `{plugin-dir}/skills/skill-rules.json`
- Include success message with file location
## Example YAML → JSON Conversion
**SKILL.md frontmatter:**
```yaml
---
name: skill-creator
description: Generate new Claude Code skills
category: workflow-automation
priority: high
triggers:
keywords:
- create skill
- new skill
- skill template
patterns:
- (create|add|generate).*?skill
- how to.*?create.*?skill
---
```
**Generated skill-rules.json entry:**
```json
{
"skill-creator": {
"type": "domain",
"enforcement": "suggest",
"priority": "high",
"description": "Generate new Claude Code skills",
"promptTriggers": {
"keywords": ["create skill", "new skill", "skill template"],
"intentPatterns": [
"(create|add|generate).*?skill",
"how to.*?create.*?skill"
]
}
}
}
```
## Success Criteria
- Successfully parses all SKILL.md files
- Generates valid JSON matching schema
- Handles skills without triggers gracefully
- Provides clear output and error messages
- Works for both dry-run and write modes
## Notes
- This is a maintainer tool for initial migration
- After migration, maintain skill-rules.json directly
- YAML triggers in SKILL.md can be removed after migration
- Always validate generated JSON with `/workflow:configure`

View File

@@ -0,0 +1,28 @@
---
name: openspec:apply
description: Implement an approved OpenSpec change and keep tasks in sync.
category: openspec
tags: [openspec, apply]
---
<!-- OPENSPEC:START -->
**Guardrails**
- Favor straightforward, minimal implementations first and add complexity only when it is requested or clearly required.
- Keep changes tightly scoped to the requested outcome.
- Refer to `openspec/AGENTS.md` (located inside the `openspec/` directory—run `ls openspec` or `openspec update` if you don't see it) if you need additional OpenSpec conventions or clarifications.
**Steps**
Track these steps as TODOs and complete them one by one.
1. Read `changes/<id>/proposal.md`, `design.md` (if present), and `tasks.md` to confirm scope and acceptance criteria.
2. Work through tasks sequentially, keeping edits minimal and focused on the requested change.
3. Confirm completion before updating statuses—make sure every item in `tasks.md` is finished.
4. Update the checklist after all work is done so each task is marked `- [x]` and reflects reality.
5. Reference `openspec list` or `openspec show <item>` when additional context is required.
**Reference**
- Use `openspec show <id> --json --deltas-only` if you need additional context from the proposal while implementing.
<!-- OPENSPEC:END -->

View File

@@ -0,0 +1,36 @@
---
name: openspec:archive
description: Archive a deployed OpenSpec change and update specs.
category: openspec
tags: [openspec, archive]
---
<!-- OPENSPEC:START -->
**Guardrails**
- Favor straightforward, minimal implementations first and add complexity only when it is requested or clearly required.
- Keep changes tightly scoped to the requested outcome.
- Refer to `openspec/AGENTS.md` (located inside the `openspec/` directory—run `ls openspec` or `openspec update` if you don't see it) if you need additional OpenSpec conventions or clarifications.
**Steps**
1. Determine the change ID to archive:
- If this prompt already includes a specific change ID (for example inside a `<ChangeId>` block populated by slash-command arguments), use that value after trimming whitespace.
- If the conversation references a change loosely (for example by title or summary), run `openspec list` to surface likely IDs, share the relevant candidates, and confirm which one the user intends.
- Otherwise, review the conversation, run `openspec list`, and ask the user which change to archive; wait for a confirmed change ID before proceeding.
- If you still cannot identify a single change ID, stop and tell the user you cannot archive anything yet.
2. Validate the change ID by running `openspec list` (or `openspec show <id>`) and stop if the change is missing, already archived, or otherwise not ready to archive.
3. Run `openspec archive <id> --yes` so the CLI moves the change and applies spec updates without prompts (use `--skip-specs` only for tooling-only work).
4. Review the command output to confirm the target specs were updated and the change landed in `changes/archive/`.
5. **Update CHANGELOG.md** - Add entry under appropriate version (Unreleased or next version) and category:
- **Added** - New skills/features
- **Changed** - Modified existing functionality
- **Fixed** - Bug fixes
6. Validate with `openspec validate --strict` and inspect with `openspec show <id>` if anything looks off.
**Reference**
- Use `openspec list` to confirm change IDs before archiving.
- Inspect refreshed specs with `openspec list --specs` and address any validation issues before handing off.
<!-- OPENSPEC:END -->

View File

@@ -0,0 +1,162 @@
---
name: openspec:checkpoint
description: Save current progress and context to design.md.
category: openspec
tags: [openspec, checkpoint, save]
---
<!-- OPENSPEC:START -->
**Purpose**
This command saves your current progress as a checkpoint in design.md. It's the equivalent of the Reddit post's "checkpoint" concept - preserving context so you can resume work later without losing your train of thought.
**When to Use**
- Before taking a break or ending a session
- After completing a significant subtask
- When you've made important decisions or discoveries
- Before switching to a different change
- Regularly during long work sessions (every 30-60 minutes)
**Steps**
1. **Check for active change**
- Read `openspec/active.json`
- If no active change: "No active change. Use /openspec:work to start working on a change first."
- Exit if no active change
2. **Gather current context**
- Ask user to summarize current progress:
```txt
Let's save a checkpoint. Please provide:
1. What did you just complete?
2. What are you working on now?
3. What's next?
4. Any blockers or decisions made?
(You can provide a brief summary or detailed notes)
```
3. **Load existing design.md**
- Path: `openspec/changes/<change-id>/design.md`
- If doesn't exist, create with initial structure:
```markdown
# Design: <change-id>
## Overview
(Brief description of the approach)
## Progress Log
### Checkpoint: <ISO 8601 timestamp>
(User's progress notes)
```
- If exists, append new checkpoint section
4. **Append checkpoint to design.md**
- Add new section at the end:
```markdown
### Checkpoint: <ISO 8601 timestamp>
**Completed:**
- (what user completed)
**Current:**
- (what user is working on)
**Next:**
- (what's next)
**Notes:**
- (any blockers/decisions)
```
5. **Update tasks.md if needed**
- Ask user: "Any tasks to mark complete in tasks.md? (y/n)"
- If yes, ask which task numbers to mark with `[x]`
- Update tasks.md with completed tasks
6. **Update active.json**
- Update `lastCheckpoint` field to current timestamp:
```json
{
"change": "<change-id>",
"started": "<original timestamp>",
"lastCheckpoint": "<current ISO 8601 timestamp>"
}
```
7. **Confirm checkpoint saved**
```txt
✓ Checkpoint saved to design.md
Updated:
- design.md: Added progress notes
- tasks.md: Marked <X> tasks complete
- active.json: Updated lastCheckpoint
You can safely resume this work later. The SessionStart hook will load this context automatically.
Use /openspec:status to see current progress.
```
**Error Handling**
- If no active change: Guide user to use /openspec:work first
- If design.md write fails: Show error and suggest checking file permissions
- If tasks.md parsing fails: Skip task updates but still save checkpoint
**Example Usage**
**Scenario 1: Quick checkpoint**
```txt
User: /openspec:checkpoint
Assistant: Let's save a checkpoint. Please provide:
1. What did you just complete?
2. What are you working on now?
3. What's next?
User: Just finished the theme provider. Working on the toggle component now. Next is localStorage persistence.
Assistant: [Appends to design.md]
[Updates active.json]
✓ Checkpoint saved
```
**Scenario 2: Checkpoint with task updates**
```txt
User: /openspec:checkpoint
Assistant: Let's save a checkpoint...
User: Completed theme context and provider setup
Assistant: Any tasks to mark complete in tasks.md? (y/n)
User: y
Assistant: Which task numbers? (e.g., 1,3,5)
User: 1,2
Assistant: [Updates tasks.md: marks tasks 1 and 2 complete]
[Appends checkpoint to design.md]
✓ Checkpoint saved. 2 tasks marked complete.
```
**Notes**
- design.md acts as a "living doc" that grows with the project
- Checkpoints create a timeline of progress and decisions
- The SessionStart hook reads design.md to restore context
- This is inspired by diet103's "context.md" approach from Reddit
- Unlike git commits, checkpoints capture thought process and decisions
<!-- OPENSPEC:END -->

149
commands/openspec/done.md Normal file
View File

@@ -0,0 +1,149 @@
---
name: openspec:done
description: Complete and archive an OpenSpec change.
category: openspec
tags: [openspec, done, archive, complete]
---
<!-- OPENSPEC:START -->
**Purpose**
This command finalizes your work on an OpenSpec change:
- Verifies all tasks are complete
- Archives the change proposal
- Updates CHANGELOG.md
- Clears the active change tracker
- Guides you to commit the changes
**Steps**
1. **Check for active change**
- Read `openspec/active.json`
- If no active change: "No active change. Use /openspec:work to start working on a change first."
- Exit if no active change
2. **Verify all tasks complete**
- Read `openspec/changes/<change-id>/tasks.md`
- Count incomplete tasks (lines with `- [ ]`)
- If any incomplete:
```txt
⚠️ Not all tasks are complete!
Remaining tasks: <X>
- (list first 5 incomplete tasks)
Options:
1. Continue anyway and mark as done (not recommended)
2. Cancel and finish remaining tasks
3. Save checkpoint and resume later (/openspec:checkpoint)
What would you like to do?
```
- Wait for user decision
3. **Final checkpoint**
- Ask user: "Would you like to save a final checkpoint before archiving? (y/n)"
- If yes, run /openspec:checkpoint workflow
- This captures final state in design.md
4. **Run OpenSpec archive**
- Execute: `openspec archive <change-id>`
- This moves the change to archived folder with timestamp
- Updates specs/ folder with approved changes
- Shows success message from OpenSpec CLI
5. **Clear active change tracker**
- Delete or clear `openspec/active.json`:
```json
{}
```
- Or delete the file entirely
6. **Guide CHANGELOG update**
- Show message:
```txt
✓ Change archived successfully!
Next steps:
1. Review the changes made by OpenSpec
2. Update CHANGELOG.md with this change:
## [Unreleased]
### Added
- **<change-id>** - <brief description>
3. Commit all changes:
git add .
git commit -m "feat: <change description>"
4. The change is now archived in:
openspec/changes/<timestamp>-<change-id>/
Use /openspec:work to start on the next change.
```
7. **Show OpenSpec view**
- Run `openspec view` to show updated dashboard
- Confirms change is archived and specs are updated
**Error Handling**
- If no active change: Guide user to use /openspec:work
- If openspec archive fails: Show error and suggest checking change validity
- If CHANGELOG.md doesn't exist: Create it with standard format
- If active.json clear fails: Warn but continue (non-critical)
**Example Usage**
**Scenario 1: All tasks complete**
```txt
User: /openspec:done
Assistant: [Checks tasks.md - all complete ✓]
Would you like to save a final checkpoint? (y/n)
User: y
Assistant: [Runs checkpoint flow]
[Runs openspec archive add-dark-mode]
[Clears active.json]
✓ Change archived successfully!
[Shows next steps]
```
**Scenario 2: Tasks incomplete**
```txt
User: /openspec:done
Assistant: ⚠️ Not all tasks are complete!
Remaining tasks: 3
- [ ] Add localStorage persistence
- [ ] Write tests for theme toggle
- [ ] Update documentation
Options:
1. Continue anyway (not recommended)
2. Cancel and finish tasks
3. Save checkpoint and resume later
What would you like to do?
User: 2
Assistant: Cancelled. Use /openspec:status to see remaining work.
```
**Notes**
- This command wraps `openspec archive` with pre/post checks
- Clears active.json so SessionStart hook doesn't load old context
- Encourages final checkpoint for documentation
- Guides user through commit process
- Ensures clean state for starting next change
<!-- OPENSPEC:END -->

145
commands/openspec/init.md Normal file
View File

@@ -0,0 +1,145 @@
---
name: openspec:init
description: Initialize OpenSpec directory structure in your project without duplicating slash commands.
category: openspec
tags: [openspec, setup, init]
---
# OpenSpec Init Command
Initialize OpenSpec directory structure in your project without duplicating slash commands.
## Purpose
Creates the `openspec/` directory structure (specs, changes, AGENTS.md, project.md) while avoiding conflicts with the workflow plugin's enhanced OpenSpec commands.
## Usage
This command should be run **once per project** when you first want to use OpenSpec.
## What This Command Does
1. **Validates openspec CLI is installed**
- Check if `openspec` command is available
- If not, provide installation instructions
2. **Runs `openspec init --tools none`**
- Creates `openspec/` directory structure
- Creates `openspec/AGENTS.md` (OpenSpec workflow instructions)
- Creates `openspec/project.md` (project context template)
- Creates `openspec/changes/` (for proposals)
- Creates `openspec/specs/` (for specifications)
- Creates root `AGENTS.md` (agent instructions)
- Does NOT create `.claude/commands/` (prevents duplication)
3. **Explains next steps**
- How to fill out `openspec/project.md`
- How to use OpenSpec slash commands from this plugin
- How to create first change proposal
## Why `--tools none`?
The workflow plugin provides **enhanced OpenSpec commands** with additional context and customization:
- `/openspec:proposal` - Create new change proposals
- `/openspec:work` - Start working on a proposal with full context loading
- `/openspec:apply` - Implement approved proposals with task tracking
- `/openspec:checkpoint` - Save progress and context
- `/openspec:status` - Show current proposal status
- `/openspec:done` - Complete and prepare for archiving
- `/openspec:archive` - Archive completed changes
Using `--tools none` prevents OpenSpec CLI from creating duplicate basic commands, ensuring you get the full enhanced experience from this plugin.
## Implementation
```bash
# Get current working directory first for cleaner checks
PROJECT_DIR=$(pwd)
# Check if already initialized - exit early with helpful message
if [ -d "$PROJECT_DIR/openspec" ]; then
echo "✅ OpenSpec is already initialized in this project!"
echo ""
echo "📂 Current structure:"
echo " openspec/"
echo " ├── AGENTS.md"
echo " ├── project.md"
echo " ├── changes/"
echo " └── specs/"
echo ""
echo "💡 Useful commands:"
echo " /openspec:update - Update instruction files to latest"
echo " /openspec:proposal - Create a new change proposal"
echo " /openspec:status - Check current proposal status"
echo ""
echo "🔧 To reinitialize (advanced):"
echo " 1. Remove openspec/ directory manually"
echo " 2. Run /openspec:init again"
echo ""
exit 0
fi
# Check if openspec is installed
if ! command -v openspec &> /dev/null; then
echo "Error: openspec CLI not found"
echo ""
echo "Install with:"
echo " npm install -g @jsdocs-io/openspec"
echo " # or"
echo " pnpm add -g @jsdocs-io/openspec"
echo " # or"
echo " yarn global add @jsdocs-io/openspec"
exit 1
fi
# Initialize OpenSpec without tool-specific commands
echo "Initializing OpenSpec in: $PROJECT_DIR"
echo ""
openspec init "$PROJECT_DIR" --tools none
# Check if successful
if [ $? -eq 0 ]; then
echo ""
echo "✅ OpenSpec initialized successfully!"
echo ""
echo "📂 Created structure:"
echo " openspec/"
echo " ├── AGENTS.md # OpenSpec workflow instructions"
echo " ├── project.md # Project context (fill this out!)"
echo " ├── changes/ # Change proposals"
echo " └── specs/ # Specifications"
echo ""
echo "🎯 Next steps:"
echo ""
echo "1. Fill out project context:"
echo " 'Please read openspec/project.md and help me fill it out"
echo " with details about my project, tech stack, and conventions'"
echo ""
echo "2. Create your first proposal:"
echo " 'I want to add [FEATURE]. Please create an OpenSpec change"
echo " proposal using /openspec:proposal'"
echo ""
echo "3. Available commands from workflow plugin:"
echo " /openspec:proposal - Create new proposal"
echo " /openspec:work - Start working on proposal"
echo " /openspec:apply - Implement approved proposal"
echo " /openspec:checkpoint - Save progress"
echo " /openspec:status - Show current status"
echo " /openspec:done - Mark proposal complete"
echo " /openspec:archive - Archive completed proposal"
echo ""
else
echo ""
echo "❌ OpenSpec initialization failed"
echo "Check the error messages above"
exit 1
fi
```
## Notes
- **Run once per project** - Not needed in every session
- **Safe to re-run** - Will ask before overwriting existing structure
- **No conflicts** - Won't create duplicate commands (uses `--tools none`)
- **Enhanced commands** - You get our customized OpenSpec workflow from the plugin

View File

@@ -0,0 +1,32 @@
---
name: openspec:proposal
description: Scaffold a new OpenSpec change and validate strictly.
category: openspec
tags: [openspec, change]
---
<!-- OPENSPEC:START -->
**Guardrails**
- Favor straightforward, minimal implementations first and add complexity only when it is requested or clearly required.
- Keep changes tightly scoped to the requested outcome.
- Refer to `openspec/AGENTS.md` (located inside the `openspec/` directory—run `ls openspec` or `openspec update` if you don't see it) if you need additional OpenSpec conventions or clarifications.
- Identify any vague or ambiguous details and ask the necessary follow-up questions before editing files.
**Steps**
1. Review `openspec/project.md`, run `openspec list` and `openspec list --specs`, and inspect related code or docs (e.g., via `rg`/`ls`) to ground the proposal in current behavior; note any gaps that require clarification.
2. Choose a unique verb-led `change-id` and scaffold `proposal.md`, `tasks.md`, and `design.md` (when needed) under `openspec/changes/<id>/`.
3. Map the change into concrete capabilities or requirements, breaking multi-scope efforts into distinct spec deltas with clear relationships and sequencing.
4. Capture architectural reasoning in `design.md` when the solution spans multiple systems, introduces new patterns, or demands trade-off discussion before committing to specs.
5. Draft spec deltas in `changes/<id>/specs/<capability>/spec.md` (one folder per capability) using `## ADDED|MODIFIED|REMOVED Requirements` with at least one `#### Scenario:` per requirement and cross-reference related capabilities when relevant.
6. Draft `tasks.md` as an ordered list of small, verifiable work items that deliver user-visible progress, include validation (tests, tooling), and highlight dependencies or parallelizable work.
7. Validate with `openspec validate <id> --strict` and resolve every issue before sharing the proposal.
**Reference**
- Use `openspec show <id> --json --deltas-only` or `openspec show <spec> --type spec` to inspect details when validation fails.
- Search existing requirements with `rg -n "Requirement:|Scenario:" openspec/specs` before writing new ones.
- Explore the codebase with `rg <keyword>`, `ls`, or direct file reads so proposals align with current implementation realities.
<!-- OPENSPEC:END -->

104
commands/openspec/status.md Normal file
View File

@@ -0,0 +1,104 @@
---
name: openspec:status
description: Show current OpenSpec change status and progress.
category: openspec
tags: [openspec, status, progress]
---
<!-- OPENSPEC:START -->
**Purpose**
This command shows the current state of your OpenSpec work:
- Which change you're actively working on
- Progress on tasks (completed vs remaining)
- Time since you started and last checkpoint
- Quick access to the OpenSpec dashboard
**Steps**
1. **Check for active change**
- Read `openspec/active.json`
- If file doesn't exist or is empty: "No active change. Use /openspec:work to start working on a change."
- Exit if no active change
2. **Parse active change data**
- Extract: `change` (change ID), `started` (timestamp), `lastCheckpoint` (timestamp)
- Calculate time elapsed since started and last checkpoint
3. **Run OpenSpec dashboard**
- Execute `openspec view` to get current state of all changes
- This shows the progress bars and task counts
4. **Load task progress**
- Read `openspec/changes/<change-id>/tasks.md`
- Count total tasks (lines starting with `- [ ]` or `- [x]`)
- Count completed tasks (lines starting with `- [x]`)
- Calculate percentage: `(completed / total) * 100`
5. **Display status summary**
```txt
📊 OpenSpec Status
Active Change: <change-id>
Started: <X hours/days ago>
Last Checkpoint: <Y minutes/hours ago>
Progress:
├─ Tasks: <completed>/<total> (<percentage>%)
├─ Status: <In Progress|Blocked|Ready for Review>
└─ Next: <first incomplete task from tasks.md>
Recent Context (from design.md):
<last 5-10 lines of design.md to show recent decisions/progress>
Commands:
- /openspec:checkpoint - Save current progress
- /openspec:work - Switch to different change
- /openspec:done - Complete and archive
```
6. **Show OpenSpec dashboard**
- Output result of `openspec view` for full context
**Error Handling**
- If active.json exists but change directory missing: "Active change '<change-id>' not found. It may have been archived. Use /openspec:work to select a new change."
- If tasks.md missing: Show "0/0 tasks (no tasks.md found)"
- If design.md missing: Skip "Recent Context" section
**Example Usage**
```txt
User: /openspec:status
Assistant:
📊 OpenSpec Status
Active Change: add-dark-mode
Started: 2 hours ago
Last Checkpoint: 15 minutes ago
Progress:
├─ Tasks: 8/12 (67%)
├─ Status: In Progress
└─ Next: Implement theme toggle in settings page
Recent Context (from design.md):
- Created ThemeContext with light/dark modes
- Added theme provider to root layout
- Implemented CSS variable system for colors
- Need to add persistence with localStorage
[openspec view output shown]
```
**Notes**
- This command is read-only - it doesn't modify anything
- Useful for quick progress checks without reading all files
- Shows "at a glance" summary before diving into details
- Complements `openspec view` with active change focus
<!-- OPENSPEC:END -->

122
commands/openspec/update.md Normal file
View File

@@ -0,0 +1,122 @@
---
name: openspec:update
description: Update OpenSpec instruction files to the latest version without affecting slash commands.
category: openspec
tags: [openspec, setup, update]
---
# OpenSpec Update Command
Update OpenSpec instruction files to the latest version without affecting slash commands.
## Purpose
Refreshes OpenSpec workflow documentation (AGENTS.md files) when the OpenSpec CLI is updated, ensuring you have the latest best practices and patterns.
## Usage
Run this command after updating the OpenSpec CLI to get the latest instruction files:
```bash
# Update OpenSpec CLI first
npm update -g @jsdocs-io/openspec
# Then refresh instruction files
/openspec-update
```
## What This Command Does
1. **Validates openspec CLI is installed**
- Checks if `openspec` command is available
- Shows current version
2. **Runs `openspec update`**
- Updates `openspec/AGENTS.md` (OpenSpec workflow instructions)
- Updates root `AGENTS.md` (if it exists)
- **Does NOT touch slash commands** (we maintain our own enhanced versions)
3. **Shows what was updated**
- Lists files that changed
- Explains what's new (if possible)
## Safety
This command is **safe to run repeatedly**:
- ✅ Updates instruction files only
- ✅ Won't override workflow plugin commands
- ✅ Won't modify your specs or changes
- ✅ Won't affect project configuration
## When to Run
- After updating OpenSpec CLI to a new version
- When you want the latest OpenSpec patterns and best practices
- After reading OpenSpec release notes mentioning instruction updates
## Implementation
```bash
# Check if openspec is installed
if ! command -v openspec &> /dev/null; then
echo "Error: openspec CLI not found"
echo ""
echo "Install with:"
echo " npm install -g @jsdocs-io/openspec"
echo " # or"
echo " pnpm add -g @jsdocs-io/openspec"
echo " # or"
echo " yarn global add @jsdocs-io/openspec"
exit 1
fi
# Show current version
OPENSPEC_VERSION=$(openspec --version 2>&1 || echo "unknown")
echo "OpenSpec CLI version: $OPENSPEC_VERSION"
echo ""
# Get current working directory
PROJECT_DIR=$(pwd)
# Check if initialized
if [ ! -d "$PROJECT_DIR/openspec" ]; then
echo "Error: OpenSpec not initialized in this project"
echo ""
echo "Run /openspec-init first to set up OpenSpec"
exit 1
fi
# Update instruction files
echo "Updating OpenSpec instruction files in: $PROJECT_DIR"
echo ""
openspec update "$PROJECT_DIR"
# Check if successful
if [ $? -eq 0 ]; then
echo ""
echo "✅ OpenSpec instruction files updated successfully!"
echo ""
echo "📝 Updated files:"
echo " openspec/AGENTS.md # Latest workflow instructions"
echo " AGENTS.md # Updated agent guidance"
echo ""
echo "💡 Note:"
echo " Slash commands (/openspec:*) are managed by the workflow plugin"
echo " and are NOT affected by this update. You're using enhanced versions"
echo " customized for Claude Code."
echo ""
else
echo ""
echo "❌ Update failed"
echo "Check the error messages above"
exit 1
fi
```
## Notes
- **Safe to run anytime** - Won't break existing work
- **No command conflicts** - Won't override workflow plugin commands
- **Version aware** - Get instructions matching your CLI version
- **Preserves customization** - Your specs and changes untouched

101
commands/openspec/work.md Normal file
View File

@@ -0,0 +1,101 @@
---
name: openspec:work
description: Start working on an OpenSpec change with full context loading.
category: openspec
tags: [openspec, work, context]
---
<!-- OPENSPEC:START -->
**Purpose**
This command helps you start or resume work on an OpenSpec change proposal. It:
- Shows the OpenSpec dashboard with all changes
- Loads the change context (proposal, design, tasks)
- Tracks the active change for session persistence
- Enables automatic context loading on session resume
**Steps**
1. **Show OpenSpec dashboard**
- Run `openspec view` to display all changes with progress
- Output the dashboard so user can see status
2. **Select change to work on**
- Ask user: "Which change would you like to work on? (provide change ID)"
- Change ID is the folder name in `openspec/changes/`
- Example: `add-dark-mode`, `fix-auth-bug`, `refactor-api`
3. **Verify change exists**
- Check that `openspec/changes/<change-id>/` directory exists
- If not found, show error: "Change '<change-id>' not found. Run 'openspec view' to see available changes."
- Exit if not found
4. **Load change context**
- Read and display key files in this order:
- `openspec/changes/<change-id>/proposal.md` - The WHY (goals, motivation)
- `openspec/changes/<change-id>/design.md` - The HOW (living doc with approach)
- `openspec/changes/<change-id>/tasks.md` - The WHAT (checklist of work)
- If design.md doesn't exist, note: "No design.md yet. Create one to track your approach and decisions."
5. **Update active change tracker**
- Write to `openspec/active.json`:
```json
{
"change": "<change-id>",
"started": "<ISO 8601 timestamp>",
"lastCheckpoint": "<ISO 8601 timestamp>"
}
```
- Use JavaScript/TypeScript Date: `new Date().toISOString()`
6. **Confirm and guide next steps**
- Show success message:
```txt
✓ Now working on: <change-id>
Context loaded:
- Proposal: <brief summary from proposal.md>
- Tasks: <X> remaining, <Y> completed
Next steps:
1. Review the proposal and design above
2. Work through tasks in tasks.md sequentially
3. Use /openspec:checkpoint to save progress
4. Use /openspec:status to check progress anytime
5. Use /openspec:done when all tasks complete
The SessionStart hook will automatically load this context if you resume later.
```
**Error Handling**
- If `openspec` CLI not found: "OpenSpec CLI not installed. Run 'npm install -g @fission-codes/openspec'"
- If no changes exist: "No OpenSpec changes found. Create one with /openspec:proposal"
- If `openspec/` directory doesn't exist: Show error (should be created by 'openspec init')
- If active.json write fails: Show error but continue (non-critical)
**Example Usage**
```txt
User: /openspec:work
Assistant: [Runs openspec view, shows dashboard]
Which change would you like to work on? (provide change ID)
User: add-dark-mode
Assistant: [Loads proposal.md, design.md, tasks.md]
[Updates active.json]
[Shows success message with context summary]
```
**Notes**
- This command wraps `openspec view` and adds context loading
- The active.json file enables session resume via SessionStart hook
- design.md serves as the "living doc" (Reddit's context.md equivalent)
- Use /openspec:checkpoint frequently to update design.md with progress
<!-- OPENSPEC:END -->