@clawhub-xueyetianya-5e1be6a645
Renko reference tool. Use when working with renko in finance contexts.
--- name: "renko" version: "1.0.0" description: "Renko reference tool. Use when working with renko in finance contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [renko, finance, finance, reference, cli] category: "finance" --- # Renko Renko reference tool. Use when working with renko in finance contexts. ## When to Use - Working with renko and need quick reference - Looking up finance standards or best practices for renko - Troubleshooting renko issues - Need a checklist or guide for renko tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and fundamentals ### `formulas` ```bash scripts/script.sh formulas ``` Key formulas and calculations ### `regulations` ```bash scripts/script.sh regulations ``` Regulatory framework and compliance ### `risks` ```bash scripts/script.sh risks ``` Risk factors and mitigation ### `instruments` ```bash scripts/script.sh instruments ``` Instruments and tools overview ### `strategies` ```bash scripts/script.sh strategies ``` Common strategies and approaches ### `glossary` ```bash scripts/script.sh glossary ``` Key terms and definitions ### `checklist` ```bash scripts/script.sh checklist ``` Due diligence checklist ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # renko — Renko reference tool. Use when working with renko in finance contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' renko v$VERSION — Renko Reference Tool Usage: renko <command> Commands: intro Overview and fundamentals formulas Key formulas and calculations regulations Regulatory framework and compliance risks Risk factors and mitigation instruments Instruments and tools overview strategies Common strategies and approaches glossary Key terms and definitions checklist Due diligence checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Renko — Overview ## What is Renko? Renko (renko) is a specialized tool/concept in the finance domain. It provides essential capabilities for professionals working with renko. ## Key Concepts - Core renko principles and fundamentals - How renko fits into the broader finance ecosystem - Essential terminology every practitioner should know ## Why Renko Matters Understanding renko is critical for: - Improving efficiency in finance workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic renko concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_formulas() { cat << 'EOF' # Renko — Key Formulas & Calculations ## Core Formulas - **Basic ratio**: Value = Input / Reference × 100 - **Growth rate**: (Current - Previous) / Previous × 100% - **Weighted average**: Sum(Value × Weight) / Sum(Weight) ## Common Calculations 1. Risk-adjusted return 2. Break-even analysis 3. Compound growth 4. Present/future value 5. Standard deviation ## Quick Reference | Metric | Formula | Use Case | |--------|---------|----------| | ROI | (Gain - Cost) / Cost | Investment evaluation | | CAGR | (End/Start)^(1/n) - 1 | Growth measurement | | Sharpe | (Return - RiskFree) / StdDev | Risk-adjusted performance | EOF } cmd_regulations() { cat << 'EOF' # Renko — Regulatory Framework ## Key Regulations - Primary governing laws and statutes - Industry-specific compliance requirements - International standards and agreements ## Compliance Requirements - Registration and licensing - Reporting obligations - Record-keeping requirements - Audit and inspection readiness ## Enforcement - Regulatory bodies and their jurisdiction - Penalty structures for non-compliance - Appeal and dispute resolution processes EOF } cmd_risks() { cat << 'EOF' # Renko — Risk Analysis ## Risk Categories 1. **Market Risk**: Price volatility and liquidity 2. **Operational Risk**: System failures and human error 3. **Regulatory Risk**: Changing laws and compliance 4. **Credit Risk**: Counterparty default ## Risk Mitigation - Diversification strategies - Hedging instruments - Insurance and guarantees - Contingency planning ## Risk Assessment Framework | Risk | Probability | Impact | Mitigation | |------|-------------|--------|------------| | High | Likely | Severe | Immediate action | | Medium | Possible | Moderate | Monitor closely | | Low | Unlikely | Minor | Accept or transfer | EOF } cmd_instruments() { cat << 'EOF' # Renko — Instruments & Tools Overview ## Primary Instruments - Core tools used in renko operations - Measurement and monitoring equipment - Software platforms and applications ## Selection Guide 1. Define requirements and constraints 2. Evaluate available options 3. Consider total cost of ownership 4. Assess vendor support and community 5. Test before committing EOF } cmd_strategies() { cat << 'EOF' # Renko — Common Strategies ## Fundamental Strategies 1. **Conservative**: Low risk, steady returns 2. **Balanced**: Moderate risk, diversified approach 3. **Aggressive**: Higher risk, growth-focused ## Implementation Steps 1. Define objectives and constraints 2. Select appropriate strategy 3. Execute with discipline 4. Monitor and adjust 5. Review periodically EOF } cmd_glossary() { cat << 'EOF' # Renko — Key Terms & Definitions ## Core Terminology - **Renko**: The primary subject of this reference - **finance**: The broader domain category - **Baseline**: A reference point for comparison - **Benchmark**: A standard for measuring performance - **Compliance**: Adherence to rules and standards - **Configuration**: System settings and parameters - **Diagnostics**: Tools and procedures for identifying issues - **Integration**: Connecting multiple systems together - **Protocol**: A set of rules governing communication - **Specification**: Detailed requirements document EOF } cmd_checklist() { cat << 'EOF' # Renko — Inspection Checklist ## Pre-Operation Checklist - [ ] Visual inspection completed - [ ] All connections secure - [ ] Safety systems functional - [ ] Operating parameters within range - [ ] Documentation current ## Daily Checks - [ ] System startup normal - [ ] No error indicators or alarms - [ ] Performance within expected range - [ ] Environmental conditions acceptable - [ ] Log entries reviewed ## Periodic Inspection - [ ] Comprehensive system test - [ ] Calibration verification - [ ] Wear component inspection - [ ] Firmware/software version check - [ ] Backup systems tested ## Shutdown Checklist - [ ] Proper shutdown sequence followed - [ ] All data saved and backed up - [ ] System secured - [ ] Maintenance items logged - [ ] Next startup requirements noted EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; formulas) cmd_formulas "$@" ;; regulations) cmd_regulations "$@" ;; risks) cmd_risks "$@" ;; instruments) cmd_instruments "$@" ;; strategies) cmd_strategies "$@" ;; glossary) cmd_glossary "$@" ;; checklist) cmd_checklist "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "renko v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: renko help"; exit 1 ;; esac
Candlestick reference tool. Use when working with candlestick in finance contexts.
--- name: "candlestick" version: "1.0.0" description: "Candlestick reference tool. Use when working with candlestick in finance contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [candlestick, finance, finance, reference, cli] category: "finance" --- # Candlestick Candlestick reference tool. Use when working with candlestick in finance contexts. ## When to Use - Working with candlestick and need quick reference - Looking up finance standards or best practices for candlestick - Troubleshooting candlestick issues - Need a checklist or guide for candlestick tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and fundamentals ### `formulas` ```bash scripts/script.sh formulas ``` Key formulas and calculations ### `regulations` ```bash scripts/script.sh regulations ``` Regulatory framework and compliance ### `risks` ```bash scripts/script.sh risks ``` Risk factors and mitigation ### `instruments` ```bash scripts/script.sh instruments ``` Instruments and tools overview ### `strategies` ```bash scripts/script.sh strategies ``` Common strategies and approaches ### `glossary` ```bash scripts/script.sh glossary ``` Key terms and definitions ### `checklist` ```bash scripts/script.sh checklist ``` Due diligence checklist ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # candlestick — Candlestick reference tool. Use when working with candlestick in finance contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' candlestick v$VERSION — Candlestick Reference Tool Usage: candlestick <command> Commands: intro Overview and fundamentals formulas Key formulas and calculations regulations Regulatory framework and compliance risks Risk factors and mitigation instruments Instruments and tools overview strategies Common strategies and approaches glossary Key terms and definitions checklist Due diligence checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Candlestick — Overview ## What is Candlestick? Candlestick (candlestick) is a specialized tool/concept in the finance domain. It provides essential capabilities for professionals working with candlestick. ## Key Concepts - Core candlestick principles and fundamentals - How candlestick fits into the broader finance ecosystem - Essential terminology every practitioner should know ## Why Candlestick Matters Understanding candlestick is critical for: - Improving efficiency in finance workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic candlestick concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_formulas() { cat << 'EOF' # Candlestick — Key Formulas & Calculations ## Core Formulas - **Basic ratio**: Value = Input / Reference × 100 - **Growth rate**: (Current - Previous) / Previous × 100% - **Weighted average**: Sum(Value × Weight) / Sum(Weight) ## Common Calculations 1. Risk-adjusted return 2. Break-even analysis 3. Compound growth 4. Present/future value 5. Standard deviation ## Quick Reference | Metric | Formula | Use Case | |--------|---------|----------| | ROI | (Gain - Cost) / Cost | Investment evaluation | | CAGR | (End/Start)^(1/n) - 1 | Growth measurement | | Sharpe | (Return - RiskFree) / StdDev | Risk-adjusted performance | EOF } cmd_regulations() { cat << 'EOF' # Candlestick — Regulatory Framework ## Key Regulations - Primary governing laws and statutes - Industry-specific compliance requirements - International standards and agreements ## Compliance Requirements - Registration and licensing - Reporting obligations - Record-keeping requirements - Audit and inspection readiness ## Enforcement - Regulatory bodies and their jurisdiction - Penalty structures for non-compliance - Appeal and dispute resolution processes EOF } cmd_risks() { cat << 'EOF' # Candlestick — Risk Analysis ## Risk Categories 1. **Market Risk**: Price volatility and liquidity 2. **Operational Risk**: System failures and human error 3. **Regulatory Risk**: Changing laws and compliance 4. **Credit Risk**: Counterparty default ## Risk Mitigation - Diversification strategies - Hedging instruments - Insurance and guarantees - Contingency planning ## Risk Assessment Framework | Risk | Probability | Impact | Mitigation | |------|-------------|--------|------------| | High | Likely | Severe | Immediate action | | Medium | Possible | Moderate | Monitor closely | | Low | Unlikely | Minor | Accept or transfer | EOF } cmd_instruments() { cat << 'EOF' # Candlestick — Instruments & Tools Overview ## Primary Instruments - Core tools used in candlestick operations - Measurement and monitoring equipment - Software platforms and applications ## Selection Guide 1. Define requirements and constraints 2. Evaluate available options 3. Consider total cost of ownership 4. Assess vendor support and community 5. Test before committing EOF } cmd_strategies() { cat << 'EOF' # Candlestick — Common Strategies ## Fundamental Strategies 1. **Conservative**: Low risk, steady returns 2. **Balanced**: Moderate risk, diversified approach 3. **Aggressive**: Higher risk, growth-focused ## Implementation Steps 1. Define objectives and constraints 2. Select appropriate strategy 3. Execute with discipline 4. Monitor and adjust 5. Review periodically EOF } cmd_glossary() { cat << 'EOF' # Candlestick — Key Terms & Definitions ## Core Terminology - **Candlestick**: The primary subject of this reference - **finance**: The broader domain category - **Baseline**: A reference point for comparison - **Benchmark**: A standard for measuring performance - **Compliance**: Adherence to rules and standards - **Configuration**: System settings and parameters - **Diagnostics**: Tools and procedures for identifying issues - **Integration**: Connecting multiple systems together - **Protocol**: A set of rules governing communication - **Specification**: Detailed requirements document EOF } cmd_checklist() { cat << 'EOF' # Candlestick — Inspection Checklist ## Pre-Operation Checklist - [ ] Visual inspection completed - [ ] All connections secure - [ ] Safety systems functional - [ ] Operating parameters within range - [ ] Documentation current ## Daily Checks - [ ] System startup normal - [ ] No error indicators or alarms - [ ] Performance within expected range - [ ] Environmental conditions acceptable - [ ] Log entries reviewed ## Periodic Inspection - [ ] Comprehensive system test - [ ] Calibration verification - [ ] Wear component inspection - [ ] Firmware/software version check - [ ] Backup systems tested ## Shutdown Checklist - [ ] Proper shutdown sequence followed - [ ] All data saved and backed up - [ ] System secured - [ ] Maintenance items logged - [ ] Next startup requirements noted EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; formulas) cmd_formulas "$@" ;; regulations) cmd_regulations "$@" ;; risks) cmd_risks "$@" ;; instruments) cmd_instruments "$@" ;; strategies) cmd_strategies "$@" ;; glossary) cmd_glossary "$@" ;; checklist) cmd_checklist "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "candlestick v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: candlestick help"; exit 1 ;; esac
Tailwind reference tool. Use when working with tailwind in frontend contexts.
--- name: "tailwind" version: "1.0.0" description: "Tailwind reference tool. Use when working with tailwind in frontend contexts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [tailwind, frontend, dev, reference, cli] category: "frontend" --- # Tailwind Tailwind reference tool. Use when working with tailwind in frontend contexts. ## When to Use - Working with tailwind and need quick reference - Looking up frontend standards or best practices for tailwind - Troubleshooting tailwind issues - Need a checklist or guide for tailwind tasks ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview and core concepts ### `quickstart` ```bash scripts/script.sh quickstart ``` Getting started guide ### `patterns` ```bash scripts/script.sh patterns ``` Common patterns and best practices ### `debugging` ```bash scripts/script.sh debugging ``` Debugging and troubleshooting ### `performance` ```bash scripts/script.sh performance ``` Performance optimization tips ### `security` ```bash scripts/script.sh security ``` Security considerations ### `migration` ```bash scripts/script.sh migration ``` Migration and upgrade guide ### `cheatsheet` ```bash scripts/script.sh cheatsheet ``` Quick reference cheat sheet ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # tailwind — Tailwind reference tool. Use when working with tailwind in frontend contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" show_help() { cat << 'HELPEOF' tailwind v$VERSION — Tailwind Reference Tool Usage: tailwind <command> Commands: intro Overview and core concepts quickstart Getting started guide patterns Common patterns and best practices debugging Debugging and troubleshooting performance Performance optimization tips security Security considerations migration Migration and upgrade guide cheatsheet Quick reference cheat sheet help Show this help version Show version Powered by BytesAgain | bytesagain.com HELPEOF } cmd_intro() { cat << 'EOF' # Tailwind — Overview ## What is Tailwind? Tailwind (tailwind) is a specialized tool/concept in the frontend domain. It provides essential capabilities for professionals working with tailwind. ## Key Concepts - Core tailwind principles and fundamentals - How tailwind fits into the broader frontend ecosystem - Essential terminology every practitioner should know ## Why Tailwind Matters Understanding tailwind is critical for: - Improving efficiency in frontend workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic tailwind concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Tailwind — Quick Start Guide ## Prerequisites - Basic understanding of frontend concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the tailwind package 2. Install dependencies 3. Configure initial settings 4. Verify installation ## First Steps 1. Run the hello-world example 2. Review the default configuration 3. Try a simple real-world task 4. Explore available commands and options ## Next Steps - Read the full documentation - Join the community forum - Try advanced features - Set up automated workflows EOF } cmd_patterns() { cat << 'EOF' # Tailwind — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for tailwind 2. **Scalable Pattern**: For high-volume or distributed scenarios 3. **Resilient Pattern**: For fault-tolerant implementations ## Best Practices - Follow the principle of least privilege - Use version control for all configurations - Implement comprehensive logging - Test changes in staging before production - Document all custom configurations ## Anti-Patterns to Avoid - Hardcoding credentials or configuration - Skipping validation and error handling - Ignoring monitoring and alerting - Making changes without documentation - Over-engineering simple solutions EOF } cmd_debugging() { cat << 'EOF' # Tailwind — Debugging Guide ## Common Errors 1. **Connection refused**: Check service status and network 2. **Permission denied**: Verify credentials and access rights 3. **Timeout**: Check network, increase limits, optimize queries 4. **Invalid input**: Validate data format and encoding ## Debugging Tools - Built-in logging and diagnostics - Network analysis tools (tcpdump, wireshark) - System monitoring (top, htop, iostat) - Application-specific debug modes ## Debug Workflow 1. Reproduce the issue consistently 2. Check logs for error messages 3. Isolate the failing component 4. Test with minimal configuration 5. Apply fix and verify EOF } cmd_performance() { cat << 'EOF' # Tailwind — Performance Optimization ## Key Metrics - Response time / latency - Throughput / operations per second - Resource utilization (CPU, memory, I/O) - Error rate and retry frequency ## Optimization Strategies 1. **Caching**: Reduce redundant operations 2. **Batching**: Group small operations 3. **Indexing**: Speed up data lookups 4. **Compression**: Reduce data transfer size 5. **Parallel Processing**: Utilize multiple cores ## Monitoring - Set up baseline performance metrics - Configure alerts for anomalies - Track trends over time - Regular capacity planning reviews EOF } cmd_security() { cat << 'EOF' # Tailwind — Security Considerations ## Authentication & Authorization - Use strong, unique credentials - Implement role-based access control - Enable multi-factor authentication where possible - Regularly review and rotate credentials ## Data Protection - Encrypt data at rest and in transit - Implement proper backup procedures - Follow data retention policies - Sanitize inputs to prevent injection ## Network Security - Use firewalls and network segmentation - Monitor for suspicious activity - Keep all software patched and updated - Disable unnecessary services and ports EOF } cmd_migration() { cat << 'EOF' # Tailwind — Migration & Upgrade Guide ## Pre-Migration Checklist - [ ] Current system fully documented - [ ] Complete backup taken and verified - [ ] Target environment prepared - [ ] Rollback plan documented - [ ] Stakeholders notified ## Migration Steps 1. Prepare target environment 2. Export data from source 3. Transform data if needed 4. Import to target 5. Verify data integrity 6. Update configurations 7. Test all functionality 8. Switch traffic / go live ## Post-Migration - Monitor for errors and performance - Verify all integrations working - Update documentation - Decommission old system after confirmation EOF } cmd_cheatsheet() { cat << 'EOF' # Tailwind — Quick Reference ## Essential Commands | Command | Description | |---------|-------------| | help | Show available commands | | version | Display version info | | intro | Overview and fundamentals | | troubleshooting | Common problems and fixes | ## Common Workflows 1. **Setup**: install → configure → verify → test 2. **Daily**: check → monitor → report → review 3. **Issue**: diagnose → isolate → fix → verify → document ## Key Shortcuts - Use tab completion for commands - Check logs first when troubleshooting - Always backup before making changes - Document everything you change EOF } CMD="-help" shift 2>/dev/null || true case "$CMD" in intro) cmd_intro "$@" ;; quickstart) cmd_quickstart "$@" ;; patterns) cmd_patterns "$@" ;; debugging) cmd_debugging "$@" ;; performance) cmd_performance "$@" ;; security) cmd_security "$@" ;; migration) cmd_migration "$@" ;; cheatsheet) cmd_cheatsheet "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "tailwind v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: tailwind help"; exit 1 ;; esac
Analyze rugpull operations. Use when you need to understand rugpull mechanisms, evaluate protocol security, or reference on-chain concepts.
--- name: "rugpull" version: "1.0.0" description: "Analyze rugpull operations. Use when you need to understand rugpull mechanisms, evaluate protocol security, or reference on-chain concepts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [rugpull, blockchain, cli, tool] category: "blockchain" --- # Rugpull Analyze rugpull operations. Use when you need to understand rugpull mechanisms, evaluate protocol security, or reference on-chain concepts. ## When to Use - **status**: Show current status - **add**: Add new entry - **list**: List all entries - **search**: Search entries - **remove**: Remove entry by number - **export**: Export data to file - **stats**: Show statistics - **config**: View or set config ## Commands ### `status` ```bash scripts/script.sh status ``` Show current status ### `add` ```bash scripts/script.sh add ``` Add new entry ### `list` ```bash scripts/script.sh list ``` List all entries ### `search` ```bash scripts/script.sh search ``` Search entries ### `remove` ```bash scripts/script.sh remove ``` Remove entry by number ### `export` ```bash scripts/script.sh export ``` Export data to file ### `stats` ```bash scripts/script.sh stats ``` Show statistics ### `config` ```bash scripts/script.sh config ``` View or set config ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration Use `scripts/script.sh config <key> <value>` to customize behavior. | Variable | Description | |----------|-------------| | `RUGPULL_DIR` | Data directory (default: ~/.rugpull/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # rugpull -- Analyze rugpull operations. Use when you need to understand rugpull mechanisms, evaluate protocol security, or reference on-chain concepts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.rugpull" _ensure_dirs() { mkdir -p "$DATA_DIR"; } _save_entry() { _ensure_dirs local cmd="$1" val="$2" local ts=$(date '+%Y-%m-%d %H:%M:%S') printf '{"ts":"%s","cmd":"%s","val":"%s"}\n' "$ts" "$cmd" "$val" >> "$DATA_DIR/data.jsonl" } show_help() { cat << EOF rugpull v$VERSION -- Analyze rugpull operations. Use when you need to understand rugpull mechanisms, evaluate protocol security, or reference on-chain concepts. Usage: rugpull <command> [args] Commands: status Show current status add Add new entry list List all entries search Search entries remove Remove entry by number export Export data to file stats Show statistics config View or set config help Show this help version Show version Data: $DATA_DIR Powered by BytesAgain | bytesagain.com EOF } cmd_status() { echo "=== rugpull Status ===" echo " Version: $VERSION" echo " Data dir: $DATA_DIR" local entries=$(cat "$DATA_DIR"/*.jsonl 2>/dev/null | wc -l || echo 0) echo " Entries: $entries" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1 || echo empty)" } cmd_add() { local value="?Usage: rugpull add <entry>" shift || true _save_entry "add" "$value $*" local count=$(wc -l < "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Added: $value (entry #$count)" } cmd_list() { echo "=== Rugpull Entries ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local count=$(wc -l < "$DATA_DIR/data.jsonl") echo "Total: $count" echo "---" tail -20 "$DATA_DIR/data.jsonl" | while IFS= read -r line; do local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) local cmd=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo " [$ts] $cmd: $val" done else echo "No entries yet." fi } cmd_search() { local term="?Usage: rugpull search <term>" if [ -f "$DATA_DIR/data.jsonl" ]; then local matches=$(grep -ic "$term" "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Found: $matches matches" grep -i "$term" "$DATA_DIR/data.jsonl" 2>/dev/null | head -20 | while IFS= read -r line; do local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) echo " [$ts] $val" done else echo "No data to search." fi } cmd_remove() { local num="?Usage: rugpull remove <line-number>" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") if [ "$num" -ge 1 ] 2>/dev/null && [ "$num" -le "$total" ] 2>/dev/null; then sed -i "numd" "$DATA_DIR/data.jsonl" echo "Removed #$num ($((total-1)) remaining)" else echo "Invalid: $num (total: $total)"; fi else echo "No data."; fi } cmd_export() { local fmt="-json" local out="rugpull-export.$fmt" if [ ! -f "$DATA_DIR/data.jsonl" ]; then echo "No data."; return 0; fi case "$fmt" in json) cp "$DATA_DIR/data.jsonl" "$out" ;; csv) echo "timestamp,command,value" > "$out" while IFS= read -r line; do ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) c2=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) vl=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo "$ts,$c2,$vl" >> "$out" done < "$DATA_DIR/data.jsonl" ;; *) echo "Formats: json, csv"; return 1 ;; esac echo "Exported: $out ($(wc -c < "$out") bytes)" } cmd_stats() { echo "=== Rugpull Stats ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") local bytes=$(wc -c < "$DATA_DIR/data.jsonl") echo " Entries: $total" echo " Size: $bytes bytes" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" else echo " No data yet."; fi } cmd_config() { local key="-" val="-" local cfg="$DATA_DIR/config.txt" if [ -z "$key" ]; then echo "=== Config ===" if [ -f "$cfg" ]; then while IFS="=" read -r k v; do echo " $k=$v"; done < "$cfg" else echo " (empty — use config <key> <value>)"; fi elif [ -z "$val" ]; then grep "^key=" "$cfg" 2>/dev/null | cut -d= -f2- || echo "(not set)" else if [ -f "$cfg" ] && grep -q "^key=" "$cfg" 2>/dev/null; then sed -i "s|^key=.*|key=val|" "$cfg" else echo "key=val" >> "$cfg" fi echo "Set: $key=$val" fi } CMD="-help" shift 2>/dev/null || true _ensure_dirs case "$CMD" in status) cmd_status "$@" ;; add) cmd_add "$@" ;; list) cmd_list "$@" ;; search) cmd_search "$@" ;; remove) cmd_remove "$@" ;; export) cmd_export "$@" ;; stats) cmd_stats "$@" ;; config) cmd_config "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "rugpull v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: rugpull help"; exit 1 ;; esac
Analyze flashloan operations. Use when you need to understand flashloan mechanisms, evaluate protocol security, or reference on-chain concepts.
--- name: "flashloan" version: "1.0.0" description: "Analyze flashloan operations. Use when you need to understand flashloan mechanisms, evaluate protocol security, or reference on-chain concepts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [flashloan, blockchain, cli, tool] category: "blockchain" --- # Flashloan Analyze flashloan operations. Use when you need to understand flashloan mechanisms, evaluate protocol security, or reference on-chain concepts. ## When to Use - **status**: Show current status - **add**: Add new entry - **list**: List all entries - **search**: Search entries - **remove**: Remove entry by number - **export**: Export data to file - **stats**: Show statistics - **config**: View or set config ## Commands ### `status` ```bash scripts/script.sh status ``` Show current status ### `add` ```bash scripts/script.sh add ``` Add new entry ### `list` ```bash scripts/script.sh list ``` List all entries ### `search` ```bash scripts/script.sh search ``` Search entries ### `remove` ```bash scripts/script.sh remove ``` Remove entry by number ### `export` ```bash scripts/script.sh export ``` Export data to file ### `stats` ```bash scripts/script.sh stats ``` Show statistics ### `config` ```bash scripts/script.sh config ``` View or set config ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration Use `scripts/script.sh config <key> <value>` to customize behavior. | Variable | Description | |----------|-------------| | `FLASHLOAN_DIR` | Data directory (default: ~/.flashloan/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # flashloan -- Analyze flashloan operations. Use when you need to understand flashloan mechanisms, evaluate protocol security, or reference on-chain concepts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.flashloan" _ensure_dirs() { mkdir -p "$DATA_DIR"; } _save_entry() { _ensure_dirs local cmd="$1" val="$2" local ts=$(date '+%Y-%m-%d %H:%M:%S') printf '{"ts":"%s","cmd":"%s","val":"%s"}\n' "$ts" "$cmd" "$val" >> "$DATA_DIR/data.jsonl" } show_help() { cat << EOF flashloan v$VERSION -- Analyze flashloan operations. Use when you need to understand flashloan mechanisms, evaluate protocol security, or reference on-chain concepts. Usage: flashloan <command> [args] Commands: status Show current status add Add new entry list List all entries search Search entries remove Remove entry by number export Export data to file stats Show statistics config View or set config help Show this help version Show version Data: $DATA_DIR Powered by BytesAgain | bytesagain.com EOF } cmd_status() { echo "=== flashloan Status ===" echo " Version: $VERSION" echo " Data dir: $DATA_DIR" local entries=$(cat "$DATA_DIR"/*.jsonl 2>/dev/null | wc -l || echo 0) echo " Entries: $entries" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1 || echo empty)" } cmd_add() { local value="?Usage: flashloan add <entry>" shift || true _save_entry "add" "$value $*" local count=$(wc -l < "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Added: $value (entry #$count)" } cmd_list() { echo "=== Flashloan Entries ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local count=$(wc -l < "$DATA_DIR/data.jsonl") echo "Total: $count" echo "---" tail -20 "$DATA_DIR/data.jsonl" | while IFS= read -r line; do local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) local cmd=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo " [$ts] $cmd: $val" done else echo "No entries yet." fi } cmd_search() { local term="?Usage: flashloan search <term>" if [ -f "$DATA_DIR/data.jsonl" ]; then local matches=$(grep -ic "$term" "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Found: $matches matches" grep -i "$term" "$DATA_DIR/data.jsonl" 2>/dev/null | head -20 | while IFS= read -r line; do local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) echo " [$ts] $val" done else echo "No data to search." fi } cmd_remove() { local num="?Usage: flashloan remove <line-number>" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") if [ "$num" -ge 1 ] 2>/dev/null && [ "$num" -le "$total" ] 2>/dev/null; then sed -i "numd" "$DATA_DIR/data.jsonl" echo "Removed #$num ($((total-1)) remaining)" else echo "Invalid: $num (total: $total)"; fi else echo "No data."; fi } cmd_export() { local fmt="-json" local out="flashloan-export.$fmt" if [ ! -f "$DATA_DIR/data.jsonl" ]; then echo "No data."; return 0; fi case "$fmt" in json) cp "$DATA_DIR/data.jsonl" "$out" ;; csv) echo "timestamp,command,value" > "$out" while IFS= read -r line; do ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) c2=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) vl=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo "$ts,$c2,$vl" >> "$out" done < "$DATA_DIR/data.jsonl" ;; *) echo "Formats: json, csv"; return 1 ;; esac echo "Exported: $out ($(wc -c < "$out") bytes)" } cmd_stats() { echo "=== Flashloan Stats ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") local bytes=$(wc -c < "$DATA_DIR/data.jsonl") echo " Entries: $total" echo " Size: $bytes bytes" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" else echo " No data yet."; fi } cmd_config() { local key="-" val="-" local cfg="$DATA_DIR/config.txt" if [ -z "$key" ]; then echo "=== Config ===" if [ -f "$cfg" ]; then while IFS="=" read -r k v; do echo " $k=$v"; done < "$cfg" else echo " (empty — use config <key> <value>)"; fi elif [ -z "$val" ]; then grep "^key=" "$cfg" 2>/dev/null | cut -d= -f2- || echo "(not set)" else if [ -f "$cfg" ] && grep -q "^key=" "$cfg" 2>/dev/null; then sed -i "s|^key=.*|key=val|" "$cfg" else echo "key=val" >> "$cfg" fi echo "Set: $key=$val" fi } CMD="-help" shift 2>/dev/null || true _ensure_dirs case "$CMD" in status) cmd_status "$@" ;; add) cmd_add "$@" ;; list) cmd_list "$@" ;; search) cmd_search "$@" ;; remove) cmd_remove "$@" ;; export) cmd_export "$@" ;; stats) cmd_stats "$@" ;; config) cmd_config "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "flashloan v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: flashloan help"; exit 1 ;; esac
Analyze cex operations. Use when you need to understand cex mechanisms, evaluate protocol security, or reference on-chain concepts.
--- name: "cex" version: "1.0.0" description: "Analyze cex operations. Use when you need to understand cex mechanisms, evaluate protocol security, or reference on-chain concepts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [cex, blockchain, cli, tool] category: "blockchain" --- # Cex Analyze cex operations. Use when you need to understand cex mechanisms, evaluate protocol security, or reference on-chain concepts. ## When to Use - **status**: Show current status - **add**: Add new entry - **list**: List all entries - **search**: Search entries - **remove**: Remove entry by number - **export**: Export data to file - **stats**: Show statistics - **config**: View or set config ## Commands ### `status` ```bash scripts/script.sh status ``` Show current status ### `add` ```bash scripts/script.sh add ``` Add new entry ### `list` ```bash scripts/script.sh list ``` List all entries ### `search` ```bash scripts/script.sh search ``` Search entries ### `remove` ```bash scripts/script.sh remove ``` Remove entry by number ### `export` ```bash scripts/script.sh export ``` Export data to file ### `stats` ```bash scripts/script.sh stats ``` Show statistics ### `config` ```bash scripts/script.sh config ``` View or set config ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration Use `scripts/script.sh config <key> <value>` to customize behavior. | Variable | Description | |----------|-------------| | `CEX_DIR` | Data directory (default: ~/.cex/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # cex -- Analyze cex operations. Use when you need to understand cex mechanisms, evaluate protocol security, or reference on-chain concepts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.cex" _ensure_dirs() { mkdir -p "$DATA_DIR"; } _save_entry() { _ensure_dirs local cmd="$1" val="$2" local ts=$(date '+%Y-%m-%d %H:%M:%S') printf '{"ts":"%s","cmd":"%s","val":"%s"}\n' "$ts" "$cmd" "$val" >> "$DATA_DIR/data.jsonl" } show_help() { cat << EOF cex v$VERSION -- Analyze cex operations. Use when you need to understand cex mechanisms, evaluate protocol security, or reference on-chain concepts. Usage: cex <command> [args] Commands: status Show current status add Add new entry list List all entries search Search entries remove Remove entry by number export Export data to file stats Show statistics config View or set config help Show this help version Show version Data: $DATA_DIR Powered by BytesAgain | bytesagain.com EOF } cmd_status() { echo "=== cex Status ===" echo " Version: $VERSION" echo " Data dir: $DATA_DIR" local entries=$(cat "$DATA_DIR"/*.jsonl 2>/dev/null | wc -l || echo 0) echo " Entries: $entries" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1 || echo empty)" } cmd_add() { local value="?Usage: cex add <entry>" shift || true _save_entry "add" "$value $*" local count=$(wc -l < "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Added: $value (entry #$count)" } cmd_list() { echo "=== Cex Entries ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local count=$(wc -l < "$DATA_DIR/data.jsonl") echo "Total: $count" echo "---" tail -20 "$DATA_DIR/data.jsonl" | while IFS= read -r line; do local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) local cmd=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo " [$ts] $cmd: $val" done else echo "No entries yet." fi } cmd_search() { local term="?Usage: cex search <term>" if [ -f "$DATA_DIR/data.jsonl" ]; then local matches=$(grep -ic "$term" "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Found: $matches matches" grep -i "$term" "$DATA_DIR/data.jsonl" 2>/dev/null | head -20 | while IFS= read -r line; do local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) echo " [$ts] $val" done else echo "No data to search." fi } cmd_remove() { local num="?Usage: cex remove <line-number>" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") if [ "$num" -ge 1 ] 2>/dev/null && [ "$num" -le "$total" ] 2>/dev/null; then sed -i "numd" "$DATA_DIR/data.jsonl" echo "Removed #$num ($((total-1)) remaining)" else echo "Invalid: $num (total: $total)"; fi else echo "No data."; fi } cmd_export() { local fmt="-json" local out="cex-export.$fmt" if [ ! -f "$DATA_DIR/data.jsonl" ]; then echo "No data."; return 0; fi case "$fmt" in json) cp "$DATA_DIR/data.jsonl" "$out" ;; csv) echo "timestamp,command,value" > "$out" while IFS= read -r line; do ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) c2=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) vl=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo "$ts,$c2,$vl" >> "$out" done < "$DATA_DIR/data.jsonl" ;; *) echo "Formats: json, csv"; return 1 ;; esac echo "Exported: $out ($(wc -c < "$out") bytes)" } cmd_stats() { echo "=== Cex Stats ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") local bytes=$(wc -c < "$DATA_DIR/data.jsonl") echo " Entries: $total" echo " Size: $bytes bytes" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" else echo " No data yet."; fi } cmd_config() { local key="-" val="-" local cfg="$DATA_DIR/config.txt" if [ -z "$key" ]; then echo "=== Config ===" if [ -f "$cfg" ]; then while IFS="=" read -r k v; do echo " $k=$v"; done < "$cfg" else echo " (empty — use config <key> <value>)"; fi elif [ -z "$val" ]; then grep "^key=" "$cfg" 2>/dev/null | cut -d= -f2- || echo "(not set)" else if [ -f "$cfg" ] && grep -q "^key=" "$cfg" 2>/dev/null; then sed -i "s|^key=.*|key=val|" "$cfg" else echo "key=val" >> "$cfg" fi echo "Set: $key=$val" fi } CMD="-help" shift 2>/dev/null || true _ensure_dirs case "$CMD" in status) cmd_status "$@" ;; add) cmd_add "$@" ;; list) cmd_list "$@" ;; search) cmd_search "$@" ;; remove) cmd_remove "$@" ;; export) cmd_export "$@" ;; stats) cmd_stats "$@" ;; config) cmd_config "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "cex v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: cex help"; exit 1 ;; esac
Use when managing time slots, creating schedule blocks, detecting booking conflicts, exporting calendars, or applying scheduling templates for appointments.
--- name: "Slot — Time Slot & Schedule Block Manager" description: "Use when managing time slots, creating schedule blocks, detecting booking conflicts, exporting calendars, or applying scheduling templates for appointments." version: "2.0.3" author: "BytesAgain" homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: ["slot", "schedule", "calendar", "time-management", "booking", "planner"] --- # Slot — Time Slot & Schedule Block Manager Create, query, and manage time slots and schedule blocks. Detect conflicts, export to standard calendar formats, and apply reusable templates. ## Commands ### create Create a new time slot with date, start/end time, and label. ```bash bash scripts/script.sh create "2024-03-15" "09:00" "10:30" "Team Standup" ``` ### list List all scheduled slots, optionally filtered by date range. ```bash bash scripts/script.sh list bash scripts/script.sh list "2024-03-15" "2024-03-22" ``` ### check-conflict Check if a proposed time slot conflicts with existing bookings. ```bash bash scripts/script.sh check-conflict "2024-03-15" "09:30" "10:00" ``` ### export Export slots to iCal (.ics) or CSV format. ```bash bash scripts/script.sh export ics bash scripts/script.sh export csv ``` ### templates Show or apply common scheduling templates (work day, pomodoro, etc.). ```bash bash scripts/script.sh templates bash scripts/script.sh templates pomodoro ``` ### help Show all commands. ```bash bash scripts/script.sh help ``` ## Output - Slot listings with conflict indicators - iCal and CSV exports - Template-based batch slot creation ## Feedback https://bytesagain.com/feedback/ Powered by BytesAgain | bytesagain.com FILE:scripts/script.sh #!/usr/bin/env bash # slot — Time Slot & Schedule Block Manager # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="2.0.3" SLOT_DIR="-$HOME/.slot-manager" SLOT_FILE="SLOT_DIR/slots.csv" ensure_data_dir() { mkdir -p "$SLOT_DIR" if [ ! -f "$SLOT_FILE" ]; then echo "id,date,start,end,label,category,created_at" > "$SLOT_FILE" fi } generate_id() { date +%s%N | sha256sum | head -c 8 } validate_time() { local t="$1" if [[ ! "$t" =~ ^[0-2][0-9]:[0-5][0-9]$ ]]; then echo "❌ Invalid time format: $t (use HH:MM, 24h)" >&2 return 1 fi local hour="*" if (( hour > 23 )); then echo "❌ Invalid hour: $hour" >&2 return 1 fi } validate_date() { local d="$1" if [[ ! "$d" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then echo "❌ Invalid date format: $d (use YYYY-MM-DD)" >&2 return 1 fi } time_to_minutes() { local t="$1" local h="*" local m="t##*" echo $(( 10#$h * 60 + 10#$m )) } minutes_to_time() { local mins="$1" printf "%02d:%02d" $(( mins / 60 )) $(( mins % 60 )) } cmd_create() { local date_str="-" local start_time="-" local end_time="-" local label="-Untitled" local category="-general" if [ -z "$date_str" ] || [ -z "$start_time" ] || [ -z "$end_time" ]; then cat <<'EOF' ═══════════════════════════════════════════════════ Create Time Slot ═══════════════════════════════════════════════════ Usage: bash scripts/script.sh create <date> <start> <end> [label] [category] Arguments: date Date in YYYY-MM-DD format start Start time in HH:MM (24h) end End time in HH:MM (24h) label Slot label/name (optional, default: "Untitled") category Category tag (optional, default: "general") Examples: bash scripts/script.sh create "2024-03-15" "09:00" "10:30" "Team Standup" "meeting" bash scripts/script.sh create "2024-03-15" "14:00" "15:00" "Deep Work" "focus" bash scripts/script.sh create "2024-03-16" "08:00" "08:30" "Morning Review" Categories: meeting — Meetings and calls focus — Deep work / focus time break — Breaks and rest admin — Administrative tasks personal — Personal appointments general — Default category 📖 More skills: bytesagain.com EOF return 0 fi ensure_data_dir validate_date "$date_str" || return 1 validate_time "$start_time" || return 1 validate_time "$end_time" || return 1 local start_min end_min start_min=$(time_to_minutes "$start_time") end_min=$(time_to_minutes "$end_time") if (( start_min >= end_min )); then echo "❌ Start time ($start_time) must be before end time ($end_time)" >&2 return 1 fi local duration=$(( end_min - start_min )) local id id=$(generate_id) local created_at created_at=$(date -Iseconds 2>/dev/null || date +%Y-%m-%dT%H:%M:%S) # Check for conflicts before creating local conflicts=0 while IFS=',' read -r sid sdate sstart send slabel scat screated; do [ "$sid" = "id" ] && continue [ "$sdate" != "$date_str" ] && continue local existing_start existing_end existing_start=$(time_to_minutes "$sstart") existing_end=$(time_to_minutes "$send") if (( start_min < existing_end && end_min > existing_start )); then conflicts=1 echo "⚠️ Conflict detected with: [$slabel] $sstart-$send" fi done < "$SLOT_FILE" if (( conflicts )); then echo "" echo "⚠️ Creating slot despite conflict(s). Use check-conflict to review." fi echo "$id,$date_str,$start_time,$end_time,$label,$category,$created_at" >> "$SLOT_FILE" cat <<EOF ═══════════════════════════════════════════════════ ✅ Slot Created ═══════════════════════════════════════════════════ ID: $id Date: $date_str Time: $start_time — $end_time (duration min) Label: $label Category: $category Created: $created_at Stored in: $SLOT_FILE 📖 More skills: bytesagain.com EOF } cmd_list() { local from_date="-" local to_date="-" ensure_data_dir local total=0 local total_minutes=0 echo "═══════════════════════════════════════════════════" echo " 📅 Scheduled Time Slots" echo "═══════════════════════════════════════════════════" echo "" if [ ! -s "$SLOT_FILE" ] || [ "$(wc -l < "$SLOT_FILE")" -le 1 ]; then echo " (No slots found. Use 'create' to add one.)" echo "" echo "📖 More skills: bytesagain.com" return 0 fi printf " %-8s %-12s %-6s %-6s %-5s %-10s %s\n" \ "ID" "Date" "Start" "End" "Min" "Category" "Label" echo " ─────────────────────────────────────────────────────────────────────" while IFS=',' read -r sid sdate sstart send slabel scat screated; do [ "$sid" = "id" ] && continue # Date range filtering if [ -n "$from_date" ] && [[ "$sdate" < "$from_date" ]]; then continue fi if [ -n "$to_date" ] && [[ "$sdate" > "$to_date" ]]; then continue fi local start_min end_min duration start_min=$(time_to_minutes "$sstart") end_min=$(time_to_minutes "$send") duration=$(( end_min - start_min )) total_minutes=$(( total_minutes + duration )) total=$(( total + 1 )) printf " %-8s %-12s %-6s %-6s %3dm %-10s %s\n" \ "$sid" "$sdate" "$sstart" "$send" "$duration" "$scat" "$slabel" done < "$SLOT_FILE" echo "" echo " Total: $total slots, $(( total_minutes / 60 ))h $((total_minutes % 60))m scheduled" if [ -n "$from_date" ]; then echo " Filter: $from_date → -now" fi echo "" echo "📖 More skills: bytesagain.com" } cmd_check_conflict() { local date_str="-" local start_time="-" local end_time="-" if [ -z "$date_str" ] || [ -z "$start_time" ] || [ -z "$end_time" ]; then cat <<'EOF' ═══════════════════════════════════════════════════ Check Schedule Conflicts ═══════════════════════════════════════════════════ Usage: bash scripts/script.sh check-conflict <date> <start> <end> Examples: bash scripts/script.sh check-conflict "2024-03-15" "09:30" "10:00" bash scripts/script.sh check-conflict "2024-03-15" "14:00" "16:00" Conflict Types: 🔴 Full Overlap — Proposed slot entirely within existing 🟠 Partial Overlap — Start or end falls within existing slot 🟡 Enclosing — Proposed slot contains an existing slot 🟢 Adjacent — Slots touch but don't overlap (no conflict) 📖 More skills: bytesagain.com EOF return 0 fi ensure_data_dir validate_date "$date_str" || return 1 validate_time "$start_time" || return 1 validate_time "$end_time" || return 1 local new_start new_end new_start=$(time_to_minutes "$start_time") new_end=$(time_to_minutes "$end_time") echo "═══════════════════════════════════════════════════" echo " 🔍 Conflict Check: $date_str $start_time—$end_time" echo "═══════════════════════════════════════════════════" echo "" local conflicts=0 while IFS=',' read -r sid sdate sstart send slabel scat screated; do [ "$sid" = "id" ] && continue [ "$sdate" != "$date_str" ] && continue local ex_start ex_end ex_start=$(time_to_minutes "$sstart") ex_end=$(time_to_minutes "$send") if (( new_start < ex_end && new_end > ex_start )); then conflicts=$(( conflicts + 1 )) local ctype if (( new_start >= ex_start && new_end <= ex_end )); then ctype="🔴 Full Overlap" elif (( new_start <= ex_start && new_end >= ex_end )); then ctype="🟡 Enclosing" else ctype="🟠 Partial Overlap" fi local overlap_start=$(( new_start > ex_start ? new_start : ex_start )) local overlap_end=$(( new_end < ex_end ? new_end : ex_end )) local overlap_min=$(( overlap_end - overlap_start )) echo " $ctype with [$slabel]" echo " Existing: $sstart — $send" echo " Overlap: $(minutes_to_time $overlap_start) — $(minutes_to_time $overlap_end) (overlap_minm)" echo "" fi done < "$SLOT_FILE" if (( conflicts == 0 )); then echo " ✅ No conflicts found! Time slot is available." else echo " ⚠️ Found $conflicts conflict(s)." fi echo "" echo "📖 More skills: bytesagain.com" } cmd_export() { local format="-ics" ensure_data_dir case "$format" in ics|ical) local outfile="SLOT_DIR/slots.ics" { echo "BEGIN:VCALENDAR" echo "VERSION:2.0" echo "PRODID:-//BytesAgain//Slot Manager//EN" echo "CALSCALE:GREGORIAN" echo "METHOD:PUBLISH" while IFS=',' read -r sid sdate sstart send slabel scat screated; do [ "$sid" = "id" ] && continue local dnum="sdate//-/" local snum="/00" local enum="/00" echo "BEGIN:VEVENT" echo "UID:sid@slot-manager" echo "DTSTART:dnumTsnum" echo "DTEND:dnumTenum" echo "SUMMARY:slabel" echo "CATEGORIES:scat" echo "DESCRIPTION:Created by Slot Manager vVERSION" echo "END:VEVENT" done < "$SLOT_FILE" echo "END:VCALENDAR" } > "$outfile" echo "═══════════════════════════════════════════════════" echo " 📤 Export — iCalendar (.ics)" echo "═══════════════════════════════════════════════════" echo "" echo " ✅ Exported to: $outfile" echo " Format: iCalendar 2.0 (RFC 5545)" echo "" echo " Import into:" echo " • Google Calendar → Settings → Import" echo " • Apple Calendar → File → Import" echo " • Outlook → File → Open & Export" echo "" echo "📖 More skills: bytesagain.com" ;; csv) local outfile="SLOT_DIR/slots_export.csv" cp "$SLOT_FILE" "$outfile" echo "═══════════════════════════════════════════════════" echo " 📤 Export — CSV" echo "═══════════════════════════════════════════════════" echo "" echo " ✅ Exported to: $outfile" echo " Columns: id, date, start, end, label, category, created_at" echo "" echo " Open with: Excel, Google Sheets, LibreOffice Calc" echo "" echo "📖 More skills: bytesagain.com" ;; *) echo "❌ Unknown format: $format" echo "Supported: ics, csv" echo "" echo "📖 More skills: bytesagain.com" ;; esac } cmd_templates() { local template="-" if [ -z "$template" ]; then cat <<'EOF' ═══════════════════════════════════════════════════ 📋 Scheduling Templates ═══════════════════════════════════════════════════ 【Available Templates】 pomodoro 4 × 25-min focus + 5-min breaks, then 15-min long break work-day Standard 9-5 with lunch break and focus blocks meeting-day Back-to-back meeting blocks with buffer time deep-work Cal Newport-style: 2 × 90-min deep work blocks interview Interview day: prep, sessions, debrief school Class periods with passing time Usage: bash scripts/script.sh templates <name> bash scripts/script.sh templates pomodoro Template Structure: Each template defines time blocks relative to a start time. Blocks include: label, duration, category, and break indicators. 【Template Design Principles】 • Every focus block has a matched break • Buffer time between meetings (min 5 min) • Longest unbroken focus: 90 minutes • Lunch minimum: 30 minutes • Context-switch cost: add 10-min transition blocks 📖 More skills: bytesagain.com EOF return 0 fi case "$template" in pomodoro) cat <<'EOF' ═══════════════════════════════════════════════════ 🍅 Pomodoro Template ═══════════════════════════════════════════════════ Cycle: 4 pomodoros + 1 long break = ~2h 25m Block 1: 00:00 — 00:25 Focus Session #1 [focus] Break 1: 00:25 — 00:30 Short Break [break] Block 2: 00:30 — 00:55 Focus Session #2 [focus] Break 2: 00:55 — 01:00 Short Break [break] Block 3: 01:00 — 01:25 Focus Session #3 [focus] Break 3: 01:25 — 01:30 Short Break [break] Block 4: 01:30 — 01:55 Focus Session #4 [focus] Break 4: 01:55 — 02:10 Long Break (15 min) [break] Total Focus: 100 min | Total Break: 30 min Recommended: 2–3 cycles per day Tips: • During focus: no email, no chat, phone silent • During short break: stretch, water, look away • During long break: walk, snack, real rest • Track completed pomodoros for productivity metrics 📖 More skills: bytesagain.com EOF ;; work-day) cat <<'EOF' ═══════════════════════════════════════════════════ 💼 Standard Work Day Template ═══════════════════════════════════════════════════ 08:30 — 09:00 Morning Planning & Review [admin] 09:00 — 10:30 Deep Work Block #1 [focus] 10:30 — 10:45 Break [break] 10:45 — 11:30 Meetings / Collaboration [meeting] 11:30 — 12:00 Email & Communications [admin] 12:00 — 13:00 Lunch [break] 13:00 — 14:30 Deep Work Block #2 [focus] 14:30 — 14:45 Break [break] 14:45 — 16:00 Meetings / Collaboration [meeting] 16:00 — 16:30 Admin & Follow-ups [admin] 16:30 — 17:00 Daily Review & Tomorrow Prep [admin] Focus Time: 3h | Meeting Time: 2h 45m Admin: 1h 30m | Breaks: 1h 15m 📖 More skills: bytesagain.com EOF ;; deep-work) cat <<'EOF' ═══════════════════════════════════════════════════ 🧠 Deep Work Template (Cal Newport) ═══════════════════════════════════════════════════ 08:00 — 08:15 Warm-up & Intention Setting [admin] 08:15 — 09:45 Deep Work Session #1 (90 min) [focus] 09:45 — 10:15 Recovery Break [break] 10:15 — 11:45 Deep Work Session #2 (90 min) [focus] 11:45 — 13:00 Lunch & Shallow Work [break] 13:00 — 14:00 Email, Meetings, Admin [admin] 14:00 — 15:30 Deep Work Session #3 (90 min) [focus] 15:30 — 16:00 Recovery Break [break] 16:00 — 17:00 Shutdown Routine & Review [admin] Deep Focus: 4h 30m (3 × 90-min blocks) Max cognitive output per day Rules: • Zero notifications during deep work • Pre-commit: what will you produce this session? • Shutdown ritual: review, plan tomorrow, close loops 📖 More skills: bytesagain.com EOF ;; *) echo "❌ Unknown template: $template" echo "Available: pomodoro, work-day, deep-work, meeting-day, interview, school" echo "" echo "📖 More skills: bytesagain.com" ;; esac } cmd_help() { cat <<EOF Slot vVERSION — Time Slot & Schedule Block Manager Commands: create <date> <start> <end> [label] [category] Create a new time slot list [from] [to] List slots, optionally filtered by date range check-conflict <date> <start> <end> Check for scheduling conflicts export <ics|csv> Export slots to iCal or CSV templates [name] Show or apply scheduling templates help Show this help version Show version Usage: bash scripts/script.sh create "2024-03-15" "09:00" "10:30" "Standup" "meeting" bash scripts/script.sh list "2024-03-15" "2024-03-22" bash scripts/script.sh check-conflict "2024-03-15" "09:30" "10:00" bash scripts/script.sh export ics bash scripts/script.sh templates pomodoro Related skills: clawhub install cal clawhub install pomodoro Browse all: bytesagain.com Powered by BytesAgain | bytesagain.com EOF } case "-help" in create) shift; cmd_create "$@" ;; list) shift; cmd_list "$@" ;; check-conflict) shift; cmd_check_conflict "$@" ;; export) shift; cmd_export "$@" ;; templates) shift; cmd_templates "$@" ;; version) echo "slot vVERSION" ;; help|*) cmd_help ;; esac
Analyze mining operations. Use when you need to understand mining mechanisms, evaluate protocol security, or reference on-chain concepts.
--- name: "mining" version: "1.0.0" description: "Analyze mining operations. Use when you need to understand mining mechanisms, evaluate protocol security, or reference on-chain concepts." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [mining, blockchain, cli, tool] category: "blockchain" --- # Mining Analyze mining operations. Use when you need to understand mining mechanisms, evaluate protocol security, or reference on-chain concepts. ## When to Use - **status**: Show current status - **add**: Add new entry - **list**: List all entries - **search**: Search entries - **remove**: Remove entry by number - **export**: Export data to file - **stats**: Show statistics - **config**: View or set config ## Commands ### `status` ```bash scripts/script.sh status ``` Show current status ### `add` ```bash scripts/script.sh add ``` Add new entry ### `list` ```bash scripts/script.sh list ``` List all entries ### `search` ```bash scripts/script.sh search ``` Search entries ### `remove` ```bash scripts/script.sh remove ``` Remove entry by number ### `export` ```bash scripts/script.sh export ``` Export data to file ### `stats` ```bash scripts/script.sh stats ``` Show statistics ### `config` ```bash scripts/script.sh config ``` View or set config ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration Use `scripts/script.sh config <key> <value>` to customize behavior. | Variable | Description | |----------|-------------| | `MINING_DIR` | Data directory (default: ~/.mining/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # mining -- Analyze mining operations. Use when you need to understand mining mechanisms, evaluate protocol security, or reference on-chain concepts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.mining" _ensure_dirs() { mkdir -p "$DATA_DIR"; } _save_entry() { _ensure_dirs local cmd="$1" val="$2" local ts=$(date '+%Y-%m-%d %H:%M:%S') printf '{"ts":"%s","cmd":"%s","val":"%s"}\n' "$ts" "$cmd" "$val" >> "$DATA_DIR/data.jsonl" } show_help() { cat << EOF mining v$VERSION -- Analyze mining operations. Use when you need to understand mining mechanisms, evaluate protocol security, or reference on-chain concepts. Usage: mining <command> [args] Commands: status Show current status add Add new entry list List all entries search Search entries remove Remove entry by number export Export data to file stats Show statistics config View or set config help Show this help version Show version Data: $DATA_DIR Powered by BytesAgain | bytesagain.com EOF } cmd_status() { echo "=== mining Status ===" echo " Version: $VERSION" echo " Data dir: $DATA_DIR" local entries=$(cat "$DATA_DIR"/*.jsonl 2>/dev/null | wc -l || echo 0) echo " Entries: $entries" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1 || echo empty)" } cmd_add() { local value="?Usage: mining add <entry>" shift || true _save_entry "add" "$value $*" local count=$(wc -l < "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Added: $value (entry #$count)" } cmd_list() { echo "=== Mining Entries ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local count=$(wc -l < "$DATA_DIR/data.jsonl") echo "Total: $count" echo "---" tail -20 "$DATA_DIR/data.jsonl" | while IFS= read -r line; do local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) local cmd=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo " [$ts] $cmd: $val" done else echo "No entries yet." fi } cmd_search() { local term="?Usage: mining search <term>" if [ -f "$DATA_DIR/data.jsonl" ]; then local matches=$(grep -ic "$term" "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Found: $matches matches" grep -i "$term" "$DATA_DIR/data.jsonl" 2>/dev/null | head -20 | while IFS= read -r line; do local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) echo " [$ts] $val" done else echo "No data to search." fi } cmd_remove() { local num="?Usage: mining remove <line-number>" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") if [ "$num" -ge 1 ] 2>/dev/null && [ "$num" -le "$total" ] 2>/dev/null; then sed -i "numd" "$DATA_DIR/data.jsonl" echo "Removed #$num ($((total-1)) remaining)" else echo "Invalid: $num (total: $total)"; fi else echo "No data."; fi } cmd_export() { local fmt="-json" local out="mining-export.$fmt" if [ ! -f "$DATA_DIR/data.jsonl" ]; then echo "No data."; return 0; fi case "$fmt" in json) cp "$DATA_DIR/data.jsonl" "$out" ;; csv) echo "timestamp,command,value" > "$out" while IFS= read -r line; do ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) c2=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) vl=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo "$ts,$c2,$vl" >> "$out" done < "$DATA_DIR/data.jsonl" ;; *) echo "Formats: json, csv"; return 1 ;; esac echo "Exported: $out ($(wc -c < "$out") bytes)" } cmd_stats() { echo "=== Mining Stats ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") local bytes=$(wc -c < "$DATA_DIR/data.jsonl") echo " Entries: $total" echo " Size: $bytes bytes" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" else echo " No data yet."; fi } cmd_config() { local key="-" val="-" local cfg="$DATA_DIR/config.txt" if [ -z "$key" ]; then echo "=== Config ===" if [ -f "$cfg" ]; then while IFS="=" read -r k v; do echo " $k=$v"; done < "$cfg" else echo " (empty — use config <key> <value>)"; fi elif [ -z "$val" ]; then grep "^key=" "$cfg" 2>/dev/null | cut -d= -f2- || echo "(not set)" else if [ -f "$cfg" ] && grep -q "^key=" "$cfg" 2>/dev/null; then sed -i "s|^key=.*|key=val|" "$cfg" else echo "key=val" >> "$cfg" fi echo "Set: $key=$val" fi } CMD="-help" shift 2>/dev/null || true _ensure_dirs case "$CMD" in status) cmd_status "$@" ;; add) cmd_add "$@" ;; list) cmd_list "$@" ;; search) cmd_search "$@" ;; remove) cmd_remove "$@" ;; export) cmd_export "$@" ;; stats) cmd_stats "$@" ;; config) cmd_config "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "mining v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: mining help"; exit 1 ;; esac
Subpoena law reference — types of subpoenas, service requirements, compliance obligations, and motion to quash. Use when issuing, receiving, or responding to...
--- name: "subpoena" version: "1.0.0" description: "Subpoena law reference — types of subpoenas, service requirements, compliance obligations, and motion to quash. Use when issuing, receiving, or responding to subpoenas in legal proceedings." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [subpoena, legal, discovery, testimony, documents, court, litigation] category: "legal" --- # Subpoena — Legal Subpoena Reference Quick-reference skill for subpoena types, procedures, compliance, and challenges. ## When to Use - Understanding types of subpoenas (ad testificandum, duces tecum) - Issuing subpoenas to witnesses or for documents - Responding to or complying with a subpoena - Filing motions to quash or modify subpoenas - Understanding contempt consequences for non-compliance ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of subpoenas — definition, purpose, and legal authority. ### `types` ```bash scripts/script.sh types ``` Types of subpoenas — testimony, documents, deposition, administrative. ### `procedure` ```bash scripts/script.sh procedure ``` How to issue and serve a subpoena — rules and requirements. ### `compliance` ```bash scripts/script.sh compliance ``` Responding to subpoenas — obligations, timelines, and privilege. ### `quash` ```bash scripts/script.sh quash ``` Motions to quash or modify — grounds and procedures. ### `federal` ```bash scripts/script.sh federal ``` Federal subpoena rules — FRCP Rule 45 details. ### `examples` ```bash scripts/script.sh examples ``` Practical subpoena scenarios and common issues. ### `checklist` ```bash scripts/script.sh checklist ``` Subpoena issuance and response checklist. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `SUBPOENA_DIR` | Data directory (default: ~/.subpoena/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # subpoena — Legal Subpoena Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Subpoenas — Overview === A subpoena is a court order compelling a person to testify, produce documents, or both. Failure to comply can result in contempt of court. Etymology: Latin "sub poena" = "under penalty" The recipient faces penalties for non-compliance Purpose: - Compel witness testimony at trial or hearing - Obtain documents and records in litigation - Gather evidence during discovery phase - Require testimony at depositions - Administrative and regulatory investigations Legal Authority: Federal: FRCP Rule 45 (civil), FRCrP Rule 17 (criminal) State: Each state has its own subpoena rules Admin: Agencies have statutory subpoena power (e.g., SEC, IRS, FTC) Grand Jury: Broad investigative subpoena power Key Characteristics: - Not a request — it's a court ORDER - Can be issued by attorneys (not just judges in most jurisdictions) - Subject to constitutional protections (5th Amendment privilege) - Can be challenged through motion to quash - Geographic reach limitations apply - Must be properly served to be enforceable Who Can Be Subpoenaed: - Any person within the court's jurisdiction - Non-party witnesses (not involved in the case) - Custodians of records (corporations, agencies) - Expert witnesses (under certain conditions) - NOT immune officials (legislative/diplomatic immunity exceptions) Distinction from Other Court Orders: Subpoena Compels non-parties to produce evidence/testify Summons Notifies a defendant of a lawsuit Warrant Authorizes law enforcement search/arrest Court Order Broader directive from a judge EOF } cmd_types() { cat << 'EOF' === Types of Subpoenas === Subpoena Ad Testificandum: Purpose: Compels a person to testify When: At trial, hearing, or deposition Requirements: - Identify the witness - State date, time, and location of testimony - Specify the proceeding and court Notes: - Witness must appear in person - May request travel accommodations in some jurisdictions - Remote testimony may be permitted (post-COVID rules) Subpoena Duces Tecum: Purpose: Compels production of documents, records, or things When: Discovery phase, pre-trial, or at trial Requirements: - Describe documents with reasonable particularity - Cannot be overly broad or unduly burdensome - Must allow reasonable time for compliance Common Targets: - Business records, emails, contracts - Medical records - Financial records (bank, tax) - Electronic data (ESI - Electronically Stored Information) - Phone records, surveillance footage Combined Subpoena (Testify + Produce): Most common in practice Witness must appear AND bring documents Example: "Appear on [date] and bring all contracts between..." Deposition Subpoena: Compels testimony at a deposition (out-of-court, under oath) Can include duces tecum component Used primarily during discovery Rules vary: federal vs state procedures Administrative Subpoena: Issued by government agencies (not courts) Authority: Enabling statute grants subpoena power Examples: SEC subpoena for trading records IRS summons for tax documents OSHA investigation records FTC investigation demands Enforcement: Agency must petition court if recipient refuses Grand Jury Subpoena: Issued as part of criminal investigation Very broad scope (relevant to investigation) Harder to challenge than civil subpoenas Secrecy rules apply (Fed. R. Crim. P. 6(e)) Fifth Amendment privilege against self-incrimination applies EOF } cmd_procedure() { cat << 'EOF' === Issuing and Serving Subpoenas === Issuing a Subpoena (Federal — FRCP Rule 45): Who Can Issue: - Clerk of court issues blank subpoenas - Attorney authorized to practice in issuing court - Attorney signs and fills in details - Pro se litigants: must request from clerk Required Contents: 1. Name of the court 2. Title and case number of the action 3. Name of the person commanded 4. Command to attend/testify and/or produce documents 5. Date, time, and place of compliance 6. Text of Rule 45(d) and (e) — rights of recipient 7. Attorney signature and contact information Service Requirements: Personal Service: - Deliver a copy to the named person - Must be served by a non-party (18+ years old) - Some states allow service by mail or email Witness Fees: - Must tender witness fee with service (federal: $40/day) - Must tender mileage costs (federal: $0.655/mile) - Failure to tender fees = subpoena unenforceable - Some states don't require advance tender Timing: - "Reasonable time" before compliance date - No specific federal minimum (but courts require reasonableness) - State rules vary: some require 5-14 days minimum - Document subpoenas: typically 30 days for production Geographic Limits (Federal): Trial subpoena: - Within 100 miles of courthouse, OR - Within the state if state law allows Deposition subpoena: - Within 100 miles of deposition location Note: FRCP Rule 45(c) — must not impose undue burden Service on Corporations: Rule 30(b)(6) deposition notice (not technically a subpoena) Corporation designates person(s) most knowledgeable Topics must be described with reasonable particularity Corporation must prepare designated witness on listed topics Proof of Service: File proof of service with the court Include: date, time, place, manner of service Affidavit or declaration of the process server EOF } cmd_compliance() { cat << 'EOF' === Responding to Subpoenas === Recipient's Obligations: 1. Take the subpoena seriously (it's a court order) 2. Note the compliance deadline 3. Review scope of documents/testimony requested 4. Preserve all responsive materials (litigation hold) 5. Consult an attorney if unclear 6. Respond by the deadline (even if objecting) Response Options: Full Compliance: - Produce all requested documents - Appear for testimony as commanded - Certify completeness of production Partial Compliance with Objections: - Produce non-objectionable documents - Serve written objections before deadline - Common objections: · Overly broad or unduly burdensome · Seeks privileged information · Not relevant to the case · Trade secrets / confidential business info · Compliance impossible (documents don't exist) Negotiate Modification: - Contact issuing attorney to narrow scope - Agree on search terms, date ranges, custodians - Most courts prefer informal resolution - Document the agreement in writing Privilege Considerations: Attorney-Client Privilege: - Communications with your lawyer for legal advice - Must be claimed specifically (not blanket) - Produce privilege log describing withheld documents Work Product Doctrine: - Materials prepared in anticipation of litigation - Qualified protection (can be overcome by need) Fifth Amendment: - Privilege against self-incrimination - Applies to testimony, not existing documents (generally) - Must be claimed question-by-question Other Privileges: - Doctor-patient, clergy-penitent, spousal - Trade secrets (may require protective order) - Journalist's privilege (shield laws, varies by state) Privilege Log Requirements: For each withheld document: - Date of document - Author and recipients - Subject matter (without revealing privileged content) - Privilege claimed (A/C, work product, etc.) - Basis for the claim Consequences of Non-Compliance: Contempt of Court: - Civil contempt: coercive fines until compliance - Criminal contempt: punitive fines and/or jail Sanctions: - Monetary penalties - Adverse inference (court assumes documents harmful) Warrant: Court may issue warrant for arrest EOF } cmd_quash() { cat << 'EOF' === Motions to Quash or Modify === Motion to Quash: Asks the court to invalidate the subpoena entirely Filed by the subpoena recipient or affected party Must be filed "timely" — typically before compliance deadline Grounds for Quashing (FRCP 45(d)(3)): Mandatory Quashing — Court MUST quash if subpoena: (A) Fails to allow reasonable time for compliance (B) Requires travel beyond geographic limits (C) Requires disclosure of privileged matter (no waiver) (D) Subjects person to undue burden Discretionary Quashing — Court MAY quash if subpoena: (A) Requires disclosure of trade secrets or confidential info (may modify with protective order instead) (B) Requires unretained expert opinion (unless exceptional circumstances) Filing Procedure: 1. Draft motion identifying defects or grounds 2. File in the court where compliance is required (not necessarily the court where case is pending) 3. Include supporting declaration/affidavit 4. Serve on all parties 5. Request hearing (may be decided on papers) Motion to Modify: Alternative to quashing — asks court to narrow scope Common modifications: - Reduce date range of document requests - Limit number of custodians searched - Allow redaction of irrelevant information - Set a protective order for confidential material - Change location or date of testimony - Allow remote testimony instead of in-person Protective Orders: Used with trade secrets or confidential information Common terms: - "Attorneys' Eyes Only" designation - Limited use (only for this litigation) - Return/destroy after case concludes - Penalties for unauthorized disclosure Meet and Confer Requirement: Most courts require parties to try resolving disputes before filing motions Federal: Rule 45 Advisory Committee Notes encourage negotiation State: Many require certification of good-faith effort Document all communications about the dispute Strategic Considerations: - Quashing may delay but not eliminate the obligation - Court may order compliance with modified terms - Excessive objections can antagonize the court - Negotiate first, litigate second - Cost-shifting: court may order issuing party to pay costs EOF } cmd_federal() { cat << 'EOF' === FRCP Rule 45 — Key Provisions === Rule 45(a) — In General: - Subpoenas issued from court where action is pending - Clerk must issue to party who requests it - Attorney may issue as officer of the court - Must include text of 45(d) and (e) Rule 45(b) — Service: - Personal delivery to named person - Tender fees for one day's attendance + mileage - Notice to all parties before serving non-party subpoena - Proof of service filed with issuing court Rule 45(c) — Place of Compliance: Trial/Hearing: Within 100 miles or within state Deposition: Within 100 miles of where person resides, works, or regularly transacts business Documents only: May be produced at place of compliance or at another reasonably agreed location Rule 45(d) — Protecting Rights: (1) Avoid undue burden or expense (2) Party/attorney responsible for compliance violations (3) Court must quash or modify if: - Unreasonable time - Beyond geographic limits - Requires privileged disclosure - Undue burden (3)(B) Court may quash/modify if: - Trade secrets (unless exceptional circumstances + fees) - Unretained expert opinion Rule 45(e) — Duties in Responding: (1) Producing documents: - As kept in ordinary course of business, OR - Organized and labeled by request category (2) Claiming privilege: - Expressly claim privilege - Describe nature of documents sufficiently - Notify all parties Rule 45(g) — Contempt: Court may hold in contempt any person who: - Fails to obey without adequate excuse - Must be served in the issuing court's jurisdiction 2013 Amendments (Major): - Subpoena issued only from court where action pending - Compliance disputes resolved in district where compliance required - Transfer provision for exceptional circumstances - Harmonized geographic limitations EOF } cmd_examples() { cat << 'EOF' === Subpoena Scenarios === --- Third-Party Document Subpoena --- Scenario: Plaintiff suing employer needs payroll records from outsourced payroll company (non-party) Steps: 1. Attorney issues subpoena duces tecum 2. Serve on payroll company's registered agent 3. Include $40 witness fee + mileage 4. Allow 30 days for document production 5. Describe documents: "All payroll records for [employee] from January 2020 to present" 6. Notice sent to opposing counsel Potential Issues: - Payroll company may object (privacy, burden) - May require protective order for employee data - HIPAA considerations if health deductions included --- Deposition of Treating Physician --- Scenario: Defense wants to depose plaintiff's doctor Steps: 1. Issue deposition subpoena ad testificandum 2. Serve on physician personally 3. Include duces tecum for medical records 4. Coordinate schedule (medical professionals get courtesy) 5. Tender expert witness fee (if opinion testimony expected) Potential Issues: - Doctor-patient privilege (plaintiff may waive by suing) - Expert vs fact witness distinction affects fees - May need patient authorization for records --- Corporate Records Subpoena --- Scenario: Regulatory investigation of company's practices Steps: 1. Agency issues administrative subpoena 2. Serve on company's registered agent 3. Broad request: "All documents related to..." 4. Company reviews, collects, processes responsive docs 5. Company produces non-privileged docs + privilege log Practical Reality: - E-discovery: may involve terabytes of email - Proportionality: negotiate reasonable scope - Cost: $50K-$500K+ for large corporate productions - Timeline: often months for large productions --- Motion to Quash — Trade Secrets --- Scenario: Competitor subpoenas proprietary pricing formulas Response: 1. File motion to quash (trade secret protection) 2. Alternatively: request protective order 3. Court may order production under "AEO" designation 4. Only attorneys can view the information 5. Must destroy after litigation concludes EOF } cmd_checklist() { cat << 'EOF' === Subpoena Checklist === Issuing a Subpoena: [ ] Identify correct type (testimony, documents, or both) [ ] Verify court has jurisdiction over the recipient [ ] Check geographic compliance limits (100-mile rule) [ ] Draft with required contents (court, case, command) [ ] Include Rule 45(d)/(e) text (federal) [ ] Describe documents with reasonable particularity [ ] Set reasonable compliance deadline [ ] Arrange proper service (non-party, 18+) [ ] Tender witness fee and mileage [ ] Serve notice on all parties [ ] File proof of service with court Responding to a Subpoena: [ ] Note the compliance deadline immediately [ ] Determine if subpoena is valid (proper service, jurisdiction) [ ] Issue litigation hold for responsive materials [ ] Review scope — identify responsive documents [ ] Identify any privileged or confidential materials [ ] Consider objections (burden, relevance, privilege) [ ] Contact issuing attorney to negotiate scope if needed [ ] Prepare privilege log for withheld documents [ ] Produce documents in organized manner [ ] Respond by deadline (even if filing objections) Challenging a Subpoena: [ ] Evaluate grounds for motion to quash [ ] Check timing — file before compliance date [ ] Attempt meet-and-confer with issuing party [ ] Draft motion with supporting declaration [ ] File in correct court (compliance district) [ ] Request hearing or expedited ruling [ ] Propose modifications as alternative to quashing Preparing Witness for Testimony: [ ] Review subpoena scope with witness [ ] Prepare witness on anticipated questions [ ] Gather and organize requested documents [ ] Advise on privilege assertions (5th Amendment, A/C) [ ] Arrange travel and logistics [ ] Confirm date, time, and location EOF } show_help() { cat << EOF subpoena v$VERSION — Legal Subpoena Reference Usage: script.sh <command> Commands: intro Subpoenas overview — definition and legal authority types Types — testimony, documents, deposition, admin procedure Issuing and serving subpoenas compliance Responding — obligations, privilege, consequences quash Motions to quash or modify federal FRCP Rule 45 key provisions examples Practical subpoena scenarios checklist Issuance and response checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; types) cmd_types ;; procedure) cmd_procedure ;; compliance) cmd_compliance ;; quash) cmd_quash ;; federal) cmd_federal ;; examples) cmd_examples ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "subpoena v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Sarbanes-Oxley Act compliance reference — SOX sections, internal controls, audit requirements, and IT governance. Use when evaluating SOX compliance, designi...
--- name: "sox" version: "1.0.0" description: "Sarbanes-Oxley Act compliance reference — SOX sections, internal controls, audit requirements, and IT governance. Use when evaluating SOX compliance, designing internal controls, or preparing for financial audits." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [sox, sarbanes-oxley, compliance, audit, internal-controls, financial-reporting, legal] category: "legal" --- # SOX — Sarbanes-Oxley Act Compliance Reference Quick-reference skill for Sarbanes-Oxley Act requirements, internal controls, and audit compliance. ## When to Use - Understanding SOX section requirements (302, 404, 906) - Designing internal controls over financial reporting (ICFR) - Preparing for SOX compliance audits - Implementing IT general controls (ITGCs) - Evaluating material weakness vs significant deficiency ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of the Sarbanes-Oxley Act — history, purpose, and key provisions. ### `sections` ```bash scripts/script.sh sections ``` Key SOX sections: 302, 404, 409, 802, 906 and their requirements. ### `controls` ```bash scripts/script.sh controls ``` Internal controls framework — COSO components, control types, and design principles. ### `itgc` ```bash scripts/script.sh itgc ``` IT General Controls — access management, change management, operations, and SDLC. ### `audit` ```bash scripts/script.sh audit ``` SOX audit process — planning, testing, reporting, and remediation. ### `penalties` ```bash scripts/script.sh penalties ``` SOX penalties and enforcement — criminal and civil consequences for non-compliance. ### `examples` ```bash scripts/script.sh examples ``` Real-world SOX compliance scenarios and common findings. ### `checklist` ```bash scripts/script.sh checklist ``` SOX compliance readiness checklist for organizations. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `SOX_DIR` | Data directory (default: ~/.sox/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # sox — Sarbanes-Oxley Act Compliance Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Sarbanes-Oxley Act (SOX) === The Sarbanes-Oxley Act of 2002 (SOX) is a U.S. federal law enacted in response to corporate accounting scandals (Enron, WorldCom, Tyco). Purpose: - Protect investors from fraudulent financial reporting - Improve accuracy and reliability of corporate disclosures - Restore public confidence in capital markets Key Facts: Full Name: Sarbanes-Oxley Act of 2002 (Pub.L. 107-204) Sponsors: Senator Paul Sarbanes, Rep. Michael Oxley Signed: July 30, 2002 by President George W. Bush Applies to: All U.S. public companies (SEC registrants) Enforced by: SEC and PCAOB Major Provisions: Title I Public Company Accounting Oversight Board (PCAOB) Title II Auditor Independence Title III Corporate Responsibility (CEO/CFO certifications) Title IV Enhanced Financial Disclosures (Section 404) Title V Analyst Conflicts of Interest Title VI Commission Resources and Authority Title VII Studies and Reports Title VIII Corporate Fraud Accountability Title IX White-Collar Crime Penalty Enhancements Title X Corporate Tax Returns Title XI Corporate Fraud and Accountability Impact: - Created PCAOB to oversee auditors of public companies - Required CEO/CFO personal certification of financial statements - Mandated internal control assessments and auditor attestation - Established criminal penalties for securities fraud - Average compliance cost: $1-5M/year for large companies EOF } cmd_sections() { cat << 'EOF' === Key SOX Sections === Section 302 — Corporate Responsibility for Financial Reports CEO and CFO must personally certify that: - They reviewed the report - It contains no material misstatements or omissions - Financial statements fairly present the company's condition - They are responsible for internal controls - They disclosed any control deficiencies to auditors Frequency: Every quarterly (10-Q) and annual (10-K) filing Penalty: Up to $5M fine and/or 20 years imprisonment for willful violations Section 404 — Management Assessment of Internal Controls 404(a) — Management must: - Assess effectiveness of ICFR (Internal Controls over Financial Reporting) - Include assessment in annual report - Use a recognized framework (typically COSO) 404(b) — External auditor must: - Attest to and report on management's assessment - Issue opinion on effectiveness of ICFR Note: 404(b) exemption for smaller reporting companies (<$75M public float) Section 409 — Real-Time Issuer Disclosures Companies must disclose material changes in financial condition "on a rapid and current basis" (Form 8-K within 4 business days) Material events: acquisitions, dispositions, defaults, delisting Section 802 — Criminal Penalties for Document Destruction Illegal to alter, destroy, conceal, or falsify records with intent to impede a federal investigation Penalty: Up to 20 years imprisonment Applies to auditors retaining workpapers (minimum 7 years) Section 806 — Whistleblower Protection Protects employees who report fraud from retaliation Covers discharge, demotion, suspension, threats, harassment Employees can file complaints with DOL within 180 days Remedies: reinstatement, back pay, compensatory damages Section 906 — Corporate Responsibility for Financial Reports CEO/CFO must certify reports "fully comply" with SEC requirements and "fairly present" the financial condition Criminal penalties: Up to $5M fine and 20 years (willful) Knowing violation: Up to $1M fine and 10 years EOF } cmd_controls() { cat << 'EOF' === Internal Controls Framework (COSO) === SOX Section 404 requires using a recognized framework. Most companies use COSO (Committee of Sponsoring Organizations). COSO 2013 Framework — 5 Components: 1. Control Environment - Tone at the top (management integrity and ethics) - Board of Directors oversight - Organizational structure and authority - Commitment to competence - Accountability mechanisms 2. Risk Assessment - Identify risks to financial reporting objectives - Assess likelihood and impact - Consider fraud risk (incentive, opportunity, rationalization) - Identify and assess changes that could affect controls 3. Control Activities - Policies and procedures that enforce directives Types: Preventive Stop errors before they occur (approvals, segregation) Detective Find errors after they occur (reconciliations, reviews) Manual Human judgment required (management review) Automated System-enforced (access controls, edit checks) Key controls: - Segregation of duties (authorize ≠ record ≠ custody) - Authorization and approval limits - Reconciliations (bank, intercompany, subledger) - Physical controls (asset safeguarding) 4. Information & Communication - Relevant financial information captured and communicated - Internal communication (up, down, across) - External communication (regulators, auditors, investors) - IT systems that support financial reporting 5. Monitoring Activities - Ongoing evaluations (daily supervision, metrics) - Separate evaluations (internal audit, SOX testing) - Report deficiencies to management and board - Track remediation of identified issues Control Deficiency Severity: Deficiency Control does not operate as designed Significant Reasonable possibility of material misstatement Deficiency (less severe than material weakness) Material Weakness Reasonable possibility of material misstatement not being prevented or detected timely → Must be disclosed in 10-K filing EOF } cmd_itgc() { cat << 'EOF' === IT General Controls (ITGCs) === ITGCs support the reliability of automated controls and financial data integrity. Four key domains: 1. Access to Programs and Data Purpose: Only authorized users access financial systems Key Controls: - User access provisioning (approval workflow) - Periodic access reviews (quarterly/semi-annual) - Privileged access management (admin accounts) - Termination/transfer access removal (<24 hours) - Password policies (complexity, rotation, lockout) - Segregation of duties in system access Common Findings: - Stale accounts not removed - Shared admin credentials - No periodic access review evidence 2. Program Change Management Purpose: Changes to financial systems are authorized and tested Key Controls: - Change request and approval process - Segregation: developer ≠ approver ≠ deployer - Testing before production deployment - Version control and rollback capability - Emergency change procedures with post-hoc approval Common Findings: - Developers with production access - Missing test evidence - Undocumented emergency changes 3. Program Development (SDLC) Purpose: New systems meet business requirements Key Controls: - Requirements documentation and sign-off - Design review and approval - User acceptance testing (UAT) - Data migration validation - Go-live authorization Common Findings: - Insufficient UAT documentation - No data conversion reconciliation 4. Computer Operations Purpose: Systems operate reliably for financial processing Key Controls: - Job scheduling and monitoring - Backup and recovery procedures - Disaster recovery / business continuity plan - Incident management and escalation - Batch processing integrity checks Common Findings: - Untested disaster recovery plan - Missing backup restoration tests - No monitoring for failed batch jobs EOF } cmd_audit() { cat << 'EOF' === SOX Audit Process === Phase 1: Scoping and Planning - Identify significant accounts and disclosures - Determine materiality thresholds Typical: 5% of pre-tax income, 0.5-1% of revenue - Map accounts to business processes - Identify relevant IT systems (in-scope applications) - Determine locations in scope (quantitative + qualitative) - Identify key controls for each process Timeline: 3-4 months before year-end Phase 2: Walkthroughs - Trace one transaction end-to-end through each process - Verify control design (would it prevent/detect misstatement?) - Confirm control owner understands responsibilities - Document using flowcharts and narratives - Identify gaps in control design Timeline: 2-3 months before year-end Phase 3: Testing Testing approaches: Inquiry Ask control owner how control operates Observation Watch control being performed Inspection Examine evidence (approvals, reconciliations) Re-performance Re-execute the control procedure Sample sizes (risk-based): Control Frequency Typical Sample Annual 1 (the instance) Quarterly 2-4 Monthly 3-5 Weekly 5-15 Daily 20-30 Per occurrence 25-40 Testing must cover entire audit period (usually fiscal year) Interim testing + rollforward testing for remaining period Phase 4: Evaluation and Reporting - Aggregate deficiencies by process - Evaluate compensating controls for deficiencies - Classify: deficiency / significant deficiency / material weakness - Management remediation of identified issues - External auditor issues opinion on ICFR effectiveness - Adverse opinion if material weakness exists at year-end Timeline: Within 60-90 days of fiscal year-end Phase 5: Remediation - Develop corrective action plans - Assign owners and deadlines - Implement fixes and re-test - Track closure in GRC system - Design sustainable controls (not just fixing one instance) EOF } cmd_penalties() { cat << 'EOF' === SOX Penalties and Enforcement === Criminal Penalties: Section 906 (False Certification): Knowing: Up to $1,000,000 fine and/or 10 years imprisonment Willful: Up to $5,000,000 fine and/or 20 years imprisonment Section 802 (Document Destruction): Up to $250,000 fine and/or 20 years imprisonment Applies to anyone who alters/destroys records in federal investigations Section 807 (Securities Fraud): Up to $5,000,000 fine and/or 25 years imprisonment Section 1107 (Whistleblower Retaliation): Up to $250,000 fine and/or 10 years imprisonment Civil Penalties: SEC enforcement actions Officer and director bars Disgorgement of ill-gotten gains Civil monetary penalties per violation PCAOB Enforcement: Sanctions against audit firms - Censure - Temporary or permanent suspension - Monetary penalties ($750K individual, $15M firm) Required for firms auditing public companies Notable Enforcement Cases: Enron (2001) Triggered SOX; $74B in shareholder losses WorldCom (2002) $11B accounting fraud; CEO sentenced 25 years Tyco (2002) CEO looted $600M; sentenced to 8-25 years HealthSouth (2003) $2.7B fraud; CEO acquitted, CFOs convicted Satyam (2009) India's Enron; $1B fabricated cash balances Recent Trends: - Increased focus on cybersecurity as SOX control - Cloud computing and third-party risk in ITGC scope - SEC proposed rules on climate-related disclosures - Remote work impact on control environment - AI/automation in testing and monitoring EOF } cmd_examples() { cat << 'EOF' === SOX Compliance Scenarios === --- Revenue Recognition Controls --- Risk: Revenue recorded in wrong period or overstated Key Controls: 1. System-enforced cutoff (orders cannot ship after period close) 2. Three-way match: PO → receiving → invoice 3. Management review of revenue journal entries >$X 4. Automated calculation of multi-element arrangements 5. Quarterly analytical review of revenue trends Common Finding: Manual journal entries to revenue without adequate documentation or independent review --- Segregation of Duties (SoD) --- Risk: Single person can initiate and approve transactions Example Conflict Matrix: Create Vendor × Approve Payments = CONFLICT Create PO × Receive Goods = CONFLICT Process Payroll × Add Employees = CONFLICT Post JE × Approve JE = CONFLICT Mitigation: Role-based access, compensating detective controls --- Financial Close Process --- Risk: Errors in period-end financial statements Key Controls: 1. Close calendar with defined deadlines 2. Account reconciliation (balance sheet accounts monthly) 3. Journal entry approval (all manual JEs reviewed) 4. Intercompany elimination and reconciliation 5. Management review of financial statements (flux analysis) 6. Disclosure checklist completion Typical timeline: 5-10 business days for quarterly close --- IT Application Control Example --- ERP System: Three-way match PO amount ± tolerance → invoice automatically approved Outside tolerance → routed to manager for approval Testing: Select sample of invoices, verify matching logic Evidence: System configuration screenshot, sample transactions Key: Automated controls tested once if ITGCs are effective EOF } cmd_checklist() { cat << 'EOF' === SOX Compliance Readiness Checklist === Governance and Oversight: [ ] Audit committee established with financial expert [ ] Code of ethics adopted and communicated [ ] Whistleblower hotline operational [ ] Disclosure committee formed and meeting regularly [ ] CEO/CFO certification process documented Risk Assessment: [ ] Significant accounts and disclosures identified [ ] Materiality thresholds determined [ ] Fraud risk assessment completed [ ] Entity-level controls evaluated [ ] Risk of material misstatement mapped to controls Control Documentation: [ ] Process narratives/flowcharts current [ ] Key controls identified and documented [ ] Control owners assigned and acknowledged [ ] Control design evaluated (preventive vs detective) [ ] Compensating controls documented where needed IT Controls: [ ] In-scope applications identified [ ] User access reviews completed and documented [ ] Change management procedures followed with evidence [ ] Segregation of duties enforced in systems [ ] Backup and recovery tested [ ] Third-party SOC reports obtained and reviewed (SOC 1 Type II) Testing and Monitoring: [ ] Test plan covers all key controls [ ] Sample sizes aligned with control frequency [ ] Testing covers full audit period [ ] Deficiencies evaluated and classified [ ] Remediation plans in place with deadlines Reporting: [ ] Management assessment of ICFR completed [ ] Material weaknesses disclosed (if any) [ ] External auditor opinion obtained [ ] Section 302 certifications signed [ ] Section 906 certifications signed EOF } show_help() { cat << EOF sox v$VERSION — Sarbanes-Oxley Act Compliance Reference Usage: script.sh <command> Commands: intro SOX overview — history, purpose, and key provisions sections Key SOX sections: 302, 404, 802, 906 controls COSO internal controls framework itgc IT General Controls — access, change, operations audit SOX audit process — planning through remediation penalties Penalties and enforcement actions examples Real-world compliance scenarios and findings checklist SOX compliance readiness checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; sections) cmd_sections ;; controls) cmd_controls ;; itgc) cmd_itgc ;; audit) cmd_audit ;; penalties) cmd_penalties ;; examples) cmd_examples ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "sox v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Shell scripting reference — Bash syntax, redirections, process substitution, signal handling, debugging techniques. Use when writing shell scripts, troublesh...
--- name: "shell" version: "1.0.0" description: "Shell scripting reference — Bash syntax, redirections, process substitution, signal handling, debugging techniques. Use when writing shell scripts, troubleshooting Bash behavior, or automating system tasks." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [shell, bash, scripting, linux, unix, terminal, automation, devtools] category: "devtools" --- # Shell — Shell Scripting Reference Quick-reference skill for Bash shell scripting, built-in features, and best practices. ## When to Use - Writing reliable Bash scripts with proper error handling - Understanding redirections, pipes, and process substitution - Managing signals, traps, and background processes - Debugging shell scripts with set options and tracing - Choosing between shell features and external tools ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of shell scripting — Bash features, shebang, execution, portability. ### `variables` ```bash scripts/script.sh variables ``` Variables — declaration, scope, arrays, parameter expansion, special variables. ### `control` ```bash scripts/script.sh control ``` Control flow — if/else, case, for, while, until, select, functions. ### `redirections` ```bash scripts/script.sh redirections ``` Redirections and pipes — stdin/stdout/stderr, heredocs, process substitution. ### `safety` ```bash scripts/script.sh safety ``` Safety practices — set -euo pipefail, quoting, shellcheck, error handling. ### `tools` ```bash scripts/script.sh tools ``` Essential tools — awk, sed, grep, find, xargs, cut, sort, jq patterns. ### `signals` ```bash scripts/script.sh signals ``` Signals and traps — SIGTERM, SIGINT, cleanup handlers, background jobs. ### `checklist` ```bash scripts/script.sh checklist ``` Shell script quality checklist. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `SHELL_DIR` | Data directory (default: ~/.shell/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # shell — Shell Scripting Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Shell Scripting === The shell is both a command interpreter and a programming language. Bash (Bourne Again Shell) is the most common shell on Linux systems. Shebang Line: #!/bin/bash — Use system bash #!/usr/bin/env bash — Use bash from PATH (more portable) #!/bin/sh — POSIX shell (not Bash! fewer features) The shebang MUST be the first line, no leading spaces. Execution Methods: chmod +x script.sh && ./script.sh # Direct execution (uses shebang) bash script.sh # Explicit interpreter source script.sh # Run in current shell (no subshell) . script.sh # Same as source (POSIX) Shell Comparison: sh (Bourne): POSIX base, minimal, maximum portability bash: Most common, rich features, arrays, [[ ]] zsh: macOS default, globbing, spelling correction dash: Fast POSIX shell (Debian /bin/sh → dash) fish: User-friendly, not POSIX (no sh compatibility) When to Use Shell vs Other Languages: USE SHELL: - Gluing programs together (pipe-based workflows) - File operations (copy, move, rename, permissions) - System administration tasks - Quick-and-dirty automation (<100 lines) - Anything that's mostly calling other commands USE PYTHON/OTHER: - Complex data structures (beyond arrays) - Error handling needs to be robust - Math-heavy operations - JSON/XML processing (shell struggles) - >200 lines (shell gets unwieldy) - Cross-platform requirements Exit Codes: 0: Success 1: General error 2: Misuse of shell command 126: Command found but not executable 127: Command not found 128+N: Killed by signal N (130 = Ctrl+C = SIGINT) Custom: use exit N in your script (0-255) EOF } cmd_variables() { cat << 'EOF' === Variables & Parameter Expansion === Declaration: name="Alice" # No spaces around = readonly PI=3.14159 # Cannot be reassigned local count=0 # Function-local (only in functions) export PATH # Make available to child processes declare -i num=42 # Integer attribute declare -r const="x" # Read-only (same as readonly) declare -a arr # Indexed array declare -A map # Associative array (Bash 4+) Special Variables: $0 Script name $1-$9 Positional arguments 10 Arguments beyond 9 (braces required) $# Number of arguments $@ All arguments (separate words when quoted) $* All arguments (single string when quoted) $$ Current process PID $! Last background process PID $? Last command exit code $_ Last argument of previous command $LINENO Current line number Parameter Expansion: -default Use default if var is unset or empty =default Set var to default if unset or empty +alternate Use alternate if var IS set ?error msg Exit with error if var is unset #var Length of string var#pattern Remove shortest prefix match var##pattern Remove longest prefix match var%pattern Remove shortest suffix match var%%pattern Remove longest suffix match var/old/new Replace first occurrence var//old/new Replace all occurrences var^ Uppercase first letter var^^ Uppercase all var, Lowercase first letter var,, Lowercase all Arrays: arr=("one" "two" "three") # Indexed array arr[0]="zero" # Set element echo "arr[0]" # Get element echo "arr[@]" # All elements echo "#arr[@]" # Array length echo "!arr[@]" # All indices arr+=("four") # Append Associative Arrays (Bash 4+): declare -A colors colors[red]="#ff0000" colors[green]="#00ff00" echo "colors[red]" # Get value echo "!colors[@]" # All keys EOF } cmd_control() { cat << 'EOF' === Control Flow === if/elif/else: if [[ "$name" == "Alice" ]]; then echo "Hello Alice" elif [[ "$name" == "Bob" ]]; then echo "Hello Bob" else echo "Hello stranger" fi Test Operators ([[ ]] — Bash extended test): String: == != < > -z (empty) -n (non-empty) =~ (regex) Integer: -eq -ne -lt -le -gt -ge File: -f (file) -d (dir) -e (exists) -r (readable) -w (writable) -x (executable) -s (non-empty) -L (symlink) -nt (newer than) -ot (older than) Logic: && (and) || (or) ! (not) [[ ]] vs [ ]: [[ ]] — Bash keyword, supports regex, no word splitting [ ] — POSIX, portable, but needs more quoting case: case "$input" in start|begin) echo "Starting..." ;; stop) echo "Stopping..." ;; restart) echo "Restarting..." do_restart ;; *) echo "Unknown: $input" ;; esac for: for item in "one" "two" "three"; do echo "$item"; done for file in *.txt; do echo "$file"; done for i in {1..10}; do echo "$i"; done for ((i=0; i<10; i++)); do echo "$i"; done for arg in "$@"; do echo "$arg"; done while/until: while read -r line; do echo "$line"; done < file.txt while [[ $count -lt 10 ]]; do ((count++)); done until [[ -f /tmp/ready ]]; do sleep 1; done # Infinite loop while true; do echo "running..." sleep 5 done Functions: greet() { local name="?Name required" echo "Hello, $name" return 0 } greet "Alice" # Capture output result=$(greet "Alice") # Functions share global scope unless 'local' used # Always use 'local' for function variables EOF } cmd_redirections() { cat << 'EOF' === Redirections & Pipes === File Descriptors: 0 = stdin (standard input) 1 = stdout (standard output) 2 = stderr (standard error) Basic Redirections: cmd > file Stdout to file (overwrite) cmd >> file Stdout to file (append) cmd < file File to stdin cmd 2> file Stderr to file cmd 2>&1 Stderr to stdout (merge) cmd &> file Both stdout and stderr to file (Bash) cmd > file 2>&1 Same, but POSIX compatible cmd > /dev/null Discard output Pipes: cmd1 | cmd2 Stdout of cmd1 → stdin of cmd2 cmd1 |& cmd2 Stdout AND stderr → stdin (Bash 4+) cmd1 | tee file Stdout to both pipe and file cmd1 | tee -a file Same but append Here Documents: cat << EOF # Variables expanded Hello, $USER Today is $(date) EOF cat << 'EOF' # Literal — no expansion Hello, $USER # Prints literally: $USER EOF cat <<- EOF # Strip leading tabs Indented content EOF Here Strings: grep "pattern" <<< "$variable" # Feeds variable as stdin (one line) Process Substitution: diff <(sort file1) <(sort file2) # Treats command output as a file cmd > >(tee log.txt) # Redirect output through a process Named Pipes (FIFO): mkfifo /tmp/mypipe cmd1 > /tmp/mypipe & cmd2 < /tmp/mypipe Advanced: exec 3> logfile.txt # Open FD 3 for writing echo "log entry" >&3 # Write to FD 3 exec 3>&- # Close FD 3 # Read file line-by-line without subshell while IFS= read -r line; do echo "$line" done < file.txt # PITFALL: pipe creates subshell! count=0 cat file.txt | while read -r line; do ((count++)); done echo "$count" # Always 0! (subshell variable) # FIX: use redirect instead of pipe count=0 while read -r line; do ((count++)); done < file.txt echo "$count" # Correct! EOF } cmd_safety() { cat << 'EOF' === Shell Script Safety === The Holy Trinity — set -euo pipefail: set -e Exit on first error (non-zero exit code) set -u Error on undefined variables set -o pipefail Pipe fails if ANY command in pipe fails Combined: set -euo pipefail (put at top of every script) Exceptions to -e: cmd || true # Intentionally allow failure if cmd; then ... # Tested in condition — no exit cmd || handle_error # Error handling pattern Quoting — ALWAYS QUOTE YOUR VARIABLES: Bad: if [ $file = "test" ] # Breaks on spaces/globs Good: if [[ "$file" == "test" ]] Bad: for f in $(ls); do ... # Word splitting disasters Good: for f in *; do ... # Glob expansion is safe Bad: echo $var # Glob expansion, word splitting Good: echo "$var" # Preserved as-is When to NOT quote: Glob patterns: for f in *.txt (intentional expansion) Arithmetic: $(( count + 1 )) (already evaluated) ShellCheck: Static analysis tool — catches bugs before running Install: apt install shellcheck / brew install shellcheck Usage: shellcheck script.sh Online: https://www.shellcheck.net Integrate into CI/CD pipeline EVERY shell script should pass ShellCheck Error Handling Patterns: # Trap for cleanup cleanup() { rm -f "$tmpfile" echo "Cleaned up" >&2 } trap cleanup EXIT # Die function die() { echo "ERROR: $*" >&2 exit 1 } # Safe temp files tmpfile=$(mktemp) || die "Failed to create temp file" trap 'rm -f "$tmpfile"' EXIT # Check commands exist command -v jq &>/dev/null || die "jq is required" Common Gotchas: cd /some/dir && do_stuff # cd might fail! cd /some/dir || exit 1 # Safe if [ -f "$file" ]; then # Race condition possible var=$(cmd) # $? is now cmd's exit code, not previous local var=$(cmd) # 'local' masks exit code! Always: local var; var=$(cmd) EOF } cmd_tools() { cat << 'EOF' === Essential CLI Tools === grep — Pattern Matching: grep "pattern" file # Basic search grep -r "pattern" dir/ # Recursive grep -i "pattern" file # Case-insensitive grep -v "pattern" file # Invert match grep -c "pattern" file # Count matches grep -l "pattern" *.txt # List matching files grep -n "pattern" file # Line numbers grep -E "regex|pattern" file # Extended regex (egrep) grep -o "pattern" file # Only matching part grep -P "\d+" file # Perl regex (GNU grep) sed — Stream Editor: sed 's/old/new/' file # Replace first per line sed 's/old/new/g' file # Replace all sed -i 's/old/new/g' file # In-place edit sed -n '5,10p' file # Print lines 5-10 sed '/pattern/d' file # Delete matching lines sed '3a\new line' file # Insert after line 3 awk — Field Processing: awk '{print $1}' file # First field (space-delimited) awk -F: '{print $1}' /etc/passwd # Custom delimiter awk '$3 > 100' file # Filter by field value awk '{sum+=$1} END{print sum}' # Sum a column awk 'NR==5,NR==10' file # Lines 5-10 awk '!seen[$0]++' file # Remove duplicates (order preserved) find — File Discovery: find . -name "*.log" # By name pattern find . -type f -mtime -7 # Modified in last 7 days find . -size +100M # Larger than 100MB find . -name "*.tmp" -delete # Find and delete find . -type f -exec chmod 644 {} \; # Execute on each xargs — Build Commands from Input: find . -name "*.log" | xargs rm # Delete found files find . -name "*.log" -print0 | xargs -0 rm # Handle spaces cat urls.txt | xargs -P 4 -I {} curl {} # Parallel downloads jq — JSON Processing: echo '{"name":"Ada"}' | jq '.name' # "Ada" cat data.json | jq '.items[0]' # First item cat data.json | jq '.items | length' # Array length cat data.json | jq -r '.name' # Raw output (no quotes) cat data.json | jq 'select(.age > 30)' # Filter sort/uniq/cut/wc: sort file # Sort lines sort -n file # Numeric sort sort -k2 file # Sort by 2nd field sort file | uniq -c # Count unique lines cut -d: -f1 /etc/passwd # Extract field wc -l file # Count lines wc -w file # Count words EOF } cmd_signals() { cat << 'EOF' === Signals & Traps === Common Signals: Signal Number Default Source SIGHUP 1 Terminate Terminal closed SIGINT 2 Terminate Ctrl+C SIGQUIT 3 Core dump Ctrl+\ SIGKILL 9 Terminate Cannot be caught! (kill -9) SIGTERM 15 Terminate Graceful shutdown (kill default) SIGCHLD 17 Ignore Child process stopped/terminated SIGSTOP 19 Stop Cannot be caught! (like SIGKILL) SIGTSTP 20 Stop Ctrl+Z SIGUSR1 10 Terminate User-defined SIGUSR2 12 Terminate User-defined trap — Catch Signals: # Cleanup on exit (any exit — normal or error) trap 'echo "Cleaning up..."; rm -f "$tmpfile"' EXIT # Catch Ctrl+C trap 'echo "Interrupted!"; exit 130' INT # Catch termination trap 'echo "Terminated!"; cleanup; exit 143' TERM # Multiple signals trap 'cleanup' EXIT INT TERM HUP # Reset trap to default trap - INT # Ignore signal trap '' INT # Ctrl+C does nothing # List active traps trap -p Cleanup Pattern: #!/usr/bin/env bash set -euo pipefail tmpdir=$(mktemp -d) cleanup() { local exit_code=$? rm -rf "$tmpdir" exit "$exit_code" # Preserve original exit code } trap cleanup EXIT INT TERM # ... script logic ... # cleanup runs automatically on any exit Background Jobs: cmd & # Run in background wait # Wait for all background jobs wait $pid # Wait for specific PID wait -n # Wait for any one job (Bash 4.3+) jobs # List background jobs fg %1 # Bring job 1 to foreground bg %1 # Resume stopped job in background kill %1 # Kill job 1 disown %1 # Detach job from shell Parallel Execution: # Run commands in parallel, wait for all cmd1 & cmd2 & cmd3 & wait # With exit code checking pids=() cmd1 & pids+=($!) cmd2 & pids+=($!) for pid in "pids[@]"; do wait "$pid" || echo "PID $pid failed" done # GNU Parallel (more sophisticated) parallel -j4 process_file ::: *.csv Nohup / Disown: nohup cmd & # Survives terminal close (output → nohup.out) cmd & disown # Detach from shell (no nohup.out) setsid cmd # New session (fully detached) EOF } cmd_checklist() { cat << 'EOF' === Shell Script Quality Checklist === Structure: [ ] Shebang line present (#!/usr/bin/env bash) [ ] set -euo pipefail at top [ ] Script purpose documented in header comment [ ] Usage/help function for arguments [ ] Consistent indentation (2 or 4 spaces, not tabs) [ ] Functions defined before use [ ] main() function pattern if script is complex Safety: [ ] All variables quoted ("$var" not $var) [ ] No uninitialized variable access (set -u catches these) [ ] Temp files created with mktemp [ ] Cleanup trap registered (trap cleanup EXIT) [ ] Exit codes meaningful and documented [ ] No eval with user input (security risk!) [ ] No unescaped glob patterns where not intended Error Handling: [ ] Critical commands checked for failure [ ] die/error function for clean error reporting [ ] Stderr used for error messages (>&2) [ ] Dependencies checked at start (command -v) [ ] Permissions verified before operations [ ] Network operations have timeouts Code Quality: [ ] ShellCheck passes with no warnings [ ] Functions are small and focused [ ] Local variables used in functions [ ] No useless cat (use < file instead of cat file |) [ ] No parsing ls output (use globs) [ ] No cd without || exit [ ] Arrays used for lists (not space-separated strings) Input Handling: [ ] Arguments validated (count and format) [ ] Paths handled with spaces and special characters [ ] User input sanitized before use [ ] Default values provided where appropriate [ ] --help / -h supported [ ] -- handled for option termination Portability (if needed): [ ] Tested on target systems (Linux, macOS, both?) [ ] bash-specific features noted if not POSIX [ ] GNU vs BSD tool differences handled (sed -i, grep -P) [ ] No hardcoded paths (/usr/local vs /usr) [ ] External tool versions documented EOF } show_help() { cat << EOF shell v$VERSION — Shell Scripting Reference Usage: script.sh <command> Commands: intro Bash overview, shebang, exit codes, when to use shell variables Variables, arrays, parameter expansion, special vars control if/case/for/while, functions, test operators redirections Pipes, heredocs, process substitution, FD management safety set -euo pipefail, quoting, ShellCheck, error handling tools grep, sed, awk, find, xargs, jq essential patterns signals Traps, cleanup, background jobs, parallel execution checklist Shell script quality checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; variables) cmd_variables ;; control) cmd_control ;; redirections) cmd_redirections ;; safety) cmd_safety ;; tools) cmd_tools ;; signals) cmd_signals ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "shell v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Phosphate fertilizer reference — P2O5 forms, application timing, soil testing, runoff management, crop requirements. Use when planning phosphorus fertilizati...
--- name: "phosphate" version: "1.0.0" description: "Phosphate fertilizer reference — P2O5 forms, application timing, soil testing, runoff management, crop requirements. Use when planning phosphorus fertilization programs or managing phosphate resources." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [phosphate, phosphorus, fertilizer, agriculture, soil, nutrient, p2o5] category: "agriculture" --- # Phosphate — Phosphorus Fertilizer Reference Quick-reference skill for phosphorus nutrition, fertilizer products, and management. ## When to Use - Planning phosphorus fertilization for crops - Interpreting soil test phosphorus levels - Selecting phosphate fertilizer products and forms - Managing environmental phosphorus runoff risks - Understanding phosphorus cycling in soil ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of phosphorus in agriculture — role, cycling, global reserves. ### `products` ```bash scripts/script.sh products ``` Phosphate fertilizer products — MAP, DAP, TSP, rock phosphate, SSP. ### `soiltest` ```bash scripts/script.sh soiltest ``` Soil phosphorus testing — Bray, Olsen, Mehlich, interpretation tables. ### `placement` ```bash scripts/script.sh placement ``` Application methods — broadcast, band, starter, foliar, timing. ### `crops` ```bash scripts/script.sh crops ``` Crop phosphorus requirements and removal rates. ### `cycling` ```bash scripts/script.sh cycling ``` Phosphorus cycling — fixation, mineralization, pH effects, mycorrhizae. ### `environmental` ```bash scripts/script.sh environmental ``` Environmental management — runoff, P index, eutrophication, 4R stewardship. ### `checklist` ```bash scripts/script.sh checklist ``` Phosphorus management planning checklist. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `PHOSPHATE_DIR` | Data directory (default: ~/.phosphate/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # phosphate — Phosphorus Fertilizer Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Phosphorus in Agriculture === Phosphorus (P) is one of the three primary macronutrients (N-P-K) essential for plant growth. It cannot be substituted by any other element — plants must have P to complete their life cycle. Roles in Plants: Energy transfer: ATP and ADP (cellular energy currency) DNA/RNA: Backbone of genetic material Cell membranes: Phospholipid bilayers Root development: Stimulates early root growth Flowering/fruiting: Promotes reproductive development Seed formation: High P content in seeds Photosynthesis: Part of energy capture cycle Phosphorus Cycle: Rock phosphate (geological) → Mining/weathering → Fertilizer/soil → Plant uptake (H2PO4⁻, HPO4²⁻) → Harvest removal / organic return → Soil organic P → mineralization → available P → fixation → unavailable P → runoff/erosion → water bodies Global Reserves: Total reserves: ~70 billion tonnes (USGS estimate) Major producers: China: ~85 Mt/year (largest producer) Morocco: ~40 Mt/year (largest reserves: 50B tonnes) United States: ~22 Mt/year (Florida, Idaho, Utah) Russia: ~14 Mt/year Jordan: ~9 Mt/year "Peak phosphorus": estimated 50-100 years at current extraction No synthetic alternative — P must be mined or recycled Phosphorus vs Phosphate: Phosphorus (P): The element Phosphate (PO4): The ion (P bound to oxygen) P2O5: Phosphorus pentoxide (fertilizer standard) Conversion: P × 2.29 = P2O5 | P2O5 × 0.44 = P Deficiency Symptoms: - Purple/reddish leaves (anthocyanin accumulation) - Stunted growth (small plants) - Delayed maturity - Poor root development - Reduced tillering in cereals - Low seed set Most visible in young plants and cool soil conditions EOF } cmd_products() { cat << 'EOF' === Phosphate Fertilizer Products === Product Formula N-P2O5-K2O P2O5% MAP (Mono-ammonium) NH4H2PO4 11-52-0 52% DAP (Di-ammonium) (NH4)2HPO4 18-46-0 46% TSP (Triple Super) Ca(H2PO4)2 0-46-0 46% SSP (Single Super) Ca(H2PO4)2+ 0-20-0 20% CaSO4 Rock Phosphate Ca3(PO4)2 0-30-0* 30%* Bone Meal Ca3(PO4)2 3-15-0 15% Ammonium Polyphosphate NH4 poly-P 10-34-0 34% * Rock phosphate: total P, only 2-3% available in neutral/alkaline soil MAP (Monoammonium Phosphate): Most common phosphate fertilizer worldwide Granular, excellent handling properties Slightly acidic reaction in soil (pH effect: acidifying) Good for banding (starter fertilizer) Dissolves readily in soil moisture DAP (Diammonium Phosphate): Second most common globally Higher N content than MAP (18% vs 11%) Alkaline initial reaction (pH ~8 at dissolution zone) Can cause seedling ammonia injury if placed too close Preferred for broadcast applications TSP (Triple Superphosphate): No nitrogen — pure P source Good when N not needed but P is Made from rock phosphate + phosphoric acid Water-soluble, fast-acting SSP (Single Superphosphate): Contains calcium and sulfur (bonus nutrients) Lower P concentration = higher transport cost per unit P Good for S-deficient soils Made from rock phosphate + sulfuric acid Liquid Phosphate: Ammonium polyphosphate (10-34-0): fluid fertilizer Compatible with UAN (32-0-0) for blending Used in starter/popup fertilizers Excellent for fertigation and foliar application Polyphosphate hydrolyzes to orthophosphate in soil Organic Phosphate Sources: Bone meal: 3-15-0 (slow release, needs acidic soil) Compost: variable (typically 0.5-1% P) Manure: varies widely — test before applying Biosolids: 1-3% P (sewage sludge, regulated) Fish meal: 4-7% P2O5 Guano: variable, up to 30% P2O5 (historical) EOF } cmd_soiltest() { cat << 'EOF' === Soil Phosphorus Testing === Common Extraction Methods: Bray P1 (Bray-Kurtz): Extractant: 0.025N HCl + 0.03N NH4F Best for: acid to neutral soils (pH < 7.2) Not valid for: alkaline soils (dissolves calcium phosphate → overestimates) Most common in US Midwest Olsen (Sodium Bicarbonate): Extractant: 0.5M NaHCO3 at pH 8.5 Best for: alkaline soils (pH > 7.0) Also works for acid soils Universal — used worldwide (especially arid regions) Mehlich 3: Extractant: acetic acid + NH4NO3 + NH4F + HNO3 + EDTA Multi-element extraction (P, K, Ca, Mg, micronutrients) Works across wide pH range Increasingly preferred for efficiency (one test, many nutrients) Interpretation (ppm or mg/kg): Category Bray P1 Olsen Mehlich 3 Action Very Low <5 <3 <12 Heavy P needed Low 5-15 3-7 12-20 Build P level Medium 16-25 8-14 21-30 Maintenance High 26-50 15-25 31-50 Reduce/skip P Very High >50 >25 >50 No P needed Sampling Protocol: 1. Sample 0-6 inches (15 cm) depth for P 2. Collect 15-20 cores per field (zigzag pattern) 3. Mix cores into composite sample 4. Avoid recent fertilizer bands, field edges, dead furrows 5. Sample every 2-4 years (P changes slowly) 6. Sample same time of year for consistency 7. For precision: grid sample at 2.5-acre cells Soil P Buildup: To raise soil test P by 1 ppm: Approximately 10-20 lb P2O5/acre needed (varies by soil type) Clay soils: higher fixation → more P needed to raise test Sandy soils: lower fixation → less P needed but higher loss risk Maintenance: replace P removed by crop harvest Critical Level Concept: Below critical level: strong yield response to P At critical level: 95% of maximum yield Above critical level: diminishing returns Way above: no response, environmental risk, waste of money EOF } cmd_placement() { cat << 'EOF' === Phosphorus Application Methods === Broadcast: Spread uniformly across entire field surface Incorporate by tillage (P doesn't move much in soil) Best for: building soil P levels, high P rates When: pre-plant or fall application Efficiency: lower than banding (more soil contact = more fixation) Band/Starter: Place P in concentrated band near seed 2" beside and 2" below seed (2×2 placement) Or in-furrow (with seed — low rates only!) Best for: low-P soils, cold soils, early season boost Efficiency: 2-4× more efficient than broadcast per unit P Warning: in-furrow rate max 5-10 lb P2O5/acre (salt injury) Deep Band: Place P at 6-8" depth (chisel/knife injection) Benefits: accessible during dry topsoil conditions Reduced runoff risk (below surface) Common in no-till systems Foliar: Spray liquid P on leaves (emergency correction) Low rates only: 2-5 lb P2O5/acre per application Uptake limited — leaves not primary P absorption organ Use: supplement, not replacement for soil P Fertigation: Apply liquid P through irrigation system Requires water-soluble products (polyphosphate, phosphoric acid) Good for: drip irrigation, high-value crops Caution: phosphoric acid can clog emitters if Ca is high Timing: Pre-plant (fall or spring): most common At planting (starter): highest efficiency per unit In-season (top-dress): limited for P (low mobility) Split application: generally not needed (P is immobile) No-Till Considerations: P stratifies at surface without tillage Top 2" may test very high, below 4" may test low Solutions: - Deep banding every 2-3 years - Subsurface placement at planting - Accept some stratification (roots near surface anyway) Phosphorus Placement Comparison: Method Efficiency Cost Best Use Broadcast Low-Med Low Building soil P 2×2 band High Medium Low-P soils, cold soils In-furrow Very High Medium Starter, small amounts Deep band High High No-till, dry climates Foliar Very Low High Emergency only EOF } cmd_crops() { cat << 'EOF' === Crop Phosphorus Requirements === Phosphorus Removal in Harvested Crop: Crop Yield Unit P2O5 Removal (lb/unit) Corn (grain) 1 bushel 0.37 Soybean 1 bushel 0.75 Wheat 1 bushel 0.50 Rice 1 cwt 0.27 Cotton (lint) 1 bale 13.0 Alfalfa hay 1 ton 12.0 Corn silage 1 ton 3.5 Potato 1 cwt 0.18 Tomato 1 ton 0.5 Apple 1 ton 0.5 Example — Corn at 200 bu/acre: Removal = 200 × 0.37 = 74 lb P2O5/acre removed in grain Maintenance rate: apply ≥74 lb P2O5/acre to maintain soil test Crop Sensitivity to P: Very responsive: corn, potato, sugar beet, alfalfa Moderately responsive: soybean, wheat, canola Less responsive: barley, oats (efficient P scavengers) Very high demand: potato (weak root system, high removal) Phosphorus Uptake Timing: Corn: 60% of P taken up by silking (V12-R1) Soybean: peak uptake R3-R5 (pod fill) Wheat: most P taken up by heading Key: P must be available EARLY — roots need it from day 1 Phosphorus and Crop Quality: Sugar beet: excess P reduces sugar content Potato: P improves tuber set and early bulking Grain crops: P affects grain test weight and protein (indirect) Fruit: P promotes flowering and fruit set Forage: P affects stand persistence (alfalfa especially) Cover Crop P Cycling: Cover crops take up residual P, prevent loss When terminated, P returns to soil surface Best P-scavenging covers: buckwheat, brassicas Mycorrhizal covers: improve P access for following cash crop EOF } cmd_cycling() { cat << 'EOF' === Phosphorus Cycling in Soil === Soil Phosphorus Pools: Solution P: 0.01-1 ppm (immediately plant-available) Labile P: readily exchangeable with solution (days-weeks) Non-labile P: slowly exchangeable (months-years) Mineral P: bound to Ca, Fe, Al minerals (very slow release) Organic P: 30-65% of total P in many soils Phosphorus Fixation: Definition: conversion of soluble P to insoluble forms pH effect on fixation: pH < 5.5: P fixed by Fe and Al oxides (most severe) pH 6.0-7.0: LEAST fixation (optimal range) pH > 7.5: P fixed by calcium (calcium phosphate precipitation) Fixation factors: - Soil pH (strongest factor) - Clay content (more clay = more fixation sites) - Organic matter (competes for fixation sites — helps P) - Fe/Al oxide content (tropical soils fix heavily) - Time (newly applied P more available than aged P) Mycorrhizal Association: 70-80% of plant species form arbuscular mycorrhizal (AM) relationships Fungal hyphae extend root exploration volume 10-100× AM fungi access P from smaller pores and greater distances Non-mycorrhizal crops: brassicas, beets, spinach (need more P) Mycorrhizal crops: corn, wheat, soybean, potato Promoting mycorrhizae: - Reduce tillage (hyphal network preserved) - Reduce high-P fertilizer rates (fungi less active when P abundant) - Use mycorrhizal cover crops in rotation - Avoid long fallow (fungi die without host roots) Mineralization / Immobilization: Organic P → Inorganic P (mineralization): C:P ratio < 200 Inorganic P → Organic P (immobilization): C:P ratio > 300 Most crop residues have C:P 200-300 (near equilibrium) Manure additions stimulate mineralization (low C:P) Temperature and moisture drive microbial activity Phosphorus Movement: Extremely immobile in soil (moves <1 inch per year) Diffusion is primary uptake mechanism (not mass flow) Roots must grow TO the phosphorus Band placement: concentrates P where roots are developing Leaching: rare except in sandy soils with very high P EOF } cmd_environmental() { cat << 'EOF' === Environmental Phosphorus Management === Eutrophication: Excess P in surface water → algal blooms → oxygen depletion → fish kills → dead zones P is the limiting nutrient in most freshwater systems As little as 0.02 ppm P can trigger algal growth Examples: Lake Erie, Gulf of Mexico, Chesapeake Bay Phosphorus Loss Pathways: 1. Surface runoff (attached to sediment particles) 2. Dissolved P in runoff water (most bioavailable) 3. Erosion (major P transport mechanism) 4. Tile drainage (subsurface, dissolved P — growing concern) 5. Wind erosion of P-rich topsoil Phosphorus Index (PI): Risk assessment tool rating field vulnerability to P loss Factors: Source: soil test P level, P application rate, method Transport: erosion rate, runoff, proximity to water, slope Rating: Low / Medium / High / Very High High/Very High: no additional P allowed until risk reduced 4R Nutrient Stewardship: Right Source: Match P form to crop/soil need Right Rate: Based on soil test and crop removal Right Time: When crop can use it (not fall on frozen ground) Right Place: Incorporate or band (not surface-applied before rain) Best Management Practices (BMPs): 1. Soil test regularly — don't over-apply 2. Incorporate broadcast P within 24 hours 3. No surface P application on frozen or saturated soil 4. Maintain >30 feet vegetated buffer along waterways 5. Use cover crops to hold soil and cycle P 6. Reduce erosion: no-till, terraces, contour farming 7. Manage manure P: test, calibrate, and apply at agronomic rates 8. Consider P drawdown if soil test P is excessive Manure P Management: Problem: manure applied at N rates often over-applies P Corn needs 150 lb N, gets enough P from ~3-4 tons manure But 6-8 tons applied for N needs → 2× P needed Solution: supplement manure with commercial N, apply manure at P rate Manure nutrient content varies — always lab-test before applying Phosphorus Recycling: Struvite recovery: precipitate P from wastewater as fertilizer Manure processing: concentrate P for targeted application Biochar: can capture and slowly release P Urban waste: potential P source (food waste, biosolids) Goal: close the P cycle — from linear mining to circular economy EOF } cmd_checklist() { cat << 'EOF' === Phosphorus Management Checklist === Soil Testing: [ ] Soil sampled within last 3 years (0-6" depth) [ ] Appropriate test method for soil pH (Bray/Olsen/Mehlich) [ ] Soil test P interpreted correctly for local guidelines [ ] Field mapped by soil test P level (precision if possible) Fertilizer Planning: [ ] Crop P removal calculated for expected yield [ ] Build/maintain/drawdown strategy determined [ ] P source selected (MAP, DAP, TSP, manure, etc.) [ ] P rate calculated: maintenance + any build-up needed [ ] Application method chosen (broadcast, band, starter) [ ] P2O5 to product conversion correct [ ] Manure P credited (if applying manure) Application: [ ] Equipment calibrated for target rate [ ] Timing appropriate (not on frozen/saturated soil) [ ] Broadcast P incorporated within 24 hours [ ] Starter P placed correctly (2×2 or safe in-furrow rate) [ ] Setback from waterways maintained (30+ feet) [ ] Manure applied at P-based rate (not just N-based) Environmental: [ ] Phosphorus Index assessed for sensitive fields [ ] Buffers established along water bodies [ ] Erosion control practices in place [ ] No P applied on snow-covered or frozen ground [ ] Cover crops planned for erosion-prone fields [ ] Nutrient management plan filed (if required) Record-Keeping: [ ] P application date, rate, source, method recorded [ ] Soil test results filed [ ] Yield data collected for removal calculations [ ] Manure analysis on file (if using manure) [ ] 4R documentation maintained for compliance EOF } show_help() { cat << EOF phosphate v$VERSION — Phosphorus Fertilizer Reference Usage: script.sh <command> Commands: intro Phosphorus role, cycling, global reserves products MAP, DAP, TSP, rock phosphate, organics soiltest Bray, Olsen, Mehlich tests and interpretation placement Broadcast, band, starter, foliar methods crops Crop P requirements and removal rates cycling Fixation, pH effects, mycorrhizae environmental Runoff, P index, eutrophication, 4R checklist Phosphorus management planning checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; products) cmd_products ;; soiltest) cmd_soiltest ;; placement) cmd_placement ;; crops) cmd_crops ;; cycling) cmd_cycling ;; environmental) cmd_environmental ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "phosphate v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Seed germination reference — imbibition, dormancy breaking, temperature/moisture requirements, testing protocols. Use when planning seed starting, evaluating...
--- name: "germination" version: "1.0.0" description: "Seed germination reference — imbibition, dormancy breaking, temperature/moisture requirements, testing protocols. Use when planning seed starting, evaluating germination rates, or troubleshooting poor emergence." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [germination, seed, agriculture, planting, dormancy, emergence, propagation] category: "agriculture" --- # Germination — Seed Germination Reference Quick-reference skill for seed germination science, testing, and practical growing. ## When to Use - Planning seed starting schedules for crops - Troubleshooting poor germination rates - Breaking seed dormancy with scarification or stratification - Running germination tests to evaluate seed viability - Optimizing temperature and moisture for emergence ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of germination — phases, biology, key factors. ### `conditions` ```bash scripts/script.sh conditions ``` Optimal conditions — temperature, moisture, oxygen, light requirements by crop. ### `dormancy` ```bash scripts/script.sh dormancy ``` Seed dormancy types and breaking methods — stratification, scarification, leaching. ### `testing` ```bash scripts/script.sh testing ``` Germination testing protocols — ISTA rules, paper towel test, tetrazolium. ### `crops` ```bash scripts/script.sh crops ``` Germination data for common crops — days, temperature, depth, rate benchmarks. ### `problems` ```bash scripts/script.sh problems ``` Troubleshooting poor germination — damping off, crusting, seed age, pathogens. ### `enhancement` ```bash scripts/script.sh enhancement ``` Seed enhancement — priming, pelleting, coating, biopriming techniques. ### `schedule` ```bash scripts/script.sh schedule ``` Germination scheduling — calculating start dates, hardening off, transplant timing. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `GERMINATION_DIR` | Data directory (default: ~/.germination/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # germination — Seed Germination Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Seed Germination === Germination is the process by which a seed develops into a new plant. It begins with water uptake (imbibition) and ends when the radicle (embryonic root) emerges from the seed coat. Three Phases of Germination: Phase I — Imbibition (0-12 hours): Rapid water uptake through seed coat Seed swells 50-200% of original size Enzymes reactivate, cellular repair begins Physical: seed coat softens and may crack Phase II — Lag Phase (12-48 hours): Water uptake slows Metabolic activation: respiration ↑, DNA repair mRNA translation, protein synthesis begins Stored reserves (starch, lipids) mobilized Gibberellic acid (GA3) signals aleurone layer Phase III — Radicle Emergence (48-120+ hours): Cell elongation in embryonic axis Radicle breaks through seed coat This is the formal endpoint of "germination" Subsequent growth = seedling establishment, not germination Essential Requirements: 1. Water — triggers imbibition and enzyme activation 2. Oxygen — aerobic respiration for energy 3. Temperature — within species-specific range 4. Light/Dark — species-dependent (some need light, some dark) Seed Viability: Most seeds remain viable 1-5 years under proper storage Some exceptional cases: Lotus seeds: germinated after 1,300 years Date palm: germinated from 2,000-year-old seed (Masada) Storage rule: cool (5-10°C) + dry (< 8% moisture) = long life EOF } cmd_conditions() { cat << 'EOF' === Optimal Germination Conditions === Temperature Ranges (°C): Category Min Optimal Max Cool-season 2-5 15-20 25-30 Warm-season 10-15 25-30 35-40 Tropical 15-20 30-35 40-45 Examples: Lettuce 2°C 18°C 25°C (thermodormancy above 25°C) Tomato 10°C 25°C 35°C Pepper 15°C 30°C 35°C Corn 10°C 30°C 40°C Wheat 4°C 20°C 30°C Rice 10°C 30°C 40°C Moisture: Imbibition requires 25-50% of seed weight in water Too little: germination stalls at Phase I Too much: oxygen deprivation → anaerobic rot Ideal soil moisture: 50-75% of field capacity Testing: squeeze soil — should form ball but not drip Oxygen: Seeds need O2 for aerobic respiration Waterlogged soil = anaerobic = poor germination Planting depth affects O2 availability Large seeds tolerate deeper planting (more stored energy) Soil crusting blocks both O2 and emergence Light Requirements: Positive photoblastic (need light): lettuce, celery, petunia Plant on surface or barely cover Negative photoblastic (need dark): onion, phlox, calendula Cover well with soil or vermiculite Neutral (light indifferent): most crops — tomato, pepper, corn Light detected by phytochrome pigment (red/far-red ratio) Soil pH: Most seeds germinate in pH 5.5-7.5 Acidic (<5): aluminum toxicity inhibits root growth Alkaline (>8): micronutrient lockout Ideal germination mix: pH 6.0-6.5 EOF } cmd_dormancy() { cat << 'EOF' === Seed Dormancy === Dormancy is a survival mechanism preventing germination under unfavorable conditions, even when water, oxygen, and temperature are present. Types of Dormancy: 1. Physical Dormancy (Hardseededness): Impermeable seed coat blocks water entry Common in: legumes, morning glory, lotus, acacia Breaking methods: Scarification — mechanical (sandpaper, nicking) Hot water soak — 80°C water, cool naturally Acid scarification — H2SO4 for 1-30 minutes (careful!) Freeze-thaw cycles — natural winter weathering 2. Physiological Dormancy: Embryo chemical/hormonal block ABA (abscisic acid) inhibits germination GA (gibberellic acid) promotes germination Breaking methods: Cold stratification — 1-5°C moist for 30-120 days Warm stratification — 20-25°C moist for 30-60 days GA3 application — soak in 100-500 ppm gibberellic acid After-ripening — dry storage at room temp for months 3. Morphological Dormancy: Embryo not fully developed at seed shed Must grow inside seed before germination Common in: carrot family, magnolia, ginseng Breaking: warm stratification to allow embryo growth 4. Combinational Dormancy: Physical + physiological (double dormancy) Common in: redbud, hawthorn, some roses Requires: scarification THEN stratification Can take 2 seasons in nature 5. Morphophysiological Dormancy: Underdeveloped embryo + physiological block Most complex — requires specific warm/cold sequences Common in: trillium, peony, lily May take 2-3 years to germinate naturally Stratification Protocol: 1. Soak seeds 24h in water 2. Mix with moist peat or vermiculite (1:3 ratio) 3. Place in sealed bag with air holes 4. Refrigerate at 1-5°C 5. Check weekly for moisture and premature germination 6. Duration: 30-120 days depending on species EOF } cmd_testing() { cat << 'EOF' === Germination Testing === Standard Germination Test (ISTA Rules): International Seed Testing Association (ISTA) protocols Used by seed labs worldwide for official results Procedure: 1. Draw 400 seeds (4 replicates × 100 seeds) 2. Place on moist germination paper or sand 3. Incubate at species-specific temp (see ISTA tables) 4. Count normal seedlings at first count (early vigor) 5. Count again at final count (total germination) 6. Record: normal, abnormal, dead, fresh ungerminated Result: Germination % = (Normal seedlings / Total seeds) × 100 Paper Towel (Ragdoll) Test — DIY: 1. Wet paper towels (damp, not dripping) 2. Place 10-25 seeds on towel 3. Roll up loosely, place in plastic bag (partially open) 4. Keep at 20-25°C 5. Check daily for 7-14 days 6. Count seeds with visible radicle (≥2mm) Interpretation: >90%: Excellent — full seeding rate 70-90%: Good — slight overseeding may help 50-70%: Fair — increase seeding rate 25-50% <50%: Poor — consider new seed lot Tetrazolium (TZ) Test: Rapid viability test (24-48 hours vs 7-28 days) Seeds soaked in 2,3,5-triphenyltetrazolium chloride solution Living tissue stains RED (respiring cells reduce TZ) Dead tissue stays WHITE Cut seeds and evaluate staining pattern Not a germination test — a viability estimate Vigor Tests: Cold test: germinate at 10°C in soil (simulates early planting) Accelerated aging: 41°C at 100% RH for 72h, then germinate Electrical conductivity: measure solute leakage from soaked seeds Low leakage = intact membranes = high vigor Seed Lot Quality Metrics: Pure seed %: ≥98% for certified seed Germination %: species-specific minimums (e.g., corn ≥80%) Vigor index: germination % × mean seedling length Moisture content: <13% for safe storage EOF } cmd_crops() { cat << 'EOF' === Germination Data by Crop === Vegetables: Crop Days Opt°C Depth(cm) Min Germ% Tomato 5-10 25 0.6 75% Pepper 7-14 30 0.6 55% Lettuce 2-7 18 0.3 80% Carrot 10-21 25 0.6 55% Onion 7-10 20 1.3 70% Cucumber 3-7 30 1.3 80% Bean 5-10 25 2.5 70% Pea 5-10 20 2.5 80% Corn (sweet) 4-7 30 2.5 75% Spinach 5-10 20 1.3 60% Squash 4-7 30 2.5 75% Radish 3-5 25 1.3 75% Broccoli 3-7 25 0.6 75% Watermelon 4-8 30 2.5 70% Field Crops: Crop Days Opt°C Depth(cm) Min Germ% Wheat 5-10 20 3-5 85% Rice 5-10 30 1-2 80% Corn (field) 4-7 30 4-5 90% Soybean 5-10 25 3-4 80% Cotton 5-10 30 3-5 80% Sunflower 5-10 25 3-5 75% Barley 5-10 20 3-4 85% Canola 3-7 20 1-2 80% Herbs: Crop Days Opt°C Depth(cm) Light? Basil 5-10 25 0.3 Light Cilantro 7-14 20 0.6 Dark Dill 7-14 20 0.3 Light Parsley 14-28 20 0.6 Dark Thyme 7-21 20 surface Light Oregano 7-14 20 surface Light Sage 10-21 20 0.3 Light Seeding Rate Adjustment: If germination test shows 70% and target is 100 plants: Seeds needed = Target plants / (Germ% × Field emergence%) = 100 / (0.70 × 0.85) = 168 seeds Field emergence is typically 80-90% of lab germination EOF } cmd_problems() { cat << 'EOF' === Troubleshooting Poor Germination === Damping Off: Cause: Pythium, Rhizoctonia, Fusarium fungi Symptoms: seedlings collapse at soil line, wire-stem Pre-emergence: seeds rot before emerging Prevention: - Use sterile/pasteurized growing media - Don't overwater (let surface dry between waterings) - Good air circulation - Treat seed with fungicide (thiram, captan) - Biological: Trichoderma seed treatment Soil Crusting: Cause: heavy rain/irrigation on fine-textured soil Blocks emergence physically Prevention: - Light mulch over seeded rows - Vermiculite/perlite topdressing - Gentle irrigation (mist, not flood) - Plant at proper depth Temperature Problems: Too cold: slow/no germination, seed rot in wet soil Too hot: thermodormancy (lettuce >25°C), embryo damage Fluctuating: can actually improve germination for some species Solution: use heat mats (set 5°C above ambient for warm crops) Old Seed / Low Viability: Seed deterioration accelerates with: - High moisture (>13%) - High temperature - Age beyond recommended storage life Quick test: paper towel test before planting Onion, parsley: use within 1-2 years Tomato, pepper: good for 4-5 years if stored well Cucumber, melon: can last 5-10 years Seed-Borne Pathogens: Bacterial: black rot (Xanthomonas) in brassicas Fungal: Alternaria on carrots, Ascochyta on peas Treatment: - Hot water treatment (50°C for 20-30 min, species-specific) - Bleach soak (10% for 10 min, rinse well) - Commercial seed treatment fungicides Other Causes: - Planting too deep (small seeds especially) - Fertilizer burn (salt damage to emerging radicle) - Herbicide residue in soil or compost - Bird/rodent predation - Insufficient seed-to-soil contact EOF } cmd_enhancement() { cat << 'EOF' === Seed Enhancement Technologies === Seed Priming: Controlled hydration to initiate Phase I/II without radicle emergence Then dry back to original moisture for storage/planting Types: Hydropriming: soak in water for defined hours, then dry Osmopriming: soak in PEG or salt solution (controlled ψ) Matripriming: mix with moist solid matrix (vermiculite) Biopriming: prime + beneficial microbes (Trichoderma, Bacillus) Benefits: - Faster emergence (2-5 days earlier) - More uniform stand - Better performance under stress - Improved early vigor Seed Pelleting: Coat seeds with inert material to create uniform round shape Used for small/irregular seeds: lettuce, carrot, onion, petunia Materials: clay, diatomaceous earth, talc + binder Benefits: precision planting, less thinning, singulation Drawback: slightly slower imbibition (coating barrier) Common in: commercial vegetable production, flowers Seed Coating: Thin layer of material applied to seed surface Types: Film coating: thin polymer + colorant (ID + protection) Fungicide coating: thiram, metalaxyl, fludioxonil Insecticide coating: imidacloprid, clothianidin (neonicotinoids) Biological coating: Rhizobium for legumes, mycorrhizae Nutrient coating: zinc, molybdenum for early nutrition Seed Tapes / Mats: Seeds embedded in water-soluble paper at proper spacing Benefits: perfect spacing, no thinning, easy planting Popular for: carrot, radish, lettuce in small gardens DIY: flour paste + toilet paper + seeds Seed Enhancement Comparison: Method Speed↑ Uniform↑ Protect Cost Hydropriming ++ ++ - $ Osmopriming +++ +++ - $$ Biopriming ++ ++ ++ $$ Pelleting - +++ + $$$ Film coating + + ++ $$ Seed tape - +++ - $$ EOF } cmd_schedule() { cat << 'EOF' === Germination Scheduling === Working Backwards from Transplant Date: Last frost date (your area): ___________ Minus transplant age: ___________ Minus germination days: ___________ = Indoor seed start date ___________ Example (Tomato, last frost April 15): Transplant age: 6-8 weeks = 42-56 days Germination: 5-10 days Start seeds: Feb 5-20 (indoors) Transplant: April 15-May 1 (after last frost) Common Indoor Start Times (before last frost): 10-12 weeks: onion, leek, celery, artichoke 8-10 weeks: pepper, eggplant 6-8 weeks: tomato, broccoli, cabbage, cauliflower 4-6 weeks: lettuce, kale, Swiss chard 3-4 weeks: cucumber, squash, melon (if starting indoors) 0 weeks: beans, corn, peas (direct sow only) Hardening Off Protocol: Day 1-2: Outdoors 1-2 hours, shade, no wind Day 3-4: Outdoors 3-4 hours, partial sun Day 5-6: Outdoors 5-6 hours, morning sun Day 7-8: Outdoors all day, full sun, bring in at night Day 9-10: Outdoors day and night (if no frost threat) Day 11+: Transplant Succession Planting: For continuous harvest, start new batch every 2-3 weeks: Lettuce: every 2 weeks, April through September Beans: every 3 weeks, May through July Cilantro: every 2 weeks (bolts quickly in heat) Radish: every 2 weeks, spring and fall Growing Degree Days (GDD): GDD = ((Tmax + Tmin) / 2) - Tbase Corn Tbase = 10°C, needs ~100 GDD to emerge Wheat Tbase = 0°C, needs ~50 GDD to emerge Track cumulative GDD to predict field emergence date Many extension services provide GDD calculators EOF } show_help() { cat << EOF germination v$VERSION — Seed Germination Reference Usage: script.sh <command> Commands: intro Germination phases, biology, requirements conditions Temperature, moisture, light, pH by crop dormancy Dormancy types, stratification, scarification testing ISTA protocols, paper towel test, TZ test crops Germination data tables for common crops problems Troubleshooting poor germination enhancement Priming, pelleting, coating, seed tapes schedule Start date calculations, hardening off, GDD help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; conditions) cmd_conditions ;; dormancy) cmd_dormancy ;; testing) cmd_testing ;; crops) cmd_crops ;; problems) cmd_problems ;; enhancement) cmd_enhancement ;; schedule) cmd_schedule ;; help|--help|-h) show_help ;; version|--version|-v) echo "germination v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
EULA drafting reference — license grant, restrictions, termination, IP ownership, and enforceability. Use when drafting or reviewing End User License Agreeme...
--- name: "eula" version: "1.0.0" description: "EULA drafting reference — license grant, restrictions, termination, IP ownership, and enforceability. Use when drafting or reviewing End User License Agreements for software products." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [eula, license, software, ip, terms, agreement, legal] category: "legal" --- # EULA — End User License Agreement Reference Quick-reference skill for EULA drafting, key clauses, and enforceability considerations. ## When to Use - Drafting an EULA for a software product or SaaS - Reviewing existing EULA for completeness - Understanding license grant vs ownership distinctions - Implementing click-wrap or browse-wrap agreements - Comparing EULA approaches for different software models ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of EULAs — purpose, legal basis, and EULA vs ToS. ### `grant` ```bash scripts/script.sh grant ``` License grant clauses — scope, limitations, and permitted use. ### `restrictions` ```bash scripts/script.sh restrictions ``` Common restrictions — reverse engineering, redistribution, modifications. ### `ip` ```bash scripts/script.sh ip ``` Intellectual property clauses — ownership, user content, trademarks. ### `liability` ```bash scripts/script.sh liability ``` Liability limitations, warranty disclaimers, and indemnification. ### `termination` ```bash scripts/script.sh termination ``` Termination clauses — breach, convenience, effects, and survival. ### `enforcement` ```bash scripts/script.sh enforcement ``` Enforceability — click-wrap, browse-wrap, and unconscionability. ### `checklist` ```bash scripts/script.sh checklist ``` EULA drafting checklist for comprehensive coverage. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `EULA_DIR` | Data directory (default: ~/.eula/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # eula — End User License Agreement Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === EULA — End User License Agreement Overview === A EULA is a legal contract between a software developer/publisher and the end user that governs how the software may be used. What Is a EULA? A license agreement (not a sale) that grants the user a limited right to use the software under specified conditions. The user does not own the software — they receive a license to use it. EULA vs Terms of Service: EULA Terms of Service ───────────────────────────── ────────────────────────── Software license Service usage terms Downloaded/installed software Web-based services (SaaS) Focus: license grant/restrictions Focus: acceptable use/policies One-time or subscription Ongoing service relationship IP ownership central Platform rules central Often includes installation Often includes account terms When Is a EULA Needed? - Desktop or mobile applications - Downloadable software - SDK or API libraries - Firmware or embedded software - Game software - SaaS products (often combined with ToS) - Browser extensions - WordPress plugins / themes Key Legal Principles: License vs Sale: Software is licensed, not sold (per most EULAs) UCC Article 2 (sale of goods) may not apply Copyright law governs (17 U.S.C. § 106) First sale doctrine may be limited Contract Formation: Requires: offer, acceptance, consideration Click-wrap: user clicks "I Agree" → valid contract Shrink-wrap: opening package = acceptance (varies) Browse-wrap: mere use = acceptance (weakest) Enforceability Varies By: Jurisdiction (US vs EU vs other) Consumer vs business user Conspicuousness of terms Reasonableness of restrictions Whether user had meaningful choice EOF } cmd_grant() { cat << 'EOF' === License Grant Clauses === Standard License Grant Elements: 1. Scope of License: - Personal vs commercial use - Single user vs multi-user vs site license - Number of installations/devices - Territory restrictions (geographic) 2. License Types: Perpetual One-time purchase, use forever Subscription Time-limited (monthly/annual renewal) Evaluation/Trial Free limited-time evaluation Freemium Free basic + paid premium features Per-Seat License per named user Concurrent License per simultaneous user Site License Unlimited users at one location Enterprise Organization-wide, negotiated terms 3. Grant Language: "Licensor grants Licensee a [non-exclusive, non-transferable, revocable, limited] license to [install and use / access] the Software on [one device / up to N devices] solely for [personal / internal business] purposes, subject to the terms of this Agreement." Key Modifiers: Non-exclusive Others can also be licensed Non-transferable Cannot give or sell the license Revocable Licensor can terminate Limited Not unlimited rights Worldwide Or specific territories Sublicensable Can the user grant sub-licenses? Open Source vs Proprietary: Open Source Proprietary EULA ───────────────────── ────────────────── Can modify source code No modification Can redistribute No redistribution Must comply with license Must comply with EULA (GPL, MIT, Apache, etc.) Custom restrictions Copyright remains w/ author Copyright w/ company No warranty (typically) No warranty (typically) SaaS License Grant: "We grant you a limited, non-exclusive right to access and use the Service during the Subscription Term for your internal business purposes, subject to the terms herein." Key: "access and use" not "install" EOF } cmd_restrictions() { cat << 'EOF' === Common EULA Restrictions === Reverse Engineering: "You shall not reverse engineer, decompile, disassemble, or otherwise attempt to derive the source code of the Software." Enforceability: - Generally enforceable in US (DMCA supports this) - EU: cannot prohibit decompilation for interoperability (EU Software Directive, Article 6) - May not apply to open-source components Redistribution: "You may not distribute, sublicense, lease, rent, loan, or otherwise transfer the Software or any copy thereof to any third party." Variations: - May allow copies for backup purposes - May allow transfer with entire device sale - Must address both physical and digital distribution Modification: "You may not modify, adapt, translate, or create derivative works based upon the Software." Note: Limits user's ability to customize or extend Exception: API/SDK EULAs often permit integration Copying: "You may make one copy of the Software solely for backup or archival purposes." Issues: - Backup copies are often legally permitted regardless - Digital copies for cloud backup unclear - Installation itself creates a copy Commercial Use Restrictions: "The Software is licensed for personal, non-commercial use only. Any commercial use requires a separate commercial license." Define "commercial use" clearly: - Direct revenue generation using the software - Internal business operations - Academic/research vs commercial Competitive Use: "You may not use the Software to develop a competing product or service." Enforceability varies by jurisdiction Must be reasonable in scope Usage Limitations: - Number of users/seats - Number of API calls - Data volume or storage limits - Feature restrictions (free vs paid tiers) - Geographic restrictions - Industry restrictions (no military/nuclear use) Circumvention: "You shall not circumvent, disable, or interfere with any security, licensing, or access control features." Supported by DMCA Section 1201 (anti-circumvention) EOF } cmd_ip() { cat << 'EOF' === Intellectual Property Clauses === Software Ownership: "The Software is owned by [Company] and is protected by copyright laws and international treaty provisions. All rights not expressly granted herein are reserved." Key principle: - License ≠ ownership transfer - Copyright, patents, trade secrets remain with developer - User receives only the rights explicitly granted - "All rights reserved" for anything not mentioned User-Generated Content: "You retain ownership of any content you create using the Software. By using the Software, you grant [Company] a non-exclusive, worldwide, royalty-free license to [use/ display/process] your content solely for providing the Service." Considerations: - Who owns output generated by AI tools? - License scope (broad vs narrow) - Can company use content for training/improvement? - Data portability rights Feedback & Suggestions: "Any feedback, suggestions, or ideas you provide regarding the Software shall become the exclusive property of [Company], which may use such feedback without restriction or compensation." Alternative (less aggressive): "You grant [Company] a perpetual, irrevocable, royalty-free license to use any feedback you provide to improve the Software." Trademarks: "The name, logo, and all related names, logos, product and service names are trademarks of [Company]. You may not use these marks without prior written permission." Restrictions: - No use in user's marketing without permission - No modification of trademarks - No registration of similar marks Third-Party Components: "The Software may include third-party components subject to separate license terms. Such terms are set forth in the THIRD_PARTY_LICENSES file or documentation." Requirements: - List all open-source components used - Include their respective license texts - Comply with attribution requirements - Ensure license compatibility - GPL components require special attention (copyleft) Trade Secrets: "The Software contains trade secrets and proprietary information of [Company]. You agree to maintain the confidentiality of such information." EOF } cmd_liability() { cat << 'EOF' === Liability & Warranty Clauses === Warranty Disclaimer: "THE SOFTWARE IS PROVIDED 'AS IS' WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT." Must be CONSPICUOUS (caps, bold, or highlighted) Under UCC, must specifically mention "merchantability" Limited Warranty (alternative to full disclaimer): "Licensor warrants that the Software will perform substantially in accordance with the documentation for [90 days / 1 year] from the date of purchase. Licensor's sole obligation under this warranty shall be, at Licensor's option, to repair or replace the Software." Limits: - Time-limited (not indefinite) - Performance standard (not bug-free) - Remedy specified (repair/replace, not unlimited damages) Limitation of Liability: "IN NO EVENT SHALL [COMPANY] BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, INCLUDING BUT NOT LIMITED TO LOSS OF PROFITS, DATA, USE, GOODWILL, OR OTHER INTANGIBLE LOSSES." Damage Cap: "TOTAL LIABILITY SHALL NOT EXCEED THE AMOUNT PAID BY YOU FOR THE SOFTWARE IN THE [12 MONTHS / PERIOD] PRECEDING THE CLAIM." Cannot Disclaim (typically): - Death or personal injury from negligence - Fraud or fraudulent misrepresentation - Gross negligence or willful misconduct - Statutory consumer rights (varies by jurisdiction) Indemnification: "You agree to indemnify and hold harmless [Company] from any claims, damages, losses, or expenses arising from your use of the Software or violation of this Agreement." Direction: - User indemnifies developer (most common in EULA) - Developer indemnifies user (enterprise/B2B agreements) - Mutual indemnification (balanced enterprise deals) IP Indemnity (enterprise): "Licensor shall defend and indemnify Licensee against any third-party claim that the Software infringes any patent or copyright." Data Loss Disclaimer: "Licensor shall not be liable for any loss, corruption, or unauthorized access to your data. You are solely responsible for maintaining backup copies of your data." EOF } cmd_termination() { cat << 'EOF' === Termination Clauses === Termination for Breach: "This Agreement and the license granted hereunder will terminate automatically if you fail to comply with any term or condition of this Agreement." Options: - Automatic termination (immediate upon breach) - Termination with cure period (30 days to fix) - Termination with notice (written notice required) Termination for Convenience: "Either party may terminate this Agreement at any time by providing [30 days] written notice to the other party." For subscriptions: - Non-renewal at end of term - Mid-term cancellation (refund policy?) - Auto-renewal disclosure requirements Effects of Termination: User Must: - Cease all use of the Software - Uninstall/delete all copies - Destroy any documentation - Certify destruction in writing (if requested) Licensor May: - Deactivate license keys - Disable access to online features - Delete user account and data - Provide data export period (grace period) Survival Clauses: "The following sections shall survive termination: [IP Ownership, Warranty Disclaimer, Limitation of Liability, Confidentiality, Governing Law, Dispute Resolution]." Should survive termination: - Intellectual property rights - Confidentiality obligations - Limitation of liability - Indemnification - Dispute resolution - Any accrued payment obligations Subscription-Specific: Auto-Renewal: "Subscriptions automatically renew for successive [monthly/ annual] periods unless cancelled [30 days] before renewal." Refund Policy: - Pro-rata refund for unused time? - No refund for mid-term cancellation? - Free trial conversion rules - Must comply with app store policies (Apple, Google) Data After Termination: "Upon termination, your data will be retained for [30 days] to allow export. After this period, data will be permanently deleted." EOF } cmd_enforcement() { cat << 'EOF' === EULA Enforceability === Formation Methods (strongest to weakest): 1. Signed Agreement (strongest): - Physical or electronic signature (ESIGN Act / eIDAS) - Clear mutual assent - Used for enterprise/B2B licenses 2. Click-Wrap (strong): - User must click "I Agree" or check a box - Full text available before acceptance - Scroll requirement (some jurisdictions) - Generally enforceable (ProCD v. Zeidenberg) 3. Shrink-Wrap (moderate): - Terms inside sealed package - Opening package = acceptance - Enforceability varies by jurisdiction - Less common in digital era 4. Browse-Wrap (weakest): - Terms available via hyperlink - No affirmative action required - Often NOT enforceable (Specht v. Netscape) - Must show "inquiry notice" (user should have seen it) Enforceability Factors: ✓ User had notice of terms ✓ User took affirmative action to accept ✓ Terms were available before purchase/use ✓ Terms are readable and accessible ✓ User is of legal age to contract ✓ Adequate consideration exists ✗ Terms are unconscionable (substantive or procedural) ✗ Terms violate statutory consumer rights ✗ No meaningful choice (adhesion contract issues) Key Court Cases (US): ProCD v. Zeidenberg (1996) Shrink-wrap license enforceable Terms inside box accepted by use Specht v. Netscape (2002) Browse-wrap NOT enforceable Users didn't have to scroll past terms Nguyen v. Barnes & Noble (2014) Browse-wrap link insufficient No "reasonably conspicuous notice" Meyer v. Uber (2017) Small hyperlink in registration flow Not conspicuous enough for arbitration clause EU Consumer Protections: Unfair Contract Terms Directive: - Terms must be in plain language - Unfair terms not binding on consumers - Core terms exempt only if clear/plain - Significant imbalance = unfair Consumer Rights Directive: - 14-day withdrawal right for digital content - Must inform before withdrawal right is waived - Pre-contractual information requirements Best Practices for Enforcement: 1. Use click-wrap (not browse-wrap) 2. Require scrolling before "I Agree" button activates 3. Make terms readable (not 50 pages of legalese) 4. Version and date the EULA 5. Notify users of material changes 6. Re-consent for significant updates 7. Keep records of acceptance (timestamp, IP, version) 8. Separate arbitration clause with explicit consent EOF } cmd_checklist() { cat << 'EOF' === EULA Drafting Checklist === Core Provisions: [ ] License grant (scope, type, duration) [ ] License restrictions clearly stated [ ] Intellectual property ownership affirmed [ ] Warranty disclaimer (conspicuous) [ ] Limitation of liability [ ] Termination provisions [ ] Governing law and jurisdiction User Rights: [ ] Permitted uses clearly described [ ] Number of installations/devices specified [ ] Backup copy rights addressed [ ] Transfer/assignment rights (or restrictions) [ ] Free trial terms (if applicable) [ ] Subscription auto-renewal disclosure Restrictions: [ ] Reverse engineering prohibition [ ] Redistribution prohibition [ ] Modification restrictions [ ] Commercial use restrictions (if applicable) [ ] Competitive use restrictions (if applicable) [ ] Usage limits (API calls, storage, users) Data & Privacy: [ ] Data collection disclosure [ ] Privacy policy reference or inclusion [ ] User content ownership clarified [ ] Data portability/export rights [ ] Data handling on termination [ ] Analytics/telemetry disclosure Third-Party: [ ] Third-party component licenses listed [ ] Open-source attribution included [ ] Third-party service disclaimers [ ] App store terms compliance (Apple, Google) Technical: [ ] System requirements stated [ ] Update/upgrade policy [ ] Support terms (scope, hours, channels) [ ] Service level agreements (if SaaS) [ ] Maintenance windows and downtime policy Legal: [ ] Dispute resolution mechanism (arbitration, courts) [ ] Class action waiver (where enforceable) [ ] Export compliance statement [ ] Government use restrictions [ ] Severability clause [ ] Entire agreement clause [ ] Amendment/modification process Presentation: [ ] Plain language (readable by non-lawyers) [ ] Effective date clearly shown [ ] Version number for tracking [ ] Click-wrap acceptance mechanism [ ] Conspicuous warranty/liability sections [ ] Table of contents for long agreements [ ] Available in user's language (if international) [ ] Acceptance records retained (timestamp, version, IP) EOF } show_help() { cat << EOF eula v$VERSION — End User License Agreement Reference Usage: script.sh <command> Commands: intro EULA overview — purpose, legal basis, EULA vs ToS grant License grant clauses — scope, types, language restrictions Common restrictions — reverse engineering, redistribution ip Intellectual property — ownership, user content, trademarks liability Liability limits, warranty disclaimers, indemnification termination Termination — breach, convenience, effects, survival enforcement Enforceability — click-wrap, browse-wrap, court cases checklist EULA drafting checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; grant) cmd_grant ;; restrictions) cmd_restrictions ;; ip) cmd_ip ;; liability) cmd_liability ;; termination) cmd_termination ;; enforcement) cmd_enforcement ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "eula v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Rule engine reference — decision tables, Rete algorithm, forward/backward chaining, and business rule management. Use when evaluating business rules, buildin...
--- name: "engine" version: "1.0.0" description: "Rule engine reference — decision tables, Rete algorithm, forward/backward chaining, and business rule management. Use when evaluating business rules, building decision trees, or implementing policy engines." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [engine, rules, decision-table, rete, workflow, policy, devtools] category: "devtools" --- # Engine — Rule Engine & Decision Logic Reference Quick-reference skill for rule engines, decision tables, and business rule patterns. ## When to Use - Implementing business rules that change frequently - Building decision trees or scoring systems - Choosing between rule engine approaches - Designing policy engines for access control or pricing - Separating business logic from application code ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of rule engines — types, benefits, when to use. ### `patterns` ```bash scripts/script.sh patterns ``` Rule engine patterns — forward chaining, backward chaining, Rete. ### `tables` ```bash scripts/script.sh tables ``` Decision tables — structure, completeness, and implementation. ### `dsl` ```bash scripts/script.sh dsl ``` Domain-specific languages for rules — syntax approaches and examples. ### `tools` ```bash scripts/script.sh tools ``` Rule engine tools — Drools, OPA, json-rules-engine, and more. ### `scoring` ```bash scripts/script.sh scoring ``` Scoring and ranking engines — weighted rules, multi-criteria decisions. ### `testing` ```bash scripts/script.sh testing ``` Testing rule engines — coverage, conflict detection, regression. ### `checklist` ```bash scripts/script.sh checklist ``` Rule engine implementation checklist. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `ENGINE_DIR` | Data directory (default: ~/.engine/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # engine — Rule Engine & Decision Logic Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Rule Engine Overview === A rule engine evaluates business rules against data to produce decisions, separating business logic from application code. What Is a Rule Engine? A software system that executes business rules in a runtime production environment. Rules are expressed as condition-action pairs: "IF conditions THEN actions." Why Use a Rule Engine? 1. Business rules change frequently (no code deployment needed) 2. Non-developers need to manage rules (business analysts) 3. Complex interdependent rules (hundreds of conditions) 4. Audit trail requirements (which rules fired, why) 5. Consistency across systems (single rule repository) 6. Regulatory compliance (rules map to regulations) Types of Rule Engines: Production Rule Systems: IF-THEN rules with pattern matching Forward chaining (data-driven) Examples: Drools, CLIPS, Jess Decision Table Engines: Tabular rule representation Easy for business users to understand Examples: DMN, Excel-based rules Complex Event Processing (CEP): Rules over streams of events Temporal patterns and windows Examples: Esper, Siddhi, Flink CEP Policy Engines: Access control and authorization rules ABAC (Attribute-Based Access Control) Examples: OPA, Casbin, Cedar Workflow/Orchestration Engines: Long-running business processes State machines with rule-based transitions Examples: Camunda, Temporal, Step Functions When NOT to Use a Rule Engine: ✗ Simple if/else logic (< 10 rules) ✗ Rules that never change ✗ Performance-critical hot paths (overhead) ✗ When rules have no business ownership ✗ When a lookup table or config file suffices EOF } cmd_patterns() { cat << 'EOF' === Rule Engine Patterns === Forward Chaining (Data-Driven): Process: 1. Assert facts (data) into working memory 2. Match rules against facts (pattern matching) 3. Select rules to fire (conflict resolution) 4. Execute rule actions (may add/modify facts) 5. Repeat until no more rules can fire Example: Fact: customer.age = 25, customer.income = 80000 Rule 1: IF age < 30 AND income > 50000 THEN tier = "Gold" Rule 2: IF tier = "Gold" THEN discount = 15% → Rule 1 fires, adds tier=Gold → Rule 2 fires, sets discount=15% Use when: Starting from data, discovering conclusions Backward Chaining (Goal-Driven): Process: 1. Start with a goal (what to prove) 2. Find rules that conclude the goal 3. Check if rule conditions are satisfied 4. If not, set sub-goals for unproven conditions 5. Recursively prove sub-goals Example: Goal: Can customer get a loan? Rule: IF credit_score > 700 AND debt_ratio < 0.4 THEN approve Sub-goal 1: What is credit_score? → Look up Sub-goal 2: What is debt_ratio? → Calculate Use when: Need to prove/disprove a specific conclusion Rete Algorithm: Invented by Charles Forgy (1979) Optimization for forward chaining with many rules: - Build a network of nodes from rule conditions - Alpha nodes test individual conditions - Beta nodes test combinations (joins) - Token passing through the network - Only re-evaluate when facts change (incremental) Performance: Naive: O(rules × facts^conditions) per cycle Rete: O(changes × affected_rules) per cycle Massive improvement for large rule sets with few changes Used by: Drools, CLIPS, Jess, OpenRules Conflict Resolution Strategies: When multiple rules match, which fires first? Priority/Salience Explicit rule priority number Specificity More specific rules fire first Recency Rules matching newer facts first Refraction Each rule fires only once per fact set Random Non-deterministic selection Rule Chaining: Rules can trigger other rules by modifying facts Advantages: modular, composable logic Risks: infinite loops, unintended cascades Mitigation: loop detection, max iterations, rule ordering EOF } cmd_tables() { cat << 'EOF' === Decision Tables === A decision table maps conditions to actions in a tabular format. Easy for business users to read, review, and maintain. Structure: ┌───────────┬──────────┬──────────┬───────────────┐ │ Condition1│Condition2│Condition3│ Action │ ├───────────┼──────────┼──────────┼───────────────┤ │ Yes │ High │ ≤ 30 │ Approve │ │ Yes │ High │ > 30 │ Review │ │ Yes │ Low │ - │ Decline │ │ No │ - │ - │ Decline │ └───────────┴──────────┴──────────┴───────────────┘ "-" means "any value" (don't care) Decision Table Types: Limited Entry: Conditions have binary values (Yes/No, True/False) Simplest form, easy to verify completeness Extended Entry: Conditions have ranges or enumerated values More expressive, common in practice Mixed Entry: Combination of limited and extended entries Hit Policies (DMN standard): U Unique Exactly one rule matches (error if overlap) A Any Multiple rules may match, all give same result F First First matching rule wins (order matters) P Priority Highest priority matching rule wins C Collect Collect results from all matching rules R Rule Order All matching rules, in table order Completeness Analysis: Total combinations = product of all condition values Example: 3 conditions with 2, 3, 4 values = 2×3×4 = 24 rows needed Check: Are all 24 combinations covered? Missing combinations → undefined behavior (bug!) DMN (Decision Model and Notation): OMG standard for decision modeling Visual notation for decision requirements Standardized decision table format FEEL expression language for conditions Tools: Camunda, Red Hat Decision Manager Implementation Approaches: 1. Spreadsheet-based (Excel/Google Sheets → parse at runtime) 2. Database-driven (rules in SQL tables) 3. JSON/YAML configuration files 4. DMN files (XML standard) 5. Code-generated from decision tables Example JSON Decision Table: { "rules": [ {"conditions": {"age": "<25", "score": ">700"}, "action": "approve"}, {"conditions": {"age": "<25", "score": "<=700"}, "action": "review"}, {"conditions": {"age": ">=25", "score": ">600"}, "action": "approve"}, {"conditions": {"age": ">=25", "score": "<=600"}, "action": "decline"} ] } EOF } cmd_dsl() { cat << 'EOF' === Domain-Specific Languages for Rules === A rule DSL makes business rules readable by non-programmers. Natural Language Style: WHEN customer.age >= 18 AND customer.credit_score > 650 AND order.total < customer.credit_limit THEN APPROVE order SET customer.last_order_date = TODAY JSON-Based Rules: { "conditions": { "all": [ {"fact": "age", "operator": "greaterThanInclusive", "value": 18}, {"fact": "credit_score", "operator": "greaterThan", "value": 650} ] }, "event": { "type": "approve", "params": {"message": "Order approved"} } } YAML-Based Rules: rules: - name: premium_discount when: all: - field: customer.tier equals: premium - field: order.total greaterThan: 100 then: - set: order.discount value: 0.20 Rego (Open Policy Agent): package authz default allow = false allow { input.user.role == "admin" } allow { input.user.role == "editor" input.action == "read" } allow { input.user.role == "editor" input.action == "write" input.resource.owner == input.user.id } Drools DRL: rule "High Value Customer Discount" when $customer : Customer(totalPurchases > 10000) $order : Order(customer == $customer, total > 500) then $order.setDiscount(0.15); update($order); end Expression Languages: FEEL (DMN): if age >= 18 then "adult" else "minor" SpEL (Spring): #customer.age >= 18 and #order.total > 100 JEXL: customer.age >= 18 && order.total > 100 CEL (Google): customer.age >= 18 && order.total > 100 DSL Design Principles: 1. Readable by domain experts (not just developers) 2. Declarative (what, not how) 3. Composable (combine simple rules into complex) 4. Testable (each rule independently verifiable) 5. Versionable (track changes over time) 6. Validated at parse time (catch errors early) EOF } cmd_tools() { cat << 'EOF' === Rule Engine Tools === Enterprise / JVM: Drools (Red Hat): Language: Java, DRL, DMN Algorithm: Rete / Phreak Features: Forward/backward chaining, DMN, CEP Use: Complex enterprise rules, financial services License: Apache 2.0 Easy Rules: Language: Java Lightweight: Annotation or YAML-based rules Good for: Simple rule evaluation, microservices License: MIT JavaScript / Node.js: json-rules-engine: JSON-based rule definition Supports rule priorities, conditions, events npm: json-rules-engine Good for: REST APIs, form validation, pricing Nools: Rete-based engine for Node.js Drools-like DSL Forward chaining Good for: Complex matching in Node RulesJS: Lightweight, JSON rules Good for: Client-side rule evaluation Python: Durable Rules: Rete-based, supports Python/Node/Ruby Stateful sessions, forward chaining pip: durable-rules Business Rules Engine: Simple condition-action rules pip: business-rules Good for: Basic business logic PyKnow (experta): CLIPS-inspired expert system Forward chaining with Rete pip: experta Policy Engines: Open Policy Agent (OPA): Language: Rego Use: Authorization, Kubernetes admission, API policies Decoupled from application (sidecar or library) CNCF graduated project Casbin: Multi-language (Go, Java, Node, Python, Rust) Models: ACL, RBAC, ABAC, RESTful Policy storage: file, database, API Cedar (AWS): Language: Cedar policy language Use: Fine-grained authorization Formally verified Used by: Amazon Verified Permissions Cerbos: Language: YAML policies Deployment: Container/sidecar Use: Application-level authorization Spreadsheet-Based: GoRules: Visual rule builder, DMN tables, JSON rules Corticon: No-code rule modeling, enterprise-grade BRMS: Business Rule Management Systems (IBM, Oracle) EOF } cmd_scoring() { cat << 'EOF' === Scoring & Ranking Engines === Weighted Scoring Model: Score = Σ (weight_i × value_i) for each criterion Example — Lead Scoring: Criterion Weight Value Range Company size 0.25 1-10 Budget 0.30 1-10 Decision authority 0.20 1-10 Timeline 0.15 1-10 Engagement 0.10 1-10 Score = 0.25×8 + 0.30×7 + 0.20×9 + 0.15×6 + 0.10×5 = 2.0 + 2.1 + 1.8 + 0.9 + 0.5 = 7.3 / 10 Point-Based Systems: Rule Points ───────────────────────────────────────── Visited pricing page +10 Downloaded whitepaper +15 Attended webinar +20 Opened email +3 Clicked email link +5 Unsubscribed from list -25 No activity in 30 days -10 Job title contains "VP/Director" +15 Company revenue > $10M +20 Threshold Actions: 0-30 Cold lead → nurture campaign 31-60 Warm lead → targeted content 61-80 Hot lead → SDR outreach 81+ Sales-ready → assign to AE Risk Scoring: Credit Risk: Payment history 35% Credit utilization 30% Credit age 15% Credit mix 10% New inquiries 10% Fraud Risk: IP geolocation mismatch +30 First-time buyer +10 Order value > 3× average +20 Multiple failed payment attempts +25 Shipping ≠ billing address +15 High-risk product category +10 Velocity: > 3 orders in 1 hour +35 Multi-Criteria Decision Analysis (MCDA): Methods: TOPSIS Closest to ideal solution AHP Analytic Hierarchy Process (pairwise comparison) ELECTRE Outranking methods PROMETHEE Preference ranking AHP Process: 1. Define criteria hierarchy 2. Pairwise comparison of criteria (1-9 scale) 3. Calculate priority weights 4. Check consistency ratio (< 0.1) 5. Score alternatives against criteria 6. Calculate weighted scores 7. Rank alternatives Normalization Methods: Min-Max: (value - min) / (max - min) → [0, 1] Z-Score: (value - mean) / std_dev → [-∞, +∞] Percentile: rank / count → [0, 1] Log scale: log(value) / log(max) → [0, 1] EOF } cmd_testing() { cat << 'EOF' === Testing Rule Engines === Rule Testing Challenges: - Combinatorial explosion of condition combinations - Rule interactions and cascading effects - Order-dependent behavior - Temporal rules (time-based conditions) - Performance under load with many rules Testing Approaches: 1. Unit Testing (per rule): - Test each rule in isolation - Provide minimal facts to trigger the rule - Verify expected action fires - Verify rule does NOT fire for non-matching facts 2. Integration Testing (rule interactions): - Test groups of related rules together - Verify rule chaining produces correct results - Check for unintended rule interactions - Test conflict resolution behavior 3. Boundary Testing: - Test at condition boundaries (age = 17, 18, 19) - Test null/missing values - Test extreme values - Test type mismatches 4. Coverage Analysis: - Which rules were triggered during tests? - Which condition branches were exercised? - Are there unreachable rules (dead rules)? - Decision table completeness check Conflict Detection: Overlapping Rules: Rule A: IF age > 18 AND income > 50k THEN approve Rule B: IF age > 25 AND income > 30k THEN approve Overlap: age=30, income=60k → both match Contradicting Rules: Rule A: IF score > 700 THEN approve Rule B: IF debt_ratio > 0.5 THEN decline Contradiction: score=750, debt_ratio=0.6 → approve or decline? Subsumption: Rule A: IF color = "red" THEN stop Rule B: IF color = "red" AND size = "large" THEN stop Rule B is subsumed by Rule A (never adds value) Shadow Rules: Higher-priority rule always fires before a lower one Lower rule effectively never executes Testing Patterns: Given-When-Then: Given: customer.age=25, customer.tier="gold" When: evaluate discount rules Then: discount should be 15% Truth Table Testing: Enumerate all condition combinations Verify each produces expected outcome Identify gaps in coverage Regression Suite: Capture real decisions as test cases Re-run after rule changes Alert on any behavior changes Performance Testing: Load test with realistic fact volumes Measure: rules/second, latency p99 Test rule set scaling (100 vs 10,000 rules) Memory profiling (Rete network can be large) EOF } cmd_checklist() { cat << 'EOF' === Rule Engine Implementation Checklist === Design: [ ] Rules clearly separate from application code [ ] Rule language chosen (DSL, JSON, decision tables) [ ] Conflict resolution strategy defined [ ] Rule versioning and change management planned [ ] Performance requirements defined (throughput, latency) [ ] Rule authoring workflow designed (who can create/edit) Rule Authoring: [ ] Rules reviewed by domain expert [ ] Decision table completeness verified [ ] No contradicting rules (or contradiction resolved) [ ] No shadowed/unreachable rules [ ] Default/fallback case handled [ ] Rule priorities/salience assigned where needed Testing: [ ] Unit tests for each rule [ ] Integration tests for rule interactions [ ] Boundary value tests [ ] Negative tests (rule should NOT fire) [ ] Performance benchmarks established [ ] Regression test suite from production decisions Deployment: [ ] Rules can be updated without code deployment [ ] Rule versioning with rollback capability [ ] A/B testing capability for rule changes [ ] Gradual rollout support (canary deployment) [ ] Monitoring for rule engine health Observability: [ ] Logging: which rules fired and why [ ] Metrics: rule execution count, latency, error rate [ ] Audit trail: who changed which rules when [ ] Alerting: rule errors, unexpected patterns [ ] Dashboard: rule coverage, hit rates Governance: [ ] Rule ownership assigned (who maintains each rule set) [ ] Change approval process defined [ ] Documentation for each rule's business purpose [ ] Regular review schedule (quarterly rule audit) [ ] Retirement process for obsolete rules [ ] Compliance mapping (which rules implement which regulations) EOF } show_help() { cat << EOF engine v$VERSION — Rule Engine & Decision Logic Reference Usage: script.sh <command> Commands: intro Rule engine overview — types, benefits, when to use patterns Forward/backward chaining, Rete algorithm tables Decision tables — structure, hit policies, DMN dsl Domain-specific languages for rule definition tools Rule engine tools — Drools, OPA, json-rules-engine scoring Scoring engines — weighted rules, MCDA, risk scoring testing Testing rules — coverage, conflicts, regression checklist Rule engine implementation checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; patterns) cmd_patterns ;; tables) cmd_tables ;; dsl) cmd_dsl ;; tools) cmd_tools ;; scoring) cmd_scoring ;; testing) cmd_testing ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "engine v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Deduplication reference — exact matching, fuzzy matching, hash-based dedup, bloom filters, and data quality. Use when removing duplicate records, files, or d...
--- name: "dedupe" version: "1.0.0" description: "Deduplication reference — exact matching, fuzzy matching, hash-based dedup, bloom filters, and data quality. Use when removing duplicate records, files, or data entries." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [dedupe, deduplication, data-quality, hash, fuzzy-match, etl, atomic] category: "atomic" --- # Dedupe — Data Deduplication Reference Quick-reference skill for deduplication strategies, algorithms, and data quality patterns. ## When to Use - Removing duplicate rows from datasets or databases - Deduplicating files in storage systems - Implementing fuzzy matching for near-duplicate detection - Choosing between exact and probabilistic dedup methods - Building ETL pipelines with deduplication stages ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of deduplication — types, strategies, and tradeoffs. ### `exact` ```bash scripts/script.sh exact ``` Exact deduplication — hash-based, key-based, and sorting approaches. ### `fuzzy` ```bash scripts/script.sh fuzzy ``` Fuzzy deduplication — similarity measures, blocking, and record linkage. ### `files` ```bash scripts/script.sh files ``` File-level deduplication — fdupes, jdupes, rdfind, and storage dedup. ### `algorithms` ```bash scripts/script.sh algorithms ``` Dedup algorithms — bloom filters, HyperLogLog, MinHash, SimHash. ### `sql` ```bash scripts/script.sh sql ``` SQL deduplication patterns — ROW_NUMBER, DISTINCT, GROUP BY strategies. ### `cli` ```bash scripts/script.sh cli ``` Command-line dedup tools — sort, uniq, awk, and stream processing. ### `checklist` ```bash scripts/script.sh checklist ``` Deduplication quality checklist and validation steps. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `DEDUPE_DIR` | Data directory (default: ~/.dedupe/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # dedupe — Data Deduplication Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Deduplication Overview === Deduplication (dedup) is the process of identifying and removing duplicate copies of data. Critical for data quality, storage efficiency, and accurate analytics. Types of Duplication: Exact Duplicates Identical records in every field Near-Duplicates Records that refer to same entity but differ (typos, formatting, missing fields) Semantic Duplicates Different representations of same concept ("USA" vs "United States" vs "US") Deduplication Levels: 1. File-level Identical files on disk (fdupes, rdfind) 2. Block-level Identical data blocks within files (ZFS, Btrfs) 3. Record-level Duplicate rows in databases/datasets 4. Field-level Duplicate values within a column 5. Entity-level Records referring to same real-world entity Strategies: Hash-based Compute hash, group by hash value Sort-based Sort data, compare adjacent records Key-based Define unique key, detect conflicts Probabilistic Bloom filters, sampling (scale trade-off) ML-based Train model to identify duplicates Common Causes of Duplicates: - Multiple data entry points (web form + phone + import) - System migrations without dedup - Failed idempotency (retry creates second record) - Merge/acquisition combining overlapping databases - ETL bugs (re-processing same batch) - No unique constraint at database level Impact of Duplicates: - Inflated counts and incorrect analytics - Wasted storage and compute - Multiple mailings to same customer - Incorrect inventory counts - Failed joins (which duplicate to match?) - Regulatory risk (GDPR: can't delete all copies) EOF } cmd_exact() { cat << 'EOF' === Exact Deduplication === Hash-Based Dedup: 1. Compute hash of each record (or key fields) 2. Group records by hash 3. Within each group, keep one (first, latest, or best) Common Hash Functions: MD5 Fast, 128-bit, sufficient for dedup (not security) SHA-1 160-bit, slightly slower SHA-256 256-bit, overkill for dedup but available everywhere xxHash Extremely fast, good for large datasets CRC32 Fast but higher collision risk Python Example: import hashlib def record_hash(row): key = f"{row['email'].lower().strip()}" return hashlib.md5(key.encode()).hexdigest() Key-Based Dedup: Define a natural key (or composite key) that uniquely identifies an entity: Customer: email OR (first_name + last_name + phone) Product: SKU or UPC Order: order_number + line_number Event: (event_type, timestamp, source_id) Normalize keys before comparison: - Lowercase all strings - Strip whitespace - Remove punctuation - Standardize formats (phone: +1-555-123-4567) Sort-Based Dedup: 1. Sort dataset by dedup key 2. Scan linearly, compare each record to previous 3. O(n log n) for sort + O(n) for scan 4. Memory efficient (only hold 2 records at a time) Works well for: - Very large files that don't fit in memory - Streaming data (sort window + dedup) - External sort with merge Keep Strategy (which duplicate to keep): First occurrence Keep the earliest by insertion order Last occurrence Keep the most recent version Most complete Keep record with fewest null fields Highest quality Score records, keep highest score Merge/golden record Combine best fields from all duplicates EOF } cmd_fuzzy() { cat << 'EOF' === Fuzzy Deduplication === String Similarity Measures: Levenshtein Distance (Edit Distance): Minimum edits (insert, delete, substitute) to transform A → B "kitten" → "sitting" = 3 edits Normalized: 1 - (distance / max(len(A), len(B))) Jaro-Winkler Similarity: Best for short strings (names, cities) Range: 0.0 (no match) to 1.0 (exact) Threshold: > 0.90 usually indicates match Gives extra weight to matching prefixes Soundex / Metaphone: Phonetic encoding (sounds-alike matching) "Smith" and "Smythe" → same code Good for names, poor for other data n-gram / Jaccard Similarity: Break strings into n-character chunks Similarity = |intersection| / |union| "hello" (bigrams): {he, el, ll, lo} Robust to character transpositions TF-IDF + Cosine Similarity: For longer text fields (descriptions, addresses) Weight rare terms higher Good for detecting paraphrased content Blocking (Scalability): Problem: Comparing every pair = O(n²) — infeasible for large data Solution: Only compare records within the same "block": Block by first 3 chars of last name + ZIP code Block by Soundex code Block by year of birth + gender Block by domain of email address Reduces O(n²) to O(n × avg_block_size) Record Linkage Pipeline: 1. Standardize Clean, normalize, parse fields 2. Block Group candidates to reduce comparisons 3. Compare Calculate field-level similarity scores 4. Classify Match / Non-match / Possible (thresholds) 5. Cluster Group all records belonging to same entity 6. Merge Create golden record from cluster Tools: dedupe (Python) ML-based, active learning recordlinkage (Python) Statistical record linkage splink (Python/Spark) Probabilistic linking at scale fuzzywuzzy (Python) Simple fuzzy string matching OpenRefine GUI-based clustering and dedup Duke (Java) Configurable record linkage engine EOF } cmd_files() { cat << 'EOF' === File-Level Deduplication === Finding Duplicate Files: fdupes (most popular): fdupes -r /path/to/dir # Find dupes recursively fdupes -rd /path/to/dir # Find and delete (interactive) fdupes -rdN /path/to/dir # Auto-delete, keep first fdupes -rS /path/to/dir # Show sizes # Process: size comparison → partial hash → full hash jdupes (faster fork of fdupes): jdupes -rS /path/to/dir # Find with sizes jdupes -rdN /path/to/dir # Auto-delete jdupes -rL /path/to/dir # Hard-link duplicates (save space) jdupes -rB /path/to/dir # Use btrfs reflinks rdfind (fastest): rdfind /path/to/dir # Find duplicates rdfind -deleteduplicates true # Delete duplicates rdfind -makesymlinks true # Replace with symlinks rdfind -makehardlinks true # Replace with hardlinks Using standard tools: # Find by MD5 hash find . -type f -exec md5sum {} + | sort | uniq -Dw 32 # Find by size first, then hash (faster) find . -type f -printf '%s %p\n' | sort -n | \ uniq -Dw 15 | awk '{print $2}' | xargs md5sum | \ sort | uniq -Dw 32 Storage-Level Dedup: ZFS Deduplication: zfs set dedup=on pool/dataset # Enable block-level dedup zpool get dedup # Check status zdb -DD pool # Dedup statistics # Warning: requires ~5GB RAM per TB of data for DDT Btrfs Deduplication: duperemove -rd /path # Offline dedup (reflinks) bees /path # Online dedup daemon Backup Tool Dedup: borgbackup Content-defined chunking + dedup restic CDC with rabin fingerprinting duplicacy Variable-size chunk dedup zbackup Global dedup across backups Inline vs Post-Process: Inline Dedup during write (ZFS) — CPU overhead Post-process Dedup after write (duperemove) — batch friendly CDC Content-Defined Chunking — handles shifted data EOF } cmd_algorithms() { cat << 'EOF' === Dedup Algorithms & Data Structures === Bloom Filter: Purpose: Probabilistic set membership test Properties: - "Definitely not in set" or "Probably in set" - No false negatives, tunable false positive rate - Very memory efficient (10 bits per element for 1% FP) Use: Pre-filter before expensive exact check Size: m = -(n × ln(p)) / (ln2)² n = expected elements, p = false positive rate 1M elements, 1% FP → ~1.2 MB Counting Bloom Filter: Like Bloom filter but supports deletion Uses counters instead of single bits Typically 4 bits per counter (16x larger than basic) HyperLogLog: Purpose: Estimate number of distinct elements (cardinality) Accuracy: ~2% error with 1.5 KB memory Use: "How many unique records?" before full dedup Not for: identifying WHICH records are duplicates MinHash (MinWise Hashing): Purpose: Estimate Jaccard similarity between sets Process: 1. Apply k hash functions to each set 2. Keep minimum hash value for each function 3. Similarity ≈ fraction of matching minimums Use: Near-duplicate document detection Tool: datasketch Python library SimHash: Purpose: Locality-sensitive hash for near-duplicate detection Property: Similar items → similar hash values Hamming distance between hashes ≈ dissimilarity Use: Web page dedup (Google uses SimHash) Efficient: compare 64-bit hashes instead of full documents Content-Defined Chunking (CDC): Purpose: Split data into variable-size chunks for dedup Process: 1. Slide window over data 2. Hash window contents (Rabin fingerprint) 3. Split when hash matches pattern (e.g., low 13 bits = 0) 4. Average chunk size = 2^13 = 8 KB Advantage: Insertion/deletion only affects nearby chunks Use: Backup systems (borg, restic, duplicacy) Sorted Neighborhood Method: Purpose: Efficient pairwise comparison for record dedup Process: 1. Compute sorting key for each record 2. Sort records by key 3. Slide window of size w over sorted records 4. Compare all pairs within window Complexity: O(n × w) instead of O(n²) Window size: typically 3-20 EOF } cmd_sql() { cat << 'EOF' === SQL Deduplication Patterns === Find Duplicates: -- By single column SELECT email, COUNT(*) as cnt FROM users GROUP BY email HAVING COUNT(*) > 1; -- By multiple columns SELECT first_name, last_name, phone, COUNT(*) FROM customers GROUP BY first_name, last_name, phone HAVING COUNT(*) > 1; Keep One, Delete Rest (ROW_NUMBER): -- Mark duplicates, keep the row with lowest id WITH ranked AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY email ORDER BY id ASC ) AS rn FROM users ) DELETE FROM users WHERE id IN (SELECT id FROM ranked WHERE rn > 1); -- Keep most recently updated WITH ranked AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY email ORDER BY updated_at DESC ) AS rn FROM users ) DELETE FROM users WHERE id IN (SELECT id FROM ranked WHERE rn > 1); Select Deduplicated View: -- Without modifying data SELECT DISTINCT ON (email) * FROM users ORDER BY email, created_at DESC; -- PostgreSQL -- Standard SQL equivalent SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC) AS rn FROM users ) t WHERE rn = 1; Merge Duplicates (Golden Record): -- Combine best fields from duplicates SELECT email, MAX(first_name) AS first_name, -- non-null preference MAX(last_name) AS last_name, MAX(phone) AS phone, MIN(created_at) AS first_seen, MAX(updated_at) AS last_seen, SUM(order_count) AS total_orders FROM customers GROUP BY email; Prevent Future Duplicates: -- Add unique constraint ALTER TABLE users ADD CONSTRAINT uq_email UNIQUE (email); -- Upsert (PostgreSQL) INSERT INTO users (email, name) VALUES ('[email protected]', 'Alice') ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name; -- Upsert (MySQL) INSERT INTO users (email, name) VALUES ('[email protected]', 'Alice') ON DUPLICATE KEY UPDATE name = VALUES(name); EOF } cmd_cli() { cat << 'EOF' === Command-Line Dedup Tools === sort + uniq (classic): # Remove exact duplicate lines sort file.txt | uniq > deduped.txt # Show duplicate lines only sort file.txt | uniq -d # Count occurrences sort file.txt | uniq -c | sort -rn # Case-insensitive dedup sort -f file.txt | uniq -i > deduped.txt awk (preserve order): # Dedup preserving original order (first occurrence) awk '!seen[$0]++' file.txt > deduped.txt # Dedup by specific field (field 2) awk -F',' '!seen[$2]++' data.csv > deduped.csv # Dedup by multiple fields awk -F',' '!seen[$1","$3]++' data.csv > deduped.csv # Dedup case-insensitive awk '!seen[tolower($0)]++' file.txt > deduped.txt sed (adjacent duplicates only): # Remove consecutive duplicate lines (like uniq without sort) sed '$!N; /^\(.*\)\n\1$/!P; D' file.txt Python one-liners: # Dedup preserving order python3 -c " import sys; seen=set() [sys.stdout.write(l) for l in sys.stdin if l not in seen and not seen.add(l)] " < input.txt > output.txt # Dedup CSV by column python3 -c " import csv, sys; seen=set(); r=csv.reader(sys.stdin); w=csv.writer(sys.stdout) [w.writerow(row) for row in r if row[1] not in seen and not seen.add(row[1])] " < input.csv > output.csv csvkit: # Dedup CSV csvsort -c email input.csv | csvcut -c 1-5 | uniq > deduped.csv Miller (mlr): # Dedup CSV by field mlr --csv uniq -f email input.csv > deduped.csv # Dedup keeping last occurrence mlr --csv group-by email then tail -n 1 input.csv > deduped.csv datamash: # Count duplicates by column 1 datamash -s -g 1 count 1 < input.tsv # -s = sort, -g 1 = group by column 1 Stream Dedup (large files): # Using sort with temporary files (handles files > RAM) sort -T /tmp -S 2G file.txt | uniq > deduped.txt # Using LC_ALL=C for faster sorting LC_ALL=C sort file.txt | uniq > deduped.txt EOF } cmd_checklist() { cat << 'EOF' === Deduplication Quality Checklist === Planning: [ ] Define what constitutes a "duplicate" (exact vs fuzzy) [ ] Identify dedup key fields [ ] Determine "keep" strategy (first, latest, most complete, merge) [ ] Estimate duplicate rate (sample 1000 records) [ ] Back up data before deduplication [ ] Test on subset before running on full dataset Key Normalization: [ ] Lowercase all string keys [ ] Trim whitespace (leading, trailing, multiple internal spaces) [ ] Remove punctuation where appropriate [ ] Standardize formats (dates, phones, addresses) [ ] Handle encoding issues (UTF-8, accents, special chars) [ ] Map synonyms if needed ("St." → "Street") Execution: [ ] Run dedup on staging/copy first [ ] Log all duplicates found (before deletion) [ ] Track which record was kept and why [ ] Handle foreign key references (update related tables) [ ] Process in batches for large datasets Validation: [ ] Record count: before - duplicates_removed = after [ ] No false positives (legitimate distinct records deleted) [ ] Spot-check merged/golden records for quality [ ] Run dedup again on result (should find zero duplicates) [ ] Verify downstream reports/dashboards still accurate [ ] Check referential integrity (no orphaned records) Prevention: [ ] Add unique constraints to database [ ] Implement upsert logic in data pipelines [ ] Normalize data at ingestion (not after) [ ] Set up duplicate detection alerts [ ] Schedule periodic dedup runs [ ] Document dedup rules for team knowledge Monitoring: [ ] Track duplicate rate over time (should decrease) [ ] Alert on sudden spikes in duplicate creation [ ] Review dedup rules quarterly [ ] Monitor data source quality EOF } show_help() { cat << EOF dedupe v$VERSION — Data Deduplication Reference Usage: script.sh <command> Commands: intro Dedup overview — types, strategies, causes exact Exact dedup — hash-based, key-based, sort-based fuzzy Fuzzy dedup — similarity measures, blocking, linkage files File-level dedup — fdupes, jdupes, storage dedup algorithms Algorithms — bloom filters, MinHash, SimHash, CDC sql SQL dedup patterns — ROW_NUMBER, upsert, golden record cli Command-line dedup — sort, uniq, awk, streaming checklist Dedup quality checklist and validation help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; exact) cmd_exact ;; fuzzy) cmd_fuzzy ;; files) cmd_files ;; algorithms) cmd_algorithms ;; sql) cmd_sql ;; cli) cmd_cli ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "dedupe v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Composting reference — methods, C:N ratio, thermophilic stages, vermicomposting, troubleshooting. Use when building compost systems, optimizing decomposition...
--- name: "compost" version: "1.0.0" description: "Composting reference — methods, C:N ratio, thermophilic stages, vermicomposting, troubleshooting. Use when building compost systems, optimizing decomposition, or managing organic waste." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [compost, agriculture, soil, organic, decomposition, carbon-nitrogen, vermiculture] category: "agriculture" --- # Compost — Composting Science & Practice Reference Quick-reference skill for composting methods, the science of decomposition, and practical troubleshooting. ## When to Use - Setting up a composting system (home, farm, or municipal) - Optimizing carbon-to-nitrogen ratios for faster decomposition - Troubleshooting compost problems (smell, slow breakdown, pests) - Choosing between composting methods (hot, cold, vermi, bokashi) - Understanding the microbiology and thermophilic stages ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of composting — what it is, why it matters, and the basic science. ### `ratio` ```bash scripts/script.sh ratio ``` Carbon-to-nitrogen ratio — the key to successful composting. ### `methods` ```bash scripts/script.sh methods ``` Composting methods — hot, cold, vermicomposting, bokashi, in-vessel. ### `stages` ```bash scripts/script.sh stages ``` Decomposition stages — mesophilic, thermophilic, cooling, curing. ### `materials` ```bash scripts/script.sh materials ``` What to compost — greens, browns, and what to avoid. ### `troubleshoot` ```bash scripts/script.sh troubleshoot ``` Troubleshooting — smells, pests, slow decomposition, wet/dry problems. ### `quality` ```bash scripts/script.sh quality ``` Compost quality assessment — maturity tests, nutrient content, application rates. ### `systems` ```bash scripts/script.sh systems ``` Composting systems — bins, tumblers, windrows, static piles, aerated systems. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `COMPOST_DIR` | Data directory (default: ~/.compost/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # compost — Composting Science & Practice Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Composting Fundamentals === Composting is the controlled biological decomposition of organic matter into a stable, humus-like material called compost. Microorganisms (bacteria, fungi, actinomycetes) break down organic waste under managed conditions. Why Compost? - Diverts 30-40% of household waste from landfills - Creates rich soil amendment (improves structure, nutrients, water retention) - Reduces methane emissions (landfill organic waste produces methane) - Suppresses plant diseases and pests - Reduces need for chemical fertilizers - Sequesters carbon in soil (climate benefit) The Four Requirements: 1. Carbon (browns): Energy source for microbes 2. Nitrogen (greens): Protein for microbial growth 3. Water: Moisture for microbial activity (40-60%) 4. Oxygen: Aerobic decomposition (turning/aeration) Get these four right → compost works. Get them wrong → problems (smell, slow, pests). Key Microorganisms: Bacteria: Primary decomposers, dominate early stages Fungi: Break down tough materials (cellulose, lignin) Actinomycetes: "White threads" — break down woody material Protozoa: Feed on bacteria, release nutrients Macro-organisms: Worms, beetles, mites (in cold composting) Timeline: Hot composting: 4-8 weeks (properly managed) Cold composting: 6-24 months (passive, low effort) Vermicomposting: 3-6 months (worm-driven) Bokashi: 2-4 weeks fermentation + 2-4 weeks soil burial EOF } cmd_ratio() { cat << 'EOF' === Carbon-to-Nitrogen Ratio (C:N) === The Most Important Number in Composting: Ideal C:N ratio: 25:1 to 30:1 Microbes need carbon for energy and nitrogen for protein Too much carbon (>40:1): slow decomposition Too much nitrogen (<20:1): ammonia smell, nitrogen loss C:N Ratios of Common Materials: HIGH NITROGEN (Greens): Material C:N Notes Grass clippings 15-25:1 Excellent nitrogen source Food scraps (mixed) 15-20:1 Fruit, vegetables, coffee Coffee grounds 20:1 Also adds acidity Chicken manure 5-10:1 Very hot, use sparingly Horse manure 25-30:1 Good balance Cow manure 18-25:1 Well-balanced Fresh alfalfa 12:1 Excellent activator Seaweed/kelp 19:1 Rich in micronutrients HIGH CARBON (Browns): Material C:N Notes Dry leaves 40-80:1 Shred for faster breakdown Straw 75-100:1 Good bulking agent Cardboard 300-500:1 Shred, remove tape Newspaper 150-200:1 Shred, soy-ink OK Wood chips 200-500:1 Very slow, use for mulch Sawdust 300-500:1 Fine particles, absorbs N Pine needles 60-100:1 Acidic, slow to break down Dryer lint 100:1 Only from natural fibers Corn stalks 60-70:1 Chop into pieces Practical Mixing Guide: Simple rule: 3 parts browns to 1 part greens by volume (Volume, not weight — browns are lighter) Example recipe: 5 gallons food scraps (N) → 1 part green 15 gallons dry leaves (C) → 3 parts brown Mix thoroughly, add water until sponge-damp Quick fixes: Too much nitrogen → add shredded cardboard/leaves Too much carbon → add grass clippings/food scraps Not sure → err on the side of more browns EOF } cmd_methods() { cat << 'EOF' === Composting Methods === Hot Composting (Thermophilic): Temperature: 130-160°F (55-70°C) at peak Time: 4-8 weeks Effort: high (turning, monitoring, building volume) Kills weed seeds and pathogens (at >131°F for 3+ days) Requires: minimum 1 cubic yard (3×3×3 ft) to maintain heat Turn every 3-5 days, maintain 40-60% moisture Best for: large volumes, fast results, clean compost Cold Composting (Passive): Temperature: ambient Time: 6-24 months Effort: minimal (add materials, wait) Does NOT kill weed seeds or pathogens reliably No minimum size required Turn occasionally or never Best for: small households, low effort, patience available Vermicomposting (Worm Composting): Uses: red wigglers (Eisenia fetida), NOT earthworms Temperature: 55-77°F (13-25°C), indoor-friendly Time: 3-6 months Feed: fruit/veg scraps, coffee grounds, shredded paper Avoid: citrus, onions, meat, dairy, oils Produces: vermicast (worm castings) — premium fertilizer Worm population doubles every 3-4 months 1 lb worms eats ~0.5 lb food scraps per day Bokashi: Anaerobic fermentation using Effective Microorganisms (EM) Not true composting — fermentation (pickles the waste) Process: 1. Layer food waste with bokashi bran in sealed bucket 2. Drain liquid every 2-3 days (dilute 100:1, use as fertilizer) 3. After 2-4 weeks, bury in soil for final decomposition CAN process: meat, dairy, cooked food (unlike traditional compost) Best for: apartments, small spaces, all food types In-Vessel Composting: Enclosed reactor (drum, tunnel, container) Controlled: temperature, moisture, aeration, turning Fast: 1-3 weeks for initial decomposition Used by: municipalities, commercial operations Capital-intensive but scalable and low-odor EOF } cmd_stages() { cat << 'EOF' === Decomposition Stages === Stage 1 — Mesophilic (Days 1-3): Temperature: 68-113°F (20-45°C) Organisms: mesophilic bacteria, fungi Activity: - Bacteria colonize fresh material - Easy sugars and starches consumed first - Rapid population growth - Temperature begins rising - pH may drop temporarily (organic acids) Stage 2 — Thermophilic (Days 3-30+): Temperature: 113-160°F (45-70°C) Organisms: thermophilic bacteria, actinomycetes Activity: - Rapid breakdown of proteins, fats, complex carbohydrates - Maximum microbial activity - Pathogens and weed seeds killed (>131°F for 72 hours) - Pile shrinks rapidly (30-50% volume reduction) - Ammonia may off-gas (high nitrogen) - Turn pile when temp drops below 130°F Critical temperatures: <90°F: Too cold — add nitrogen, turn, check moisture 113-131°F: Good decomposition but not pathogen-killing 131-150°F: Ideal — pathogens killed, rapid breakdown >160°F: Too hot — kills beneficial microbes, turn immediately >180°F: Fire risk — turn and add water immediately Stage 3 — Cooling (Weeks 4-8): Temperature: drops back to 113°F and below Organisms: mesophilic bacteria return, fungi increase Activity: - Cellulose and lignin breakdown (slower materials) - Fungi produce visible white mycelium - Actinomycetes create earthy smell - Macro-organisms appear (mites, springtails, beetles) - Less turning needed Stage 4 — Curing/Maturation (Weeks 8-16): Temperature: ambient Activity: - Humic substances form (stable organic matter) - Microbial community stabilizes - Phytotoxic compounds break down - pH stabilizes near neutral (6.5-7.5) - C:N ratio settles to 10-15:1 DO NOT skip curing — immature compost can: - Rob nitrogen from soil (high C:N) - Release phytotoxic compounds (harm plants) - Contain unstable organic acids - Minimum 4 weeks curing recommended EOF } cmd_materials() { cat << 'EOF' === What to Compost === ✅ GREENS (Nitrogen-Rich): Kitchen: - Fruit and vegetable scraps - Coffee grounds and paper filters - Tea bags (remove staples) - Eggshells (crush for faster breakdown) - Stale bread and grains Garden: - Grass clippings (thin layers, mix with browns) - Fresh plant trimmings - Weeds (before seeding — or hot compost only) - Fresh manure (herbivore: horse, cow, chicken, rabbit) ✅ BROWNS (Carbon-Rich): Kitchen: - Paper towels and napkins (unbleached preferred) - Cardboard (shredded, tape removed) - Paper bags Garden: - Dry leaves (shred for faster decomposition) - Straw and hay - Wood chips and bark (slow, better as mulch) - Pine needles (acidic, use in moderation) - Corn stalks and cobs (chop up) - Dried garden debris Other: - Newspaper (shredded, soy-ink OK) - Paper egg cartons - Natural fiber scraps (cotton, wool, silk) - Sawdust (untreated wood only) - Dryer lint (natural fiber clothing only) - Hair and fur (human and pet) ❌ DO NOT COMPOST: - Meat, fish, bones (attracts pests — unless bokashi) - Dairy products (attracts pests, smells — unless bokashi) - Oils and fats (smothers microbes, attracts pests) - Pet waste (dog, cat — pathogens harmful to humans) - Diseased plants (may spread disease in garden) - Treated/painted wood (chemicals leach into compost) - Coal ash (contains sulfur, heavy metals) - Synthetic materials (plastic, nylon, polyester) - Aggressive weeds (bindweed, bermuda grass — survive composting) - Citrus and onions in vermicompost (worms dislike) EOF } cmd_troubleshoot() { cat << 'EOF' === Troubleshooting Compost Problems === Problem: Compost smells like rotten eggs / ammonia Cause: Anaerobic conditions (too wet, too compact, no air) Fix: Turn the pile, add dry browns, improve aeration If ammonia: too much nitrogen → add carbon (cardboard, leaves) If sulfur (rotten eggs): waterlogged → turn, add straw for structure Problem: Compost is too slow (nothing happening) Causes and fixes: Too dry → add water until sponge-damp Too much carbon → add nitrogen (grass, food scraps) Pieces too large → chop/shred materials smaller Pile too small → needs minimum 3×3×3 ft for heat Cold weather → insulate pile, add more nitrogen Problem: Attracting flies Cause: Exposed food scraps Fix: Always cover food with 4-6 inches of browns Also: Bury food scraps in center of pile Also: Avoid meat/dairy (unless bokashi or sealed system) Fruit flies: normal in summer, reduce by covering food Problem: Attracting rodents/raccoons Cause: Meat, dairy, or bread in open pile Fix: Use enclosed bin with secure lid Fix: Don't add cooked food, meat, or dairy Fix: Hardware cloth (1/4") on bottom of bin Problem: Pile is too wet / soggy Cause: Too much green material, rain, poor drainage Fix: Add shredded browns (cardboard, straw) Fix: Turn to aerate Fix: Cover pile during rain Fix: Elevate bin for drainage Problem: Pile is too dry Cause: Too much brown material, hot/windy weather Fix: Water thoroughly and turn Fix: Add juicy greens (fruit scraps, fresh grass) Fix: Cover to retain moisture Problem: White mold / fungus This is NORMAL — actinomycetes (beneficial) White threads = healthy decomposition No action needed Problem: Fire ants / termites Fire ants: pile too dry → moisten and turn Termites: attracted to woody material → turn more, keep moist Both: normal in warm climates, usually self-limiting EOF } cmd_quality() { cat << 'EOF' === Compost Quality Assessment === Maturity Tests (Is It Ready?): Visual: Dark brown/black, crumbly texture, no recognizable inputs Smell: Earthy, like forest floor (no ammonia or sour smell) Temperature: Ambient (no re-heating after turning) Volume: Reduced to 40-60% of original Squeeze: Handful should hold together but not drip water Bag Test: 1. Fill a sealed plastic bag with moist compost 2. Wait 3 days at room temperature 3. Open and smell 4. Earthy = mature, sour/ammonia = immature (needs more time) Germination Test: 1. Fill pot with compost, plant 10 radish seeds 2. Fill another pot with potting soil (control) 3. Wait 7-10 days 4. Compare germination rate and seedling vigor 5. >80% germination matching control = mature compost Nutrient Content (Typical Finished Compost): Nitrogen (N): 1-2% Phosphorus (P): 0.5-1% Potassium (K): 0.5-1% pH: 6.5-7.5 C:N ratio: 10-15:1 Organic matter: 30-60% Moisture: 40-50% Note: compost is a soil AMENDMENT, not a fertilizer It feeds the soil biology, which feeds the plants Nutrient release is slow and steady (won't burn plants) Application Rates: Garden beds: 1-3 inches, worked into top 6 inches Lawn topdressing: 1/4-1/2 inch, raked into grass Potting mix: 25-50% compost, rest perlite/peat/coir Trees/shrubs: 2-4 inches as mulch ring (keep from trunk) New raised bed: 50% compost, 50% native soil or topsoil Compost tea: 5 gallons water + 1 cup compost, aerate 24hr Annual application: Light: 1/2 inch (maintenance) Medium: 1-2 inches (building soil) Heavy: 3-4 inches (new garden, poor soil) Storage: Finished compost stores for 1+ years Keep covered but not sealed (needs some air exchange) Protect from rain (nutrients leach out) Use within 12 months for maximum nutrient value EOF } cmd_systems() { cat << 'EOF' === Composting Systems === Open Pile: Simplest method — pile materials on the ground Minimum size: 3×3×3 ft (1 cubic yard) for hot composting Turn with pitchfork every 5-7 days Pros: free, unlimited size, easy to build Cons: aesthetics, pests, weather exposure, slow edges Three-Bin System: Bin 1: Active (adding new material) Bin 2: Cooking (no new additions, turning) Bin 3: Curing (finished, ready to use) Material: pallets, wire mesh, cinder blocks, wood Size: each bin 3×3×3 ft minimum Best for: continuous production, serious gardeners Tumbler: Enclosed drum that rotates for easy turning Pros: pest-proof, easy turning, contained, tidy Cons: expensive ($100-400), limited capacity, can overheat Best for: small spaces, suburban yards, beginners Tip: have TWO tumblers — one filling, one cooking Worm Bin: Stacking tray system (Can-O-Worms, Worm Factory) Start: 1 lb red wigglers in bedding (shredded newspaper) Feed: bury food scraps under bedding Harvest: when top tray full, add new tray on top Location: indoor, garage, shaded outdoor (55-77°F) Best for: apartments, kitchens, year-round composting Windrow (Commercial): Long rows of compost (4-8 ft high, 14-16 ft wide) Turned with tractor-mounted windrow turner Scale: municipal, farm, industrial Time: 3-6 months with regular turning Aerated static pile: perforated pipes blow air (no turning needed) In-Vessel (Industrial): Enclosed drums, tunnels, or containers Forced aeration, temperature monitoring, automated turning Time: 1-3 weeks primary decomposition Pros: fast, consistent, low odor, weather-independent Cons: expensive ($50K-$1M+), energy-intensive Best for: large-scale municipal or commercial operations Trench/Pit Composting: Dig a trench or hole, fill with food scraps, cover with soil No bin needed, fully contained Time: 3-12 months (no turning, slower) Rotate: dig in different spots each time Best for: lazy composting, directly under future garden beds Keyhole Garden: Circular raised bed with central compost basket Add food scraps to center, nutrients leach into garden Water the compost basket → nutrients flow to plants African design, excellent for water-scarce areas EOF } show_help() { cat << EOF compost v$VERSION — Composting Science & Practice Reference Usage: script.sh <command> Commands: intro Composting fundamentals and why it matters ratio Carbon-to-nitrogen ratio guide and mixing methods Hot, cold, vermicomposting, bokashi, in-vessel stages Decomposition stages — mesophilic to curing materials What to compost and what to avoid troubleshoot Fix smells, pests, slow decomposition problems quality Maturity tests, nutrient content, application rates systems Bins, tumblers, windrows, worm bins, trench help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; ratio) cmd_ratio ;; methods) cmd_methods ;; stages) cmd_stages ;; materials) cmd_materials ;; troubleshoot) cmd_troubleshoot ;; quality) cmd_quality ;; systems) cmd_systems ;; help|--help|-h) show_help ;; version|--version|-v) echo "compost v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Hydration reference — daily water intake, electrolytes, dehydration signs, exercise hydration, rehydration protocols. Use when planning fluid intake for heal...
--- name: "hydrate" version: "1.0.0" description: "Hydration reference — daily water intake, electrolytes, dehydration signs, exercise hydration, rehydration protocols. Use when planning fluid intake for health, fitness, or recovery." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [hydrate, water, electrolytes, dehydration, health, fitness, life] category: "life" --- # Hydrate — Hydration & Fluid Balance Reference Quick-reference skill for understanding hydration science, calculating fluid needs, and managing electrolyte balance for health and performance. ## When to Use - Calculating daily water intake requirements - Planning hydration strategies for exercise or hot weather - Recognizing and addressing dehydration symptoms - Understanding electrolyte balance and supplementation - Designing rehydration protocols for illness or recovery ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of hydration — why water matters and how the body regulates fluids. ### `intake` ```bash scripts/script.sh intake ``` Daily water intake guidelines — how much, when, and adjustment factors. ### `electrolytes` ```bash scripts/script.sh electrolytes ``` Electrolyte guide — sodium, potassium, magnesium, calcium roles and sources. ### `signs` ```bash scripts/script.sh signs ``` Dehydration signs and stages — mild, moderate, severe symptoms. ### `exercise` ```bash scripts/script.sh exercise ``` Exercise hydration — pre, during, post workout fluid and electrolyte strategies. ### `rehydrate` ```bash scripts/script.sh rehydrate ``` Rehydration protocols — ORS formula, illness recovery, hangover recovery. ### `myths` ```bash scripts/script.sh myths ``` Hydration myths debunked — 8 glasses, clear urine, overhydration risks. ### `checklist` ```bash scripts/script.sh checklist ``` Daily hydration checklist and tracking tips. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `HYDRATE_DIR` | Data directory (default: ~/.hydrate/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # hydrate — Hydration & Fluid Balance Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Hydration Science === Water makes up 50-70% of body weight and is essential for every biological process. Even mild dehydration (1-2% body weight loss) impairs cognitive and physical performance. Why Water Matters: - Regulates body temperature (sweating, vasodilation) - Transports nutrients and oxygen via blood - Removes waste through kidneys and bowels - Lubricates joints (synovial fluid) - Cushions organs and tissues - Enables chemical reactions (hydrolysis, metabolism) - Maintains blood pressure and volume Body Water Distribution: Intracellular (inside cells): ~65% of total body water Extracellular (outside cells): ~35% - Interstitial (between cells): ~75% of extracellular - Plasma (blood): ~25% of extracellular How the Body Regulates Water: Input: Drinking (~60%), food (~30%), metabolic water (~10%) Output: Urine (~60%), sweat (~6%), breath (~12%), feces (~4%) Regulation mechanisms: Thirst: Triggered at ~1-2% dehydration ADH hormone: Signals kidneys to retain water Aldosterone: Signals kidneys to retain sodium (and water) Renin-angiotensin: Blood pressure regulation Average daily water turnover: Sedentary adult: 2.5L in, 2.5L out Active adult: 3.5-4.5L in, 3.5-4.5L out Endurance athlete in heat: 6-10L+ in/out Water Quality Matters: Tap water: Generally safe in developed countries, check local reports Filtered: Removes chlorine taste, some contaminants Mineral water: Contains natural electrolytes (varies by source) Distilled: No minerals — not ideal for regular drinking Temperature: Cold water absorbs faster, warm water aids digestion EOF } cmd_intake() { cat << 'EOF' === Daily Water Intake Guidelines === General Recommendations: Men: ~3.7L (125 oz) total water/day (all sources) Women: ~2.7L (91 oz) total water/day (all sources) Source: National Academies of Sciences (2004) This includes water from food (~20% of intake) Drinking water target: Men: ~3.0L (~13 cups) Women: ~2.2L (~9 cups) Simple Formula (body weight method): Ounces = Body weight (lbs) × 0.5 to 0.67 Example: 150 lbs → 75-100 oz (2.2-3.0L) per day Liters = Body weight (kg) × 0.033 Example: 70 kg → 2.3L per day Adjustment Factors: Add 500-1000mL for each factor: ☀ Hot weather (>30°C / 86°F) 🏃 Exercise (add 500mL per 30 min of moderate exercise) 🏔 Altitude (>2500m — faster breathing, more water loss) ✈️ Air travel (cabin humidity ~10-20%, very dehydrating) 🤒 Illness (fever, vomiting, diarrhea increase losses) 🤰 Pregnancy (+300mL) / Breastfeeding (+700mL) ☕ High caffeine intake (mild diuretic effect above 400mg) 🍺 Alcohol (diuretic — match each drink with water) Timing Strategy: Wake up: 500mL (rehydrate from overnight fast) 30 min before meals: 250mL (aids digestion) Between meals: sip regularly (don't chug) Before bed: small sip (enough to prevent thirst, not disruptive) Before exercise: 500mL 2 hours prior After exercise: 150% of sweat loss over 2-4 hours Water-Rich Foods (contribute to daily intake): Cucumber: 96% water Watermelon: 92% water Lettuce: 96% water Strawberries: 91% water Celery: 95% water Oranges: 87% water Tomatoes: 94% water Yogurt: 85% water Zucchini: 94% water Soup/broth: 90%+ water EOF } cmd_electrolytes() { cat << 'EOF' === Electrolyte Guide === Electrolytes are minerals that carry electric charges in body fluids. They're critical for nerve function, muscle contraction, pH balance, and fluid regulation. Sodium (Na⁺): Role: fluid balance, nerve impulses, muscle contraction RDI: 1500-2300 mg/day (varies by guidelines) Lost in sweat: 200-2000 mg/L (average ~900 mg/L) Deficiency (hyponatremia): confusion, seizures, coma Sources: salt, pickles, broth, olives, cheese Athletes: may need 500-1000 mg/hour during intense exercise Potassium (K⁺): Role: heart rhythm, muscle function, blood pressure RDI: 2600-3400 mg/day Lost in sweat: ~200 mg/L Deficiency: muscle cramps, weakness, irregular heartbeat Sources: banana (422mg), potato (926mg), avocado (485mg), spinach (558mg/cup), coconut water (600mg/cup) Magnesium (Mg²⁺): Role: 300+ enzyme reactions, muscle/nerve function, sleep RDI: 310-420 mg/day Lost in sweat: ~15 mg/L (small but cumulative) Deficiency: cramps, fatigue, insomnia, anxiety Sources: almonds (80mg/oz), dark chocolate (65mg/oz), pumpkin seeds (156mg/oz), spinach (157mg/cup) Note: ~50% of population is deficient Calcium (Ca²⁺): Role: bone health, muscle contraction, blood clotting RDI: 1000-1300 mg/day Lost in sweat: ~40 mg/L Deficiency: osteoporosis, muscle spasms, dental problems Sources: dairy, sardines, fortified foods, broccoli, kale Chloride (Cl⁻): Role: stomach acid (HCl), fluid balance (follows sodium) RDI: 2300 mg/day Usually sufficient if sodium intake is adequate DIY Electrolyte Drink: 1L water + 1/4 tsp salt (575mg Na) + 1/4 tsp salt substitute (KCl, ~600mg K) + 2 tbsp honey + juice of 1 lemon Cost: ~$0.10 vs $2-3 for commercial drinks EOF } cmd_signs() { cat << 'EOF' === Dehydration Signs & Stages === Stage 1 — Mild Dehydration (1-3% body weight loss): Symptoms: - Thirst (most obvious but LATE indicator) - Dry mouth and lips - Slightly darker urine (straw to dark yellow) - Mild headache - Decreased concentration - Slight fatigue Performance impact: 10-20% reduction in endurance Fix: drink 500-1000mL water over 1-2 hours Stage 2 — Moderate Dehydration (3-5% body weight loss): Symptoms: - Strong thirst - Dark yellow/amber urine, reduced volume - Dry, cool skin - Headache (more intense) - Dizziness when standing (orthostatic hypotension) - Rapid heartbeat - Muscle cramps - Irritability, difficulty concentrating Performance impact: 20-40% reduction Fix: oral rehydration solution (ORS), slow sipping over 2-4 hours Stage 3 — Severe Dehydration (>5% body weight loss): Symptoms: - No urine output or very dark urine - Sunken eyes - Rapid, weak pulse - Low blood pressure - Confusion, delirium - Fainting - Skin tenting (pinched skin stays raised) - In children: no tears when crying MEDICAL EMERGENCY — seek immediate medical attention Treatment: IV fluid replacement in hospital Urine Color Chart: 1. Clear/pale straw → Well hydrated 2. Light yellow → Adequately hydrated 3. Yellow → Normal, drink soon 4. Dark yellow → Mildly dehydrated — drink now 5. Amber/honey → Moderately dehydrated 6. Dark amber/brown → Severely dehydrated — seek help Note: B vitamins, beets, medications can alter color Quick Self-Tests: Skin turgor: pinch back of hand, skin should snap back instantly Capillary refill: press fingernail, color returns in <2 seconds Weight: weigh before/after exercise — each kg lost ≈ 1L sweat EOF } cmd_exercise() { cat << 'EOF' === Exercise Hydration Strategy === Pre-Exercise (2-4 hours before): Drink 500-600mL (17-20 oz) 2-4 hours before Then 200-300mL (7-10 oz) 10-20 minutes before Goal: start well-hydrated (pale yellow urine) Avoid chugging — spread intake over the pre-exercise window During Exercise: General: 150-250mL (5-8 oz) every 15-20 minutes Adjust by intensity: Light (walking, yoga): 100-200 mL/hour Moderate (jogging, cycling): 400-800 mL/hour Intense (racing, team sport): 800-1200 mL/hour Ultra/heat: up to 1500 mL/hour When to add electrolytes: < 60 min exercise: water is sufficient 60-90 min: water + light electrolytes > 90 min: electrolyte sports drink essential Heavy sweater: sodium supplement needed (salt tabs or drink) Sports Drink Composition (optimal): Carbohydrates: 4-8% (40-80g/L) — glucose + fructose mix Sodium: 300-800 mg/L Potassium: 75-200 mg/L Osmolality: 200-300 mOsm/kg (hypotonic to isotonic) Post-Exercise Recovery: Weigh before and after exercise Each 1 kg lost = 1L of sweat Replace 150% of weight lost over 2-4 hours Lost 2 kg → drink 3L over 2-4 hours Recovery drink priorities: Fluid (water or electrolyte drink) Sodium (to retain the fluid you drink) Carbohydrates (replenish glycogen) Protein (muscle recovery, within 30 min) Example: chocolate milk (surprisingly optimal ratio) Sweat Rate Calculation: 1. Weigh yourself nude before exercise (kg) 2. Exercise for 1 hour (no bathroom, track fluid intake) 3. Weigh yourself nude after 4. Sweat rate = (Pre-weight - Post-weight) + fluid consumed Example: 70.0 kg → 69.2 kg, drank 0.5L Sweat rate = 0.8 + 0.5 = 1.3 L/hour EOF } cmd_rehydrate() { cat << 'EOF' === Rehydration Protocols === WHO Oral Rehydration Solution (ORS): The gold standard for treating dehydration from diarrhea/vomiting Formula (per liter of clean water): Salt (NaCl): 3.5g (¾ tsp) Sugar (glucose): 20g (4 tsp) Baking soda: 2.5g (½ tsp) — or trisodium citrate 2.9g Potassium chloride: 1.5g (salt substitute) Simplified WHO-ORS: 1L water + 6 tsp sugar + ½ tsp salt (less precise but effective in emergencies) How to use: Sip small amounts frequently (not big gulps) Children: 1 teaspoon every 1-2 minutes Adults: 200-400mL after each loose stool Continue until urine is pale yellow Illness Rehydration: Fever: add 500mL per degree above 37°C (per day) Vomiting: wait 15-20 min after episode, then small sips Diarrhea: replace with ORS, avoid plain water (no electrolytes) Food poisoning: ORS + BRAT diet (banana, rice, applesauce, toast) What to avoid when sick: - Sugary sodas (osmotic diarrhea) - Caffeine (mild diuretic) - Alcohol (dehydrating) - Fruit juice undiluted (too much sugar) - Dairy if lactose intolerant Hangover Rehydration: Alcohol blocks ADH → excess urine production Each alcoholic drink → ~120mL extra urine (net fluid loss) Prevention: 1 glass water per alcoholic drink during the night Morning after protocol: 1. 500mL water with electrolytes immediately 2. Light breakfast with salt (eggs, toast, broth) 3. Continue sipping water through the day 4. Avoid coffee until baseline hydration restored 5. Coconut water is excellent (natural electrolytes + potassium) Heat Exhaustion Recovery: 1. Move to shade/cool area 2. Lie down, elevate legs 3. Remove excess clothing 4. Cool with wet cloths on neck, armpits, groin 5. Sip cool (not ice cold) electrolyte water 6. If no improvement in 30 min → emergency services EOF } cmd_myths() { cat << 'EOF' === Hydration Myths Debunked === Myth: "Drink 8 glasses of water a day" Reality: No scientific basis for this specific number Origin: 1945 US Food and Nutrition Board recommendation (included water from ALL sources, including food) Truth: needs vary wildly by body size, activity, climate, diet Better rule: drink when thirsty + check urine color Myth: "Clear urine means you're well hydrated" Reality: completely clear urine may mean OVER-hydration Target: pale straw color (not clear, not dark) Clear urine = dilute urine = potentially flushing electrolytes Exception: some medications change urine color regardless Myth: "Coffee and tea dehydrate you" Reality: caffeine is a mild diuretic, but the fluid content far outweighs the diuretic effect Studies show: regular caffeine consumers develop tolerance Net hydration: a cup of coffee still adds net positive fluid Caution: >400mg caffeine/day may have mild dehydrating effect Myth: "You can't drink too much water" Reality: overhydration (hyponatremia) can be FATAL Occurs when: blood sodium drops below 135 mEq/L Risk groups: marathon runners, military, ecstasy users Symptoms: nausea, headache, confusion, seizures Prevention: don't drink more than 1L/hour consistently Replace electrolytes during prolonged sweating Myth: "Thirst means you're already dehydrated" Reality: partly true but overstated Thirst kicks in at ~1-2% dehydration (very mild) For most people, drinking when thirsty is perfectly adequate Exception: elderly (thirst mechanism weakens with age) Exception: during intense exercise (thirst lags behind need) Myth: "Cold water is dangerous during exercise" Reality: cold water (5-10°C) is actually BETTER during exercise Absorbs faster than warm water Helps cool core body temperature People drink more of it voluntarily (tastes better when hot) The "cold water shock" myth has no scientific support Myth: "Sparkling water doesn't hydrate as well" Reality: sparkling water hydrates identically to still water CO₂ doesn't affect absorption May cause bloating → people drink less (only concern) No effect on bone density (old myth debunked) EOF } cmd_checklist() { cat << 'EOF' === Daily Hydration Checklist === Morning Routine: [ ] Drink 500mL water within 30 min of waking [ ] Check urine color (aim for pale straw) [ ] Prepare water bottle for the day Throughout the Day: [ ] Keep water bottle visible and within reach [ ] Sip water before each meal (250mL, 30 min prior) [ ] Drink water with every meal [ ] Set reminders if you forget to drink (every 1-2 hours) [ ] Eat at least 2 water-rich foods (fruit, vegetables, soup) Exercise Days: [ ] Pre-hydrate: 500mL 2 hours before exercise [ ] During: 150-250mL every 15-20 min [ ] Post: weigh yourself, replace 150% of weight lost [ ] Add electrolytes if exercising >60 minutes Environmental Adjustments: [ ] Hot day: add 500-1000mL to baseline [ ] Air-conditioned office: still drink (AC dehydrates) [ ] Flying: drink 250mL per hour of flight [ ] High altitude: increase by 500mL Tracking Methods: 1. Water bottle method: Buy a marked 1L bottle, aim to finish it 2-3 times/day 2. Rubber band method: Put 8 rubber bands on bottle, remove one per glass 3. App tracking: WaterMinder, Plant Nanny, My Water (gamified) 4. Urine color: Simplest — if pale yellow, you're on track Signs You're On Track: ✓ Urine is pale straw color ✓ No persistent thirst ✓ Skin is supple (no tenting) ✓ Energy levels stable through the day ✓ Urinating every 2-4 hours ✓ No headaches from dehydration Signs You Need More: ✗ Dark urine (after ruling out supplements/meds) ✗ Dry mouth or lips ✗ Afternoon headaches ✗ Feeling sluggish or foggy ✗ Muscle cramps during/after exercise ✗ Constipation EOF } show_help() { cat << EOF hydrate v$VERSION — Hydration & Fluid Balance Reference Usage: script.sh <command> Commands: intro Why water matters and body fluid regulation intake Daily water intake guidelines and adjustment factors electrolytes Sodium, potassium, magnesium, calcium guide signs Dehydration stages — mild, moderate, severe exercise Exercise hydration — pre, during, post workout rehydrate Rehydration protocols — ORS, illness, hangover myths Hydration myths debunked checklist Daily hydration tracking checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; intake) cmd_intake ;; electrolytes) cmd_electrolytes ;; signs) cmd_signs ;; exercise) cmd_exercise ;; rehydrate) cmd_rehydrate ;; myths) cmd_myths ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "hydrate v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Beta coefficient reference — CAPM, systematic risk, portfolio sensitivity, regression analysis. Use when measuring stock volatility relative to the market or...
--- name: "beta" version: "1.0.0" description: "Beta coefficient reference — CAPM, systematic risk, portfolio sensitivity, regression analysis. Use when measuring stock volatility relative to the market or constructing risk-adjusted portfolios." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [beta, capm, risk, portfolio, volatility, finance, regression] category: "finance" --- # Beta — Beta Coefficient & Systematic Risk Reference Quick-reference skill for understanding and applying the beta coefficient in finance, portfolio management, and risk analysis. ## When to Use - Calculating a stock's beta relative to a benchmark index - Understanding systematic vs unsystematic risk - Applying CAPM to estimate expected returns - Constructing beta-neutral or target-beta portfolios - Interpreting regression output for asset sensitivity ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of beta — definition, intuition, and role in modern finance. ### `capm` ```bash scripts/script.sh capm ``` Capital Asset Pricing Model — formula, assumptions, and expected return calculation. ### `calculate` ```bash scripts/script.sh calculate ``` How to calculate beta — regression method, covariance/variance method, and practical steps. ### `interpret` ```bash scripts/script.sh interpret ``` Interpreting beta values — what β>1, β=1, β<1, and β<0 mean in practice. ### `types` ```bash scripts/script.sh types ``` Types of beta — levered vs unlevered, adjusted beta, fundamental beta, bottom-up beta. ### `portfolio` ```bash scripts/script.sh portfolio ``` Portfolio beta — weighted average calculation, target beta, beta hedging strategies. ### `pitfalls` ```bash scripts/script.sh pitfalls ``` Common pitfalls — estimation window, benchmark choice, non-stationarity, and survivorship bias. ### `examples` ```bash scripts/script.sh examples ``` Worked examples with real-world beta scenarios and calculations. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `BETA_DIR` | Data directory (default: ~/.beta/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # beta — Beta Coefficient & Systematic Risk Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Beta Coefficient === Beta (β) measures the sensitivity of an asset's returns to the returns of a benchmark (usually the market portfolio). It is the cornerstone of systematic risk measurement in modern finance. Definition: β = Cov(Rᵢ, Rₘ) / Var(Rₘ) Rᵢ = Return of asset i Rₘ = Return of the market portfolio Intuition: β = 1.0 Asset moves exactly with the market β > 1.0 Asset amplifies market moves (more volatile) β < 1.0 Asset dampens market moves (less volatile) β = 0 Asset is uncorrelated with the market β < 0 Asset moves opposite to the market (rare) Key Properties: - Beta captures only SYSTEMATIC risk (market-wide) - It does NOT capture firm-specific (idiosyncratic) risk - Diversification eliminates idiosyncratic risk, not beta risk - The market portfolio has β = 1.0 by definition - Risk-free asset has β = 0 History: 1964 William Sharpe introduces CAPM and beta 1965 John Lintner independently derives CAPM 1972 Fischer Black extends to zero-beta version 1992 Fama-French challenge beta's explanatory power 2000s Beta remains central despite multi-factor models EOF } cmd_capm() { cat << 'EOF' === Capital Asset Pricing Model (CAPM) === Formula: E(Rᵢ) = Rᶠ + βᵢ × (E(Rₘ) - Rᶠ) E(Rᵢ) Expected return of asset i Rᶠ Risk-free rate (e.g., T-bill yield) βᵢ Beta of asset i E(Rₘ) Expected market return E(Rₘ) - Rᶠ Market risk premium (equity risk premium) Example: Risk-free rate: 3% Market return: 10% Stock beta: 1.5 E(Rᵢ) = 3% + 1.5 × (10% - 3%) = 3% + 10.5% = 13.5% CAPM Assumptions: 1. Investors are rational mean-variance optimizers 2. Single-period investment horizon 3. Homogeneous expectations (everyone agrees on inputs) 4. No taxes, transaction costs, or short-selling constraints 5. All assets are infinitely divisible 6. Investors can borrow/lend at the risk-free rate Security Market Line (SML): E(R) = Rᶠ + β × (E(Rₘ) - Rᶠ) - Plots expected return vs beta - Assets ABOVE the SML are undervalued (positive alpha) - Assets BELOW the SML are overvalued (negative alpha) - Alpha (α) = Actual Return - CAPM Expected Return Capital Market Line (CML): E(Rₚ) = Rᶠ + [(E(Rₘ) - Rᶠ) / σₘ] × σₚ - Only efficient portfolios lie on the CML - Slope = Sharpe ratio of the market portfolio EOF } cmd_calculate() { cat << 'EOF' === Calculating Beta === Method 1: Regression (Most Common) Run OLS regression: Rᵢ - Rᶠ = α + β(Rₘ - Rᶠ) + ε - Slope coefficient = beta - Intercept = Jensen's alpha - R² = proportion of variance explained by market Practical Steps: 1. Gather returns (monthly for 3-5 years is standard) 2. Choose benchmark (S&P 500, MSCI World, sector index) 3. Calculate excess returns (subtract risk-free rate) 4. Run regression: Y = asset excess returns, X = market excess returns 5. Slope = β, Standard error tells you precision Method 2: Covariance/Variance β = Cov(Rᵢ, Rₘ) / Var(Rₘ) Equivalent to regression but calculated directly Step-by-step: 1. Calculate mean returns for asset and market 2. Compute deviations from mean for each period 3. Multiply paired deviations → covariance 4. Divide by market variance Method 3: Correlation-Based β = ρ(Rᵢ, Rₘ) × (σᵢ / σₘ) Where ρ = correlation, σ = standard deviation Data Choices That Matter: Frequency Daily, weekly, monthly (monthly = less noise) Window 2 years, 3 years, 5 years (longer = more stable) Benchmark S&P 500, Russell 2000, sector index Returns Arithmetic vs logarithmic Adjusted Dividends included or price-only? Rule of thumb: 60 monthly observations against a broad index EOF } cmd_interpret() { cat << 'EOF' === Interpreting Beta Values === β > 1.0 — Aggressive / High-Beta More volatile than the market Amplifies both gains and losses Examples: Tech stocks, small caps, leveraged companies AAPL historically ~1.2, TSLA ~1.5-2.0 Higher expected return (per CAPM) to compensate β = 1.0 — Market-Matching Moves in lockstep with the market A well-diversified index fund ≈ 1.0 Useful as a benchmark for comparison 0 < β < 1.0 — Defensive / Low-Beta Less volatile than the market Dampens market swings Examples: Utilities (0.3-0.5), consumer staples (0.5-0.7) Lower expected return but smoother ride Often called "defensive" stocks β = 0 — Uncorrelated No linear relationship with the market Examples: Some commodities, certain hedge fund strategies NOT the same as "riskless" — can have high total volatility β < 0 — Inverse / Negative Beta Moves opposite to the market Very rare in equities Examples: Gold (~-0.1 to 0.1), inverse ETFs (by design) Valuable for hedging (natural portfolio insurance) Important Nuances: - Beta is NOT total risk (σ), it's systematic risk only - A stock with β=0.5 can still be very volatile (high idiosyncratic risk) - Beta changes over time (non-stationary) - Industry matters: fintech firm β ≠ traditional bank β - Leverage increases beta mechanically EOF } cmd_types() { cat << 'EOF' === Types of Beta === Levered Beta (Equity Beta, βₑ): The observed beta from market data Reflects BOTH business risk and financial risk (leverage) This is what you get from regression on stock returns Unlevered Beta (Asset Beta, βₐ): Removes the effect of financial leverage βₐ = βₑ / [1 + (1 - Tax Rate) × (Debt/Equity)] Reflects pure business/operating risk Used for comparing companies with different capital structures Essential for WACC calculations in DCF Re-levering Beta: βₑ = βₐ × [1 + (1 - Tax Rate) × (Debt/Equity)] Apply target company's capital structure to peer's asset beta Used when the target has no publicly traded equity Adjusted Beta (Bloomberg Beta): βₐdⱼ = (2/3) × Raw β + (1/3) × 1.0 Shrinks raw beta toward 1.0 (mean-reversion assumption) Rationale: betas tend to regress toward the market average Vasicek adjustment uses Bayesian shrinkage with standard error Bottom-Up Beta: Average the unlevered betas of comparable public companies Re-lever using the target company's D/E ratio Advantages: - More stable than single-stock regression - Usable for private companies - Forward-looking (can adjust for changing business mix) Steps: 1. Identify comparable companies 2. Get each company's levered beta 3. Unlever each using their D/E ratios 4. Average the unlevered betas 5. Re-lever using the target's D/E ratio Fundamental Beta: Estimated from company fundamentals, not market data Factors: size, leverage, earnings variability, dividend yield, growth Used by Barra/MSCI risk models EOF } cmd_portfolio() { cat << 'EOF' === Portfolio Beta === Portfolio Beta = Weighted Average: βₚ = Σ(wᵢ × βᵢ) Where wᵢ = weight of asset i in portfolio Example: Asset A: 40% weight, β = 1.2 → contribution = 0.48 Asset B: 35% weight, β = 0.8 → contribution = 0.28 Asset C: 25% weight, β = 1.5 → contribution = 0.375 Portfolio β = 0.48 + 0.28 + 0.375 = 1.135 Target Beta Construction: To achieve a target beta, solve for weights For β-neutral portfolio (βₚ = 0): Long high-β stocks + Short enough to offset Example: Long $100 of β=1.2, Short $120 of β=1.0 Net β = (1.0)(1.2) + (-1.2)(1.0) = 0 Beta Hedging with Futures: Number of contracts = (βₜ - βₚ) × (Portfolio Value / Futures Value) βₜ = target beta βₚ = current portfolio beta To eliminate market risk (βₜ = 0): If portfolio = $10M, β = 1.3, S&P futures = $250,000 Contracts = (0 - 1.3) × (10,000,000 / 250,000) = -52 Short 52 futures contracts Portable Alpha Strategy: 1. Generate alpha in any asset class 2. Use futures/swaps to overlay desired beta exposure 3. Total return = Alpha + Beta × Market Return Smart Beta / Factor Investing: Low-volatility anomaly: low-β stocks have historically outperformed on a risk-adjusted basis (contradicts CAPM) Minimum variance portfolios tilt toward low-beta stocks EOF } cmd_pitfalls() { cat << 'EOF' === Common Pitfalls in Beta Estimation === 1. Estimation Window: Too short (< 1 year): noisy, unreliable Too long (> 5 years): may not reflect current business Standard: 3-5 years of monthly data (60 observations) Exception: fast-changing firms → use 2 years weekly 2. Benchmark Choice: S&P 500 for US large-caps Russell 2000 for US small-caps MSCI EAFE for international Wrong benchmark → misleading beta Example: measuring a Japanese stock vs S&P 500 = bad idea 3. Return Frequency: Daily: more data points but noisy (microstructure effects) Weekly: reasonable compromise Monthly: standard for practitioners Thin-trading bias: illiquid stocks show downward-biased beta Fix: use Dimson beta (lagged market returns in regression) 4. Non-Stationarity: Beta changes over time — it's NOT a constant Company events: M&A, leverage changes, new business lines Market regime: betas increase during crises (correlation spike) Rolling-window beta: use 36-month rolling to visualize shifts 5. Survivorship Bias: Using only surviving companies overestimates historical returns Failed companies (often high-beta) drop out of the sample 6. Beta ≠ Total Risk: High R² → most risk is systematic (beta captures it) Low R² → most risk is idiosyncratic (beta misses it) Biotech: β=1.5 but R²=0.10 (drug trial risk dominates) 7. Leverage Distortion: Highly levered firms have mechanically higher equity beta Always unlever before comparing business risk across firms A company that doubles debt will roughly double its equity beta 8. Negative Beta Illusion: Very few assets have truly negative beta Often an artifact of low correlation + noise Test: is the negative beta statistically significant? EOF } cmd_examples() { cat << 'EOF' === Beta Worked Examples === --- Example 1: Calculating Beta from Returns --- Month Stock Market 1 +4% +3% 2 -2% -1% 3 +6% +4% 4 -3% -2% 5 +5% +3% Mean stock = 2.0%, Mean market = 1.4% Covariance calculation: Σ[(Rᵢ - R̄ᵢ)(Rₘ - R̄ₘ)] / (n-1) = [(4-2)(3-1.4) + (-2-2)(-1-1.4) + (6-2)(4-1.4) + (-3-2)(-2-1.4) + (5-2)(3-1.4)] / 4 = [3.2 + 9.6 + 10.4 + 17.0 + 4.8] / 4 = 11.25 Var(market) = Σ(Rₘ - R̄ₘ)² / (n-1) = [2.56 + 5.76 + 6.76 + 11.56 + 2.56] / 4 = 7.30 β = 11.25 / 7.30 = 1.54 --- Example 2: CAPM Expected Return --- Risk-free rate = 4.0% Market premium = 6.0% (historical average) Stock beta = 1.54 E(R) = 4.0% + 1.54 × 6.0% = 13.24% --- Example 3: Unlevering / Re-levering --- Company A (comparable): Equity β = 1.4, D/E = 0.5, Tax = 25% Asset β = 1.4 / [1 + (1-0.25)(0.5)] = 1.4 / 1.375 = 1.018 Target company: D/E = 0.8, Tax = 25% Equity β = 1.018 × [1 + (1-0.25)(0.8)] = 1.018 × 1.6 = 1.629 --- Example 4: Portfolio Beta Hedging --- Portfolio: $5M, current β = 1.2 Goal: reduce to β = 0.7 S&P 500 futures: $250,000 per contract, β = 1.0 Contracts = (0.7 - 1.2) × (5,000,000 / 250,000) = -10 Short 10 futures contracts EOF } show_help() { cat << EOF beta v$VERSION — Beta Coefficient & Systematic Risk Reference Usage: script.sh <command> Commands: intro Beta overview — definition, intuition, history capm Capital Asset Pricing Model formula and components calculate How to calculate beta — regression and variance methods interpret What beta values mean — aggressive, defensive, negative types Levered, unlevered, adjusted, bottom-up, fundamental beta portfolio Portfolio beta, hedging, target construction pitfalls Common estimation errors and how to avoid them examples Worked calculations with real-world scenarios help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; capm) cmd_capm ;; calculate) cmd_calculate ;; interpret) cmd_interpret ;; types) cmd_types ;; portfolio) cmd_portfolio ;; pitfalls) cmd_pitfalls ;; examples) cmd_examples ;; help|--help|-h) show_help ;; version|--version|-v) echo "beta v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Tooltip UI component reference — positioning, accessibility, trigger patterns, animation. Use when implementing tooltips, popovers, or contextual help overla...
--- name: "tooltip" version: "1.0.0" description: "Tooltip UI component reference — positioning, accessibility, trigger patterns, animation. Use when implementing tooltips, popovers, or contextual help overlays in web interfaces." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [tooltip, popover, ui-component, a11y, positioning, overlay, frontend] category: "frontend" --- # Tooltip — Tooltip UI Component Reference Quick-reference skill for tooltip design, positioning logic, accessibility, and implementation patterns. ## When to Use - Adding contextual help text to UI elements - Implementing hover/focus information overlays - Choosing between tooltips, popovers, and toggletips - Making tooltips accessible to keyboard and screen reader users - Handling tooltip positioning and collision detection ## Commands ### `intro` ```bash scripts/script.sh intro ``` Tooltip overview — types, when to use, tooltip vs popover vs toggletip. ### `anatomy` ```bash scripts/script.sh anatomy ``` Tooltip anatomy — trigger, content, arrow, positioning, delay. ### `positioning` ```bash scripts/script.sh positioning ``` Positioning logic — placement options, collision detection, flip and shift. ### `accessibility` ```bash scripts/script.sh accessibility ``` Accessibility — ARIA patterns, keyboard support, screen readers, touch devices. ### `triggers` ```bash scripts/script.sh triggers ``` Trigger patterns — hover, focus, click, long-press, programmatic. ### `content` ```bash scripts/script.sh content ``` Content guidelines — what belongs in tooltips, writing style, rich content. ### `css` ```bash scripts/script.sh css ``` CSS implementation — positioning, animations, arrow rendering, theming. ### `checklist` ```bash scripts/script.sh checklist ``` Tooltip design and implementation checklist. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # tooltip — Tooltip UI Component Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Tooltip Overview === A tooltip is a small overlay that appears on hover or focus, providing brief supplementary information about a UI element. TYPES OF INFORMATIONAL OVERLAYS: Tooltip: Triggered by hover/focus, dismissed on leave/blur Text only (no interactive content) Describes or labels the trigger element Example: Icon button → "Delete item" Popover: Triggered by click, dismissed by click outside/close button Can contain interactive content (links, buttons, forms) Stays open until explicitly closed Example: "More info" button → settings panel Toggletip: Triggered by click (like popover), but text-only content Used when hover is unreliable (touch, keyboard-only) Example: Click "?" icon → explanation text Title attribute (native): HTML title="..." attribute Poor UX: slow delay, can't style, inconsistent, inaccessible ⚠️ Avoid for important information WHEN TO USE TOOLTIPS: ✓ Label for icon-only buttons (accessibility essential) ✓ Clarify abbreviations or jargon ✓ Show full text for truncated content ✓ Keyboard shortcuts ("Ctrl+S") ✓ Additional context that's not essential WHEN NOT TO USE: ✗ Essential information (user MUST see it) ✗ Interactive content (use popover instead) ✗ Long text (>1-2 sentences) ✗ Form validation messages (show inline) ✗ On touch-only devices without alternative ✗ Covering the trigger element itself ✗ On disabled elements without keyboard access KEY PRINCIPLES: 1. Supplementary, not essential (page works without them) 2. Brief (1-2 short lines maximum) 3. No interaction required to read 4. Accessible to keyboard and screen readers 5. Not the only way to convey information EOF } cmd_anatomy() { cat << 'EOF' === Tooltip Anatomy === ┌──────────────────────┐ │ Tooltip content │ │ goes here │ └─────────┬────────────┘ ▼ ← Arrow (caret) ┌──────────┐ │ Trigger │ ← Trigger element └──────────┘ COMPONENTS: Trigger Element: The UI element that activates the tooltip Examples: button, icon, link, abbreviation, truncated text Must be focusable (buttons, links) or made focusable (tabindex="0") Content: The text displayed in the tooltip overlay Text only — no links, buttons, or interactive elements 1-2 lines maximum (≈80 characters) Plain language, sentence case Arrow (Caret / Beak): Visual connector pointing from tooltip to trigger Shows relationship between tooltip and its trigger Optional but recommended for clarity Rotates based on placement (▲ ▼ ◄ ►) Container: Overlay box with padding, background, border-radius Typically: dark background + light text (inverted from page) Or: light background + shadow (card-style) TIMING: Show Delay: Time between hover start and tooltip appearing Recommended: 300-500ms (prevents accidental triggers) Too fast: tooltips flash during normal cursor movement Too slow: feels unresponsive Hide Delay: Time between hover end and tooltip disappearing Recommended: 100-200ms Allows cursor to move to tooltip without it closing Critical for users with motor impairments Group Delay (warm-up): After seeing one tooltip, next ones show immediately No delay when moving between elements quickly Resets after ~500ms of no tooltip activity ANIMATION: Fade in: opacity 0→1 (100-200ms) Scale: scale 0.95→1 (subtle, fast) Slide: translate 4px in from placement direction Keep it fast and subtle — tooltips should not distract EOF } cmd_positioning() { cat << 'EOF' === Tooltip Positioning === PLACEMENT OPTIONS: Primary: top, right, bottom, left With align: top-start, top-end, right-start, right-end, bottom-start, bottom-end, left-start, left-end Default: top (above the trigger, centered) Visual: top-start top top-end ┌────────────────┐ left │ Trigger │ right └────────────────┘ bottom-start bottom bottom-end COLLISION DETECTION: Problem: Tooltip placed "top" but trigger is near top of viewport → tooltip is clipped or hidden Solution 1 — Flip: If tooltip would overflow on primary axis, flip to opposite side top → bottom, left → right Most common collision strategy Solution 2 — Shift: If tooltip would overflow on secondary axis, shift along it Tooltip stays on same side but slides to fit in viewport Arrow position updates to point at trigger Solution 3 — Auto: Calculate available space in all directions Choose placement with most room Less predictable but always visible POSITIONING LIBRARIES: Floating UI (Popper.js successor): import { computePosition, flip, shift, arrow } from '@floating-ui/dom'; computePosition(trigger, tooltip, { placement: 'top', middleware: [flip(), shift({ padding: 8 }), arrow({ element: arrowEl })] }).then(({ x, y, placement, middlewareData }) => { Object.assign(tooltip.style, { left: x+'px', top: y+'px' }); }); Key middleware: flip() Flip to opposite side on overflow shift() Shift along axis to stay in view offset() Gap between trigger and tooltip (8px default) arrow() Position the arrow element correctly autoPlacement() Auto-choose best placement CSS ANCHOR POSITIONING (emerging standard): .tooltip { position: absolute; position-anchor: --trigger; top: anchor(bottom); left: anchor(center); position-try: flip-block, flip-inline; } (Limited browser support as of 2024 — use as progressive enhancement) VIRTUAL ELEMENTS: Position tooltip at cursor location (context menus): const virtualEl = { getBoundingClientRect() { return { x: mouseX, y: mouseY, width: 0, height: 0 ... } } }; computePosition(virtualEl, tooltip, { placement: 'right-start' }); Z-INDEX MANAGEMENT: Tooltips should be above most UI but below modals Typical: z-index: 1000 (modal: 1100, toast: 1200) Use a stacking context layer system, not arbitrary numbers EOF } cmd_accessibility() { cat << 'EOF' === Tooltip Accessibility === PATTERN 1 — DESCRIBING TOOLTIP (aria-describedby): Use when tooltip adds supplementary info to a labeled element. <button aria-describedby="tip-1">Save</button> <div role="tooltip" id="tip-1">Save changes to disk (Ctrl+S)</div> Screen reader: "Save, button. Save changes to disk, Ctrl+S." The element already has a name ("Save"), tooltip adds context. PATTERN 2 — LABELING TOOLTIP (aria-labelledby): Use when tooltip IS the element's accessible name (icon buttons). <button aria-labelledby="tip-2"> <svg>...</svg> <!-- Icon only, no text --> </button> <div role="tooltip" id="tip-2">Delete item</div> Screen reader: "Delete item, button." KEYBOARD SUPPORT: Show tooltip: Focus trigger element (Tab into it) Hide tooltip: Blur trigger (Tab away) OR press Escape Escape: Must dismiss tooltip without other side effects Stay visible: While trigger has focus, tooltip stays shown CRITICAL: Tooltips MUST be accessible via keyboard focus, not just mouse hover. If hover-only → inaccessible. TOUCH DEVICE CONSIDERATIONS: No hover on touch → tooltips don't work! Solutions: 1. Use aria-label instead (screen reader accessible) 2. Use toggletip (tap to show, tap again to hide) 3. Show tooltip on long-press (150ms+) 4. Show info inline instead of in tooltip SCREEN READER BEHAVIOR: role="tooltip": Semantically marks element as tooltip Some screen readers auto-announce tooltip content Content should be announced via aria-describedby relation Live updates: If tooltip content changes dynamically, use aria-live="polite" But static tooltips don't need aria-live REQUIREMENTS CHECKLIST: [ ] Tooltip accessible via focus (not just hover) [ ] role="tooltip" on the overlay element [ ] aria-describedby OR aria-labelledby connects trigger → tooltip [ ] Escape key dismisses tooltip [ ] Tooltip doesn't obscure the trigger element [ ] Content doesn't require interaction (no links/buttons) [ ] Touch alternative exists (label, toggletip, or inline text) [ ] Sufficient color contrast (4.5:1 minimum for text) [ ] Tooltip text is concise and meaningful EOF } cmd_triggers() { cat << 'EOF' === Trigger Patterns === HOVER TRIGGER (most common): Show: mouseenter on trigger element Hide: mouseleave from trigger element Requirements: - Show delay: 300-500ms (prevent flash on cursor pass-through) - Hide delay: 100-200ms (grace period to reach tooltip) - Keep visible while cursor is over tooltip itself - Dismiss on scroll (tooltip position becomes stale) Mouse movement handling: pointerenter/pointerleave preferred over mouseenter/mouseleave pointerenter works for mouse AND stylus (not touch) FOCUS TRIGGER (accessibility essential): Show: focus event on trigger element Hide: blur event on trigger element Requirements: - No delay needed (focus is intentional) - Must work alongside hover (both triggers) - Keep visible while trigger has focus - Dismiss with Escape key CLICK TRIGGER (toggletip pattern): Show: click/tap on trigger element Hide: click trigger again, click outside, or Escape Requirements: - Toggle behavior (click on → click off) - Click outside to dismiss - Used for touch-friendly informational overlays - Technically a toggletip or popover, not a tooltip LONG-PRESS TRIGGER (mobile): Show: press and hold 300-500ms on touch device Hide: release touch or Escape Requirements: - Visual feedback during press (scale/color change) - Haptic feedback when tooltip appears (if available) - Fallback for devices without long-press support PROGRAMMATIC TRIGGER: Show/hide controlled by application logic Examples: - Form field tooltip when validation fails - Onboarding tooltip sequence (guided tour) - Feature discovery ("New!" tooltip on menu item) Requirements: - Manual control: show(), hide(), toggle() API - Auto-dismiss after timeout (optional) - Don't interrupt user's current task COMBINED TRIGGERS (recommended pattern): Desktop: hover OR focus (whichever comes first) Mobile: long-press or tap (toggletip mode) Dismiss: mouseleave AND blur AND Escape AND scroll Implementation pseudocode: on pointerenter → start show timer on focus → show immediately on pointerleave → start hide timer on blur → start hide timer on Escape → hide immediately on scroll → hide immediately if (show timer running && hide timer starts) → cancel show timer if (hide timer running && show timer starts) → cancel hide timer EOF } cmd_content() { cat << 'EOF' === Tooltip Content Guidelines === WHAT BELONGS IN TOOLTIPS: ✓ Labels for icon-only buttons ("Bold", "Undo", "Search") ✓ Keyboard shortcuts ("Ctrl+B", "⌘+Z") ✓ Abbreviation expansion ("API: Application Programming Interface") ✓ Full text for truncated content ("Q4 2024 Sales Report Final...") ✓ Brief clarification ("Based on last 30 days of data") ✓ Units or format hints ("Enter date as YYYY-MM-DD") WHAT DOESN'T BELONG: ✗ Essential instructions (put these in the UI itself) ✗ Error messages (show inline, red text) ✗ Long explanations (use a help panel or documentation link) ✗ Interactive content (use a popover or dialog) ✗ Images or media (use a preview card) ✗ Redundant labels ("Save" tooltip on a "Save" button) WRITING GUIDELINES: Length: 1-2 lines, ≈80 characters maximum Case: Sentence case ("Save changes" not "Save Changes") Punctuation: No period for labels, period for sentences Voice: Direct, concise, plain language Tone: Helpful, not condescending EXAMPLES: Good tooltip content: Icon button: "Delete conversation" With shortcut: "Bold (Ctrl+B)" Clarification: "Includes tax and shipping" Truncated text: "Very Long Report Title That Was Truncated..." Status: "Last synced 5 minutes ago" Bad tooltip content: Too long: "This button will delete the selected conversation and all messages within it. This action cannot be undone. Please make sure you have backed up any important..." Redundant: Button text "Save" + tooltip "Save" (useless) Too vague: "Click here" Technical jargon: "Executes the PATCH /api/v2/resource endpoint" RICH TOOLTIPS (use sparingly): Some design systems support "rich" tooltips with: - Title + description - Small images/illustrations - "Learn more" link (opens new page) These blur the line with popovers If content needs interaction → use popover instead LOCALIZATION: Tooltip text may expand 30-50% in translation German, French often longer than English Right-to-left languages (Arabic, Hebrew) → flip placement Test with longest language strings EOF } cmd_css() { cat << 'EOF' === CSS Implementation === BASIC TOOLTIP: .tooltip-trigger { position: relative; } .tooltip { position: absolute; bottom: calc(100% + 8px); /* 8px gap above trigger */ left: 50%; transform: translateX(-50%); padding: 6px 12px; background: #1a1a1a; color: #ffffff; font-size: 13px; line-height: 1.4; border-radius: 6px; white-space: nowrap; pointer-events: none; z-index: 1000; opacity: 0; visibility: hidden; transition: opacity 0.15s ease, visibility 0.15s ease; } .tooltip-trigger:hover .tooltip, .tooltip-trigger:focus-within .tooltip { opacity: 1; visibility: visible; } ARROW (CSS triangle): .tooltip::after { content: ''; position: absolute; top: 100%; left: 50%; transform: translateX(-50%); border: 6px solid transparent; border-top-color: #1a1a1a; } /* Arrow for bottom placement */ .tooltip--bottom::after { top: auto; bottom: 100%; border-top-color: transparent; border-bottom-color: #1a1a1a; } ANIMATIONS: /* Fade + slide */ .tooltip--animated { opacity: 0; transform: translateX(-50%) translateY(4px); transition: opacity 0.15s ease, transform 0.15s ease, visibility 0.15s ease; } .tooltip-trigger:hover .tooltip--animated { opacity: 1; transform: translateX(-50%) translateY(0); } /* Fade + scale */ .tooltip--scale { opacity: 0; transform: translateX(-50%) scale(0.95); transform-origin: bottom center; } SHOW DELAY WITH CSS: .tooltip { transition-delay: 0.3s; /* 300ms show delay */ } .tooltip-trigger:hover .tooltip { transition-delay: 0s; /* No delay on hide */ } /* Note: CSS-only delay is limited — JS gives more control for grace periods and group warming behavior */ LIGHT THEME VARIANT: .tooltip--light { background: #ffffff; color: #1a1a1a; box-shadow: 0 2px 8px rgba(0,0,0,0.15); border: 1px solid #e5e7eb; } .tooltip--light::after { border-top-color: #ffffff; /* Shadow on arrow requires clip-path or SVG arrow */ } MAX WIDTH FOR WRAPPING: .tooltip--multiline { white-space: normal; max-width: 250px; text-align: left; } PORTAL/TELEPORT APPROACH: For complex apps, render tooltip in <body> (not near trigger): - Avoids overflow: hidden clipping - Avoids stacking context issues - Use position: fixed + JavaScript positioning - Libraries: Floating UI, Tippy.js, Radix Tooltip EOF } cmd_checklist() { cat << 'EOF' === Tooltip Design & Implementation Checklist === CONTENT: [ ] Text is brief (≤80 characters, 1-2 lines) [ ] Content is supplementary, not essential [ ] Not redundant with visible label [ ] Keyboard shortcuts included where applicable [ ] No interactive elements in tooltip (use popover instead) [ ] Localization-safe (tested with longer translations) BEHAVIOR: [ ] Show delay of 300-500ms on hover [ ] Hide delay of 100-200ms (grace period) [ ] Appears immediately on focus (no delay) [ ] Dismissed by Escape key [ ] Dismissed on scroll (position becomes stale) [ ] Persists while cursor is over tooltip itself [ ] Group warming: instant show after recent tooltip POSITIONING: [ ] Default placement defined (top recommended) [ ] Collision detection (flip when near viewport edge) [ ] Shift when near viewport edge on cross-axis [ ] Gap between tooltip and trigger (6-8px) [ ] Arrow points accurately at trigger [ ] Doesn't obscure the trigger element itself [ ] Works in scrollable containers ACCESSIBILITY: [ ] Trigger is focusable (button, link, or tabindex="0") [ ] role="tooltip" on overlay element [ ] aria-describedby OR aria-labelledby on trigger [ ] Visible on keyboard focus (not just mouse hover) [ ] Escape key dismisses without other side effects [ ] Touch alternative exists (tap, label, or inline) [ ] Color contrast ≥ 4.5:1 for tooltip text [ ] Not the only source of important information VISUAL: [ ] Consistent style across application [ ] Arrow present and rotates with placement [ ] Animation is subtle and fast (150-200ms) [ ] Z-index appropriate (above content, below modals) [ ] Dark and light theme support [ ] Maximum width set for long content (250-300px) TECHNICAL: [ ] Works in portaled/teleported rendering [ ] No overflow clipping from parent containers [ ] Cleaned up on trigger unmount (no orphan tooltips) [ ] Performance: no layout thrashing during positioning [ ] Mobile: graceful degradation (no hover on touch) EOF } show_help() { cat << EOF tooltip v$VERSION — Tooltip UI Component Reference Usage: script.sh <command> Commands: intro Tooltip overview, types, when to use vs alternatives anatomy Trigger, content, arrow, timing, animation positioning Placement, collision detection, flip/shift, libraries accessibility ARIA patterns, keyboard, screen readers, touch triggers Hover, focus, click, long-press, combined patterns content What belongs in tooltips, writing guidelines css CSS positioning, arrow, animations, theming checklist Tooltip design and implementation checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; anatomy) cmd_anatomy ;; positioning) cmd_positioning ;; accessibility) cmd_accessibility ;; triggers) cmd_triggers ;; content) cmd_content ;; css) cmd_css ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "tooltip v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Just-In-Time production reference — pull systems, kanban, takt time, inventory reduction. Use when implementing JIT manufacturing, designing pull-based workf...
--- name: "jit" version: "1.0.0" description: "Just-In-Time production reference — pull systems, kanban, takt time, inventory reduction. Use when implementing JIT manufacturing, designing pull-based workflows, or reducing inventory waste." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [jit, just-in-time, kanban, pull-system, takt-time, inventory, manufacturing] category: "industrial" --- # JIT — Just-In-Time Production Reference Quick-reference skill for Just-In-Time manufacturing principles, pull systems, and inventory optimization. ## When to Use - Implementing pull-based production systems - Calculating takt time and balancing production lines - Setting up kanban card systems and supermarkets - Reducing work-in-process inventory levels - Transitioning from push (MRP) to pull scheduling ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of JIT — origins in Toyota Production System, core principles, push vs pull. ### `pillars` ```bash scripts/script.sh pillars ``` The foundational pillars of JIT: continuous flow, takt time, pull system, zero inventory target. ### `kanban` ```bash scripts/script.sh kanban ``` Kanban card systems — types, sizing formulas, rules, two-bin and multi-bin setups. ### `takt` ```bash scripts/script.sh takt ``` Takt time calculation, line balancing, and cycle time alignment. ### `leveling` ```bash scripts/script.sh leveling ``` Heijunka (production leveling) — smoothing volume and product mix, heijunka box. ### `suppliers` ```bash scripts/script.sh suppliers ``` JIT supplier relationships — milk runs, frequent deliveries, supplier development. ### `barriers` ```bash scripts/script.sh barriers ``` Common JIT implementation barriers and countermeasures. ### `checklist` ```bash scripts/script.sh checklist ``` JIT readiness assessment checklist for evaluating current state. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # jit — Just-In-Time Production Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Just-In-Time (JIT) Production === Just-In-Time is a production strategy that produces only what is needed, when it is needed, in the quantity needed. Developed as part of the Toyota Production System by Taiichi Ohno in the 1950s-70s. Core Idea: "Making only what is needed, only when it is needed, only in the amount that is needed." Push vs Pull: Push (Traditional/MRP) Pull (JIT) ───────────────────── ────────── Forecast-driven Demand-driven Large batches Small batches / one-piece flow High inventory buffers Minimal inventory Long lead times Short lead times Defects hidden in inventory Defects exposed immediately Key Principles: 1. Eliminate waste (muda) — especially inventory and overproduction 2. Continuous flow — move parts one at a time between operations 3. Pull system — downstream processes signal upstream when to produce 4. Takt time — synchronize production pace with customer demand 5. Zero defects — quality at the source, stop and fix immediately 6. Respect for people — empower workers to stop the line Prerequisites for JIT: - Stable, predictable demand (or leveled production) - Reliable equipment (TPM — Total Productive Maintenance) - Quick changeovers (SMED) - Quality at source (Jidoka) - Disciplined suppliers - Cross-trained workforce EOF } cmd_pillars() { cat << 'EOF' === JIT Pillars === 1. CONTINUOUS FLOW (One-Piece Flow) Process one unit at a time through all operations without stopping. Benefits: - Immediate defect detection (only 1 unit at risk) - Dramatic lead time reduction - Minimal WIP inventory Implementation: - Arrange equipment in process sequence (cells) - U-shaped cells allow flexibility in staffing - Eliminate batch-and-queue between operations 2. TAKT TIME SYNCHRONIZATION Takt Time = Available Production Time / Customer Demand Every workstation completes its task within one takt beat. If cycle time > takt → bottleneck, need to rebalance If cycle time << takt → over-capacity, reduce resources 3. PULL SYSTEM Nothing is produced until the downstream customer signals need. Types of pull: a. Replenishment pull (supermarket) — replace what was consumed b. Sequential pull — produce in sequence of customer orders c. Mixed — supermarket for high-volume, sequential for specials Signal methods: kanban cards, empty bins, electronic signals 4. ZERO INVENTORY TARGET Inventory is waste — it hides problems: - Defects (found only when batch is consumed) - Machine breakdowns (buffer masks downtime) - Long setups (large batches to amortize changeover) - Supplier unreliability (safety stock compensates) JIT systematically lowers inventory to expose and solve problems. Analogy: "Lowering the water level to reveal the rocks" 5. JIDOKA (Built-In Quality) Machines and operators detect abnormalities and stop immediately. No defective part ever moves to the next process. Four steps: Detect → Stop → Fix → Prevent recurrence EOF } cmd_kanban() { cat << 'EOF' === Kanban Systems === Kanban = "signboard" in Japanese. Visual signal to trigger production or movement of materials. Types of Kanban: Production Kanban — authorizes a process to produce a quantity Withdrawal Kanban — authorizes movement from supermarket to process Signal Kanban — used for batch processes (e.g., stamping) Supplier Kanban — signals external supplier to deliver Kanban Card Information: - Part number and description - Quantity per container - Supplying process / location - Consuming process / location - Number of cards in the loop Kanban Quantity Formula: N = (D × L × (1 + S)) / C Where: N = number of kanban cards D = average demand per period L = lead time (in same units as D) S = safety factor (0.0 to 0.5 typically) C = container quantity Example: Demand = 100 units/day, Lead time = 0.5 day Safety = 10%, Container = 25 units N = (100 × 0.5 × 1.1) / 25 = 2.2 → 3 kanbans Two-Bin System (simplest kanban): - Two containers of parts at point of use - Use from Bin A until empty - Empty bin = signal to replenish - Switch to Bin B while A is refilled Six Rules of Kanban (Ohno): 1. Downstream pulls from upstream 2. Upstream produces only what is withdrawn 3. No defective parts sent downstream 4. Number of kanbans should be minimized 5. Kanban smooths small demand fluctuations 6. Process must be stabilized and rationalized EOF } cmd_takt() { cat << 'EOF' === Takt Time & Line Balancing === TAKT TIME CALCULATION: Takt = Available Time / Customer Demand Example: Shift: 8 hours = 480 minutes Breaks: 2 × 10 min = 20 minutes Available: 460 minutes = 27,600 seconds Demand: 460 units/shift Takt = 27,600 / 460 = 60 seconds per unit IMPORTANT DISTINCTIONS: Takt Time = pace set by customer demand (external) Cycle Time = actual time to complete one unit (internal) Lead Time = total time from order to delivery (end-to-end) CT must be ≤ Takt for the line to meet demand Planned CT = Takt × OEE factor (e.g., 60 × 0.85 = 51 sec target) LINE BALANCING: Goal: distribute work equally across stations to match takt Steps: 1. List all work elements and their times 2. Determine takt time 3. Calculate minimum stations: Σ element times / takt 4. Assign elements to stations (keep each ≤ takt) 5. Balance efficiency = Σ element times / (stations × takt) Example: Total work content: 240 seconds Takt: 60 seconds Min stations: 240 / 60 = 4 stations Assign tasks so each station is close to 60 sec Balance efficiency = 240 / (4 × 60) = 100% (ideal) Common issues: - Indivisible elements > takt → need parallel stations - Precedence constraints limit assignment flexibility - Cycle-to-cycle variation → need buffer capacity EOF } cmd_leveling() { cat << 'EOF' === Heijunka (Production Leveling) === Problem without leveling: Customer orders fluctuate → production swings wildly Mon: 100A, 0B, 0C Tue: 0A, 200B, 0C Wed: 0A, 0B, 150C → Equipment overloaded one day, idle the next → Inventory surges for some products, shortages for others Heijunka Solution: Level both VOLUME and MIX across the day. Instead of: AAAA AAAA BBBB BBBB CCCC Produce: ABCA BCAB CABC ABCA BCAB Two levels of leveling: Level 1 — Volume leveling: smooth total daily output Level 2 — Mix leveling: produce every product every day (EPEI=1) EPEI (Every Product Every Interval): How often you can produce every part number EPEI = 1 day → produce every part daily (ideal for JIT) EPEI = 5 days → produce each part once a week (poor) Reducing EPEI requires fast changeovers (SMED) Heijunka Box: Physical scheduling device — grid of time slots and products Columns = time intervals (e.g., every 10 minutes) Rows = product types Kanban cards placed in slots = production sequence | Time | A | B | C | |-------|-----|-----|-----| | 8:00 | [k] | | | | 8:10 | | [k] | | | 8:20 | [k] | | | | 8:30 | | | [k] | Benefits of Leveling: - Stable demand on upstream processes and suppliers - Smaller finished goods inventory - More predictable resource needs - Better customer responsiveness EOF } cmd_suppliers() { cat << 'EOF' === JIT Supplier Relationships === Traditional vs JIT Supplier Model: Traditional JIT ─────────── ─── Many suppliers per part Few (often single source) Lowest price wins Total cost focus Large infrequent deliveries Small frequent deliveries Incoming inspection Certified quality at source Adversarial negotiation Long-term partnership Short-term contracts Multi-year agreements JIT Delivery Strategies: Milk Run: One truck picks up from multiple suppliers in a circuit. Supplier A → B → C → Factory → repeat Benefits: full truckloads despite small quantities per supplier Cross-Dock: Suppliers deliver to consolidation point Parts sorted and shipped to factory same day No warehousing — just transfer between trucks Supplier Parks: Suppliers locate facilities adjacent to the assembly plant Delivery frequency: multiple times per day or per hour Example: Toyota Georgetown has supplier park across the street Requirements for JIT Suppliers: 1. Consistent quality (Cpk > 1.33, certified process) 2. On-time delivery (>99%) 3. Flexibility in volume (±20% without lead time change) 4. Small lot capability 5. Transparent communication (share forecasts, problems) 6. Continuous improvement commitment JIT Supply Chain Risks: - Single source dependency → mitigate with dual sourcing for critical parts - Transportation disruptions → safety stock for long-distance suppliers - Natural disasters → regional diversification - Quality escapes → containment plans, rapid response agreements EOF } cmd_barriers() { cat << 'EOF' === JIT Implementation Barriers & Countermeasures === Barrier 1: Unreliable Equipment Symptom: Machines break down, causing line stoppages Countermeasure: Total Productive Maintenance (TPM) - Autonomous maintenance by operators - Planned preventive maintenance schedules - Target: OEE > 85%, zero breakdowns Barrier 2: Long Changeover Times Symptom: Large batches to amortize setup costs Countermeasure: SMED (Single-Minute Exchange of Die) - Separate internal vs external setup - Convert internal to external - Streamline all steps → target < 10 minutes Barrier 3: Poor Quality Symptom: Defects require rework, scrap, and buffer stock Countermeasure: Jidoka + Poka-Yoke - Build quality in at the source - Error-proof processes - Stop and fix immediately, never pass defects Barrier 4: Unstable Demand Symptom: Wild swings in customer orders Countermeasure: Heijunka (production leveling) - Level volume and mix - Use finished goods buffer (supermarket) to absorb variation - Negotiate stable order patterns with customers Barrier 5: Supplier Unreliability Symptom: Late deliveries, quality issues from vendors Countermeasure: Supplier development program - Reduce supplier base, build partnerships - Help suppliers implement their own lean/JIT - Certify supplier quality, eliminate incoming inspection Barrier 6: Cultural Resistance Symptom: "We've always done it this way" Countermeasure: Leadership commitment + quick wins - Start with a pilot cell/line - Show measurable results (lead time, inventory, quality) - Train everyone in lean fundamentals - Celebrate successes publicly Barrier 7: Lack of Cross-Training Symptom: Operators can only run one machine/process Countermeasure: Skills matrix + rotation plan - Map skills needed vs skills available - Systematic training and rotation - Target: every operator qualified on 3+ stations EOF } cmd_checklist() { cat << 'EOF' === JIT Readiness Checklist === Equipment Reliability: [ ] OEE tracked for all critical equipment [ ] Preventive maintenance schedules in place [ ] Autonomous maintenance practiced by operators [ ] Breakdown frequency < 1 per week per machine [ ] Spare parts strategy defined (critical spares stocked) Changeover Capability: [ ] Changeover times measured and recorded [ ] SMED projects completed on bottleneck equipment [ ] Target changeover times set (< 10 minutes) [ ] Changeover procedures standardized and documented [ ] Operators trained on quick changeover techniques Quality Systems: [ ] Process capability studies done (Cpk > 1.33) [ ] Error-proofing (poka-yoke) devices installed [ ] Operators empowered to stop line for defects [ ] Root cause analysis practiced for every defect [ ] Scrap and rework rates below target Pull System Readiness: [ ] Takt time calculated for each product family [ ] Kanban quantities determined (formula-based) [ ] Supermarket locations defined [ ] Visual signals designed (cards, bins, electronic) [ ] Pull system rules documented and trained Supplier Readiness: [ ] Key suppliers identified and evaluated [ ] Delivery frequency increased (weekly → daily) [ ] Supplier quality certified (no incoming inspection) [ ] Communication systems established (EDI, kanban) [ ] Contingency plans for supply disruptions Workforce Readiness: [ ] Cross-training matrix shows multi-skill coverage [ ] Standard work documented for all operations [ ] Team leaders trained in lean/JIT principles [ ] Problem-solving skills taught (A3, 5-Why, fishbone) [ ] Suggestion system active for improvement ideas EOF } show_help() { cat << EOF jit v$VERSION — Just-In-Time Production Reference Usage: script.sh <command> Commands: intro JIT origins, push vs pull, core principles pillars Foundational pillars: flow, takt, pull, zero inventory kanban Kanban card systems, sizing formulas, rules takt Takt time calculation and line balancing leveling Heijunka production leveling and mix smoothing suppliers JIT supplier relationships and delivery strategies barriers Implementation barriers and countermeasures checklist JIT readiness assessment checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; pillars) cmd_pillars ;; kanban) cmd_kanban ;; takt) cmd_takt ;; leveling) cmd_leveling ;; suppliers) cmd_suppliers ;; barriers) cmd_barriers ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "jit v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Kaizen continuous improvement reference — event planning, PDCA cycle, gemba walks, and A3 problem solving. Use when running improvement events, coaching team...
--- name: "kaizen" version: "1.0.0" description: "Kaizen continuous improvement reference — event planning, PDCA cycle, gemba walks, and A3 problem solving. Use when running improvement events, coaching teams on continuous improvement, or documenting process changes." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [kaizen, continuous-improvement, pdca, gemba, lean, industrial] category: "industrial" --- # Kaizen — Continuous Improvement Reference Quick-reference for kaizen events, PDCA cycle, gemba walks, A3 thinking, and daily improvement culture. ## When to Use - Planning and running a kaizen event (rapid improvement) - Coaching teams on PDCA (Plan-Do-Check-Act) - Conducting gemba walks for process observation - Writing A3 problem-solving reports - Building a daily continuous improvement culture ## Commands ### `intro` ```bash scripts/script.sh intro ``` Kaizen philosophy, types, and cultural foundations. ### `event` ```bash scripts/script.sh event ``` Kaizen event planning — preparation, execution, follow-up. ### `pdca` ```bash scripts/script.sh pdca ``` PDCA (Plan-Do-Check-Act) cycle — Deming's improvement framework. ### `gemba` ```bash scripts/script.sh gemba ``` Gemba walks — going to the workplace, observation techniques, respect. ### `a3` ```bash scripts/script.sh a3 ``` A3 problem solving — structured one-page report format. ### `daily` ```bash scripts/script.sh daily ``` Daily kaizen — suggestion systems, huddle boards, small improvements. ### `examples` ```bash scripts/script.sh examples ``` Real-world kaizen event examples and results. ### `checklist` ```bash scripts/script.sh checklist ``` Kaizen event preparation and follow-up checklist. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `KAIZEN_DIR` | Data directory (default: ~/.kaizen/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # kaizen -- Kaizen continuous improvement tracker # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.kaizen" _ensure_dirs() { mkdir -p "$DATA_DIR"; } _save_entry() { _ensure_dirs local cmd="$1" val="$2" local ts=$(date '+%Y-%m-%d %H:%M:%S') printf '{"ts":"%s","cmd":"%s","val":"%s"}\n' "$ts" "$cmd" "$val" >> "$DATA_DIR/data.jsonl" } show_help() { cat << EOF kaizen v$VERSION -- Kaizen continuous improvement tracker Usage: kaizen <command> [args] Commands: status Show current status add Add new entry list List all entries search Search entries remove Remove entry by number export Export data to file stats Show statistics config View or set config help Show this help version Show version Data: $DATA_DIR Powered by BytesAgain | bytesagain.com EOF } cmd_status() { echo "=== kaizen Status ===" echo " Version: $VERSION" echo " Data dir: $DATA_DIR" local entries=$(cat "$DATA_DIR"/*.jsonl 2>/dev/null | wc -l || echo 0) echo " Entries: $entries" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1 || echo empty)" } cmd_add() { local value="?Usage: kaizen add <entry>" shift || true _save_entry "add" "$value $*" local count=$(wc -l < "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Added: $value (entry #$count)" } cmd_list() { echo "=== Kaizen Entries ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local count=$(wc -l < "$DATA_DIR/data.jsonl") echo "Total: $count" echo "---" tail -20 "$DATA_DIR/data.jsonl" | while IFS= read -r line; do local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) local cmd=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo " [$ts] $cmd: $val" done else echo "No entries yet." fi } cmd_search() { local term="?Usage: kaizen search <term>" if [ -f "$DATA_DIR/data.jsonl" ]; then local matches=$(grep -ic "$term" "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Found: $matches matches" grep -i "$term" "$DATA_DIR/data.jsonl" 2>/dev/null | head -20 | while IFS= read -r line; do local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) echo " [$ts] $val" done else echo "No data to search." fi } cmd_remove() { local num="?Usage: kaizen remove <line-number>" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") if [ "$num" -ge 1 ] 2>/dev/null && [ "$num" -le "$total" ] 2>/dev/null; then sed -i "numd" "$DATA_DIR/data.jsonl" echo "Removed #$num ($((total-1)) remaining)" else echo "Invalid: $num (total: $total)"; fi else echo "No data."; fi } cmd_export() { local fmt="-json" local out="kaizen-export.$fmt" if [ ! -f "$DATA_DIR/data.jsonl" ]; then echo "No data."; return 0; fi case "$fmt" in json) cp "$DATA_DIR/data.jsonl" "$out" ;; csv) echo "timestamp,command,value" > "$out" while IFS= read -r line; do ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) c2=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) vl=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo "$ts,$c2,$vl" >> "$out" done < "$DATA_DIR/data.jsonl" ;; *) echo "Formats: json, csv"; return 1 ;; esac echo "Exported: $out ($(wc -c < "$out") bytes)" } cmd_stats() { echo "=== Kaizen Stats ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") local bytes=$(wc -c < "$DATA_DIR/data.jsonl") echo " Entries: $total" echo " Size: $bytes bytes" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" else echo " No data yet."; fi } cmd_config() { local key="-" val="-" local cfg="$DATA_DIR/config.txt" if [ -z "$key" ]; then echo "=== Config ===" if [ -f "$cfg" ]; then while IFS="=" read -r k v; do echo " $k=$v"; done < "$cfg" else echo " (empty — use config <key> <value>)"; fi elif [ -z "$val" ]; then grep "^key=" "$cfg" 2>/dev/null | cut -d= -f2- || echo "(not set)" else if [ -f "$cfg" ] && grep -q "^key=" "$cfg" 2>/dev/null; then sed -i "s|^key=.*|key=val|" "$cfg" else echo "key=val" >> "$cfg" fi echo "Set: $key=$val" fi } CMD="-help" shift 2>/dev/null || true _ensure_dirs case "$CMD" in status) cmd_status "$@" ;; add) cmd_add "$@" ;; list) cmd_list "$@" ;; search) cmd_search "$@" ;; remove) cmd_remove "$@" ;; export) cmd_export "$@" ;; stats) cmd_stats "$@" ;; config) cmd_config "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "kaizen v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: kaizen help"; exit 1 ;; esac
OSHA compliance reference — workplace safety standards, hazard categories, inspection prep, and recordkeeping. Use when reviewing safety regulations, prepari...
--- name: "osha" version: "1.0.0" description: "OSHA compliance reference — workplace safety standards, hazard categories, inspection prep, and recordkeeping. Use when reviewing safety regulations, preparing for audits, or building safety programs." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [osha, safety, compliance, workplace, hazard, inspection] category: "safety" --- # OSHA — Occupational Safety & Health Reference Quick-reference skill for OSHA standards, hazard identification, inspection preparation, and safety program development. ## When to Use - Looking up OSHA standard numbers and requirements - Preparing for an OSHA inspection or audit - Identifying workplace hazards and controls - Setting up injury/illness recordkeeping (300 logs) - Building a safety training program ## Commands ### `intro` ```bash scripts/script.sh intro ``` OSHA overview — mission, structure, employer rights and responsibilities. ### `standards` ```bash scripts/script.sh standards ``` Key OSHA standards by number — General Industry (29 CFR 1910) and Construction (29 CFR 1926). ### `hazards` ```bash scripts/script.sh hazards ``` Top 10 OSHA violations and common workplace hazard categories. ### `hierarchy` ```bash scripts/script.sh hierarchy ``` Hierarchy of controls — elimination, substitution, engineering, administrative, PPE. ### `inspection` ```bash scripts/script.sh inspection ``` OSHA inspection process — what triggers inspections, employer rights, how to prepare. ### `records` ```bash scripts/script.sh records ``` OSHA recordkeeping — 300/300A/301 forms, what's recordable, posting requirements. ### `training` ```bash scripts/script.sh training ``` Required OSHA training topics by industry and role. ### `checklist` ```bash scripts/script.sh checklist ``` Workplace safety assessment checklist. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `OSHA_DIR` | Data directory (default: ~/.osha/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # osha — OSHA Compliance Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === OSHA — Occupational Safety and Health Administration === Mission: Ensure safe and healthful working conditions by setting and enforcing standards and providing training, outreach, education, and assistance. Established: 1970 (Occupational Safety and Health Act, signed by Nixon) Part of: U.S. Department of Labor Covers: Most private sector employers and workers in all 50 states Employer Responsibilities: - Provide a workplace free from recognized hazards (General Duty Clause) - Comply with all applicable OSHA standards - Inform employees about chemical hazards (HazCom/GHS) - Provide required PPE at no cost to employees - Keep records of injuries and illnesses (if 10+ employees) - Post OSHA 300A summary (Feb 1 – Apr 30 annually) - Display "Job Safety and Health" poster (OSHA 3165) - Not retaliate against employees who report hazards Employee Rights: - File a complaint with OSHA (anonymously if desired) - Request an OSHA inspection - Access exposure and medical records - Refuse dangerous work (if imminent danger, good faith belief) - Participate in inspections (employee representative) - Receive training in a language they understand - Whistleblower protection (Section 11(c)) Penalties (2024 rates, adjusted annually): Other-Than-Serious Up to $16,131 per violation Serious $1,116 – $16,131 per violation Willful $11,162 – $161,323 per violation Repeat $11,162 – $161,323 per violation Failure to Abate $16,131 per day beyond abatement date EOF } cmd_standards() { cat << 'EOF' === Key OSHA Standards === General Industry (29 CFR 1910): 1910.23 Walking-Working Surfaces (fall protection) 1910.95 Occupational Noise Exposure (85 dBA TWA) 1910.132 PPE General Requirements 1910.134 Respiratory Protection 1910.146 Permit-Required Confined Spaces 1910.147 Lockout/Tagout (LOTO) 1910.178 Powered Industrial Trucks (forklifts) 1910.212 Machine Guarding 1910.303 Electrical — General Requirements 1910.1200 Hazard Communication (HazCom/GHS) Construction (29 CFR 1926): 1926.451 Scaffolding 1926.501 Fall Protection (6-foot trigger) 1926.502 Fall Protection Systems Criteria 1926.503 Fall Protection Training 1926.1052 Stairways 1926.1053 Ladders 1926.1101 Asbestos 1926.62 Lead General Duty Clause (Section 5(a)(1)): "Each employer shall furnish a place of employment which is free from recognized hazards that are causing or likely to cause death or serious physical harm to employees." Used when no specific standard covers the hazard. Recordkeeping (29 CFR 1904): 1904.4 Recording criteria 1904.5 Work-relatedness determination 1904.7 General recording criteria for cases 1904.29 Forms (300, 300A, 301) 1904.32 Annual summary posting EOF } cmd_hazards() { cat << 'EOF' === Top 10 OSHA Violations (Fiscal Year 2023) === 1. Fall Protection — General (1926.501) 7,271 citations 2. Hazard Communication (1910.1200) 3,213 3. Ladders (1926.1053) 2,978 4. Scaffolding (1926.451) 2,859 5. Powered Industrial Trucks (1910.178) 2,561 6. Lockout/Tagout (1910.147) 2,554 7. Respiratory Protection (1910.134) 2,481 8. Fall Protection — Training (1926.503) 2,112 9. Eye and Face Protection (1926.102) 2,074 10. Machine Guarding (1910.212) 1,644 Hazard Categories: Physical Noise, vibration, radiation, temperature extremes Chemical Toxic substances, fumes, dust, solvents Biological Bloodborne pathogens, mold, bacteria Ergonomic Repetitive motion, awkward postures, heavy lifting Electrical Exposed wiring, no GFCI, improper grounding Fall Unguarded edges, ladders, scaffolds, floor openings Fatal Four (Construction): Falls 38.7% of construction fatalities Struck-by 9.4% Electrocution 7.2% Caught-in 5.4% These four = 60.7% of all construction worker deaths EOF } cmd_hierarchy() { cat << 'EOF' === Hierarchy of Controls === Most effective → Least effective: 1. ELIMINATION Remove the hazard entirely Example: redesign process to eliminate heights Best solution — no hazard = no risk 2. SUBSTITUTION Replace the hazard with something less dangerous Example: use water-based paint instead of solvent-based Consider: is the substitute truly less hazardous? 3. ENGINEERING CONTROLS Isolate people from the hazard Examples: - Machine guards and interlocks - Ventilation systems (LEV) - Noise enclosures - Guardrails and fall arrest anchors - Circuit breakers and GFCI Preferred over admin/PPE because they don't rely on behavior 4. ADMINISTRATIVE CONTROLS Change the way people work Examples: - Job rotation (reduce exposure time) - Warning signs and labels - Standard operating procedures - Training programs - Buddy system for confined spaces Less reliable — depend on human compliance 5. PPE (Personal Protective Equipment) Last resort — protect the individual worker Examples: - Hard hats, safety glasses, gloves - Respirators, hearing protection - Fall harness and lanyard - Steel-toe boots, face shields Limitations: must fit properly, be maintained, and be worn Employer must provide at no cost (except safety-toe shoes and prescription safety glasses in some cases) EOF } cmd_inspection() { cat << 'EOF' === OSHA Inspection Process === What Triggers an Inspection (priority order): 1. Imminent danger situations 2. Fatalities and catastrophes (≥3 hospitalizations) 3. Worker complaints and referrals 4. Programmed inspections (targeted industries) 5. Follow-up inspections The Inspection Steps: 1. Credentials - OSHA inspector (CSHO) presents credentials - Verify: federal photo ID + OSHA badge - You CAN verify by calling OSHA area office 2. Opening Conference - Inspector explains reason for visit - Request employee representative to participate - Ask for scope: full inspection or partial? 3. Walkaround - Inspector examines workplace for hazards - May take photos, samples, measurements - May interview employees (privately) - Employer representative can accompany 4. Closing Conference - Inspector discusses findings - Possible violations and citations discussed - You will receive citations by mail (not on-site) Employer Rights During Inspection: - Request a warrant (4th Amendment — inspector needs probable cause) - Accompany inspector during walkaround - Take notes and photos alongside inspector - Know the scope and reason for inspection - Contest citations within 15 working days Preparation Checklist: [ ] OSHA poster displayed [ ] 300A log posted (if in posting period) [ ] Safety programs documented and current [ ] Training records accessible [ ] SDS sheets organized and accessible [ ] PPE records (fit tests, assignments) [ ] Emergency action plan posted EOF } cmd_records() { cat << 'EOF' === OSHA Recordkeeping === Who Must Keep Records: Employers with 11+ employees (at any time during the year) Some industries exempt even with 11+ (low-hazard retail, finance) ALL employers must report fatalities and severe injuries The Three Forms: OSHA 300 — Log of Work-Related Injuries and Illnesses One line per recordable case Columns: employee name, date, description, classification Keep for 5 years after the year of occurrence OSHA 300A — Summary of Work-Related Injuries and Illnesses Annual summary of the 300 Log Must post Feb 1 – Apr 30 in visible location Signed by company executive (certifying accuracy) OSHA 301 — Injury and Illness Incident Report Detailed report for each recordable case Must be completed within 7 calendar days Workers' comp first report of injury can substitute What's Recordable: A work-related injury or illness that results in: - Death - Days away from work - Restricted work or job transfer - Medical treatment beyond first aid - Loss of consciousness - Significant injury/illness diagnosed by physician - Needlestick or sharps injury (with contamination) - Hearing loss (STS of 10 dB avg in either ear) First Aid (NOT recordable): - Bandages, butterfly closures, Steri-Strips - Non-prescription meds at nonprescription strength - Cleaning and flushing wounds - Hot/cold therapy - Finger guards, elastic bandages, wraps - Drinking fluids for heat stress Electronic Reporting (since 2017): Establishments 250+ employees: submit 300A annually via ITA portal Establishments 20-249 in certain industries: submit 300A annually Deadline: March 2 each year EOF } cmd_training() { cat << 'EOF' === Required OSHA Training === All Industries: - Hazard Communication / GHS (1910.1200) Chemical hazards, SDS reading, labeling, pictograms - Emergency Action Plan (1910.38) Evacuation routes, alarm systems, assembly points - Fire Prevention Plan (1910.39) Fire hazards, proper storage, extinguisher locations - PPE (1910.132) When required, how to use, limitations, maintenance - Bloodborne Pathogens (1910.1030) — if exposure risk Universal precautions, cleanup procedures, post-exposure Manufacturing / Industrial: - Lockout/Tagout (1910.147) Authorized vs affected employees, procedures, audit - Machine Guarding (1910.212) Types of guards, bypass prevention, inspection - Confined Space Entry (1910.146) Permit system, atmospheric testing, rescue plan - Forklift Operation (1910.178) Formal training + practical evaluation every 3 years - Hearing Conservation (1910.95) If exposed ≥85 dBA TWA — audiometric testing, HPD fit Construction: - Fall Protection (1926.503) Hazard recognition, equipment use, rescue - Scaffolding (1926.454) Competent person training, inspection - Excavation/Trenching (1926.651) Soil classification, protective systems - Crane Operation (1926.1427) Certified operator required Training Must Be: - In a language employees understand - Documented (date, topic, trainer, attendees) - Repeated when hazards change or new employees join - Refreshed periodically (check specific standard) EOF } cmd_checklist() { cat << 'EOF' === Workplace Safety Assessment Checklist === General: [ ] OSHA poster (3165) displayed in prominent location [ ] Emergency exits marked and unobstructed [ ] Emergency action plan documented and communicated [ ] First aid kits stocked and accessible [ ] Fire extinguishers inspected monthly, serviced annually [ ] Eyewash/shower stations tested weekly (if chemicals) Hazard Communication: [ ] Written HazCom program current [ ] Safety Data Sheets accessible for all chemicals [ ] Chemical containers properly labeled (GHS) [ ] Employees trained on chemicals they work with [ ] Chemical inventory list maintained Walking/Working Surfaces: [ ] Floors clean, dry, and free of tripping hazards [ ] Guardrails on open-sided platforms > 4 feet [ ] Ladders inspected and rated for intended use [ ] Stairways have handrails Electrical: [ ] No frayed cords or exposed wiring [ ] GFCI protection in wet locations [ ] Electrical panels accessible (36" clearance) [ ] Breakers labeled [ ] Junction boxes covered Machine Safety: [ ] Point of operation guards in place [ ] Emergency stops accessible and functional [ ] LOTO procedures written for each machine [ ] LOTO annual audit completed [ ] Machine operators trained on specific equipment PPE: [ ] Hazard assessment documented [ ] Appropriate PPE provided at no cost [ ] Employees trained on proper use [ ] Respirator fit testing current (annual) [ ] PPE condition inspected regularly Recordkeeping: [ ] OSHA 300 log current [ ] 300A summary posted (Feb 1 – Apr 30) [ ] Training records maintained [ ] Incident investigations completed and documented [ ] Records retained for required period (5 years) EOF } show_help() { cat << EOF osha v$VERSION — OSHA Compliance Reference Usage: script.sh <command> Commands: intro OSHA overview, employer duties, employee rights standards Key OSHA standards by number (1910/1926) hazards Top 10 violations and hazard categories hierarchy Hierarchy of controls (elimination → PPE) inspection Inspection process and employer rights records Recordkeeping: 300/300A/301 forms training Required training topics by industry checklist Workplace safety assessment checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; standards) cmd_standards ;; hazards) cmd_hazards ;; hierarchy) cmd_hierarchy ;; inspection) cmd_inspection ;; records) cmd_records ;; training) cmd_training ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "osha v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Automated guided vehicle route planner. Use when json agv tasks, csv agv tasks, checking agv status.
--- name: "agv" version: "1.0.0" description: "Automated guided vehicle route planner. Use when json agv tasks, csv agv tasks, checking agv status." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [agv, industrial, cli, tool] category: "industrial" --- # agv Automated guided vehicle route planner. Use when json agv tasks, csv agv tasks, checking agv status. ## Commands ### `status` ```bash scripts/script.sh status ``` Show current status ### `add` ```bash scripts/script.sh add ``` Add new entry ### `list` ```bash scripts/script.sh list ``` List all entries ### `search` ```bash scripts/script.sh search ``` Search entries ### `remove` ```bash scripts/script.sh remove ``` Remove entry by number ### `export` ```bash scripts/script.sh export ``` Export data to file ### `stats` ```bash scripts/script.sh stats ``` Show statistics ### `config` ```bash scripts/script.sh config ``` View or set config ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration Use `scripts/script.sh config <key> <value>` to set preferences. | Variable | Description | |----------|-------------| | `AGV_DIR` | Data directory (default: ~/.agv/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # agv -- Automated guided vehicle route planner # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.agv" _ensure_dirs() { mkdir -p "$DATA_DIR"; } _save_entry() { _ensure_dirs local cmd="$1" val="$2" local ts=$(date '+%Y-%m-%d %H:%M:%S') printf '{"ts":"%s","cmd":"%s","val":"%s"}\n' "$ts" "$cmd" "$val" >> "$DATA_DIR/data.jsonl" } show_help() { cat << EOF agv v$VERSION -- Automated guided vehicle route planner Usage: agv <command> [args] Commands: status Show current status add Add new entry list List all entries search Search entries remove Remove entry by number export Export data to file stats Show statistics config View or set config help Show this help version Show version Data: $DATA_DIR Powered by BytesAgain | bytesagain.com EOF } cmd_status() { echo "=== agv Status ===" echo " Version: $VERSION" echo " Data dir: $DATA_DIR" local entries=$(cat "$DATA_DIR"/*.jsonl 2>/dev/null | wc -l || echo 0) echo " Entries: $entries" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1 || echo empty)" } cmd_add() { local value="?Usage: agv add <entry>" shift || true _save_entry "add" "$value $*" local count=$(wc -l < "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Added: $value (entry #$count)" } cmd_list() { echo "=== Agv Entries ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local count=$(wc -l < "$DATA_DIR/data.jsonl") echo "Total: $count" echo "---" tail -20 "$DATA_DIR/data.jsonl" | while IFS= read -r line; do local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) local cmd=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo " [$ts] $cmd: $val" done else echo "No entries yet." fi } cmd_search() { local term="?Usage: agv search <term>" if [ -f "$DATA_DIR/data.jsonl" ]; then local matches=$(grep -ic "$term" "$DATA_DIR/data.jsonl" 2>/dev/null || echo 0) echo "Found: $matches matches" grep -i "$term" "$DATA_DIR/data.jsonl" 2>/dev/null | head -20 | while IFS= read -r line; do local val=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) local ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) echo " [$ts] $val" done else echo "No data to search." fi } cmd_remove() { local num="?Usage: agv remove <line-number>" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") if [ "$num" -ge 1 ] 2>/dev/null && [ "$num" -le "$total" ] 2>/dev/null; then sed -i "numd" "$DATA_DIR/data.jsonl" echo "Removed #$num ($((total-1)) remaining)" else echo "Invalid: $num (total: $total)"; fi else echo "No data."; fi } cmd_export() { local fmt="-json" local out="agv-export.$fmt" if [ ! -f "$DATA_DIR/data.jsonl" ]; then echo "No data."; return 0; fi case "$fmt" in json) cp "$DATA_DIR/data.jsonl" "$out" ;; csv) echo "timestamp,command,value" > "$out" while IFS= read -r line; do ts=$(echo "$line" | grep -o '"ts":"[^"]*' | cut -d'"' -f4) c2=$(echo "$line" | grep -o '"cmd":"[^"]*' | cut -d'"' -f4) vl=$(echo "$line" | grep -o '"val":"[^"]*' | cut -d'"' -f4) echo "$ts,$c2,$vl" >> "$out" done < "$DATA_DIR/data.jsonl" ;; *) echo "Formats: json, csv"; return 1 ;; esac echo "Exported: $out ($(wc -c < "$out") bytes)" } cmd_stats() { echo "=== Agv Stats ===" if [ -f "$DATA_DIR/data.jsonl" ]; then local total=$(wc -l < "$DATA_DIR/data.jsonl") local bytes=$(wc -c < "$DATA_DIR/data.jsonl") echo " Entries: $total" echo " Size: $bytes bytes" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" else echo " No data yet."; fi } cmd_config() { local key="-" val="-" local cfg="$DATA_DIR/config.txt" if [ -z "$key" ]; then echo "=== Config ===" if [ -f "$cfg" ]; then while IFS="=" read -r k v; do echo " $k=$v"; done < "$cfg" else echo " (empty — use config <key> <value>)"; fi elif [ -z "$val" ]; then grep "^key=" "$cfg" 2>/dev/null | cut -d= -f2- || echo "(not set)" else if [ -f "$cfg" ] && grep -q "^key=" "$cfg" 2>/dev/null; then sed -i "s|^key=.*|key=val|" "$cfg" else echo "key=val" >> "$cfg" fi echo "Set: $key=$val" fi } CMD="-help" shift 2>/dev/null || true _ensure_dirs case "$CMD" in status) cmd_status "$@" ;; add) cmd_add "$@" ;; list) cmd_list "$@" ;; search) cmd_search "$@" ;; remove) cmd_remove "$@" ;; export) cmd_export "$@" ;; stats) cmd_stats "$@" ;; config) cmd_config "$@" ;; help|--help|-h) show_help ;; version|--version|-v) echo "agv v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: agv help"; exit 1 ;; esac