mcpField
U
unix-goto-development

unix-goto-development

github.com/manutej開発62427 回インストール39 週間前に更新
リポジトリ

unix-goto-development について

unix-goto の開発・保守に取り組むコントリビューター向けのスキルです。モジュール構成、キャッシュ、機能追加の手順、テスト、ドキュメント、性能検証を説明します。

主な機能

  1. 01モジュール構成と読み込み順序
  2. 029段階の機能開発ワークフロー
  3. 03キャッシュとナビゲーションのパターン
  4. 04単体・結合・性能テスト
  5. 05API とユーザードキュメントの指針

活用シーン

  1. 01ブックマークや履歴コマンドの追加
  2. 02キャッシュを使ったディレクトリ移動の最適化
  3. 03ナビゲーションモジュール変更のテスト
  4. 04新しいシェルコマンドの文書化

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/manutej/luxor-claude-marketplace --skill unix-goto-development

インストール後、Claude Code で/unix-goto-developmentを入力して読み込まれたか確認します。

同梱ファイルREADME.md

詳細

unix-goto 開発エキスパート

unix-goto シェルナビゲーションシステムの包括的な開発エキスパートです。自然言語に対応し、キャッシュを利用したナビゲーションは 100 ミリ秒未満で、テストカバレッジ 100%を実現する、高性能な Unix ナビゲーションツールです。

このスキルを使用する場面

次のような場合に、このスキルを使用してください:

  • unix-goto シェルナビゲーションシステムの新機能を開発する
  • キャッシュベースのナビゲーション最適化を実装する
  • ブックマーク、履歴、ナビゲーションコマンドを追加する
  • 標準的な 9 ステップの機能追加ワークフローに従う
  • Linear のプロジェクト管理と連携する
  • 包括的なテストスイートを作成する(カバレッジ 100%が必須)
  • 100 ミリ秒未満の目標を満たすようパフォーマンスを最適化する
  • シェルモジュールの API ドキュメントを作成する
  • ナビゲーションやキャッシュの問題をデバッグする

次のような場合には、このスキルを使用しないでください:

  • 一般的な Bash スクリプトを書く場合(汎用の Bash スキルを使用してください)
  • ナビゲーション以外のシェルツールを扱う場合
  • パフォーマンス要件のないプロジェクトの場合
  • 単発の簡単なシェルスクリプトを書く場合

プロジェクトの概要

unix-goto システムアーキテクチャ

unix-goto は、次の 5 つの基本原則に基づいて設計された、高性能な Unix ナビゲーションシステムです。

  1. シンプル - 1 行で読み込み可能(source goto.sh)、設定は最小限
  2. 高速 - ナビゲーションのパフォーマンスは 100 ミリ秒未満
  3. 軽量 - 不必要な機能や依存関係はありません
  4. テスト済み - コア機能のテストカバレッジは 100%
  5. ドキュメント完備 - 明確で包括的なドキュメント
主なパフォーマンス指標
指標目標達成値状況
キャッシュを利用したナビゲーション<100ms26ms✅ 目標を超過
キャッシュヒット率>90%92-95%✅ 目標を超過
高速化率20-50x8x⏳ 順調
テストカバレッジ100%100%✅ 達成
キャッシュ構築時間<5s3-5s✅ 達成
システムアーキテクチャ
┌─────────────────────────────────────────────────────────────┐
│                      User Interface                         │
│  goto, bookmark, recent, back, goto list, goto benchmark   │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                    Core Navigation                          │
│  goto-function.sh - Main routing and path resolution        │
└─────────────────────────────────────────────────────────────┘
                            │
          ┌─────────────────┼─────────────────┐
          ▼                 ▼                 ▼
┌──────────────────┐ ┌──────────────┐ ┌──────────────────┐
│  Cache System    │ │  Bookmarks   │ │  History         │
│  cache-index.sh  │ │  bookmark-   │ │  history-        │
│                  │ │  command.sh  │ │  tracking.sh     │
│  O(1) lookup     │ │              │ │                  │
│  Auto-refresh    │ │  Add/Remove  │ │  Track visits    │
└──────────────────┘ └──────────────┘ └──────────────────┘
モジュールの依存関係

