Skip to content

n0an/VivaDicta / .agents/skills/ios-simulator-skill

ios-simulator-skill

Verified

21 production-ready scripts for iOS app testing, building, and automation. Provides semantic UI navigation, build automation, accessibility testing, and simulator lifecycle management. Optimized for AI agents with minimal token output.

FileKindSize
SKILL.mdskill md9.9 KB
agents/openai.yamlconfig279 B
references/accessibility_checklist.mdmarkdown1.5 KB
references/idb_quick.mdmarkdown1.1 KB
references/simctl_quick.mdmarkdown1.3 KB
references/test_patterns.mdmarkdown1.6 KB
references/troubleshooting.mdmarkdown1.3 KB
scripts/accessibility_audit.pyexecutablescript10.0 KB
scripts/app_launcher.pyexecutablescript9.5 KB
scripts/app_state_capture.pyexecutablescript12.9 KB
scripts/build_and_test.pyexecutablescript11.1 KB
scripts/clipboard.pyexecutablescript2.6 KB
scripts/common/__init__.pyscript1.5 KB
scripts/common/cache_utils.pyscript8.1 KB
scripts/common/device_utils.pyscript13.5 KB
scripts/common/idb_utils.pyscript5.3 KB
scripts/common/screenshot_utils.pyscript10.0 KB
scripts/gesture.pyexecutablescript12.3 KB
scripts/keyboard.pyexecutablescript11.5 KB
scripts/log_monitor.pyexecutablescript14.6 KB
scripts/navigator.pyexecutablescript14.0 KB
scripts/privacy_manager.pyexecutablescript8.7 KB
scripts/push_notification.pyexecutablescript6.5 KB
scripts/screen_mapper.pyexecutablescript10.4 KB
scripts/sim_health_check.shexecutablescript7.7 KB
scripts/sim_list.pyexecutablescript8.9 KB
scripts/simctl_boot.pyexecutablescript8.6 KB
scripts/simctl_create.pyexecutablescript8.9 KB
scripts/simctl_delete.pyexecutablescript10.3 KB
scripts/simctl_erase.pyexecutablescript9.8 KB
scripts/simctl_shutdown.pyexecutablescript8.4 KB
scripts/simulator_selector.pyexecutablescript10.3 KB
scripts/status_bar.pyexecutablescript6.6 KB
scripts/test_recorder.pyexecutablescript10.6 KB
scripts/visual_diff.pyexecutablescript7.6 KB
scripts/xcode/__init__.pyscript378 B
scripts/xcode/builder.pyscript12.8 KB
scripts/xcode/cache.pyscript5.5 KB
scripts/xcode/config.pyscript5.4 KB
scripts/xcode/reporter.pyscript10.3 KB
scripts/xcode/xcresult.pyscript16.5 KB

scripts/common/cache_utils.py

View on GitHub
#!/usr/bin/env python3
"""
Progressive disclosure cache for large outputs.

Implements cache system to support progressive disclosure pattern:
- Return concise summary with cache_id for large outputs
- User retrieves full details on demand via cache_id
- Reduces token usage by 96% for common queries

Cache directory: ~/.ios-simulator-skill/cache/
Cache expiration: Configurable per cache type (default 1 hour)

Used by:
- sim_list.py - Simulator listing progressive disclosure
- Future: build logs, UI trees, etc.
"""

import json
import time
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any


