Turn your corrections into reusable Claude Code Skills

version
1.0.0

Install

/plugin install skillfy@claude-code-skillfy

Run it inside Claude Code after adding the marketplace with /plugin marketplace add yhzion/claude-code-skillfy.

Contents

Discovered from source

Commands 5

/skillfy help

Show available Skillfy commands and current status.

Pre-execution Setup

Step 0: Environment Setup

set -euo pipefail
IFS=$'\n\t'

# Ensure UTF-8 locale for proper character handling
export LC_ALL=C.UTF-8 2>/dev/null || export LC_ALL=en_US.UTF-8 2>/dev/null || true

# Get project root (Git root or current directory as fallback)
PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
DB_PATH="$PROJECT_ROOT/.claude/skillfy/patterns.db"

if ! command -v sqlite3 &> /dev/null; then
  echo "❌ Error: sqlite3 is required but not installed."
  exit 1
fi

Flow

Step 1: Check Initialization Status

if [ ! -f "$DB_PATH" ]; then
  INITIALIZED=false
else
  INITIALIZED=true
fi

Step 2-A: Not Initialized Case

If INITIALIZED=false, display:

📚 Skillfy Help

Status: ⚠️ Not initialized

Commands:
  /skillfy init      Initialize Skillfy
  /skillfy help      Show this help

Quick Start:
  Run /skillfy init to get started.

Exit after displaying this message.

Step 2-B: Initialized Case

If INITIALIZED=true, query statistics:

# Query statistics
run_query() {
  result=$(sqlite3 "$DB_PATH" "$1" 2>/dev/null)
  if [ $? -ne 0 ]; then
    echo "0"
  else
    echo "${result:-0}"
  fi
}

TOTAL_PATTERNS=$(run_query "SELECT COUNT(*) FROM patterns;")
PROMOTED=$(run_query "SELECT COUNT(*) FROM patterns WHERE promoted = 1;")
PENDING=$(run_query "SELECT COUNT(*) FROM patterns WHERE promoted = 0;")

Step 3: Display Full Help

📚 Skillfy Help

Status: ✅ Initialized | Patterns: {TOTAL_PATTERNS} | Skills: {PROMOTED} | Pending: {PENDING}

Commands:
  /skillfy init      Initialize Skillfy
  /skillfy           Record an expectation mismatch
  /skillfy review    Promote patterns to Skills
  /skillfy reset     Delete all data
  /skillfy help      Show this help

Quick Start:
  1. /skillfy init → 2. /skillfy → 3. /skillfy review

💡 When Claude's output differs from your expectations, use /skillfy
   to record the mismatch. Then promote it to a Skill with /skillfy review.

Notes

  • This command is English-only (no locale/i18n)
  • Status information is only shown when initialized
  • Quick Start guide provides a simple workflow for new users

/skillfy init

Initialize the Skillfy system.

Execution Flow

Step 0: Dependency Check

# Bash strict mode for safer script execution
set -euo pipefail
IFS=$'\n\t'

# Ensure UTF-8 locale for proper character handling
export LC_ALL=C.UTF-8 2>/dev/null || export LC_ALL=en_US.UTF-8 2>/dev/null || true

# Get project root (Git root or current directory as fallback)
PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd)

# POSIX-compatible version comparison (returns 0 if $1 >= $2)
version_ge() {
  printf '%s\n%s' "$2" "$1" | awk -F. '
    NR==1 { split($0,a,"."); next }
    NR==2 { split($0,b,".")
      for(i=1; i<=3; i++) {
        if((b[i]+0) > (a[i]+0)) exit 0
        if((b[i]+0) < (a[i]+0)) exit 1
      }
      exit 0
    }'
}

# Check required dependencies
if ! command -v sqlite3 &> /dev/null; then
  echo "Error: sqlite3 is required but not installed."
  exit 1
fi

# SQLite 3.24.0+ required for compatibility
SQLITE_VERSION=$(sqlite3 --version 2>/dev/null | awk '{print $1}')
MIN_SQLITE_VERSION="3.24.0"
if ! version_ge "$SQLITE_VERSION" "$MIN_SQLITE_VERSION"; then
  echo "Error: SQLite $MIN_SQLITE_VERSION or higher required. Found: ${SQLITE_VERSION:-unknown}"
  exit 1
fi

Step 1: Check Existing Installation