重要な読み込み順序(依存先を依存元より先に読み込む必要があります):

goto.sh (loader)
  ├── history-tracking.sh (no dependencies)
  ├── back-command.sh (depends on: history-tracking.sh)
  ├── recent-command.sh (depends on: history-tracking.sh)
  ├── bookmark-command.sh (no dependencies)
  ├── cache-index.sh (no dependencies)
  ├── list-command.sh (depends on: bookmark-command.sh)
  ├── benchmark-command.sh (depends on: cache-index.sh)
  ├── benchmark-workspace.sh (no dependencies)
  └── goto-function.sh (depends on: all above)

基本知識

9 ステップの機能追加ワークフロー

unix-goto に機能を追加する際の標準的な手順です。9 つのステップすべてに従ってください。

ステップ 1:機能を計画する

コードを 1 行でも書く前に、次の質問に答えてください。

計画時の質問:

  • どのような問題を解決しますか?
  • ユーザーインターフェース(コマンド/フラグ)はどのようなものですか?
  • 想定されるパフォーマンスはどの程度ですか?
  • どのような依存関係がありますか?
  • どのようなテストが必要ですか?
  • どのようなドキュメントが必要ですか?

計画テンプレート:

Feature: [Name]
Problem: [User pain point]
Interface: [Commands/flags]
Performance: [Target metrics]
Dependencies: [Module dependencies]
Tests: [Test scenarios]
Docs: [API.md, README.md sections]

例 — 最近のディレクトリ機能(CET-77):

Feature: Recent Directories Command
Problem: Users can't quickly revisit recently navigated directories
Interface: goto recent [n]
Performance: <10ms for history retrieval
Dependencies: history-tracking.sh
Tests:
  - List recent directories
  - Handle empty history
  - Limit to N entries
  - Navigate to recent directory by number
Docs: Add to API.md and README.md
ステップ 2:モジュールを作成する(必要な場合)

モジュールテンプレート:

#!/bin/bash
# unix-goto - [Module purpose]
# https://github.com/manutej/unix-goto

# Storage location
GOTO_MODULE_FILE="${GOTO_MODULE_FILE:-$HOME/.goto_module}"

# Main function
goto_module() {
    local subcommand="$1"
    shift

    case "$subcommand" in
        list)
            # Implementation
            ;;
        add)
            # Implementation
            ;;
        --help|-h|help|"")
            echo "goto module - [Description]"
            echo ""
            echo "Usage:"
            echo "  goto module list     [Description]"
            echo "  goto module add      [Description]"
            ;;
        *)
            echo "Unknown command: $subcommand"
            return 1
            ;;
    esac
}

主なモジュールパターン:

  1. 関数の命名:

    • 公開関数:接頭辞なし(goto、bookmark、recent)
    • 内部関数:アンダースコア 2 つ(__goto_navigate_to、__goto_cache_lookup)
    • 変数:グローバル変数には大文字、ローカル変数には小文字を使用
  2. 環境変数:

    # Always provide defaults
    GOTO_INDEX_FILE="${GOTO_INDEX_FILE:-$HOME/.goto_index}"
    GOTO_CACHE_TTL="${GOTO_CACHE_TTL:-86400}"
    GOTO_SEARCH_DEPTH="${GOTO_SEARCH_DEPTH:-3}"
    
  3. 戻り値コード:

    • 0 - 成功
    • 1 - 一般エラー(見つからない、入力が無効)
    • 2 - 複数の一致が見つかった(キャッシュ検索のみ)
ステップ 3:ローダーに追加する

依存関係の正しい順序でモジュールが読み込まれるように、goto.sh を編集します。

# Add to load sequence (respect dependencies)
source "$GOTO_LIB_DIR/history-tracking.sh"
source "$GOTO_LIB_DIR/module.sh"  # NEW - add after dependencies
source "$GOTO_LIB_DIR/back-command.sh"

依存関係のルール:

  • 依存関係のないモジュールを最初に読み込みます
  • 他のモジュールに依存するモジュールは、その依存先の後に読み込みます
  • メインの goto-function.sh は最後に読み込みます(すべてに依存するため)