class ProgressiveCache:
    """Cache for progressive disclosure pattern.

    Stores large outputs with timestamped IDs for on-demand retrieval.
    Automatically cleans up expired entries.
    """

    def __init__(self, cache_dir: str | None = None, max_age_hours: int = 1):
        """Initialize cache system.

        Args:
            cache_dir: Cache directory path (default: ~/.ios-simulator-skill/cache/)
            max_age_hours: Max age for cache entries before expiration (default: 1 hour)
        """
        if cache_dir is None:
            cache_dir = str(Path("~/.ios-simulator-skill/cache").expanduser())

        self.cache_dir = Path(cache_dir)
        self.max_age_hours = max_age_hours

        # Create cache directory if needed
        self.cache_dir.mkdir(parents=True, exist_ok=True)

    def save(self, data: dict[str, Any], cache_type: str) -> str:
        """Save data to cache and return cache_id.

        Args:
            data: Dictionary data to cache
            cache_type: Type of cache ('simulator-list', 'build-log', 'ui-tree', etc.)

        Returns:
            Cache ID like 'sim-20251028-143052' for use in progressive disclosure

        Example:
            cache_id = cache.save({'devices': [...]}, 'simulator-list')
            # Returns: 'sim-20251028-143052'
        """
        # Generate cache_id with timestamp
        timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
        cache_prefix = cache_type.split("-", maxsplit=1)[0]  # e.g., 'sim' from 'simulator-list'
        cache_id = f"{cache_prefix}-{timestamp}"

        # Save to file
        cache_file = self.cache_dir / f"{cache_id}.json"
        with open(cache_file, "w") as f:
            json.dump(
                {
                    "cache_id": cache_id,
                    "cache_type": cache_type,
                    "created_at": datetime.now().isoformat(),
                    "data": data,
                },
                f,
                indent=2,
            )

        return cache_id

    def get(self, cache_id: str) -> dict[str, Any] | None:
        """Retrieve data from cache by cache_id.

        Args:
            cache_id: Cache ID from save() or list_entries()

        Returns:
            Cached data dictionary, or None if not found/expired

        Example:
            data = cache.get('sim-20251028-143052')
            if data:
                print(f"Found {len(data)} devices")
        """
        cache_file = self.cache_dir / f"{cache_id}.json"

        if not cache_file.exists():
            return None

        # Check if expired
        if self._is_expired(cache_file):
            cache_file.unlink()  # Delete expired file
            return None

        try:
            with open(cache_file) as f:
                entry = json.load(f)
                return entry.get("data")
        except (OSError, json.JSONDecodeError):
            return None

    def list_entries(self, cache_type: str | None = None) -> list[dict[str, Any]]:
        """List available cache entries with metadata.

        Args:
            cache_type: Filter by type (e.g., 'simulator-list'), or None for all

        Returns:
            List of cache entries with id, type, created_at, age_seconds

        Example:
            entries = cache.list_entries('simulator-list')
            for entry in entries:
                print(f"{entry['id']} - {entry['age_seconds']}s old")
        """
        entries = []

        for cache_file in sorted(self.cache_dir.glob("*.json"), reverse=True):
            # Check if expired
            if self._is_expired(cache_file):
                cache_file.unlink()
                continue

            try:
                with open(cache_file) as f:
                    entry = json.load(f)

                    # Filter by type if specified
                    if cache_type and entry.get("cache_type") != cache_type:
                        continue

                    created_at = datetime.fromisoformat(entry.get("created_at", ""))
                    age_seconds = (datetime.now() - created_at).total_seconds()

                    entries.append(
                        {
                            "id": entry.get("cache_id"),
                            "type": entry.get("cache_type"),
                            "created_at": entry.get("created_at"),
                            "age_seconds": int(age_seconds),
                        }
                    )
            except (OSError, json.JSONDecodeError, ValueError):
                continue

        return entries

    def cleanup(self, max_age_hours: int | None = None) -> int:
        """Remove expired cache entries.

        Args:
            max_age_hours: Age threshold (default: uses instance max_age_hours)

        Returns:
            Number of entries deleted

        Example:
            deleted = cache.cleanup()
            print(f"Deleted {deleted} expired cache entries")
        """
        if max_age_hours is None:
            max_age_hours = self.max_age_hours

        deleted = 0

        for cache_file in self.cache_dir.glob("*.json"):
            if self._is_expired(cache_file, max_age_hours):
                cache_file.unlink()
                deleted += 1

        return deleted

    def clear(self, cache_type: str | None = None) -> int:
        """Clear all cache entries of a type.

        Args:
            cache_type: Type to clear (e.g., 'simulator-list'), or None to clear all

        Returns:
            Number of entries deleted

        Example:
            cleared = cache.clear('simulator-list')
            print(f"Cleared {cleared} simulator list entries")
        """
        deleted = 0

        for cache_file in self.cache_dir.glob("*.json"):
            if cache_type is None:
                # Clear all
                cache_file.unlink()
                deleted += 1
            else:
                # Clear by type
                try:
                    with open(cache_file) as f:
                        entry = json.load(f)
                        if entry.get("cache_type") == cache_type:
                            cache_file.unlink()
                            deleted += 1
                except (OSError, json.JSONDecodeError):
                    pass

        return deleted

    def _is_expired(self, cache_file: Path, max_age_hours: int | None = None) -> bool:
        """Check if cache file is expired.

        Args:
            cache_file: Path to cache file
            max_age_hours: Age threshold (default: uses instance max_age_hours)

        Returns:
            True if file is older than max_age_hours
        """
        if max_age_hours is None:
            max_age_hours = self.max_age_hours

        try:
            with open(cache_file) as f:
                entry = json.load(f)
                created_at = datetime.fromisoformat(entry.get("created_at", ""))
                age = datetime.now() - created_at
                return age > timedelta(hours=max_age_hours)
        except (OSError, json.JSONDecodeError, ValueError):
            return True


# Module-level cache instances (lazy-loaded)
_cache_instances: dict[str, ProgressiveCache] = {}


def get_cache(cache_dir: str | None = None) -> ProgressiveCache:
    """Get or create global cache instance.

    Args:
        cache_dir: Custom cache directory (uses default if None)

    Returns:
        ProgressiveCache instance
    """
    # Use cache_dir as key, or 'default' if None
    key = cache_dir or "default"

    if key not in _cache_instances:
        _cache_instances[key] = ProgressiveCache(cache_dir)

    return _cache_instances[key]
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 322kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 322kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 322kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 198kUpdated Claude CodeCodexVerifiedInstall