# NOTE: Avoid exiting in strict mode when directory does not exist
test -d "$PROJECT_ROOT/.claude/skillfy" || true

Step 2: New Installation - User Confirmation

Ask the user for confirmation with a clear message:

Skillfy Initialization

This will create:
- .claude/skillfy/patterns.db (SQLite database for memos)
- .claude/skills/ directory (for promoted skills)

Options:
1. Initialize - Create new Skillfy database
2. Cancel

Which option? (1/2):

Wait for user response:

  • User responds "1" or "yes" or "init" → Proceed with initialization
  • User responds "2" or "cancel" → Exit with message: "Initialization cancelled."

On confirmation, execute Step 2-A, Step 2-B, and Step 2-C in order.

Step 2-A: Create Directories and Database

# Create directories (with error handling)
if ! mkdir -p "$PROJECT_ROOT/.claude/skillfy"; then
  echo "Error: Failed to create .claude/skillfy directory"
  exit 1
fi
mkdir -p "$PROJECT_ROOT/.claude/skills"

# Set secure permissions
chmod 700 "$PROJECT_ROOT/.claude/skillfy"           # Owner only: rwx
chmod 700 "$PROJECT_ROOT/.claude/skills"            # Owner only: rwx

# Create DB with inline schema (v1.0)
if ! sqlite3 "$PROJECT_ROOT/.claude/skillfy/patterns.db" <<'SCHEMA_EOF'
-- Skillfy SQLite Schema v1.0

-- Patterns table: User memos for skill promotion
-- No UNIQUE constraint - allows duplicate entries (memo purpose)
CREATE TABLE IF NOT EXISTS patterns (
  id          INTEGER PRIMARY KEY AUTOINCREMENT,
  situation   TEXT NOT NULL CHECK(length(situation) <= 500),
  expectation TEXT CHECK(length(expectation) <= 1000),
  instruction TEXT NOT NULL CHECK(length(instruction) <= 2000),
  created_at  DATETIME DEFAULT CURRENT_TIMESTAMP,
  promoted    INTEGER NOT NULL DEFAULT 0 CHECK(promoted IN (0, 1)),
  skill_path  TEXT
);