ステップ 4:メイン関数と統合する

コマンドをモジュールに振り分けるために、lib/goto-function.sh を編集します。

goto() {
    case "$1" in
        module)  # NEW
            if command -v goto_module &> /dev/null; then
                shift
                goto_module "$@"
            else
                echo "⚠️  Module command not loaded"
            fi
            return
            ;;
    esac
}
ステップ 5:テストを追加する(カバレッジ 100%が必須)

テストファイルのテンプレート:

#!/bin/bash
# Test suite for [feature] functionality

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/lib/module.sh"

# Test counters
TESTS_PASSED=0
TESTS_FAILED=0

# Test helper
pass() {
    echo "✓ PASS: $1"
    ((TESTS_PASSED++))
}

fail() {
    echo "✗ FAIL: $1"
    ((TESTS_FAILED++))
}

# Test 1: [Description]
test_feature() {
    # Arrange
    local input="test"

    # Act
    local result=$(function_under_test "$input")

    # Assert
    if [[ "$result" == "expected" ]]; then
        pass "Feature works"
    else
        fail "Feature failed: got '$result'"
    fi
}

# Run tests
test_feature

# Summary
echo ""
echo "Tests passed: $TESTS_PASSED"
echo "Tests failed: $TESTS_FAILED"

[ $TESTS_FAILED -eq 0 ] && exit 0 || exit 1

テストのカテゴリ(すべて必須):

  1. 単体テスト - 個々の関数をテストする
  2. 統合テスト - モジュール間の連携をテストする
  3. エッジケース - 境界条件をテストする
  4. パフォーマンステスト - 速度要件を検証する

CET-77(最近のディレクトリ)の例:

# Unit test
test_get_recent_dirs() {
    result=$(__goto_recent_dirs 5)
    [ $? -eq 0 ] && pass "Get recent dirs" || fail "Get recent dirs failed"
}

# Integration test
test_goto_recent_navigation() {
    goto recent 1
    [ $? -eq 0 ] && pass "Navigate to recent dir" || fail "Navigation failed"
}

# Edge case
test_empty_history() {
    rm -f ~/.goto_history
    result=$(goto recent)
    [[ "$result" == *"No history"* ]] && pass "Empty history" || fail "Empty history check"
}

# Performance test
test_recent_speed() {
    start=$(date +%s%N)
    __goto_recent_dirs 10
    end=$(date +%s%N)
    duration=$(((end - start) / 1000000))
    [ $duration -lt 10 ] && pass "Recent dirs <10ms" || fail "Too slow: ${duration}ms"
}
ステップ 6:API のドキュメント化

docs/API.md に追加します。

## Module API

### `goto module`

[Description of what the module does]

**Signature:**
```bash
goto module <subcommand>

サブコマンド:

  • list - [説明]
  • add - [説明]

パフォーマンス:[目標指標]

例:

goto module list
goto module add value

戻り値コード:

  • 0 - 成功
  • 1 - エラー

実装: lib/module.sh


**Example from CET-77:**
```markdown
## Recent Directories

### `goto recent [n]`

Display recently navigated directories in reverse chronological order.

**Signature:**
```bash
goto recent [n]

パラメーター:

  • n - 表示する最近のディレクトリ数(省略可能。デフォルト:すべて)

パフォーマンス: 履歴の取得は <10ms

例:

goto recent        # Show all recent directories
goto recent 5      # Show 5 most recent

実装: lib/recent-command.sh


#### Step 7: Update User Documentation

Add to `README.md`:

```markdown
### Module

[User-facing description]

```bash
goto module list    # [Description]
goto module add     # [Description]

#### Step 8: Performance Validation

Validate performance meets targets:

```bash
# Add benchmark if performance-critical
goto benchmark module 10

# Measure overhead
time goto_module list

# Expected: <100ms for navigation, <10ms for lookups

パフォーマンス目標:

  • キャッシュ済みナビゲーション:<100ms
  • ブックマーク検索:<10ms
  • キャッシュによる高速化:>20x
  • キャッシュヒット率:>90%
  • キャッシュ構築:<5s
ステップ 9:Linear の課題を更新してコミット

