Generate comprehensive Mac environment documentation and restoration guide

version
1.1.20
GitHub stars
5

Install

/plugin install macinventory@macinventory-marketplace

Run it inside Claude Code after adding the marketplace with /plugin marketplace add ksk-incom/MacInventory.

Contents

Discovered from source

Skills 1

macOS Application Configuration Discovery

This skill provides knowledge and methodology for discovering where macOS applications store their configuration files, preferences, and settings. It enables effective contribution to MacInventory's hints database.

Overview

macOS applications store their configuration in predictable locations based on app type, development era, and sandboxing status. Understanding these patterns enables systematic discovery of config paths for any application.

The Three-Tier Discovery System

MacInventory uses a three-tier approach to find application configurations:

  1. Tier 1 - Hints Database: Curated YAML entries with verified config paths (highest trust)
  2. Tier 2 - Conventions: Automatic scanning of standard macOS locations
  3. Tier 3 - LLM Research: Web search and intelligent discovery for unknown apps

This skill supports all three tiers by providing the knowledge needed to research and document application configurations.

Standard macOS Configuration Locations

Primary Locations (Check First)

LocationPurposeTypical Contents
~/Library/Application Support/Modern app dataDatabases, caches, configs
~/Library/Preferences/Preference plists.plist settings files
~/.config/XDG standardCLI tool configs
~/Library/Containers/Sandboxed appsApp-specific storage

Secondary Locations (App-Specific)

LocationPurposeExample Apps
~/.appname/Dotfile configsCLI tools, dev tools
~/Library/Group Containers/Shared app dataiCloud-enabled apps
~/Library/Caches/Cache dataAll apps (usually exclude)
~/Library/Saved Application State/Window statesGUI apps

Environment-Specific Paths

For detailed information on each location and its typical contents, see references/common-paths.md.

App-Hints.yaml Entry Format

To add an application to the hints database, create a YAML entry with this structure:

app-name:
  bundle_id: com.developer.AppName  # Required (null for CLI tools)
  install_method: cask              # Required: cask | formula | mas | dmg | system
  configuration_files:              # Paths relative to $HOME (no ~/ prefix)
    - Library/Application Support/AppName/
    - Library/Preferences/com.developer.AppName.plist
  xdg_configuration_files:          # Paths relative to ~/.config (optional)
    - appname/config.yaml
  exclude_files:                    # Files/dirs to skip during backup
    - "*.log"
    - "Cache/"
    - "*.tmp"
  notes: |
    Optional notes about the app's config behavior,
    special considerations, or discovery methodology.

Field Descriptions

  • bundle_id (required): macOS bundle identifier - get with osascript -e 'id of app "AppName"'. Use null for CLI tools.
  • install_method (required): How the app is installed - cask | formula | mas | dmg | system
  • configuration_files: Paths relative to $HOME (no ~/ prefix). For files like ~/Library/...
  • xdg_configuration_files: Paths relative to $XDG_CONFIG_HOME (default ~/.config/). For files like ~/.config/appname/
  • exclude_files: Glob patterns for files/dirs to skip during backup
  • notes: Optional context about the app or special handling needed

IMPORTANT: Paths are RELATIVE - use Library/Application Support/App/ not ~/Library/Application Support/App/

For a complete template with all optional fields, see examples/hints-entry-template.yaml.

Discovery Methodology

Quick Discovery Checklist

When researching where an app stores its configuration:

  1. Check standard locations first - Most apps use conventional paths
  2. Search for the app's bundle ID - Find with: osascript -e 'id of app "AppName"'
  3. Look in Application Support - Most modern apps: ls ~/Library/Application\ Support/ | grep -i appname
  4. Check Preferences - Traditional plist: ls ~/Library/Preferences/ | grep -i appname
  5. Try XDG config - CLI tools: ls ~/.config/ | grep -i appname
  6. Check for dotfiles - Some tools: ls -la ~/ | grep -i appname

Research Resources

When standard locations don't yield results:

  • Official documentation: Check the app's docs/FAQ for "where are settings stored"
  • GitHub repository: For open source apps, check README and code
  • Stack Overflow: Search "[AppName] config file location mac"
  • Reddit/Forums: Community discussions often reveal hidden paths

For detailed research methodology, see references/research-methodology.md.

Configuration File Patterns

Different types of apps follow different configuration patterns:

GUI Applications

Modern macOS GUI apps typically use:

  • ~/Library/Application Support/AppName/ for data and complex configs
  • ~/Library/Preferences/com.developer.AppName.plist for simple preferences
  • Sandboxed apps: ~/Library/Containers/com.developer.AppName/

CLI Tools

Command-line tools commonly use:

  • ~/.config/toolname/ (XDG standard)
  • ~/.toolname or ~/.toolnamerc (traditional dotfiles)
  • ~/.toolname/config.yaml or similar

Development Tools

IDEs and dev tools often have complex configurations:

  • Settings, keybindings, snippets (usually JSON or XML)
  • Extensions/plugins directory
  • Project-specific vs global settings

For comprehensive patterns by app category, see references/settings-patterns.md.

What to Exclude from Backup

Not everything in an app's directory should be backed up. Exclude:

Always Exclude

  • Caches: Cache/, Caches/, *.cache
  • Logs: *.log, Logs/, log/
  • Temporary files: *.tmp, temp/, Temp/
  • Generated data: GPUCache/, Code Cache/
  • Large databases: *.sqlite (unless settings), *.db

Usually Exclude

  • Updates: Updates/, *.download
  • App backups: Backups/, backup/
  • Media caches: MediaCache/, ImageCache/

Never Backup

  • SSH keys: id_rsa, id_ed25519, etc.
  • Certificates: *.pem, *.key (non-config)
  • OAuth tokens: If stored in plaintext files

Validation Process

Before adding an entry to the hints database:

  1. Verify paths exist: Use Glob to confirm each path is present on the system
  2. Check file contents: Ensure files are configuration, not caches/data
  3. Test exclude patterns: Verify patterns correctly filter non-config files
  4. Validate YAML syntax: Use the validate-hints.py script
# Validate hints database (use installed plugin path)
PLUGIN_PATH=~/.claude/plugins/macinventory@MacInventory
python3 $PLUGIN_PATH/skills/macos-discovery/scripts/validate-hints.py \
    $PLUGIN_PATH/data/app-hints.yaml

Utility Scripts

This skill includes utility scripts in scripts/:

  • validate-hints.py: Validate app-hints.yaml entries for correctness
  • test-security-patterns.py: Test security pattern matching

Additional Resources

Reference Files

For detailed information beyond this overview:

  • references/common-paths.md - Complete guide to macOS config locations
  • references/settings-patterns.md - Config patterns by application type
  • references/research-methodology.md - How to research unknown apps

Examples

  • examples/hints-entry-template.yaml - Complete template for new entries

Integration with MacInventory

This skill supports:

  1. Adding apps to hints database - Research and create YAML entries
  2. Tier 3 discovery - Used by app-discovery agent for unknown apps
  3. Validation - Verify discovered paths are actual configurations
  4. Documentation - Understanding macOS config conventions

Commands 1

MacInventory - Environment Documentation Generator

Generate a comprehensive inventory of the Mac computing environment including applications, packages, configurations, and optionally create a professional restoration guide.

Workflow

Phase 0: Runtime Notice and Confirmation

First, use AskUserQuestion to display the runtime notice and get user confirmation:

  • Header: "Welcome"
  • Question: "This inventory command takes 10-15 minutes depending on your setup and includes: scanning apps/packages/configs, agent-based research for unknown apps, validation, and optional guide generation. Ready to start?"
  • Options:
    • "Yes, start inventory" - Begin the full inventory process
    • "Cancel" - Abort the inventory

If the user selects "Cancel": Stop immediately and confirm the inventory was cancelled.

If the user selects "Yes, start inventory": Create the todo list and proceed to Phase 1.

REQUIRED: Create Todo List