-- Schema version tracking
CREATE TABLE IF NOT EXISTS schema_version (
  version    TEXT PRIMARY KEY,
  applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Insert current schema version
INSERT OR IGNORE INTO schema_version (version) VALUES ('1.0');

-- Performance indexes
CREATE INDEX IF NOT EXISTS idx_patterns_promoted ON patterns(promoted);
CREATE INDEX IF NOT EXISTS idx_patterns_created_at ON patterns(created_at DESC);
SCHEMA_EOF
then
  rm -f "$PROJECT_ROOT/.claude/skillfy/patterns.db"
  echo "Error: Failed to create database"
  exit 1
fi

# Set secure permissions on DB file
chmod 600 "$PROJECT_ROOT/.claude/skillfy/patterns.db"     # Owner only: rw

Step 2-B: Update .gitignore (REQUIRED for Git projects)

IMPORTANT: This step MUST be executed for Git projects to prevent accidental commits of sensitive data.

# Update .gitignore (for Git projects)
if [ -d "$PROJECT_ROOT/.git" ]; then
  GITIGNORE_ENTRIES="
# Skillfy runtime data (auto-added by /skillfy init)
.claude/skillfy/
.claude/skillfy/*.db-journal
.claude/skillfy/*.db-wal
.claude/skillfy/*.db-shm"

  if [ -f "$PROJECT_ROOT/.gitignore" ]; then
    # .gitignore exists: append if not already present
    if ! grep -q ".claude/skillfy/" "$PROJECT_ROOT/.gitignore"; then
      echo "$GITIGNORE_ENTRIES" >> "$PROJECT_ROOT/.gitignore"
      echo ".gitignore updated with Skillfy entries"
    else
      echo ".gitignore already contains Skillfy entries"
    fi
  else
    # .gitignore does not exist: create new file
    echo "$GITIGNORE_ENTRIES" > "$PROJECT_ROOT/.gitignore"
    echo ".gitignore file created with Skillfy entries"
  fi
fi

Step 2-C: Verify .gitignore was updated

# Verify .gitignore contains skillfy entries
if [ -d "$PROJECT_ROOT/.git" ]; then
  if [ -f "$PROJECT_ROOT/.gitignore" ] && grep -q ".claude/skillfy/" "$PROJECT_ROOT/.gitignore"; then
    echo ".gitignore verification passed"
  else
    echo "Warning: .gitignore may not be properly configured"
  fi
fi

Step 3: When Already Exists

If .claude/skillfy directory exists (from Step 1), display:

Skillfy already exists

Current files:
- .claude/skillfy/patterns.db

Options:
1. Keep existing data - Exit without changes
2. Reinitialize - Delete all data and start fresh

Select option (1/2):

Wait for user response:

  • User responds "1" or "keep" → Exit with message: "Keeping existing installation."
  • User responds "2" or "reinitialize" → Execute cleanup and proceed to Step 2

Step 3-A: Reinitialize (cleanup)

rm -rf "$PROJECT_ROOT/.claude/skillfy"
echo "Existing data removed"
# Then proceed with new installation (Step 2)

Step 4: Completion Message

Skillfy initialization complete

- .claude/skillfy/patterns.db created
- .claude/skills/ directory created
- .gitignore updated (if Git project)

You can now record mismatches with /skillfy.
Use /skillfy review to promote saved patterns to skills.

/skillfy reset [--all]

⚠️ Deletes Skillfy data.

Usage

  • /skillfy reset - Delete database records only (skills preserved)
  • /skillfy reset --all - Delete everything: database, skills, and all Skillfy files

Pre-execution Setup

Step 0: Dependency and DB Check

set -euo pipefail
IFS=$'\n\t'

# Ensure UTF-8 locale for proper character handling
export LC_ALL=C.UTF-8 2>/dev/null || export LC_ALL=en_US.UTF-8 2>/dev/null || true

# Get project root (Git root or current directory as fallback)
PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
DB_PATH="$PROJECT_ROOT/.claude/skillfy/patterns.db"

if ! command -v sqlite3 &> /dev/null; then
  echo "❌ Error: sqlite3 is required but not installed."
  exit 1
fi

if [ ! -f "$DB_PATH" ]; then
  echo "❌ No data to reset."
  exit 1
fi

Flow

Step 1: Display Current Status

TOTAL_PATTERNS=$(sqlite3 "$DB_PATH" "SELECT COUNT(*) FROM patterns;" 2>/dev/null || echo "0")

Step 2: Determine Reset Mode and Count Skills

Check if --all argument was provided and count generated skills:

SKILL_COUNT=$(ls -1 "$PROJECT_ROOT/.claude/skills/skillfy-"* 2>/dev/null | wc -l | tr -d ' ') || SKILL_COUNT=0

# Count promoted skills (will become orphaned if data is reset without --all)
PROMOTED_COUNT=$(sqlite3 "$DB_PATH" "SELECT COUNT(*) FROM patterns WHERE promoted = 1;" 2>/dev/null || echo "0")

Step 3: Request Confirmation

Default mode (data only): Display the warning message:

⚠️ Skillfy Reset (Data Only)

Database file:
- {DB_PATH}

Data to delete:
- {TOTAL_PATTERNS} patterns

Note: Generated Skills (.claude/skills/) will be preserved.

If PROMOTED_COUNT > 0, also display an orphan skills warning:

⚠️ Orphan Skills Warning

{PROMOTED_COUNT} promoted Skill(s) will become orphaned:
- Skill files in .claude/skills/ will remain but lose their DB connection
- These skills will still work but cannot be managed via /skillfy commands

To completely remove everything including skills, use: /skillfy reset --all

Then ask the user for confirmation:

⚠️ Are you sure you want to delete all Skillfy data?
This action cannot be undone.

1. Yes, reset data - Delete all observations and patterns permanently
2. Cancel - Keep all data and exit

Confirm (1/2):

--all mode (complete reset): Display the warning message:

⚠️ Skillfy Complete Reset

This will delete EVERYTHING:
- Database file: {DB_PATH}
- {TOTAL_PATTERNS} patterns
- {SKILL_COUNT} generated skills (.claude/skills/)
- Skillfy directory

⚠️ This action cannot be undone!

Then ask the user for confirmation:

Are you sure you want to completely remove all Skillfy data and skills?

1. Yes, delete everything - Remove all data, skills, and files
2. Reset data only - Keep skills, delete database records
3. Cancel - Keep everything and exit

Confirm (1/2/3):

Step 4: User Choice Handling

Default mode:

  • User responds "1" or "yes" → Proceed to Step 5 (data deletion)
  • User responds "2" or "cancel" → Print "Reset cancelled." and exit

--all mode:

  • User responds "1" → Proceed to Step 5 (complete deletion)
  • User responds "2" → Proceed to Step 5 (data only deletion)
  • User responds "3" or "cancel" → Print "Reset cancelled." and exit

Step 5: Execute Deletion

Data only deletion:

# Clear data using transaction (safer than rm + recreate)
# Transaction ensures atomicity: on failure, data is preserved via rollback
if ! sqlite3 "$DB_PATH" <<SQL
BEGIN IMMEDIATE;
DELETE FROM patterns;
COMMIT;
SQL
then
  echo "Error: Failed to reset database"
  exit 1
fi

Complete deletion (--all mode, option 1):

# Remove all skills
rm -rf "$PROJECT_ROOT/.claude/skills" 2>/dev/null || true

# Remove database file
rm -f "$DB_PATH"

# Remove auto-detect flag (legacy cleanup)
rm -f "$PROJECT_ROOT/.claude/skillfy/auto-detect.enabled"

# Remove skillfy directory
rm -rf "$PROJECT_ROOT/.claude/skillfy" 2>/dev/null || true

Step 6: Completion Message

Data only:

Skillfy data has been reset

- Patterns: all deleted
- Skills: preserved (.claude/skills/)

Start new records with /skillfy.

Complete reset:

Skillfy completely removed

- Database: deleted
- Patterns: deleted
- Skills: deleted

Run /skillfy-init to start fresh.

/skillfy review

Review saved patterns and promote them to Skills.

Pre-execution Setup

Step 0: Dependency and DB Check

set -euo pipefail
IFS=$'\n\t'

# Ensure UTF-8 locale for proper character handling
export LC_ALL=C.UTF-8 2>/dev/null || export LC_ALL=en_US.UTF-8 2>/dev/null || true

# Get project root (Git root or current directory as fallback)
PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
DB_PATH="$PROJECT_ROOT/.claude/skillfy/patterns.db"
SKILL_OUTPUT_PATH="$PROJECT_ROOT/.claude/skills"

# POSIX-compatible version comparison (returns 0 if $1 >= $2)
version_ge() {
  printf '%s\n%s' "$2" "$1" | awk -F. '
    NR==1 { split($0,a,"."); next }
    NR==2 { split($0,b,".")
      for(i=1; i<=3; i++) {
        if((b[i]+0) > (a[i]+0)) exit 0
        if((b[i]+0) < (a[i]+0)) exit 1
      }
      exit 0
    }'
}

if ! command -v sqlite3 &> /dev/null; then
  echo "Error: sqlite3 is required but not installed."
  exit 1
fi

# SQLite 3.24.0+ required
SQLITE_VERSION=$(sqlite3 --version 2>/dev/null | awk '{print $1}')
MIN_SQLITE_VERSION="3.24.0"
if ! version_ge "$SQLITE_VERSION" "$MIN_SQLITE_VERSION"; then
  echo "Error: SQLite $MIN_SQLITE_VERSION or higher required. Found: ${SQLITE_VERSION:-unknown}"
  exit 1
fi

if [ ! -f "$DB_PATH" ]; then
  echo "Skillfy is not initialized. Run /skillfy init first."
  exit 1
fi

# ============================================================================
# Path Validation
# ============================================================================

# POSIX-compatible path resolution (macOS/Linux)
resolve_path() {
  local p="$1"
  # Try GNU realpath, then Python fallback for macOS compatibility
  realpath -m "$p" 2>/dev/null || python3 -c "import os; print(os.path.abspath('$p'))" 2>/dev/null || echo ""
}

# Path traversal protection: validate that a path is under allowed directory
validate_skill_path() {
  local path="$1"
  local resolved_path resolved_base

  # Resolve to absolute path and check it's under SKILL_OUTPUT_PATH
  resolved_path=$(resolve_path "$path")
  resolved_base=$(resolve_path "$SKILL_OUTPUT_PATH")

  if [ -z "$resolved_path" ] || [ -z "$resolved_base" ]; then
    return 1
  fi

  # Check path starts with base directory
  case "$resolved_path" in
    "$resolved_base"/*) return 0 ;;
    *) return 1 ;;
  esac
}

Flow

Step 1: Query Unpromoted Patterns

# Query all unpromoted patterns
# Columns: id, situation, instruction, expectation, created_at
CANDIDATES=$(sqlite3 -separator $'\t' "$DB_PATH" \
  "SELECT id, situation, instruction, expectation, created_at FROM patterns WHERE promoted = 0 ORDER BY created_at DESC LIMIT 50;" \
  2>/dev/null) || CANDIDATES=""

Step 2-A: No Candidates

No saved patterns found.

Use /skillfy to record patterns first.

Step 2-B: Candidates Found

Display the candidates list with selection options:

Saved Patterns (not yet promoted)

[id=12] When creating models -> Always include timestamp fields (2024-12-18)
[id=15] When writing API endpoints -> Always include error handling (2024-12-17)

Enter pattern id(s) to promote (comma-separated for multiple, or 'skip' to cancel):
Example: 12 or 12,15

Note: The list should be dynamically generated from the CANDIDATES query result.

Wait for user response:

  • User responds with id(s) (e.g., "12" or "12,15") → Parse and process each PATTERN_ID
  • User responds "skip" or "cancel" → Exit with message: "No patterns promoted."

Step 3: Load Pattern Details

For each selected PATTERN_ID:

# Validate id defensively
if ! [[ "$PATTERN_ID" =~ ^[0-9]+$ ]]; then
  echo "Error: Invalid pattern id '$PATTERN_ID'"
  exit 1
fi

ROW=$(sqlite3 -separator $'\t' "$DB_PATH" \
  "SELECT situation, instruction, expectation, created_at FROM patterns WHERE id = $PATTERN_ID AND promoted = 0;" \
  2>/dev/null) || ROW=""

if [ -z "$ROW" ]; then
  echo "Error: Pattern not found or already promoted (id=$PATTERN_ID)"
  exit 1
fi

IFS=$'\t' read -r SITUATION INSTRUCTION EXPECTATION CREATED_AT <<<"$ROW"

Step 4: Skill Preview and Confirmation

Display the skill preview:

Skill Preview: {situation}

---
name: {kebab-case situation}
description: {instruction}. Auto-applied in {situation} situations.
learned_from: skillfy ({created_at})
---

## Rules

{instruction}

## Applies to

- {situation}

## Learning History

This Skill was created from a saved pattern.
- Created: {created_at}
- Source: /skillfy memo

Then ask the user for confirmation:

What would you like to do with this skill?

1. Save skill (Recommended) - Create the skill file and activate it
2. Edit first - Modify the instruction before saving
3. Skip - Don't create this skill

Select action (1/2/3):

Wait for user response:

  • User responds "1" or "save" → Proceed to Step 5
  • User responds "2" or "edit" → Ask "Enter the modified instruction:" and wait for response, then proceed to Step 5
  • User responds "3" or "skip" → Skip this pattern and continue to next (if any)

Step 5: Skill Creation

On save selection:

# Generate Skill name (kebab-case) - Path Traversal prevention
SKILL_NAME=$(printf '%s' "$SITUATION" | tr '[:upper:]' '[:lower:]' | tr ' ' '-' | sed 's/[^a-z0-9-]//g')
# Collapse multiple consecutive hyphens and remove leading/trailing hyphens
SKILL_NAME=$(printf '%s' "$SKILL_NAME" | sed 's/-\{2,\}/-/g; s/^-//; s/-$//')
SKILL_NAME=$(printf '%s' "$SKILL_NAME" | cut -c1-50)
# Remove any trailing hyphen that might result from truncation
SKILL_NAME=$(printf '%s' "$SKILL_NAME" | sed 's/-$//')
if [ -z "$SKILL_NAME" ]; then
  SKILL_NAME="skill-$(date +%Y%m%d-%H%M%S)"
fi

# Handle skill name collisions atomically using mkdir
mkdir -p "$SKILL_OUTPUT_PATH"

MAX_SKILL_NAME_ATTEMPTS="${SKILLFY_MAX_NAME_ATTEMPTS:-100}"

BASE_SKILL_NAME="$SKILL_NAME"
SUFFIX=0
SKILL_DIR=""

while [ $SUFFIX -le $MAX_SKILL_NAME_ATTEMPTS ]; do
  if [ $SUFFIX -eq 0 ]; then
    CURRENT_NAME="$BASE_SKILL_NAME"
  else
    CURRENT_NAME="${BASE_SKILL_NAME}-${SUFFIX}"
  fi

  # Validate path before creation
  CURRENT_PATH="$SKILL_OUTPUT_PATH/$CURRENT_NAME"
  if ! validate_skill_path "$CURRENT_PATH"; then
    echo "Error: Invalid skill path detected (potential path traversal)"
    exit 1
  fi

  # mkdir (without -p) fails if directory exists - atomic check+create
  if mkdir "$CURRENT_PATH" 2>/dev/null; then
    SKILL_NAME="$CURRENT_NAME"
    SKILL_DIR="$CURRENT_PATH"
    break
  fi
  SUFFIX=$((SUFFIX + 1))
done

if [ -z "$SKILL_DIR" ]; then
  echo "Error: Failed to generate unique skill name after $MAX_SKILL_NAME_ATTEMPTS attempts"
  exit 1
fi

# Create skill file
CURRENT_DATE=$(date '+%Y-%m-%d %H:%M:%S')

cat > "$SKILL_DIR/SKILL.md" << SKILL_EOF
---
name: $SKILL_NAME
description: $INSTRUCTION. Auto-applied in $SITUATION situations.
learned_from: skillfy ($CREATED_AT)
---

## Rules

$INSTRUCTION

## Applies to

- $SITUATION

## Examples

### Do

(Add positive examples here)

### Don't

(Add negative examples here)

## Learning History

- Original created: $CREATED_AT
- Promoted to skill: $CURRENT_DATE
- Source: /skillfy review
SKILL_EOF

# SQL Injection prevention: escape single quotes
escape_sql() {
  printf '%s' "$1" | sed "s/'/''/g"
}
SAFE_SKILL_PATH=$(escape_sql "$SKILL_DIR/SKILL.md")

# Update database
if ! sqlite3 "$DB_PATH" "UPDATE patterns SET promoted = 1, skill_path = '$SAFE_SKILL_PATH' WHERE id = $PATTERN_ID;"; then
  echo "Warning: Skill file created but database update failed"
  echo "Skill path: $SKILL_DIR/SKILL.md"
fi

printf '\nSkill created: %s/SKILL.md\n\nRestart Claude Code to activate this skill.\n' "$SKILL_DIR"

Reference: Skill Name Conversion Rules

  • Space → hyphen
  • Uppercase → lowercase
  • Remove special characters
  • Example: "Model creation" → "model-creation"
  • Example: "API endpoint" → "api-endpoint"

/skillfy

Record patterns when Claude generates something different from expectations.

Notes

This command is English-only (no locale/i18n).

Pre-execution Setup

Step 0: Dependency and DB Check

set -euo pipefail
IFS=$'\n\t'

# Ensure UTF-8 locale for proper character handling
export LC_ALL=C.UTF-8 2>/dev/null || export LC_ALL=en_US.UTF-8 2>/dev/null || true

# Get project root (Git root or current directory as fallback)
PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
DB_PATH="$PROJECT_ROOT/.claude/skillfy/patterns.db"

# POSIX-compatible version comparison (returns 0 if $1 >= $2)
version_ge() {
  printf '%s\n%s' "$2" "$1" | awk -F. '
    NR==1 { split($0,a,"."); next }
    NR==2 { split($0,b,".")
      for(i=1; i<=3; i++) {
        if((b[i]+0) > (a[i]+0)) exit 0
        if((b[i]+0) < (a[i]+0)) exit 1
      }
      exit 0
    }'
}

if ! command -v sqlite3 &> /dev/null; then
  echo "Error: sqlite3 is required but not installed."
  exit 1
fi

SQLITE_VERSION=$(sqlite3 --version 2>/dev/null | awk '{print $1}')
MIN_SQLITE_VERSION="3.24.0"
if ! version_ge "$SQLITE_VERSION" "$MIN_SQLITE_VERSION"; then
  echo "Error: SQLite $MIN_SQLITE_VERSION or higher required. Found: ${SQLITE_VERSION:-unknown}"
  exit 1
fi

if [ ! -f "$DB_PATH" ]; then
  echo "Skillfy is not initialized. Run /skillfy init first."
  exit 1
fi

Recording Flow

Step 1: Session Context Analysis (Agent Introspection)

IMPORTANT: This step requires Agent introspection, not programmatic script execution.

Analyze the current conversation session to identify potential mismatches:

  1. Review recent interactions:

    • What did the user request?
    • How did Claude respond?
    • What tools were used (especially Bash)?
  2. Identify issues/mismatches:

    • Bash execution errors (exit code != 0)
    • Lint/type/build/test failures
    • User correction requests ("no", "not that", "try again", etc.)
    • Unexpected results or behaviors
  3. Rank identified issues by probability:

    • High: Clear error messages or explicit user corrections
    • Medium: Warnings or implicit dissatisfaction
    • Low: Inferred possibilities
  4. Generate dynamic options based on analysis:

    • Create 1-3 specific situation descriptions (50 chars max each)
    • Order by probability (highest first)
    • Always include "Enter manually" as the last option

Step 2: Situation Selection (Dynamic)

Use AskUserQuestion to present situation options to the user.

Option Generation Rules:

  • Minimum 1, maximum 3 specific options based on context analysis
  • Each option should be a concrete situation description
  • Last option is always "Enter manually"

If context analysis found issues, present like:

Recording Pattern Mismatch

What situation did this happen in?

1. {Most likely situation from analysis}
2. {Second most likely situation} (if applicable)
3. {Third situation} (if applicable)
4. Enter manually

Select:

If no clear issues found in context, present:

Recording Pattern Mismatch

What situation did this happen in?

1. Enter manually

Describe the situation:

On "Enter manually" selection, prompt:

Describe the situation (max 500 chars):
Example: "When creating a model", "When writing API endpoints"

Save user's selection or input as SITUATION.

Step 3: Expectation Selection (Dynamic)

Based on the selected SITUATION, generate expectation options.

Option Generation Rules:

  • Analyze what typically goes wrong in the selected situation
  • Create 1-3 specific expectation descriptions
  • Consider the context analysis from Step 1
  • Last option is always "Enter manually"

Present like:

What did you expect?

1. {Most likely expectation based on situation}
2. {Second expectation} (if applicable)
3. {Third expectation} (if applicable)
4. Enter manually

Select:

On "Enter manually" selection, prompt:

Describe what you expected (max 1000 chars):
Example: "Include timestamp field", "Use TypeScript interfaces"

Save user's selection or input as EXPECTATION.

Step 4: Instruction Selection (Dynamic)

Based on SITUATION + EXPECTATION, generate instruction options.

Option Generation Rules:

  • Instructions must be imperative form ("Always...", "Never...", "Include...")
  • Create 1-3 specific, actionable instructions
  • Last option is always "Enter manually"

Present like:

What rule should Claude learn? (imperative form)

1. {Most appropriate instruction}
2. {Second instruction} (if applicable)
3. {Third instruction} (if applicable)
4. Enter manually

Select:

On "Enter manually" selection, prompt:

Enter the instruction (imperative form, max 2000 chars):
Example: "Always include timestamp fields", "Never use var in JavaScript"

Save user's selection or input as INSTRUCTION.

Step 5: Summary and Final Action Selection

Display summary and ask for final action:

Record Summary

Situation: {SITUATION}
Expected: {EXPECTATION}
Instruction: {INSTRUCTION}

What would you like to do?

1. Register as Skill - Create skill file immediately (requires session restart to activate)
2. Save as memo - Store in DB for later review with /skillfy review
3. Cancel - Do nothing

Select (1/2/3):

Wait for user response and save as FINAL_ACTION.

Step 6: Input Validation

# Basic length checks (match DB CHECK constraints)
if [ ${#SITUATION} -eq 0 ] || [ ${#SITUATION} -gt 500 ]; then
  echo "Error: Situation must be 1-500 characters."
  exit 1
fi

if [ ${#EXPECTATION} -gt 1000 ]; then
  echo "Error: Expectation must be 0-1000 characters."
  exit 1
fi

if [ ${#INSTRUCTION} -eq 0 ] || [ ${#INSTRUCTION} -gt 2000 ]; then
  echo "Error: Instruction must be 1-2000 characters."
  exit 1
fi

Step 7: Execute Selected Action

Option 1: Register as Skill

# SQL Injection prevention: escape single quotes
escape_sql() {
  printf '%s' "$1" | sed "s/'/''/g"
}

PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
SKILL_OUTPUT_PATH="$PROJECT_ROOT/.claude/skills"

# Generate skill name from situation (kebab-case)
SKILL_NAME=$(printf '%s' "$SITUATION" | tr '[:upper:]' '[:lower:]' | tr ' ' '-' | sed 's/[^a-z0-9-]//g')
SKILL_NAME=$(printf '%s' "$SKILL_NAME" | sed 's/-\{2,\}/-/g; s/^-//; s/-$//')
SKILL_NAME=$(printf '%s' "$SKILL_NAME" | cut -c1-50 | sed 's/-$//')
if [ -z "$SKILL_NAME" ]; then
  SKILL_NAME="skill-$(date +%Y%m%d-%H%M%S)"
fi

# Create skill directory
mkdir -p "$SKILL_OUTPUT_PATH"
SKILL_DIR="$SKILL_OUTPUT_PATH/$SKILL_NAME"

# Handle name collision
SUFFIX=0
BASE_NAME="$SKILL_NAME"
while [ -d "$SKILL_DIR" ]; do
  SUFFIX=$((SUFFIX + 1))
  if [ "$SUFFIX" -gt 100 ]; then
    echo "Error: Too many skill name collisions"
    exit 1
  fi
  SKILL_NAME="${BASE_NAME}-${SUFFIX}"
  SKILL_DIR="$SKILL_OUTPUT_PATH/$SKILL_NAME"
done
mkdir "$SKILL_DIR"

# Generate skill file from template
CURRENT_DATE=$(date '+%Y-%m-%d %H:%M:%S')

# Escape for sed replacement
escape_sed() {
  printf '%s' "$1" | sed 's/[&/\]/\\&/g; s/$/\\n/' | tr -d '\n' | sed 's/\\n$//'
}

SAFE_SKILL_NAME=$(escape_sed "$SKILL_NAME")
SAFE_INSTRUCTION=$(escape_sed "$INSTRUCTION")
SAFE_SITUATION=$(escape_sed "$SITUATION")

# Create skill file
cat > "$SKILL_DIR/SKILL.md" << SKILL_EOF
---
name: $SKILL_NAME
description: $INSTRUCTION. Auto-applied in $SITUATION situations.
learned_from: skillfy ($CURRENT_DATE)
---

## Rules

$INSTRUCTION

## Applies to

- $SITUATION

## Examples

### Do

(Add positive examples here)

### Don't

(Add negative examples here)

## Learning History

- Created: $CURRENT_DATE
- Source: Manual recording via /skillfy
SKILL_EOF

# Also save to DB as promoted
SAFE_SITUATION_SQL=$(escape_sql "$SITUATION")
SAFE_EXPECTATION_SQL=$(escape_sql "$EXPECTATION")
SAFE_INSTRUCTION_SQL=$(escape_sql "$INSTRUCTION")
SAFE_SKILL_PATH=$(escape_sql "$SKILL_DIR/SKILL.md")

sqlite3 "$DB_PATH" <<SQL
INSERT INTO patterns (situation, expectation, instruction, promoted, skill_path)
VALUES ('$SAFE_SITUATION_SQL', '$SAFE_EXPECTATION_SQL', '$SAFE_INSTRUCTION_SQL', 1, '$SAFE_SKILL_PATH');
SQL

echo ""
echo "Skill created: $SKILL_DIR/SKILL.md"
echo ""
echo "Restart Claude Code to activate this skill."

Option 2: Save as Memo

escape_sql() {
  printf '%s' "$1" | sed "s/'/''/g"
}

SAFE_SITUATION=$(escape_sql "$SITUATION")
SAFE_EXPECTATION=$(escape_sql "$EXPECTATION")
SAFE_INSTRUCTION=$(escape_sql "$INSTRUCTION")

sqlite3 "$DB_PATH" <<SQL
INSERT INTO patterns (situation, expectation, instruction)
VALUES ('$SAFE_SITUATION', '$SAFE_EXPECTATION', '$SAFE_INSTRUCTION');
SQL

if [ $? -ne 0 ]; then
  echo "Error: Failed to save pattern"
  exit 1
fi

echo ""
echo "Pattern saved to database."
echo ""
echo "Use /skillfy review to view saved patterns and promote to skills."

Option 3: Cancel

Cancelled. No changes made.

Sponsors

Details

Marketplace
yhzion/claude-code-skillfy
Source
plugins/skillfy
Category
Productivity