Linear の課題を更新:

  • 実装内容のコメントを追加
  • テスト結果を記載
  • パフォーマンス指標を記載
  • コミットへのリンクを追加
  • ステータスを「完了」に変更

コミット形式:

git commit -m "feat: implement module feature (CET-XX)

[Detailed explanation]

Features:
- Feature 1
- Feature 2

Performance:
- Metric: value

Tests:
- X/X tests passing
- 100% coverage

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>"

コミットの種類:

  • feat: - 新機能
  • fix: - バグ修正
  • perf: - パフォーマンス改善
  • refactor: - コードのリファクタリング
  • test: - テストの追加または更新
  • docs: - ドキュメントのみ
  • chore: - ビルド、依存関係、またはツール関連

CET-85 のコミット例:

feat: implement comprehensive benchmark suite (CET-85)

Implement complete benchmark framework with 5 benchmark tests, helpers,
workspace generation, and CSV results storage.

Features:
- 5 benchmark tests: cached vs uncached, multi-level paths, max depth,
  cache build performance, parallel navigation
- Benchmark helpers library with timing, stats, workspace management
- CSV results storage in ~/.goto_benchmarks/
- Performance target assertions (<100ms navigation)
- Comprehensive statistical analysis (min/max/mean/median/stddev)

Performance:
- Cached navigation: 26ms (target: <100ms) ✓
- Cache build: 3-5s (target: <5s) ✓
- Speedup ratio: 8x (target: >20x, in progress)

Tests:
- 5/5 benchmark tests passing
- All performance targets met for Phase 1

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
機能チェックリスト

機能を提出する前に、必ず以下を確認してください。

  • 実装が完了している
  • goto.sh に読み込まれている
  • メインの goto 関数と統合されている
  • テストが作成され、すべて成功している(カバレッジ 100%)
  • API が docs/API.md に記載されている
  • ユーザードキュメントが README.md で更新されている
  • パフォーマンスが検証されている(該当する場合)
  • Linear の課題が結果とともに更新されている
  • 適切な形式のメッセージでコミットされている
キャッシュシステムのアーキテクチャ

目的: 自動更新による O(1) のフォルダー検索

実装: lib/cache-index.sh

主なコンポーネント:

  • __goto_cache_build - O(n) のインデックス構築
  • __goto_cache_lookup - O(1) のハッシュテーブル検索
  • __goto_cache_is_valid - TTL に基づく検証
  • 古いキャッシュを自動更新(TTL は 24 時間)

キャッシュファイル形式:

# unix-goto folder index cache
# Version: 1.0
# Built: 1697558122
# Depth: 3
# Format: folder_name|full_path|depth|last_modified
#---
unix-goto|/Users/manu/Documents/LUXOR/Git_Repos/unix-goto|8|1697558100
GAI-3101|/Users/manu/Documents/LUXOR/PROJECTS/GAI-3101|6|1697558050

パフォーマンス:

  • 構築時間:O(n) - フォルダー 1200 件以上で 3-5s
  • 検索時間:O(1) - 目標 <100ms、実測 26ms
  • ストレージ:フォルダー 487 件で約 42KB

キャッシュ検索の戻り値コード:

__goto_cache_lookup "folder"
# Returns:
#   0 - Single match found (path to stdout)
#   1 - Not found in cache
#   2 - Multiple matches found (all paths to stdout)
ナビゲーションのデータフロー
User Input → goto "project"
    │
    ├─► Check special cases (list, index, benchmark, @bookmark)
    ├─► Check multi-level paths (contains /)
    ├─► Try cache lookup (O(1)) → Cache hit → Navigate
    ├─► Try direct folder match in search paths
    ├─► Recursive search (max depth 3)
    │   ├─► Single match → Navigate
    │   └─► Multiple matches → Show disambiguation
    └─► Natural language AI resolution (if spaces)
ブックマークシステムのアーキテクチャ

保存先: ~/.goto_bookmarks

形式:

work|/Users/manu/work|1697558122
api|/Users/manu/code/api-server|1697558130