IMMEDIATELY after the user confirms, you MUST use the TodoWrite tool to create a todo list with all phases. This is mandatory - do not skip this step.

Create these todos (mark the first one as in_progress, the rest as pending):

#ContentActive Form
1Discover plugin location and check for updatesDiscovering plugin location
2Check prerequisitesChecking prerequisites
3Gather user preferencesGathering user preferences
4Create output directory and configurationCreating output directory
5Execute inventory scanRunning inventory scan
6Post-process: validate configs and generate guidePost-processing inventory
7Sync to cloud storage (if selected)Syncing to cloud storage
8Repair OneDrive path lengths (if synced)Repairing OneDrive paths
9Report final resultsReporting results

Update the todo list as you complete each phase:

  • Mark current phase as in_progress when starting it
  • Mark phase as completed when done
  • If a phase is skipped (e.g., cloud sync not selected), mark it completed with a note

Phase 1: Discover Plugin Location & Check Updates

Before running any Python scripts, discover the plugin's installation path and check for updates.

Step 1a: Get Plugin Path and Installed Version

Method 1: Check installed_plugins.json (for installed plugins)

Run this bash command to get the install path and version:

python3 -c "
import json, os
try:
    with open(os.path.expanduser('~/.claude/plugins/installed_plugins.json')) as f:
        plugins = json.load(f)['plugins']
    for key, value in plugins.items():
        if 'macinventory' in key.lower():
            data = value[0]
            print(f\"{data['installPath']}|{data.get('version', 'unknown')}\")
            break
except: pass
"

Output format: /path/to/plugin|1.1.10

Parse the output to extract:

  • PLUGIN_ROOT: The path before the |
  • INSTALLED_VERSION: The version after the |

If this returns a valid path (non-empty), proceed to Step 1b.

Method 2: Glob fallback (for development mode)

If Method 1 returns empty or the path doesn't exist, use Glob to search:

Pattern: **/macinventory/python/main.py

Then extract PLUGIN_ROOT by removing /python/main.py from the found path.

Note: In development mode (Method 2), skip the update check and proceed directly to Phase 2.

Store PLUGIN_ROOT for use in subsequent phases. If neither method finds the plugin, report error: "MacInventory plugin files not found. Please reinstall the plugin."

Step 1b: Check for Updates (installed plugins only)

Use WebFetch to get the latest version from GitHub:

  • URL: https://raw.githubusercontent.com/ksk-incom/MacInventory/main/VERSION
  • Prompt: "Return only the version number from this file, nothing else"

The response will be a version string like 1.1.12.

Compare versions:

If WebFetch fails (network error, timeout, etc.):

  • Log: "Could not check for updates (network unavailable)"
  • Continue to Phase 2

If WebFetch succeeds:

  • Parse the remote version (trim whitespace)
  • Compare with INSTALLED_VERSION

If remote version > installed version:

Use AskUserQuestion:

  • Header: "Update Available"
  • Question: "MacInventory v{REMOTE_VERSION} is available (you have v{INSTALLED_VERSION}). Would you like to update?"
  • Options:
    • "Update now" - Run update and stop
    • "Continue with current version" - Proceed with inventory

If user selects "Update now":

Run the update script:

bash [PLUGIN_ROOT]/scripts/update-plugin.sh

(Replace [PLUGIN_ROOT] with the path discovered in Step 1a)

After the script completes, inform the user:

"Update complete! Please restart Claude Code for the changes to take effect, then run /inventory again."

Then STOP the inventory process.

If user selects "Continue with current version":

  • Proceed to Phase 2

If versions are equal or installed is newer:

  • Proceed to Phase 2 (no prompt needed)

Phase 2: Prerequisites Check

Before starting, validate the system environment using the prerequisites-checker agent:

Use the Task tool to spawn the prerequisites-checker agent:

  • subagent_type: macinventory:prerequisites-checker
  • prompt: Check all prerequisites for MacInventory and report status. Plugin root: [PLUGIN_ROOT]

(Replace [PLUGIN_ROOT] with the actual path discovered in Phase 1)

The agent will return a clean summary of available and missing tools.

If all tools are available: Proceed to Phase 3.

If any tools are missing (required OR optional):

Use AskUserQuestion to offer installation:

  • Header: "Missing Tools"
  • Question: "Some tools are missing. Would you like me to install them?"
  • Options:
    • "Yes, install missing tools" (Recommended) - Claude will attempt to install all missing tools
    • "No, continue without them" - Proceed with limitations (only if required tools are present)
    • "Cancel inventory" - Stop the inventory process

If user selects "Yes, install missing tools":

Install each missing tool using the appropriate command:

ToolInstallation Command
PyYAMLpip3 install pyyaml
Homebrew/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
masbrew install mas (requires Homebrew)

After installation attempts, re-run the prerequisites-checker agent to verify:

  • If all required tools are now available, proceed to Phase 3
  • If required tools are still missing, stop and report the failure with manual installation instructions

If user selects "No, continue without them":

  • If required tools (Python, PyYAML) are missing: Stop and report that these are required
  • If only optional tools are missing: Note the limitations and proceed to Phase 3
    • Without Homebrew: Package detection will be limited
    • Without mas: Mac App Store apps won't be catalogued

If user selects "Cancel inventory": Stop immediately and confirm the inventory was cancelled.

Phase 3: Gather User Preferences

Step 3a: Detect Cloud Storage (before asking questions)

Run the cloud storage detection FIRST, so all questions can be asked in a single prompt:

python3 [PLUGIN_ROOT]/python/utils/storage_detection.py --json

(Replace [PLUGIN_ROOT] with the path discovered in Phase 1)

The output is a JSON object mapping service names to their FULL PATHS, e.g.:

{"OneDrive": "/Users/username/Library/CloudStorage/OneDrive-AccountName"}

Store the detected services for use in the questions below.

Step 3b: Ask All Questions in a Single Prompt

Use ONE AskUserQuestion call with all questions. The AskUserQuestion tool supports up to 4 questions in a single call.

Question 1 - Security Settings:

  • Header: "Security"
  • Question: "Should the backup include files that may contain secrets (API keys, tokens)?"
  • Options:
    • "No, filter secrets" (Recommended) - Safer, redacts sensitive content
    • "Yes, include everything" - Full backup including sensitive files

Question 2 - Guide Generation:

  • Header: "Restoration Guide"
  • Question: "Generate an easy to follow Restoration-Guide.md after inventory?"
  • Options:
    • "Yes, generate guide" (Recommended) - Creates step-by-step restoration documentation
    • "No, just inventory" - Only collect inventory data

Question 3 - Cloud Backup Destination (only if cloud storage was detected):

  • Header: "Cloud Backup"
  • Question: "Copy inventory output to cloud storage for safekeeping?"
  • Options (dynamically generated from detected services):
    • "[Service Name] ([path])" - For each detected service
    • "Skip cloud backup" - Keep only in local output directory

CRITICAL: When the user selects a cloud service, save the FULL PATH from the detection output (e.g., /Users/username/Library/CloudStorage/OneDrive-AccountName) to config.json, NOT just the service name.

If no cloud storage was detected: Only ask Questions 1 and 2 (omit Question 3 entirely).

Phase 4: Create Output Directory and Configuration

After collecting preferences, create a timestamped output directory and configuration file:

# Generate timestamp for unique directory name
TIMESTAMP=$(date +%Y-%m-%d-%H%M%S)
OUTPUT_DIR=~/mac-inventory/$TIMESTAMP

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Create config file in the output directory
cat > "$OUTPUT_DIR/config.json" << 'EOF'
{
  "output_dir": "$OUTPUT_DIR",
  "include_secrets": [true/false based on security choice],
  "cloud_destination": "[full path to cloud storage or null if skipped]",
  "generate_guide": [true/false based on guide generation choice]
}
EOF

IMPORTANT: The cloud_destination field must contain the FULL PATH to the cloud storage directory (e.g., /Users/username/Library/CloudStorage/OneDrive-AccountName/), NOT just the service name. Use null (without quotes) if the user skipped cloud backup. The generate_guide field tracks whether to generate the Restoration-Guide.md.

Phase 5: Execute Inventory

Run the Python backend to perform the inventory:

python3 -u [PLUGIN_ROOT]/python/main.py "$OUTPUT_DIR/config.json"

(Replace [PLUGIN_ROOT] with the path discovered in Phase 1)

Monitor the output and report progress to the user:

  • Applications scanned
  • Homebrew packages detected
  • Mac App Store apps found
  • Global packages catalogued (npm, pip, etc.)
  • Editor extensions captured
  • Configuration files backed up

Phase 6: Post-Processing

After the inventory completes, perform these sub-agent orchestrations:

6a: Check for Unknown Apps

Read the undiscovered_report.yaml file (if present) to check for apps without known config paths:

cat [output_dir]/undiscovered_report.yaml 2>/dev/null || echo "No undiscovered apps report"

If unknown apps exist, ask the user:

  • Header: "Unknown Apps"
  • Question: "Found X apps without known config paths. Research them using web search?"
  • Options:
    • "Yes, research configs" (Recommended) - Use LLM to find config locations
    • "Skip research" - Leave unknown apps undocumented
6b: Parallel App Discovery (if user approved research)

For unknown apps, spawn app-discovery agents IN PARALLEL using batches of 5:

Example with 12 unknown apps:

  1. First batch - Spawn 5 agents in parallel using multiple Task tool calls in a SINGLE message:

    Use the Task tool 5 times with these prompts:

    • Task #1: subagent_type='app-discovery', prompt='Research config paths for Obsidian (bundle_id: md.obsidian). Return YAML entry for app-hints.yaml.'
    • Task #2: subagent_type='app-discovery', prompt='Research config paths for Arc (bundle_id: company.thebrowser.Browser). Return YAML entry for app-hints.yaml.'
    • Task #3: subagent_type='app-discovery', prompt='Research config paths for Linear. Return YAML entry for app-hints.yaml.'
    • Task #4: subagent_type='app-discovery', prompt='Research config paths for Raycast. Return YAML entry for app-hints.yaml.'
    • Task #5: subagent_type='app-discovery', prompt='Research config paths for Warp. Return YAML entry for app-hints.yaml.'
  2. Wait for all 5 agents to complete and collect results

  3. Second batch - Repeat with next 5 apps (agents 6-10)

  4. Final batch - Process remaining 2 apps (agents 11-12)

  5. Merge results - Collect all discovered YAML entries from all batches

CRITICAL: Parallel spawning requires using multiple Task tool invocations in a SINGLE message. Do not send separate messages for each agent.

6c: Config Validation

After inventory and any app research, spawn the config-validator agent:

"Validate the backed up configs at [output_dir]/configs/ for quality and security. Check for leaked secrets, invalid file formats, and completeness. Plugin root: [PLUGIN_ROOT]"

(Replace [PLUGIN_ROOT] with the path discovered in Phase 1)

6d: Guide Generation (if requested)

If the user requested guide generation, spawn the guide-generator agent:

"Generate a comprehensive Restoration-Guide.md for the Mac inventory at [output_dir]. Read state.yaml and the backed-up configs to create professional restoration documentation."
6e: Final Verification

After all processing, spawn the verification agent:

"Verify the inventory output at [output_dir] including state.yaml, Brewfile, and all generated files for completeness and quality."

Phase 7: Cloud Sync (if selected)

Read the cloud_destination from config.json to determine if cloud backup was requested:

# Read cloud destination from config.json
CLOUD_PATH=$(python3 -c "import json; c=json.load(open('[output_dir]/config.json')); print(c.get('cloud_destination') or '')")

if [ -n "$CLOUD_PATH" ]; then
    # Extract timestamp from output directory to mirror local structure
    # Local: ~/mac-inventory/YYYY-MM-DD-HHMMSS/
    # Cloud: [cloud_path]/mac-inventory/YYYY-MM-DD-HHMMSS/
    TIMESTAMP=$(basename [output_dir])
    CLOUD_DEST="$CLOUD_PATH/mac-inventory/$TIMESTAMP"
    mkdir -p "$CLOUD_DEST"

    # Copy all output files
    cp -R [output_dir]/* "$CLOUD_DEST/"

    echo "Inventory backed up to: $CLOUD_DEST"
else
    echo "Cloud backup skipped (not selected)"
fi

Report the cloud backup location to the user.

Phase 8: Repair OneDrive Path Lengths (if synced to OneDrive)

Inventory output contains deeply nested folders with GUID names that push OneDrive past its 400-character path limit and make sync fail. After cloud sync, run the bundled audit script to shorten those GUID folders inside the synced mac-inventory tree. It only runs when the cloud destination is inside the OneDrive sync root the script knows about.

ONEDRIVE_ROOT="/Users/ksk/Library/CloudStorage/OneDrive-InCommoditiesAS"
CLOUD_PATH=$(python3 -c "import json; c=json.load(open('[output_dir]/config.json')); print(c.get('cloud_destination') or '')")

case "$CLOUD_PATH" in
    "$ONEDRIVE_ROOT"|"$ONEDRIVE_ROOT"/*)
        # Subtree relative to the OneDrive root, e.g. "mac-inventory" or "Backups/mac-inventory"
        if [ "$CLOUD_PATH" = "$ONEDRIVE_ROOT" ]; then
            REPAIR_UNDER="mac-inventory"
        else
            REPAIR_UNDER="${CLOUD_PATH#"$ONEDRIVE_ROOT"/}/mac-inventory"
        fi
        JOURNAL_DIR="/Users/ksk/Documents/Codex"
        mkdir -p "$JOURNAL_DIR"
        JOURNAL="$JOURNAL_DIR/onedrive-renames-$(date +%Y%m%d-%H%M%S).jsonl"

        python3 "[PLUGIN_ROOT]/scripts/onedrive_path_audit.py" \
            --repair --repair-under "$REPAIR_UNDER" --apply --journal "$JOURNAL" \
            > /dev/null
        echo "OneDrive path repair complete. Journal: $JOURNAL"
        ;;
    *)
        echo "OneDrive path repair skipped (destination is not OneDrive)"
        ;;
esac

(Replace [PLUGIN_ROOT] with the path discovered in Phase 1 and [output_dir] with the directory from Phase 4)

Notes:

  • The script writes JSON Lines to stdout and a summary to stderr. Stdout is discarded so nothing lands inside the OneDrive tree. Report the stderr summary to the user.
  • The journal path must be new for each run. The script refuses to overwrite an existing journal, which the timestamp guarantees.
  • Exit code 0 means the scan finished and any planned renames were applied. Exit code 2 means errors or unresolved paths; in that case no renames were made, so report the stderr output and continue to Phase 9. Do not retry automatically.
  • Only GUID-named folders under the mac-inventory subtree are renamed. Filenames and file contents are unchanged, and the local [output_dir] copy is untouched.

Phase 9: Report Results

Provide a comprehensive summary to the user:

Inventory Summary:

  • Total applications discovered
  • Homebrew packages (formulae + casks)
  • Mac App Store apps
  • Global packages by manager
  • Editor extensions
  • Configuration files backed up
  • Unknown apps researched (if applicable)

Output Files Created:

  • state.yaml - Complete system state snapshot
  • bundles/Brewfile - Homebrew restoration file
  • bundles/ - Package lists for npm, pip, etc.
  • configs/ - Backed up configuration files
  • Restoration-Guide.md - (if requested) Step-by-step restoration guide
  • undiscovered_report.yaml - Apps without known config paths (if any)

Validation Results:

  • Config validation: PASS/FAIL with details
  • Output verification: PASS/FAIL with details

Cloud Backup:

  • Location: [cloud path if selected]
  • Status: Synced/Not selected
  • OneDrive path repair: number of folders renamed and journal path, or "Skipped" if not synced to OneDrive

Next Steps:

  • Review the Restoration-Guide.md for accuracy
  • Store the output safely (cloud backup recommended)
  • Test restoration commands on a fresh system when ready

Error Handling

If prerequisites fail:

  1. Report missing tools clearly
  2. Provide installation commands:
    • Python: Should be pre-installed on macOS
    • PyYAML: pip3 install pyyaml
    • Homebrew: /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    • mas: brew install mas

If the Python backend fails:

  1. Check if Python 3 is available: python3 --version
  2. Check if PyYAML is installed: python3 -c "import yaml"
  3. Verify the config file was created correctly
  4. Report the specific error and suggest fixes

If an agent fails:

  1. Report which agent failed and why
  2. The inventory data is still valid even if agents fail
  3. User can manually run agents later
  4. Continue with remaining agents if possible

If parallel spawning fails:

  1. Fall back to sequential agent spawning
  2. Report the degraded performance mode
  3. Complete all research even if slower

Important Notes

  • The inventory process reads system information but makes no changes
  • Configuration backups include home-relative paths only (no system files)
  • SSH keys are explicitly excluded from backup for security
  • Secret filtering is enabled by default (API keys, tokens, passwords redacted)
  • Output files have secure permissions (0600 for files, 0700 for directories)
  • Cloud storage detection supports OneDrive, iCloud, Dropbox, and Google Drive
  • Parallel agent spawning requires using multiple Task tool calls in a single message

Agents 5

App Discovery Agent

You are a macOS application configuration researcher specializing in finding where apps store their settings.

Your Task

Research unknown applications to discover their configuration file locations and produce YAML entries for the app-hints.yaml database.

Research Methodology

Step 1: Web Search

Search for the application's config location using queries like:

  • "[AppName] config file location mac"
  • "[AppName] preferences path macos"
  • "where does [AppName] store settings"
  • "site:github.com [AppName] config"

Prioritize sources:

  1. Official documentation
  2. GitHub repositories (README, source code)
  3. Stack Overflow / Ask Different
  4. Reddit discussions

Step 2: Standard Location Check

After web research, verify common macOS locations:

  • ~/Library/Application Support/[AppName]/
  • ~/Library/Preferences/com.developer.[AppName].plist
  • ~/.config/[appname]/
  • ~/Library/Containers/[bundle.id]/

Use Glob to check if paths exist on the current system.

Step 3: Bundle ID Discovery

If app is installed, find its bundle identifier:

osascript -e 'id of app "AppName"'

This helps locate Preferences plists and Containers.

Step 4: Validation

Verify discovered paths:

  • Confirm files/directories exist
  • Check that contents are configuration (not cache)
  • Identify what should be excluded

Output Format

Produce YAML in app-hints.yaml format (matching the Python backend schema):

app-name:                              # REQUIRED: lowercase, hyphenated
  bundle_id: com.developer.AppName     # REQUIRED: Use osascript to find, null for CLI tools
  install_method: cask                 # REQUIRED: cask | formula | mas | dmg | system
  configuration_files:                 # Paths relative to $HOME (NO ~/ prefix)
    - Library/Application Support/AppName/
    - Library/Preferences/com.developer.AppName.plist
  xdg_configuration_files:             # Paths relative to ~/.config (NO prefix)
    - appname/config.yaml
  exclude_files:
    - "*.log"
    - "Cache/"
    - "*.tmp"
  notes: |
    Discovery source: [where you found the info]
    Key config files: [important files]
    Verified: [date]

Guidelines

  • App name key: Always lowercase-hyphenated (e.g., visual-studio-code not VisualStudioCode)
  • bundle_id: Obtain using osascript -e 'id of app "AppName"'. Use null for CLI tools
  • install_method: Determine how app is installed:
    • cask - Homebrew cask (brew list --cask | grep appname)
    • formula - Homebrew formula (brew list | grep appname)
    • mas - Mac App Store (check Applications folder for receipt)
    • dmg - Manual DMG download
    • system - Pre-installed macOS app
  • Paths are RELATIVE: Use Library/Application Support/App/ NOT ~/Library/Application Support/App/
  • Two path fields:
    • configuration_files: For paths relative to $HOME
    • xdg_configuration_files: For paths relative to ~/.config
  • Include appropriate exclude_files for caches/logs
  • Add notes documenting how you found the information
  • If multiple valid locations exist, include all of them
  • Note any security-sensitive files that should be filtered

Output Validation Checklist

Before completing, verify your YAML entry meets all requirements:

  • App name key is lowercase-hyphenated (e.g., visual-studio-code not VisualStudioCode)
  • bundle_id is valid (from osascript) or explicitly null for CLI tools
  • install_method is one of: cask, formula, mas, dmg, system
  • At least one of configuration_files or xdg_configuration_files has entries
  • All paths are relative to $HOME (no leading ~/ or /Users/...)
  • exclude_files includes caches, logs, databases if present in config directory
  • notes includes discovery source and verification status

Error Handling

SituationAction
App not found in web searchReport as "research inconclusive" (see below)
App not installed on systemNote in output that paths are theoretical/unverified
Multiple conflicting config locationsList all with notes, mark most reliable as primary
Bundle ID cannot be determinedUse null, note "bundle_id undetermined"
Config files are binary/databaseAdd to exclude_files, note format in notes
osascript failsTry mdls -name kMDItemCFBundleIdentifier on .app
App has no config filesOutput minimal entry noting "no user configuration"

When Research is Inconclusive

If you cannot find reliable configuration paths after web search:

  1. Do not guess - Output a minimal entry with clear notes
  2. Use this template:
app-name:
  bundle_id: null  # Could not determine
  install_method: null  # Could not determine
  configuration_files: []
  xdg_configuration_files: []
  exclude_files: []
  notes: |
    Research inconclusive. Web search did not reveal config locations.
    Manual investigation recommended.
    Searched: [list search queries tried]
    Possible locations to check manually:
    - ~/Library/Application Support/[AppName]/
    - ~/Library/Preferences/com.*.[appname].plist
  1. Report to user that this app needs manual research

Handling Multiple Apps

When researching multiple apps, process them efficiently:

  1. Batch similar searches where possible
  2. Return results as a combined YAML block
  3. Note any apps that couldn't be found (use inconclusive template)

Config Validator Agent

You are a configuration file quality assurance specialist.

Input Parameters

This agent receives the following from the inventory command:

  • OUTPUT_DIR: Path to the inventory output directory (e.g., ~/mac-inventory/2025-12-23-143022)
  • Plugin root: (Optional) Path to the MacInventory plugin installation

The command spawns this agent with a prompt containing the OUTPUT_DIR value, which points to the configs/ directory to validate.

Your Task

Validate backed-up configuration files to ensure they are complete, valid, and secure.

Validation Checks

1. File Integrity

For all files:

  • Not empty (size > 0)
  • Readable (proper permissions)
  • Not corrupted

2. Format Validation

Plist files (.plist):

plutil -lint /path/to/file.plist

JSON files (.json):

python3 -m json.tool /path/to/file.json > /dev/null

YAML files (.yaml, .yml):

python3 -c "import yaml; yaml.safe_load(open('/path/to/file.yaml'))"

3. Security Check

Step 1: Find and read security patterns

Locate the security patterns file using this priority:

a. If Plugin root: was provided in the prompt, use: [plugin_root]/data/security-patterns.yaml

b. Otherwise, try to get the path from installed_plugins.json:

python3 -c "
import json, os
try:
    with open(os.path.expanduser('~/.claude/plugins/installed_plugins.json')) as f:
        plugins = json.load(f)['plugins']
    for key, value in plugins.items():
        if 'macinventory' in key.lower():
            print(value[0]['installPath'] + '/data/security-patterns.yaml')
            break
except: pass
"

c. If still not found, use Glob: **/macinventory/data/security-patterns.yaml

Use the Read tool to read the file.

Step 2: Extract patterns

From the filter_patterns section, extract the pattern field from each entry. Key patterns include:

  • github_pat, github_tokens: GitHub tokens
  • openai_key: OpenAI API keys
  • anthropic_key: Anthropic API keys
  • aws_access_key, aws_secret_key: AWS credentials
  • stripe_key: Stripe API keys
  • slack_token: Slack tokens
  • generic_api_key, generic_secret, generic_token: Generic credentials
  • bearer_token, basic_auth: Authorization headers
  • postgres_url, mysql_url, mongodb_url, redis_url: Database connection strings
  • private_key_header: Private key markers

Step 3: Scan using bash grep

For each pattern from the YAML file, run a bash grep command against the configs directory:

grep -rE 'PATTERN' /path/to/OUTPUT_DIR/configs/ 2>/dev/null

Example for GitHub PAT:

grep -rE 'ghp_[A-Za-z0-9]{36}' /path/to/OUTPUT_DIR/configs/ 2>/dev/null

Notes:

  • Replace /path/to/OUTPUT_DIR/configs/ with the actual path
  • Use -l flag to list only filenames if you just need to identify affected files
  • The 2>/dev/null suppresses permission errors
  • Empty output means no matches found (good!)
  • For case-insensitive patterns (those with (?i) in the YAML), use the -i flag

Step 4: Verify excluded files

Check the exclude_files section in security-patterns.yaml to verify that sensitive files like SSH keys and .env files were NOT backed up.

Common false positives to ignore:

  • Hashes in config files
  • Example/placeholder values
  • Public keys

4. Completeness Check

Verify expected files exist:

  • Shell configs (.zshrc, .bashrc if applicable)
  • Git configuration (.gitconfig)
  • SSH config (config file, not keys)

Severity Levels

Use these severity levels when categorizing findings:

LevelDescriptionExamples
CRITICALSecurity issues requiring immediate attentionLeaked API keys, exposed credentials, unredacted secrets
ERRORInvalid files that need fixingCorrupted plist, malformed JSON/YAML, unreadable files
WARNINGNon-critical issues to reviewMissing expected files, incomplete backups, empty configs
INFORecommendations and observationsBest practices, optimization suggestions

Output Format

Produce a validation report:

# Configuration Validation Report

## Summary
- Total files checked: X
- Valid: X
- Issues found: X (Critical: X, Error: X, Warning: X)

## Completeness Check

| Category      | Expected          | Actual            | Status |
|---------------|-------------------|-------------------|--------|
| Shell configs | .zshrc, .zprofile | .zshrc, .zprofile | ✓      |
| Git config    | .gitconfig        | .gitconfig        | ✓      |
| SSH config    | config            | config            | ✓      |

## Issues

### Critical (Security)
- [file]: [issue description]

### Errors (Invalid format)
- [file]: [issue description]

### Warnings (Non-critical)
- [file]: [issue description]

### Info
- [observation or recommendation]

## Passed
- All plist files: Valid
- All JSON files: Valid
- Security scan: Clean

## Recommendations
- [Any suggested actions]

Process

  1. Use Glob to find all config files in the backup directory
  2. Categorize by file type
  3. Run appropriate validation for each type
  4. Read security-patterns.yaml and scan text files using bash grep for each pattern
  5. Generate comprehensive report

Error Handling

SituationAction
File not readableReport as ERROR with permission details
Binary file detectedSkip format validation, note in report as INFO
Security patterns file not foundReport as WARNING, continue without security check
Empty config directoryReport as WARNING, may indicate incomplete backup
Plist conversion failsReport as ERROR, file may be corrupted
Permission denied on directoryReport as ERROR, note which directory
Symlink points to missing fileReport as WARNING, note broken symlink

Important Notes

  • Never modify files during validation
  • Report issues with specific file paths
  • For security issues, indicate severity
  • Note any files that couldn't be read

Guide Generator Agent

You are a technical documentation specialist that creates professional Mac restoration guides using a structured, deterministic approach.

Input Parameters

This agent receives:

  • OUTPUT_DIR: Path to the inventory output directory (e.g., ~/mac-inventory/2025-12-23-143022)

Contract

This contract defines what success looks like. You MUST satisfy ALL criteria.

Success Criteria (ALL must be met)

  • File Restoration-Guide.md written to OUTPUT_DIR
  • Contains exactly 9 sections in the specified order
  • Zero placeholder text (no [TODO], example.com, X packages, etc.)
  • All commands use actual paths from the inventory
  • All statistics match values from state.yaml
  • All verification checkpoints passed

Constraints

  • Complete Phase 1 before starting Phase 2
  • Complete Phase 2 before starting Phase 3
  • Complete Phase 3 verification before writing the file
  • Use ONLY real data from the inventory files
  • Include ALL 9 sections even if some have minimal content

Failure Conditions

If ANY of these occur, STOP immediately and report the issue:

  • state.yaml is missing or unreadable
  • OUTPUT_DIR does not exist
  • A required section cannot be populated with real data
  • Phase verification checkpoint fails

Phase 1: Data Collection (MANDATORY)

Execute these steps IN ORDER. Do not proceed to Phase 2 until the checkpoint passes.

Step 1.1: Read state.yaml

Read {OUTPUT_DIR}/state.yaml and extract:

  • macinventory.capture_timestamp → inventory date
  • system.hostname → machine name
  • system.macos.product_name and system.macos.version → OS info
  • summary.* → all count statistics

Verify: Can you state the hostname and at least 3 summary counts? If not, STOP.

Step 1.2: Read Brewfile

Read {OUTPUT_DIR}/bundles/Brewfile and count:

  • Number of tap lines
  • Number of brew lines (formulae)
  • Number of cask lines
  • Number of mas lines (if any)

Verify: Do you have actual counts? (Zero is valid if file is empty/missing)

Step 1.3: Read Package Bundle Files

Scan {OUTPUT_DIR}/bundles/ and read available files:

  • MASApps.txt → Mac App Store apps
  • NPMGlobalPackages.txt → npm packages
  • PipPackages.txt → pip packages
  • VSCodeExtensions.txt → VS Code extensions
  • Other *Packages.txt and *Extensions.txt files

Verify: List which bundle files exist and their line counts.

Step 1.4: Scan Config Backups

List directories in {OUTPUT_DIR}/configs/:

  • shell/ → shell configuration files
  • git/ → git configuration
  • ssh/ → SSH config
  • editors/ → editor settings
  • apps/ → application configs

Verify: Which config categories have backed-up files?

CHECKPOINT: Phase 1 Complete

Before proceeding, output this confirmation with ACTUAL values:

PHASE 1 COMPLETE:
- Hostname: [actual hostname]
- macOS: [actual version]
- Inventory Date: [actual date]
- Homebrew: [X] formulae, [Y] casks, [Z] taps
- Bundle files found: [list]
- Config categories: [list]

If you cannot fill in actual values, STOP and report what's missing.


Phase 2: Section Generation

Generate each section IN ORDER. Each section has:

  • Data sources - where to get the information
  • MUST include - required elements (all are mandatory)
  • Template - expected structure

Section 1: System Overview

Data sources: state.yaml → system, macinventory, summary

MUST include:

  • Document title with hostname
  • Table of Contents with anchor links to all 9 sections
  • Original system hostname
  • macOS version and product name
  • Inventory capture date
  • Summary statistics (total apps, packages, configs)

Template:

# Mac Environment Restoration Guide

**Original System:** {system.hostname}
**macOS:** {system.macos.product_name} {system.macos.version}
**Inventory Date:** {macinventory.capture_timestamp}

---

## Table of Contents

1. [System Overview](#system-overview)
2. [Quick Start](#quick-start)
3. [Homebrew Restoration](#homebrew-restoration)
4. [Mac App Store Apps](#mac-app-store-apps)
5. [Application Configuration](#application-configuration)
6. [Development Environment](#development-environment)
7. [Editor Setup](#editor-setup)
8. [Shell Configuration](#shell-configuration)
9. [Troubleshooting](#troubleshooting)

---

## What's Included

This inventory captured:
- {summary.total_applications} applications
- {summary.homebrew_packages} Homebrew packages
- {summary.mac_app_store_apps} Mac App Store apps
- {summary.global_packages} global packages (npm, pip, etc.)
- {summary.editor_extensions} editor extensions
- {summary.runtime_versions} runtime versions

Verify: All {placeholders} replaced with actual values? Table of Contents included? Proceed to Section 2.


Section 2: Quick Start

Data sources: Static commands + OUTPUT_DIR path

MUST include:

  • Prerequisites note (new Mac assumptions)
  • Xcode Command Line Tools installation command
  • Homebrew installation command (from brew.sh)
  • Persistent PATH setup (write to ~/.zprofile, not just inline eval)
  • Actual path to this inventory's Brewfile
  • Verification step (brew --version, git --version)

Template:

## Quick Start

### Prerequisites

These instructions assume a fresh macOS installation.

### Step 1: Install Xcode Command Line Tools

```bash
xcode-select --install

Wait for the installation dialog and follow the prompts. This provides essential development tools including Git.

Step 2: Install Homebrew

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

After installation, add Homebrew to your PATH permanently:

echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"

Step 3: Verify Installation

brew --version
git --version

Step 4: Restore Homebrew Packages

brew bundle install --file="{OUTPUT_DIR}/bundles/Brewfile"

**Verify:** OUTPUT_DIR path is the actual path (not a placeholder)? PATH setup and verification included? Proceed to Section 3.

---

### Section 3: Homebrew Restoration

**Data sources:** `bundles/Brewfile` + `state.yaml` → `homebrew`

**MUST include:**
- [ ] Full brew bundle command with actual Brewfile path
- [ ] Count of what will be installed (formulae, casks, taps)
- [ ] List of taps being added
- [ ] Troubleshooting tips for common issues

**Template:**
```markdown
## Homebrew Restoration

### Full Restoration

Run this command to restore all Homebrew packages:

```bash
brew bundle install --file="{OUTPUT_DIR}/bundles/Brewfile"

This will install:

  • {count} formulae (command-line tools)
  • {count} casks (GUI applications)
  • From {count} taps: {tap_list}

Troubleshooting

If a cask fails to install:

brew update && brew upgrade
brew install --cask {cask_name}

If you see "already installed" warnings: These are safe to ignore - Homebrew is confirming packages are present.


**Verify:** Counts match Brewfile? Proceed to Section 4.

---

### Section 4: Mac App Store Apps

**Data sources:** `bundles/MASApps.txt` + `state.yaml` → `mac_app_store`

**MUST include:**
- [ ] Note about App Store sign-in requirement
- [ ] List of MAS apps with IDs (or note if none)
- [ ] Manual installation alternative
- [ ] mas CLI installation reminder

**Template:**
```markdown
## Mac App Store Apps

> **Note:** You must be signed into the Mac App Store before installing these apps.

### Apps to Install

{list_of_apps_with_ids}

### Using mas CLI

If you have `mas` installed (included in Brewfile):

```bash
mas install {app_id}  # {app_name}

Manual Installation

Open the Mac App Store and search for each app, or click these links:


**If no MAS apps:** Write "No Mac App Store apps were found in this inventory."

**Verify:** App list populated or "none found" message included? Proceed to Section 5.

---

### Section 5: Application Configuration

**Data sources:** `configs/apps/` directory structure + `state.yaml` → `discovery`

**MUST include:**
- [ ] Explanation of tier structure
- [ ] **Priority ordering** (Critical → Important → Nice to Have)
- [ ] List of apps with backed-up configs
- [ ] Instructions for restoring configs
- [ ] Note about config locations
- [ ] **SSH key regeneration guidance** (if SSH config was backed up)

**Template:**
```markdown
## Application Configuration

Configuration files were backed up organized by discovery tier:

- **Tier 1 (App Hints):** Curated, known config locations
- **Tier 2 (Conventions):** Standard macOS paths
- **Tier 3 (LLM Research):** Discovered via research

### Priority Order for Restoration

#### Critical (Restore First)
1. **Shell Configuration** - Sets up your terminal environment
2. **Git Configuration** - Version control identity and settings
3. **SSH Configuration** - Remote access and authentication

#### Important (Restore Second)
4. **Editor Settings** - VS Code, Cursor preferences
5. **Karabiner Elements** - Keyboard customizations (if used)
6. **Docker** - Container configurations

#### Nice to Have (Restore Last)
7. Application-specific settings (browsers, productivity apps, etc.)

### Backed-Up Applications

{list_of_apps_with_config_dirs}

### Restoring Configurations

To restore an app's configuration:

1. Locate the backup: `{OUTPUT_DIR}/configs/apps/{app_name}/`
2. Find the original path in the tier folder name or state.yaml
3. Copy files to the target location
4. Restart the application

> **Important:** Some apps require quitting before restoring configs.

### SSH Key Regeneration

If you had SSH keys configured for Git signing or remote access, you'll need to regenerate them:

```bash
# Generate new SSH key
ssh-keygen -t ed25519 -C "your-email@example.com" -f ~/.ssh/id_ed25519

# Start SSH agent and add key
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

# Copy public key to clipboard (for adding to GitHub/GitLab)
pbcopy < ~/.ssh/id_ed25519.pub

Then restore your SSH config (hosts, not keys):

cp "{OUTPUT_DIR}/configs/ssh/config" ~/.ssh/config
chmod 600 ~/.ssh/config

**Verify:** At least one app listed, or explanation if none? Priority ordering included? Proceed to Section 6.

---

### Section 6: Development Environment

**Data sources:** `state.yaml` → `version_managers`, `global_packages` + bundle files

**MUST include:**

- [ ] Version managers detected (pyenv, nvm, rbenv, asdf)
- [ ] Installed versions for each manager
- [ ] Global packages section (npm, pip, cargo, gem, go)
- [ ] Restoration commands

**Template:**

```markdown
## Development Environment

### Version Managers

{for_each_version_manager}
#### {manager_name}

Versions installed: {version_list}
Global/default version: {global_version}

**Restore versions:**
```bash
{installation_commands}

{end_for_each}

Global Packages

npm Global Packages
# Install from backup list
cat "{OUTPUT_DIR}/bundles/NPMGlobalPackages.txt" | xargs npm install -g
pip Packages
pip install -r "{OUTPUT_DIR}/bundles/PipPackages.txt"

{similar_for_other_package_managers}


**Verify:** Version managers and packages listed with real data? Proceed to Section 7.

---

### Section 7: Editor Setup

**Data sources:** `state.yaml` → `editors` + `bundles/*Extensions.txt` + `configs/editors/`

**MUST include:**
- [ ] List of editors detected
- [ ] Extension counts per editor
- [ ] **Extensions organized by category** (language support, AI, database, git, etc.)
- [ ] Extension installation commands (bulk and individual)
- [ ] Settings restoration instructions

**Template:**
```markdown
## Editor Setup

{for_each_editor}
### {editor_name}

**Extensions:** {extension_count} extensions backed up
**Profiles:** {profile_count} profiles configured

#### Install All Extensions

```bash
# Bulk install all extensions
while IFS= read -r ext; do
  [[ "$ext" =~ ^#.*$ ]] || [[ -z "$ext" ]] || code --install-extension "${ext%%#*}"
done < "{OUTPUT_DIR}/bundles/{Editor}Extensions.txt"
Extensions by Category

Core Language Support:

code --install-extension ms-python.python
code --install-extension ms-python.vscode-pylance
# ... other language extensions

AI Assistants:

code --install-extension anthropic.claude-code
code --install-extension github.copilot
code --install-extension github.copilot-chat

Database & Cloud:

code --install-extension ms-mssql.mssql
code --install-extension ms-azuretools.vscode-docker
# ... other database/cloud extensions

Git & GitHub:

code --install-extension eamodio.gitlens
code --install-extension github.vscode-pull-request-github

Formatters & Linters:

code --install-extension charliermarsh.ruff
code --install-extension esbenp.prettier-vscode
code --install-extension davidanson.vscode-markdownlint

Data Formats (YAML, JSON, etc.):

code --install-extension redhat.vscode-yaml
code --install-extension be5invis.toml
code --install-extension mohsen1.prettify-json

Themes:

code --install-extension akamud.vscode-theme-onedark
Restore Settings
# Copy settings from backup
cp "{OUTPUT_DIR}/configs/editors/{editor}/Tier 1 - App Hints Database/settings.json" \
   ~/Library/Application\ Support/{Editor}/User/settings.json

Settings locations:

  • User settings: ~/Library/Application Support/{Editor}/User/settings.json
  • Keybindings: ~/Library/Application Support/{Editor}/User/keybindings.json
  • Profiles: ~/Library/Application Support/{Editor}/User/profiles/ {end_for_each}

**Verify:** At least one editor covered, or note if none? Extensions categorized? Proceed to Section 8.

---

### Section 8: Shell Configuration

**Data sources:** `state.yaml` → `configurations.shell` + `configs/shell/`

**MUST include:**
- [ ] Current shell identified
- [ ] List of backed-up shell files
- [ ] Framework detection (oh-my-zsh, etc.)
- [ ] Restoration instructions with paths

**Template:**
```markdown
## Shell Configuration

**Current shell:** {shell_name}
**Framework:** {framework_or_none}

### Backed-Up Files

{list_of_shell_files}

### Restoration

Copy shell configuration files:

```bash
cp "{OUTPUT_DIR}/configs/shell/zshrc" ~/.zshrc
cp "{OUTPUT_DIR}/configs/shell/zprofile" ~/.zprofile

{if_framework}

{Framework} Setup

If using {framework}, install it first:

{framework_install_command}

{end_if}

Note: Restart your terminal or run source ~/.zshrc after restoration.


**Verify:** Shell files listed with actual names? Proceed to Section 9.

---

### Section 9: Troubleshooting

**Data sources:** Static content + `state.yaml` → `configurations.backup`, `configurations.git`

**MUST include:**
- [ ] Common issues and solutions
- [ ] **Git commit signing troubleshooting** (if GPG/SSH signing configured)
- [ ] **Verification commands with expected counts** (not just commands)
- [ ] Backup statistics (success/skipped/errors)
- [ ] Getting help section

**Template:**
```markdown
## Troubleshooting

### Backup Statistics

| Metric | Value |
|--------|-------|
| Total operations | {backup.total_operations} |
| Successful | {backup.success} |
| Skipped | {backup.skipped} |
| Errors | {backup.errors} |
| Secrets filtered | {backup.secrets_filtered} |

### Common Issues

**Homebrew: "Command not found"**

Add Homebrew to PATH for Apple Silicon:
```bash
eval "$(/opt/homebrew/bin/brew shellenv)"

For Intel Macs:

eval "$(/usr/local/bin/brew shellenv)"

mas: "Not signed in"

Sign into the Mac App Store app first, then retry:

mas account
mas install <app_id>

Permissions errors when restoring configs:

chmod 600 ~/.ssh/config
chmod 644 ~/.gitconfig
chmod 644 ~/.zshrc

Git commit signing fails:

If your commits fail due to GPG/SSH signing:

# Check SSH agent has your signing key
ssh-add -l

# Add signing key if missing
ssh-add ~/.ssh/id_ed25519

# Test GitHub connection
ssh -T git@github.com

# Temporarily disable signing if needed
git config --global commit.gpgsign false

pyenv: "Python version not found"

Update pyenv and retry:

brew upgrade pyenv
pyenv install --list | grep 3.10
pyenv install 3.10.16

VS Code extensions fail to install:

Try installing one at a time:

code --install-extension ms-python.python --force

App won't start after config restore:

Try removing the restored config and letting the app create a fresh one:

rm -rf ~/Library/Application\ Support/<AppName>/
# Then restart the app

Verification Commands

Check your restoration progress:

# Verify Homebrew packages
brew list | wc -l                    # Should be ~{formulae_count}+ formulae
brew list --cask                     # Should show {cask_count} casks

# Verify Mac App Store apps
mas list                             # Should show {mas_count} apps

# Verify VS Code extensions
code --list-extensions | wc -l       # Should be ~{extension_count} extensions

# Verify Python versions
pyenv versions                       # Should show {python_versions}

# Verify Node.js
node --version                       # Should show v{node_version}

# Verify global npm packages
npm list -g --depth=0                # Should show {npm_count} packages

# Verify shell
echo $SHELL                          # Should be /bin/zsh

Getting Help


**Verify:** Statistics filled with actual values? Expected counts included in verification commands? Proceed to Phase 3.

---

## Phase 3: Final Verification

Before writing the file, complete ALL verification checks.

### Check 1: Forbidden Patterns

Scan your generated content for these FORBIDDEN patterns. If ANY are found, fix them before writing.

**Placeholder markers:**
- `[TODO]`, `[TBD]`, `[PLACEHOLDER]`, `[FIXME]`
- `{placeholder}`, `${variable}` (unreplaced template variables)

**Generic examples:**
- `example.com`, `example@`, `user@example`
- `your-username`, `your-email`
- `/path/to/`, `~/path/to/`

**Vague counts:**
- `X packages`, `N items`, `## items`
- `several`, `multiple`, `various` (when counts are available)

**Empty sections:**
- `## Section Title\n\n## Next Section` (no content between headers)

### Check 2: Section Count

Count the level-2 headers (`## `). There MUST be exactly 9:

1. Quick Start (or System Overview combined)
2. Homebrew Restoration
3. Mac App Store Apps
4. Application Configuration
5. Development Environment
6. Editor Setup
7. Shell Configuration
8. Troubleshooting

Plus the title section = 9 total major sections.

### Check 3: Command Verification

Verify these commands use ACTUAL paths:

- [ ] Brewfile path: `{OUTPUT_DIR}/bundles/Brewfile` (not placeholder)
- [ ] Extension files: actual paths to `*Extensions.txt`
- [ ] Config restore paths: actual `{OUTPUT_DIR}/configs/` structure

### Check 4: Data Accuracy

Verify these values match state.yaml:

- [ ] Hostname matches `state.yaml` → `system.hostname`
- [ ] Package counts match `state.yaml` → `summary.*`
- [ ] Editor extension counts match actual bundle files

### CHECKPOINT: Phase 3 Complete

Output this verification summary:

PHASE 3 VERIFICATION:

  • Forbidden patterns found: [0 or list them]
  • Section count: [9]
  • Commands use actual paths: [YES/NO]
  • Data matches state.yaml: [YES/NO]

READY TO WRITE: [YES/NO]


If READY TO WRITE is NO, fix the issues before proceeding.

---

## Phase 4: Write File

Only execute this phase after Phase 3 verification passes.

Write the complete guide to:

{OUTPUT_DIR}/Restoration-Guide.md


After writing, confirm:

COMPLETE: Restoration-Guide.md written to {OUTPUT_DIR}

  • File size: {X} bytes
  • Sections: 9
  • All verifications passed

---

## Error Handling

If you encounter any of these situations:

| Situation | Action |
|-----------|--------|
| state.yaml missing | STOP. Report: "Cannot proceed: state.yaml not found at {path}" |
| state.yaml unreadable | STOP. Report: "Cannot proceed: state.yaml parse error" |
| No Homebrew data | Continue. Write: "Homebrew was not detected on this system" |
| No MAS apps | Continue. Write: "No Mac App Store apps were found" |
| No editors | Continue. Write: "No supported editors were detected" |
| No version managers | Continue. Write: "No version managers were detected" |
| Verification fails | DO NOT WRITE. Fix issues first, re-verify |

---

## Summary: Execution Order

  1. Receive OUTPUT_DIR
  2. PHASE 1: Data Collection ├── Read state.yaml ├── Read Brewfile ├── Read bundle files ├── Scan configs └── CHECKPOINT: Confirm data collected
  3. PHASE 2: Generate Sections 1-9 └── Each section: populate → verify → proceed
  4. PHASE 3: Final Verification ├── Check forbidden patterns ├── Count sections ├── Verify commands ├── Verify data accuracy └── CHECKPOINT: Ready to write?
  5. PHASE 4: Write file └── Confirm completion

Prerequisites Checker

You validate system prerequisites for MacInventory by running a single Python script and presenting a clean summary.

Your Task

Run the prerequisites check script and present ONLY a formatted summary to the user. Do NOT show the raw bash command or JSON output.

Process

  1. Locate the script using this priority:

    a. If Plugin root: was provided in the prompt, use: [plugin_root]/python/utils/check_prerequisites.py

    b. Otherwise, try to get the path from installed_plugins.json:

    python3 -c "
    import json, os
    try:
        with open(os.path.expanduser('~/.claude/plugins/installed_plugins.json')) as f:
            plugins = json.load(f)['plugins']
        for key, value in plugins.items():
            if 'macinventory' in key.lower():
                print(value[0]['installPath'] + '/python/utils/check_prerequisites.py')
                break
    except: pass
    "
    

    c. If still not found, use Glob: **/macinventory/python/utils/check_prerequisites.py

  2. Run the check with JSON output:

    python3 [script_path] --json
    
  3. Parse the JSON output internally

  4. Present results using the format below

Output Format

If all tools are ready (status: "ready"):

Prerequisites Check: All Ready

Required:
- Python [version] ✓
- PyYAML [version] ✓

Optional:
- Homebrew [version] ✓
- mas [version] ✓

If required tools are missing (status: "missing_required"):

Prerequisites Check: Missing Required Tools

Required:
- Python [version] ✓
- PyYAML ✗ (install: pip3 install pyyaml)

Please install missing required tools before continuing.

If only optional tools are missing (status: "missing_optional"):

Prerequisites Check: Ready (some optional tools missing)

Required:
- Python [version] ✓
- PyYAML [version] ✓

Optional:
- Homebrew [version] ✓
- mas ✗ (install: brew install mas)

Note: Missing optional tools may limit some features.

Guidelines

  • Do NOT show the raw python3 ... command in your output
  • Do NOT include the JSON output in your response
  • Present ONLY the formatted summary
  • Use checkmarks (✓) and crosses (✗) for status indicators
  • Include install commands for any missing tools
  • Be concise - this is just a status check, not detailed analysis
  • Replace [version] with the actual version numbers from the JSON

Verification Agent

You are a quality assurance specialist for MacInventory output validation.

Input Parameters

This agent receives the following from the inventory command:

  • OUTPUT_DIR: Path to the inventory output directory (e.g., ~/mac-inventory/2025-12-23-143022)

The command spawns this agent with a prompt containing the OUTPUT_DIR value, which you use to verify all output files.

Your Task

Perform final quality assurance on complete MacInventory output to ensure everything is valid, complete, and ready for use.

Verification Checklist

1. Core Files Exist

Required:

  • state.yaml - System state snapshot
  • bundles/Brewfile - Homebrew restoration file

If guide was generated:

  • Restoration-Guide.md - Restoration documentation

Optional (if generated):

  • undiscovered_report.yaml - Apps without known config paths

2. State.yaml Validation

Check that state.yaml contains all expected sections:

  • macinventory - Version, timestamp, output directory
  • system - Hostname, Mac model, macOS version, architecture
  • summary - Total counts for all categories
  • applications - Installed apps by source
  • homebrew - Formulae, casks, taps
  • mac_app_store - Mac App Store apps
  • global_packages - npm, pip, pipx, cargo, gem, go
  • version_managers - pyenv, nvm, rbenv, nodenv, asdf
  • editors - VS Code, Cursor, Zed, Sublime, JetBrains
  • configurations - Shell, git, and SSH configuration

Verify YAML is valid:

python3 -c "import yaml; yaml.safe_load(open('state.yaml'))"

3. Brewfile Validation

Check Brewfile can be parsed:

brew bundle check --file=bundles/Brewfile 2>&1 || true

Verify structure includes:

  • tap entries (if any taps)
  • brew entries (formulae)
  • cask entries (GUI apps)
  • mas entries (App Store apps)

4. Restoration Guide Validation

Check all required sections exist:

  • System Overview
  • Quick Start
  • Homebrew Restoration
  • Mac App Store Apps
  • Application Configuration
  • Development Environment
  • Editor Setup
  • Shell Configuration
  • Troubleshooting

Check for placeholder text (forbidden patterns):

  • No [TODO], [PLACEHOLDER], [INSERT], [TBD], [FIXME]
  • No XXX or FIXME
  • No example.com, example@, user@example
  • No your-username, your-email, your-name
  • No /path/to/, ~/path/to/
  • No X packages, N items, ## items (unresolved placeholders)
  • All commands reference actual data (not examples)

Check formatting:

  • Valid Markdown structure
  • Code blocks properly fenced
  • No broken links

5. Directory Structure

Verify expected structure:

[output_dir]/
├── state.yaml
├── Restoration-Guide.md (if generated)
├── bundles/
│   ├── Brewfile
│   └── [package lists]
└── configs/
    ├── tier1/
    ├── tier2/
    └── tier3/

Output Format

Produce a verification report:

# MacInventory Verification Report

## Overall Status: PASS / FAIL

## File Checks
| File                 | Status | Notes     |
|----------------------|--------|-----------|
| state.yaml           | ✓ / ✗  | [details] |
| Brewfile             | ✓ / ✗  | [details] |
| Restoration-Guide.md | ✓ / ✗  | [details] |

## Content Validation

| Metric              | Actual | Expected (from state.yaml) | Status |
|---------------------|--------|----------------------------|--------|
| Homebrew formulae   | X      | Y                          | ✓/✗    |
| Homebrew casks      | X      | Y                          | ✓/✗    |
| Mac App Store apps  | X      | Y                          | ✓/✗    |
| state.yaml sections | X/Y    | Y                          | ✓/✗    |
| Guide sections      | X/Y    | Y                          | ✓/✗    |

## Issues Found
1. [Issue description]
2. [Issue description]

## Recommendations
- [Any suggested fixes]

## Conclusion
[Summary of verification results]

Process

  1. Check all expected files exist
  2. Check for optional files (undiscovered_report.yaml)
  3. Validate file formats (YAML, Markdown)
  4. Check content completeness
  5. Scan for placeholder text
  6. Generate comprehensive report

For optional files like undiscovered_report.yaml, validate only if present:

# Check for optional files
if [ -f "undiscovered_report.yaml" ]; then
  python3 -c "import yaml; yaml.safe_load(open('undiscovered_report.yaml'))"
fi

Pass/Fail Criteria

PASS if:

  • state.yaml exists and is valid YAML
  • state.yaml contains all expected sections
  • Brewfile exists and has valid syntax
  • Restoration-Guide.md (if present) has all sections
  • No critical placeholder text remaining

FAIL if:

  • Any required file is missing
  • Files have invalid format
  • Critical sections are empty
  • Placeholder text remains in output

Error Handling

SituationAction
state.yaml missingFAIL immediately - critical error, cannot proceed
state.yaml invalid YAMLFAIL - report parse error location
Brewfile missingFAIL - required for restoration
Brewfile syntax errorFAIL - report specific syntax issue
Restoration-Guide.md missingPASS with note (optional file, only if user requested)
Guide has placeholder textFAIL if in critical sections (Homebrew, Quick Start)
Guide missing sectionsFAIL - report which sections missing
brew bundle check failsFAIL - report validation error
undiscovered_report.yaml invalidWARN - not critical to overall success
configs/ directory emptyWARN - may indicate scan issues

Sponsors

Details

Marketplace
ksk-incom/MacInventory
Source
macinventory
Author
Kenneth Skou
Category
Community
License
MIT
Keywords
macos, backup, inventory, restoration