主な関数:

  • __goto_bookmark_add - 検証付きで追加
  • __goto_bookmark_remove - 名前を指定して削除
  • __goto_bookmark_get - パスを取得(O(1) の grep)
  • __goto_bookmark_goto - ブックマーク先へ移動

パフォーマンス目標: 検索時間 <10ms

使用方法:

bookmark add work /path/to/work
bookmark remove work
goto @work
履歴追跡のアーキテクチャ

保存先: ~/.goto_history

形式:

1697558122|/Users/manu/work
1697558130|/Users/manu/Documents/LUXOR

主な関数:

  • __goto_track - 自動トリミング(最大 100 件)付きで追記
  • __goto_get_history - 履歴全体を取得
  • __goto_recent_dirs - 新しい順に並んだ重複のないディレクトリを取得
  • __goto_stack_push/pop - スタックベースの戻るナビゲーション

使用例:

goto recent        # Show all recent directories
goto recent 5      # Show 5 most recent
back              # Go back to previous directory

例

例 1:最近使ったディレクトリ機能の追加(CET-77)

ステップ 1:計画

Feature: Recent Directories Command
Problem: Users can't quickly revisit recently navigated directories
Interface: goto recent [n]
Performance: <10ms for history retrieval
Dependencies: history-tracking.sh
Tests: List recent, empty history, limit entries, navigate by number
Docs: API.md, README.md

ステップ 2:モジュールの作成(lib/recent-command.sh)

#!/bin/bash
# unix-goto - Recent directories command
# https://github.com/manutej/unix-goto

# Get recent directories
__goto_recent_dirs() {
    local limit="${1:-}"

    if [ ! -f "$GOTO_HISTORY_FILE" ]; then
        return 1
    fi

    # Extract paths, reverse order, unique, limit
    local dirs=$(awk -F'|' '{print $2}' "$GOTO_HISTORY_FILE" | \
                 tac | \
                 awk '!seen[$0]++' | \
                 ${limit:+head -n "$limit"})

    echo "$dirs"
    return 0
}

# Recent command implementation
goto_recent() {
    local limit="${1:-}"

    local dirs=$(__goto_recent_dirs "$limit")

    if [ -z "$dirs" ]; then
        echo "No recent directories"
        return 1
    fi

    echo "$dirs"
    return 0
}

ステップ 3:ローダーへの追加(goto.sh)

source "$GOTO_LIB_DIR/history-tracking.sh"
source "$GOTO_LIB_DIR/recent-command.sh"  # NEW

ステップ 4:統合(lib/goto-function.sh)

goto() {
    case "$1" in
        recent)
            shift
            goto_recent "$@"
            return
            ;;
    esac
}

ステップ 5:テストの追加(test-recent.sh)

#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/lib/recent-command.sh"

TESTS_PASSED=0
TESTS_FAILED=0

pass() { echo "✓ PASS: $1"; ((TESTS_PASSED++)); }
fail() { echo "✗ FAIL: $1"; ((TESTS_FAILED++)); }

# Test 1: Get recent directories
test_get_recent() {
    result=$(__goto_recent_dirs)
    [ $? -eq 0 ] && pass "Get recent dirs" || fail "Failed"
}

# Test 2: Empty history
test_empty_history() {
    rm -f ~/.goto_history
    result=$(goto_recent)
    [[ "$result" == *"No recent"* ]] && pass "Empty history" || fail "Empty check"
}

# Test 3: Limit results
test_limit_results() {
    result=$(__goto_recent_dirs 5)
    count=$(echo "$result" | wc -l)
    [ $count -le 5 ] && pass "Limit to 5" || fail "Limit failed"
}

# Run tests
test_get_recent
test_empty_history
test_limit_results

echo ""
echo "Passed: $TESTS_PASSED, Failed: $TESTS_FAILED"
[ $TESTS_FAILED -eq 0 ] && exit 0 || exit 1

ステップ 6:API のドキュメント化(docs/API.md)

## Recent Directories

### `goto recent [n]`

Display recently navigated directories in reverse chronological order.

**Performance:** <10ms for history retrieval

**Examples:**
```bash
goto recent        # Show all recent directories
goto recent 5      # Show 5 most recent

**Step 7: Update README** (`README.md`)
```markdown
### Recent Directories

Quickly revisit recently navigated directories:

```bash
goto recent        # Show all recent directories
goto recent 5      # Show 5 most recent

**Step 8: Validate Performance**
```bash
time goto recent
# Expected: <10ms

ステップ 9:コミット

git commit -m "feat: implement recent directories command (CET-77)

Add goto recent command to display recently navigated directories.

Features:
- List all recent directories
- Limit to N most recent
- Unique directories only
- Reverse chronological order

Performance:
- History retrieval: <10ms ✓

Tests:
- 3/3 tests passing
- 100% coverage

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>"
例 2:ベンチマークスイートの追加(CET-85)

ヘルパー、ワークスペース、CSV 保存機能を含むベンチマークの完全な実装です。

ベンチマークの構成(benchmarks/bench-cached-vs-uncached.sh)

#!/bin/bash
# Benchmark: Cached vs Uncached Navigation Performance

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_DIR="$SCRIPT_DIR/.."

source "$SCRIPT_DIR/bench-helpers.sh"
source "$REPO_DIR/lib/cache-index.sh"

main() {
    bench_header "Cached vs Uncached Navigation Performance"

    echo "Configuration:"
    echo "  Iterations: 10"
    echo "  Warmup: 3 runs"
    echo ""

    benchmark_cached_vs_uncached

    generate_summary
}

benchmark_cached_vs_uncached() {
    bench_section "Benchmark: Cached vs Uncached Lookup"

    # Setup workspace
    local workspace=$(bench_create_workspace "medium")

    # Phase 1: Uncached lookup
    echo "Phase 1: Uncached lookup (no cache)"
    echo "─────────────────────────────────"

    # Warmup
    bench_warmup "__goto_cache_lookup unix-goto" 3

    # Run benchmark
    local uncached_stats=$(bench_run "uncached" \
        "__goto_cache_lookup unix-goto" 10)

    IFS=',' read -r uc_min uc_max uc_mean uc_median uc_stddev <<< "$uncached_stats"

    bench_print_stats "$uncached_stats" "Uncached Results"

    # Phase 2: Cached lookup
    echo ""
    echo "Phase 2: Cached lookup (with cache)"
    echo "─────────────────────────────────"

    # Build cache
    __goto_cache_build

    # Warmup
    bench_warmup "__goto_cache_lookup unix-goto" 3

    # Run benchmark
    local cached_stats=$(bench_run "cached" \
        "__goto_cache_lookup unix-goto" 10)

    IFS=',' read -r c_min c_max c_mean c_median c_stddev <<< "$cached_stats"

    bench_print_stats "$cached_stats" "Cached Results"

    # Calculate speedup
    local speedup=$(bench_compare "$uc_mean" "$c_mean")

    echo ""
    echo "Speedup Analysis:"
    echo "  Speedup ratio:                               ${speedup}x"

    # Assert targets
    bench_assert_target "$c_mean" 100 "Cached navigation time"

    # Save results
    bench_save_result "cached_vs_uncached" "$uncached_stats" "uncached"
    bench_save_result "cached_vs_uncached" "$cached_stats" "cached"

    # Cleanup
    bench_cleanup_workspace "$workspace"
}

main
exit 0

ベンチマークヘルパー(benchmarks/bench-helpers.sh)

#!/bin/bash
# Benchmark helper functions

BENCH_RESULTS_DIR="${BENCH_RESULTS_DIR:-$HOME/.goto_benchmarks}"

# High-precision timing
bench_time_ms() {
    local cmd="$*"
    local start=$(date +%s%N)
    eval "$cmd" > /dev/null 2>&1
    local end=$(date +%s%N)
    echo $(((end - start) / 1000000))
}

# Calculate statistics
bench_calculate_stats() {
    local values=("$@")
    local count=${#values[@]}

    # Sort values
    IFS=$'\n' sorted=($(sort -n <<<"${values[*]}"))

    # Min/Max
    local min=${sorted[0]}
    local max=${sorted[$((count-1))]}

    # Mean
    local sum=0
    for val in "${values[@]}"; do
        sum=$((sum + val))
    done
    local mean=$((sum / count))

    # Median
    local mid=$((count / 2))
    local median=${sorted[$mid]}

    # Standard deviation
    local variance=0
    for val in "${values[@]}"; do
        local diff=$((val - mean))
        variance=$((variance + diff * diff))
    done
    variance=$((variance / count))
    local stddev=$(echo "sqrt($variance)" | bc)

    echo "$min,$max,$mean,$median,$stddev"
}

# Print header
bench_header() {
    local title="$1"
    echo "╔══════════════════════════════════════════════════════════════════╗"
    printf "║  %-62s  ║\n" "$title"
    echo "╚══════════════════════════════════════════════════════════════════╝"
    echo ""
}

# Print section
bench_section() {
    local title="$1"
    echo "$title"
    echo "─────────────────────────────────────────────────────────────────"
}

# Print statistics block
bench_print_stats() {
    local stats="$1"
    local label="$2"

    IFS=',' read -r min max mean median stddev <<< "$stats"

    echo ""
    echo "$label:"
    printf "  Min:                                             %dms\n" "$min"
    printf "  Max:                                             %dms\n" "$max"
    printf "  Mean:                                            %dms\n" "$mean"
    printf "  Median:                                          %dms\n" "$median"
    printf "  Std Dev:                                       %.2fms\n" "$stddev"
}

# Assert performance target
bench_assert_target() {
    local actual="$1"
    local target="$2"
    local label="$3"

    if [ "$actual" -lt "$target" ]; then
        echo "✓ $label meets target: ${actual}ms (target: <${target}ms)"
    else
        echo "✗ $label exceeds target: ${actual}ms (target: <${target}ms)"
    fi
}

# Initialize results directory
bench_init() {
    mkdir -p "$BENCH_RESULTS_DIR"
}

# Save benchmark result
bench_save_result() {
    bench_init

    local name="$1"
    local stats="$2"
    local metadata="${3:-}"

    local timestamp=$(date +%s)
    local results_file="$BENCH_RESULTS_DIR/results.csv"

    # Create header if file doesn't exist
    if [ ! -f "$results_file" ]; then
        echo "timestamp,benchmark_name,operation,min_ms,max_ms,mean_ms,median_ms,stddev,metadata" > "$results_file"
    fi

    # Append result
    echo "$timestamp,$name,$metadata,$stats" >> "$results_file"
}

# Create test workspace
bench_create_workspace() {
    local size="${1:-medium}"
    local workspace=$(mktemp -d)

    case "$size" in
        small)
            # 10 folders
            for i in {1..10}; do
                mkdir -p "$workspace/folder-$i"
            done
            ;;
        medium)
            # 50 folders
            for i in {1..50}; do
                mkdir -p "$workspace/folder-$i"
            done
            ;;
        large)
            # 500 folders
            for i in {1..500}; do
                mkdir -p "$workspace/folder-$i"
            done
            ;;
    esac

    echo "$workspace"
}

# Cleanup workspace
bench_cleanup_workspace() {
    local workspace="$1"
    rm -rf "$workspace"
}

# Run benchmark iterations
bench_run() {
    local name="$1"
    local cmd="$2"
    local iterations="${3:-10}"

    local times=()

    for i in $(seq 1 $iterations); do
        local time=$(bench_time_ms "$cmd")
        times+=("$time")
        printf "  Run %2d: %dms\n" "$i" "$time"
    done

    bench_calculate_stats "${times[@]}"
}

# Warmup iterations
bench_warmup() {
    local cmd="$1"
    local iterations="${2:-3}"

    for i in $(seq 1 $iterations); do
        eval "$cmd" > /dev/null 2>&1
    done
}

# Compare performance
bench_compare() {
    local baseline="$1"
    local optimized="$2"

    local speedup=$(echo "scale=2; $baseline / $optimized" | bc)
    echo "$speedup"
}

ベストプラクティス

コードスタイルの標準

関数の構造:

function_name() {
    local param1="$1"
    local param2="${2:-default}"

    # Validate inputs
    if [ -z "$param1" ]; then
        echo "Error: param1 required"
        return 1
    fi

    # Main logic
    local result=$(process "$param1")

    # Return value
    echo "$result"
    return 0
}

エラー処理:

# Always check command success
if ! goto index rebuild; then
    echo "Failed to rebuild cache"
    return 1
fi

# Use meaningful error messages
if [ ! -d "$target_dir" ]; then
    echo "❌ Directory not found: $target_dir"
    return 1
fi

コメント:

# Good: Explain why, not what
# Cache lookup is O(1) because we use grep on indexed file

# Bad: Explain what (obvious from code)
# Set folder_name to first parameter
folder_name="$1"
データファイル形式のパターン

標準形式: メタデータヘッダー付きのパイプ区切り

# Module data file
# Version: 1.0
# Built: [timestamp]
# Format: field1|field2|field3
#---
value1|value2|value3
value1|value2|value3
パフォーマンス最適化のヒント

キャッシュシステム:

  • すべての検索でキャッシュを使用します
  • 再帰検索の深さを制限します
  • 冗長なファイルシステム操作を避けます
  • 高速なテキスト照合にはgrepを使用します

メモリ:

  • キャッシュファイル:500個のフォルダーで100KB未満
  • メモリ使用量:最小限(シェル関数のみ)
  • 永続的なプロセスはありません
デバッグのヒント

Bash トレースを有効にする:

set -x
source goto.sh
goto test
set +x

関数の存在を確認する:

if declare -f __goto_cache_lookup > /dev/null; then
    echo "Function loaded"
fi

キャッシュの問題をデバッグする:

# View cache file
cat ~/.goto_index

# Check cache age
stat -f %m ~/.goto_index

# Rebuild and observe
goto index rebuild
Linear ワークフローとの統合

Linear プロジェクトの詳細:

  • チーム:Ceti-luxor
  • プロジェクト:unix-goto - Shell Navigation Tool
  • プロジェクト ID:7232cafe-cb71-4310-856a-0d584e6f3df0

イシューのライフサイクル:

Backlog → In Progress → Complete

標準ワークフロー:

  1. Phase 3 のバックログからイシューを選びます
  2. Linear で「In Progress」に移動します
  3. フィーチャーブランチを作成します:feature/CET-XX-feature-name
  4. 9 ステップのワークフローに従って実装します
  5. 十分にテストします(カバレッジ 100%)
  6. 適切な形式でコミットします
  7. 結果を Linear のイシューに記録します
  8. 「Complete」に移動します

Linear イシューのテンプレート:

## Problem
What problem does this solve?

## Solution
How will we solve it?

## Acceptance Criteria
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] Tests pass
- [ ] Performance targets met

## Performance Targets
- Metric 1: <target>
- Metric 2: <target>

## Dependencies
- Issue CET-XX (if applicable)

クイックリファレンス

基本的なコマンド
# Development
source goto.sh                 # Load all modules
goto index rebuild             # Rebuild cache
bash test-cache.sh             # Run cache tests
bash test-benchmark.sh         # Run benchmark tests
goto benchmark all             # Run all benchmarks

# Debugging
set -x; goto project; set +x   # Trace execution
declare -F | grep goto         # List functions
cat ~/.goto_index              # View cache

# Git workflow
git checkout -b feature/CET-XX # Create branch
git commit -m "feat: ..."      # Commit with proper format
git push origin feature/CET-XX # Push to remote

# Performance
time goto project              # Measure navigation
goto benchmark navigation      # Benchmark navigation
goto index status              # Check cache health
ファイルの場所
~/.goto_index         - Cache file
~/.goto_bookmarks     - Bookmarks file
~/.goto_history       - History file
~/.goto_stack         - Navigation stack
~/.goto_benchmarks/   - Benchmark results directory
パフォーマンス目標の概要
指標目標現在
キャッシュ済みナビゲーション<100ms26ms ✓
キャッシュ構築<5s3-5s ✓
キャッシュヒット率>90%92-95% ✓
高速化率20-50x8x ⚠
テストカバレッジ100%100% ✓

スキルのバージョン: 1.0 最終更新日: October 2025 メンテナンス担当: Manu Tej + Claude Code ソースリポジトリ: https://github.com/manutej/unix-goto

コメント