@clawhub-bytesagain3-5bff6becb8
Grain threshing reference — threshing methods, combine harvester operation, crop-specific settings, grain loss reduction, and post-harvest handling. Use when...
--- name: "thresh" version: "1.0.0" description: "Grain threshing reference — threshing methods, combine harvester operation, crop-specific settings, grain loss reduction, and post-harvest handling. Use when planning harvest operations, optimizing combine settings, or reducing grain loss." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [thresh, threshing, harvest, grain, combine, agriculture, post-harvest] category: "agriculture" --- # Thresh — Grain Threshing Reference Quick-reference skill for threshing principles, combine harvester settings, and grain loss management. ## When to Use - Understanding threshing mechanisms and methods - Setting combine harvester parameters for specific crops - Reducing grain loss during harvest - Planning harvest timing and operations - Post-harvest grain handling and drying ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of threshing — history, principles, and modern methods. ### `mechanisms` ```bash scripts/script.sh mechanisms ``` Threshing mechanisms — cylinder types, concave settings, rotor systems. ### `crops` ```bash scripts/script.sh crops ``` Crop-specific threshing settings for major grain crops. ### `loss` ```bash scripts/script.sh loss ``` Grain loss sources, measurement, and reduction strategies. ### `timing` ```bash scripts/script.sh timing ``` Harvest timing — moisture content, maturity indicators, and weather. ### `postharvest` ```bash scripts/script.sh postharvest ``` Post-harvest handling — drying, cleaning, storage, and quality. ### `examples` ```bash scripts/script.sh examples ``` Practical threshing scenarios and troubleshooting. ### `checklist` ```bash scripts/script.sh checklist ``` Pre-harvest and threshing operations checklist. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `THRESH_DIR` | Data directory (default: ~/.thresh/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # thresh — Grain Threshing Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Threshing — Overview === Threshing is the process of separating grain (seeds) from the stalk and husks of cereal plants. It is one of the most critical steps in grain production. The Three Operations of Grain Harvest: 1. Cutting (reaping) Severing the crop from the ground 2. Threshing Separating grain from plant material 3. Winnowing (cleaning) Separating grain from chaff History: Ancient Hand beating, trampling by animals, flail threshing 1788 Andrew Meikle invents mechanical threshing machine 1830s Horse-powered threshers become common 1880s Steam-powered threshing machines 1930s Combine harvester merges all three operations 1960s Self-propelled combines dominate Modern GPS-guided combines with yield mapping Threshing Principle: Apply mechanical force to separate grain from panicle/ear/pod Force types: Impact Grain knocked free by rotating bars or rasp Rubbing Grain rubbed between surfaces (concave + cylinder) Stripping Grain stripped from stalk by comb-like elements Squeezing Compression forces grain from husk Modern Combine Harvester Functions: Header Gathers and cuts the crop Feeder Conveys crop to threshing unit Thresher Separates grain from straw (cylinder + concave) Separator Separates remaining grain from MOG (Material Other than Grain) Cleaner Removes chaff and debris (sieves + fan) Grain tank Stores clean grain Unloader Transfers grain to transport Key Metrics: Threshing efficiency % grain separated from heads/pods Grain loss % grain lost (target: <1-2%) Grain damage % kernels cracked or broken Capacity Acres or tons per hour Fuel efficiency Gallons per acre EOF } cmd_mechanisms() { cat << 'EOF' === Threshing Mechanisms === Conventional (Tangential) Cylinder: Configuration: Cylinder + concave (half-moon shape) Cylinder types: Rasp bar: Most common, aggressive threshing Spike tooth: For rice, tough-to-thresh crops Wire loop: Gentle, for seed crops How it works: 1. Crop enters between spinning cylinder and fixed concave 2. Impact and rubbing separate grain 3. Grain falls through concave grates 4. Straw exits rear onto straw walkers Settings: Cylinder speed: 600-1,400 RPM (crop-dependent) Concave clearance: 10-40mm (front to rear) Closer = more aggressive threshing Faster = more aggressive but more damage Axial Flow (Rotary): Configuration: Longitudinal rotor + cage/concave Crop spirals around the rotor (longer threshing path) Advantages: - Gentler threshing (grain damage lower) - Higher capacity (larger throughput) - Better in tough conditions (damp, green crop) - Simpler drive system Disadvantages: - More power required - More straw breakage (short straw pieces) - Higher fuel consumption Manufacturers: Case IH, New Holland, AGCO Hybrid Systems: Conventional cylinder for initial threshing + Axial rotors for separation Best of both: aggressive thresh + gentle separation Manufacturers: John Deere (STS), Claas (Lexion) Concave Design: Round bar concave: Large openings, high-moisture crops Wire concave: Medium openings, most grain crops Perforated plate: Small grain, grass seed, fine cleaning Concave wrap angle: Conventional: 90-120° Rotary: 270-360° (full wrap around rotor) Straw Walkers vs Rotary Separation: Straw walkers: Oscillating racks that agitate straw Grain falls through, straw moves to rear 4-6 walkers typical Rotary: Centrifugal force pushes grain through grates Straw wraps and exits rear More capacity but shorter straw EOF } cmd_crops() { cat << 'EOF' === Crop-Specific Threshing Settings === Wheat: Cylinder speed: 900-1,200 RPM Concave clearance: 15-25mm (front), 8-15mm (rear) Fan speed: 800-1,000 RPM Top sieve: 12-16mm opening Bottom sieve: 6-8mm opening Harvest moisture: 13-14% ideal, max 18% Notes: Most forgiving crop to thresh Corn (Maize): Cylinder speed: 400-600 RPM (lower to reduce damage) Concave clearance: 25-35mm (front), 15-25mm (rear) Fan speed: 700-900 RPM Top sieve: 18-22mm opening Bottom sieve: 10-14mm opening Harvest moisture: 15-20% (will need drying) Notes: Use corn head with snapping rolls, not cutting header Rice (Paddy): Cylinder speed: 600-800 RPM Concave clearance: 18-28mm (front), 10-18mm (rear) Fan speed: 600-800 RPM Top sieve: 8-12mm opening Bottom sieve: 4-6mm opening Harvest moisture: 20-24% (requires drying to 14%) Notes: Spike-tooth cylinder preferred, very prone to cracking Soybeans: Cylinder speed: 400-600 RPM (beans damage easily) Concave clearance: 20-30mm (front), 12-20mm (rear) Fan speed: 800-1,000 RPM Top sieve: 12-16mm opening Bottom sieve: 6-8mm opening Harvest moisture: 13-15% Notes: Low cylinder speed critical — cracked beans = dock at elevator Barley: Cylinder speed: 800-1,000 RPM Concave clearance: 15-22mm (front), 8-14mm (rear) Fan speed: 700-900 RPM Top sieve: 10-14mm opening Bottom sieve: 5-7mm opening Harvest moisture: 13-14% Notes: Awns can cause cleaning problems; pre-cleaner helpful Canola (Rapeseed): Cylinder speed: 600-800 RPM Concave clearance: 20-30mm Fan speed: 500-700 RPM (low to keep small seeds) Top sieve: 6-10mm opening Bottom sieve: 3-5mm opening Harvest moisture: 8-10% Notes: Very small seeds, easily blown out; seal combine well EOF } cmd_loss() { cat << 'EOF' === Grain Loss Management === Sources of Grain Loss: Pre-harvest Loss (5-25% in developing countries): Shattering Grain falls before harvest (overripe, wind, rain) Lodging Plants fall over (hard to harvest) Bird/insect Wildlife feeding on mature crop Disease Late-season fungal damage Header Loss (typically 1-3%): Shatter loss Grain knocked off by reel or header Stubble loss Cut too high, grain left on stalks Lodged crop Header misses fallen plants Fix: Adjust reel speed, cutting height, ground speed Threshing Loss (typically 0.5-1%): Unthreshed heads Grain not separated from head/ear Cause: Cylinder speed too low, concave too open Fix: Increase cylinder speed, tighten concave Separation Loss (typically 0.5-1.5%): Grain carried over straw walkers/rotors Cause: Too much material (ground speed too fast) Fix: Reduce ground speed, adjust straw walker/rotor speed Cleaning Loss (typically 0.5-1%): Grain blown out with chaff by cleaning fan Cause: Fan speed too high, sieves too closed Fix: Reduce fan speed, open sieves slightly Measuring Grain Loss: Drop pan method: 1. Place pans behind combine (known area, e.g., 1 sq ft) 2. Collect grain from several passes 3. Count kernels per square foot 4. Convert to bushels per acre using tables Approximate kernel counts per bushel: Wheat: 14 kernels/sq ft = 1 bu/acre Corn: 2 kernels/sq ft = 1 bu/acre Soybeans: 4 beans/sq ft = 1 bu/acre Barley: 19 kernels/sq ft = 1 bu/acre Acceptable Loss Targets: Total machine loss: <1% of yield for most crops Each loss point = real money lost Example: 1% loss on 200 bu/acre corn at $5/bu = $10/acre On a 1,000-acre farm = $10,000 lost per percentage point Loss Reduction Strategy: 1. Monitor loss continuously (yield monitor, drop pans) 2. Adjust settings when changing field/crop conditions 3. Reduce ground speed in tough conditions 4. Harvest at optimal moisture content 5. Maintain sharp cutter bar and tight belts 6. Clean concave and sieves regularly EOF } cmd_timing() { cat << 'EOF' === Harvest Timing === Maturity Indicators by Crop: Wheat: Physiological maturity: Peduncle (stem below head) turns yellow Harvest-ready: Kernel hard, cannot be dented with thumbnail Moisture at maturity: 30-35% → field dry to 13-14% Window: 7-14 days optimal harvest window Late harvest risk: Shattering, sprouting, quality loss Corn: Physiological maturity: Black layer forms at kernel tip Milk line: Watch progress from crown to tip Harvest-ready: Black layer formed, 25-30% moisture Dry to: 15% for safe storage (can harvest wetter, dry artificially) Window: Several weeks (corn dries on stalk) Soybeans: Physiological maturity: Pods turn brown, leaves drop Harvest-ready: Beans rattle in pods, 13-15% moisture Window: Narrow — too dry causes shattering, too wet = green stems Risk: Delayed harvest = pod shatter, field losses increase 2-4%/week Rice: Maturity: 80-85% of grains turned from green to gold Harvest-ready: Top panicle grains golden, lower grains firm Moisture at harvest: 20-24% (must dry to 14%) Window: 5-7 days optimal Late risk: Shattering, grain discoloration, quality downgrade Weather Considerations: Rain at harvest: - Increases grain moisture → drying costs - Causes sprouting (wheat, barley) - Promotes fungal growth (DON/vomitoxin in wheat) - Can lodge (flatten) mature crop Dew: - Morning harvest in dew → higher moisture - Wait until dew burns off (typically 10 AM) - Late afternoon: moisture may start rising again Wind: - Moderate wind helps dry crop - Strong wind causes shattering and lodging - Harvest windward side first if storm approaching Harvest Logistics: Combine capacity planning: - Typical combine: 30-80 acres/day (crop-dependent) - Track daily: acres × yield = bushels to handle - Grain cart + truck logistics: match to combine speed - Rule: 1 combine needs 2-3 grain carts + trucks Timing decisions: - Harvest at higher moisture → drying cost but lower field loss - Wait for field drying → save drying cost but risk weather - Calculate breakeven: drying cost vs field loss per day waiting EOF } cmd_postharvest() { cat << 'EOF' === Post-Harvest Handling === Grain Drying: Moisture Targets for Safe Storage: Crop Short-term (<6mo) Long-term (>6mo) Wheat 14.0% 13.0% Corn 15.5% 14.0% Soybeans 13.0% 11.0% Rice 14.0% 12.5% Barley 14.5% 13.0% Drying Methods: Natural air drying: - Ambient air forced through grain bin - Slow (days to weeks), low energy cost - Best when air temp >40°F, RH <70% - Fan airflow: 1.0-1.5 CFM per bushel - Maximum initial moisture: 18-20% Low-temperature drying: - Heated 5-10°F above ambient - Faster than natural air - Good for corn at 20-22% moisture High-temperature drying: - Heated to 150-230°F - Fast: removes 5-10% moisture points per pass - Types: continuous flow, batch, mixed flow - Fuel: LP gas, natural gas (~0.02 gal/bu per point removed) - Caution: over-drying = weight loss = revenue loss - Stress cracks in corn above 200°F Grain Cleaning: Remove fines (broken kernels, dust, weed seeds) Fines accumulate in center of bin → airflow blockage Pre-cleaning before storage improves airability Equipment: scalper, rotary cleaner, gravity separator Target: <3% foreign material for most grain Grain Storage: Bin preparation: - Clean out old grain completely (insect/mold source) - Inspect for leaks, seal openings - Check fans and aeration system - Treat walls with approved insecticide Aeration: - Purpose: equalize temperature, prevent condensation - Fan airflow: 0.1-0.25 CFM/bu for aeration - Run when outdoor temp is 10-15°F below grain temp - Cool grain in stages: harvest temp → fall → winter - Target: 35-40°F for winter storage Monitoring: - Check temperature cables weekly - Look for hot spots (insect activity, spoilage) - Sample for moisture, insects monthly - Watch for crusting on surface (condensation) Quality Factors (affecting price): Test weight: Bushel weight (lb/bu) — heavier = better Moisture: Dockage if above acceptable level Damage: Broken, sprouted, heat-damaged kernels Foreign material: Weed seeds, dirt, plant material Mycotoxins: Aflatoxin (corn), DON/vomitoxin (wheat) EOF } cmd_examples() { cat << 'EOF' === Threshing Scenarios & Troubleshooting === --- Unthreshed Heads Coming Out the Back --- Problem: Whole or partially threshed heads in straw residue Causes: 1. Cylinder speed too low → Increase speed 50-100 RPM 2. Concave too wide → Close concave 2-3mm 3. Feeding too fast → Reduce ground speed 4. Worn rasp bars → Replace cylinder bars Check: Look at straw residue behind combine regularly --- Cracked/Broken Grain in Tank --- Problem: High percentage of damaged kernels Causes: 1. Cylinder speed too high → Reduce speed 50-100 RPM 2. Concave too tight → Open concave 2-3mm 3. Grain too dry → Harvest earlier in the day 4. Wrong concave type → Use wider-spaced concave Acceptable damage: Corn: <3% for commercial, <1% for seed Soybeans: <10% splits for commercial Wheat: <2% broken kernels --- Grain Going Over the Sieves (Lost in Chaff) --- Problem: Clean grain found in chaff pile behind combine Causes: 1. Fan speed too high → Reduce fan speed 2. Sieves closed too tight → Open sieve 2-4mm 3. Top sieve plugged → Clean sieve screens 4. Uneven feeding → Adjust feeder house chain Test: Walk behind combine, check for grain in chaff --- Combine Plugging / Wrapping --- Problem: Crop wraps around cylinder or plugs feeder Causes: 1. Crop too green/tough → Wait for drier conditions 2. Ground speed too fast → Slow down 3. Cutting height too low → Raise header 4. Worn/dull cutter bar → Replace sections Solution: Stop immediately, reverse if possible, clear manually --- Optimizing for Wet Conditions --- Scenario: Rain forecast, crop at 18-20% moisture Adjustments: - Increase cylinder speed 10-15% - Close concave 3-5mm tighter - Reduce fan speed slightly (wet chaff heavier) - Open sieves 2-3mm wider (wet material flows slower) - Reduce ground speed 20-30% - Plan for drying costs ($0.03-0.06 per bushel per point) - Decision: field loss risk vs drying cost EOF } cmd_checklist() { cat << 'EOF' === Threshing Operations Checklist === Pre-Season Preparation: [ ] Combine serviced (oil, filters, belts, bearings) [ ] Concave bars/plates inspected (replace if worn) [ ] Cylinder rasp bars checked for wear [ ] Sieves cleaned and adjusted [ ] Straw walkers/rotors inspected [ ] Feeder chain tension checked [ ] Cutter bar sections sharpened/replaced [ ] Reel tines straight and functional [ ] Grain tank clean (no old grain/contaminants) [ ] Unloading auger inspected Pre-Harvest Field Check: [ ] Crop maturity assessed (moisture test) [ ] Weather forecast reviewed (7-day) [ ] Harvest order planned (driest fields first) [ ] Grain transport arranged (trucks, carts) [ ] Drying capacity confirmed [ ] Storage bins cleaned and prepared [ ] Buyer/elevator contacted (delivery schedule) Daily Harvest Operations: [ ] Wait for dew to dry (check grain moisture) [ ] Set initial combine settings for crop/conditions [ ] Run test strip — check behind combine for losses [ ] Adjust cylinder speed, concave, fan, sieves as needed [ ] Monitor grain sample for damage and cleanliness [ ] Check loss readings every 30-60 minutes [ ] Re-check when moving to new field or conditions change [ ] Grease and inspect at mid-day break [ ] Record yields, moisture, and field data Post-Harvest: [ ] Clean combine thoroughly (crop residue = fire risk) [ ] Drain fuel system if storing combine long-term [ ] Store combine under cover if possible [ ] Cool grain with aeration within 24 hours [ ] Verify grain moisture in bins with probe [ ] Set up temperature monitoring cables [ ] Schedule first bin check within one week [ ] Document harvest data (yield, quality, costs) EOF } show_help() { cat << EOF thresh v$VERSION — Grain Threshing Reference Usage: script.sh <command> Commands: intro Threshing overview — history, principles, modern combines mechanisms Cylinder types, concave settings, rotary systems crops Crop-specific settings (wheat, corn, rice, soy, canola) loss Grain loss sources, measurement, and reduction timing Harvest timing — moisture, maturity, weather postharvest Post-harvest — drying, cleaning, storage examples Troubleshooting scenarios checklist Pre-harvest and operations checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; mechanisms) cmd_mechanisms ;; crops) cmd_crops ;; loss) cmd_loss ;; timing) cmd_timing ;; postharvest) cmd_postharvest ;; examples) cmd_examples ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "thresh v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
SKU management reference — naming conventions, hierarchy design, lifecycle management, and inventory classification. Use when designing product catalogs, cre...
--- name: "sku" version: "1.0.0" description: "SKU management reference — naming conventions, hierarchy design, lifecycle management, and inventory classification. Use when designing product catalogs, creating SKU schemas, or optimizing inventory by SKU analysis." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [sku, inventory, product, catalog, retail, warehouse, logistics] category: "logistics" --- # SKU — SKU Management Reference Quick-reference skill for SKU design, product hierarchy, and inventory classification. ## When to Use - Designing SKU naming conventions for a product catalog - Building product hierarchy (category → family → variant) - Performing ABC/XYZ inventory analysis - Managing SKU proliferation and rationalization - Understanding UPC/EAN/GTIN barcode relationships ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of SKU concepts — definitions, purpose, and relationship to other identifiers. ### `naming` ```bash scripts/script.sh naming ``` SKU naming conventions — best practices, encoding schemes, and anti-patterns. ### `hierarchy` ```bash scripts/script.sh hierarchy ``` Product hierarchy design — categories, families, variants, and attributes. ### `barcodes` ```bash scripts/script.sh barcodes ``` Barcode and identifier systems — UPC, EAN, GTIN, ISBN, ASIN, and check digits. ### `abc` ```bash scripts/script.sh abc ``` ABC/XYZ analysis — classifying SKUs by revenue contribution and demand variability. ### `lifecycle` ```bash scripts/script.sh lifecycle ``` SKU lifecycle management — introduction, growth, maturity, decline, and end-of-life. ### `rationalization` ```bash scripts/script.sh rationalization ``` SKU rationalization — identifying and eliminating underperforming products. ### `metrics` ```bash scripts/script.sh metrics ``` Key SKU metrics — inventory turns, fill rate, days of supply, and velocity. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `SKU_DIR` | Data directory (default: ~/.sku/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # sku — SKU Management Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === SKU (Stock Keeping Unit) === A SKU is a unique alphanumeric code assigned to a product for inventory tracking and management. Each unique combination of product attributes gets its own SKU. Example: "Nike Air Max 90, Men's, Size 10, Black" = one SKU "Nike Air Max 90, Men's, Size 10, White" = different SKU Same shoe, different color = different SKU SKU vs Other Identifiers: SKU Internal to YOUR business — you define the format Different retailers have different SKUs for the same product UPC Universal Product Code — 12 digits, same globally Assigned by GS1, printed on product barcode EAN European Article Number — 13 digits, global standard UPC is a subset of EAN (add leading 0) GTIN Global Trade Item Number — umbrella for UPC/EAN/ISBN 14 digits, includes packaging level ASIN Amazon Standard Identification Number — Amazon internal MPN Manufacturer Part Number — assigned by manufacturer Why SKUs Matter: Inventory tracking Know exactly what you have and where Reorder management Trigger replenishment at right levels Sales analysis Which products sell, which don't Warehouse operations Pick, pack, ship the right item Financial reporting Cost of goods, margin by product Scale: Small retail store: 500-5,000 SKUs Department store: 50,000-200,000 SKUs Amazon marketplace: 600,000,000+ SKUs Walmart stores: ~120,000 SKUs per store Typical grocery store: 30,000-50,000 SKUs EOF } cmd_naming() { cat << 'EOF' === SKU Naming Conventions === --- Good SKU Design Principles --- 1. Human-Readable (partially) BAD: 7294832749 GOOD: SHOE-NKE-AM90-BLK-M10 2. Structured Segments Format: CATEGORY-BRAND-MODEL-COLOR-SIZE Each segment encodes a meaningful attribute Use consistent delimiters (dash preferred) 3. Consistent Length/Format All SKUs in same category should follow same pattern Easier to validate, sort, and process 4. No Spaces or Special Characters Alphanumeric + dash/underscore only Spaces cause system issues everywhere 5. Case-Insensitive Store uppercase, compare case-insensitively Prevents SKU-001 vs sku-001 confusion --- Encoding Strategies --- Significant (Intelligent) SKU: BK-OFC-DSK-WAL-72 (Book, Office, Desk, Walnut, 72") Encodes product attributes in the code itself Pro: humans can read and interpret Con: changes in attributes require SKU changes Sequential (Dumb) SKU: PRD-000001, PRD-000002, PRD-000003 Simple incrementing number with prefix Pro: never runs out, no encoding issues Con: tells you nothing about the product Hybrid (Recommended): FRN-CHAIR-00042 Category prefix + sequential within category Balance of readability and simplicity --- Anti-Patterns --- ✗ Using product name as SKU "Nike Air Max 90 Black 10" — spaces, long, inconsistent ✗ Reusing SKUs for different products Once assigned, a SKU should NEVER be reassigned ✗ Starting with zero Excel and databases eat leading zeros ✗ Encoding volatile attributes Don't encode price, supplier, or location in SKU These change; the SKU should not ✗ Too many segments AA-BB-CC-DD-EE-FF-GG-HH → too long, error-prone 3-5 segments is optimal ✗ Using letters that look like numbers O vs 0, I vs 1, S vs 5 — avoid ambiguity Consider: exclude O, I, S, B, G from alphabetic segments EOF } cmd_hierarchy() { cat << 'EOF' === Product Hierarchy Design === A well-designed product hierarchy enables reporting, merchandising, and inventory management at every level. --- Typical Hierarchy --- Level 1: Division (Apparel, Electronics, Home) Level 2: Department (Men's, Women's, Kids) Level 3: Category (Footwear, Tops, Bottoms) Level 4: Subcategory (Running Shoes, Casual Shoes, Boots) Level 5: Product Family (Nike Air Max 90) Level 6: SKU (Variant) (AM90-BLK-M10) Example Path: Apparel → Men's → Footwear → Running → Nike Air Max 90 → Black/Size 10 --- Attributes vs Hierarchy --- Fixed attributes (part of hierarchy): Category, subcategory, brand, product family Rarely change, define the product's identity Variable attributes (NOT in hierarchy): Color, size, material, scent Create variants (SKUs) within a product family Managed as attribute dimensions, not hierarchy levels Product Family (Parent): Nike Air Max 90 — the abstract "product" No inventory at this level — it's a grouping SKU (Child/Variant): Nike Air Max 90, Black, Size 10 — a purchasable item Has inventory, price, barcode --- Data Model --- categories (id, name, parent_id, level) Self-referencing tree for n-level hierarchy products (id, name, category_id, brand_id, description) The product family / parent product variants / skus (id, product_id, sku_code, attributes_json) Each purchasable combination of attributes attributes: {"color": "black", "size": "10"} inventory (sku_id, location_id, quantity, reserved) Stock tracked at SKU + location level --- Hierarchy Best Practices --- 1. Maximum 5-6 levels (deeper = harder to manage) 2. Each item belongs to exactly one path (no overlapping) 3. Balanced tree (similar depth across branches) 4. Consistent attribute dimensions per category 5. Review and prune annually (dead categories, empty branches) EOF } cmd_barcodes() { cat << 'EOF' === Barcodes and Product Identifiers === --- UPC-A (Universal Product Code) --- 12 digits: N-MMMMM-IIIII-C N: Number system (0=regular, 2=weighted items, 3=pharma) MMMMM: Manufacturer code (assigned by GS1) IIIII: Item number (assigned by manufacturer) C: Check digit (modulo 10 algorithm) Used: North America retail Printed as: 1D barcode (vertical lines) --- EAN-13 (European Article Number) --- 13 digits: CC-MMMMM-IIIII-C CC: Country code (00-09=US, 40-44=Germany, 49=Japan, 690-695=China) Rest: same as UPC UPC-A is EAN-13 with leading 0 Used: worldwide retail --- GTIN (Global Trade Item Number) --- Umbrella system: GTIN-8: EAN-8 (small products) GTIN-12: UPC-A GTIN-13: EAN-13 GTIN-14: For cases, pallets (packaging levels) In databases: store as 14-digit, left-pad with zeros --- Check Digit Calculation (Modulo 10) --- For UPC/EAN: 1. Multiply odd-position digits by 3, even by 1 (from right) 2. Sum all products 3. Check digit = (10 - sum mod 10) mod 10 Example: 07123456789? 0×1 + 7×3 + 1×1 + 2×3 + 3×1 + 4×3 + 5×1 + 6×3 + 7×1 + 8×3 + 9×1 = 0+21+1+6+3+12+5+18+7+24+9 = 106 Check = (10 - 106%10) % 10 = (10-6)%10 = 4 --- GS1 Company Prefix --- To get UPC/EAN codes: Join GS1 ($250/year US for small companies) Receive company prefix (6-10 digits) Assign remaining digits to your products Longer prefix = fewer product numbers available --- Other Identifiers --- ISBN-13: Books (prefix 978 or 979 + EAN format) ISSN: Serial publications (8 digits) ASIN: Amazon internal (10 alphanumeric characters) MPN: Manufacturer Part Number (no standard format) PLU: Price Look-Up code (4-5 digits, produce items) --- 2D Barcodes --- QR Code: Up to 4,296 alphanumeric characters Data Matrix: Up to 2,335 alphanumeric characters GS1 DataMatrix: replacing linear barcodes in healthcare PDF417: Used for shipping labels, ID cards EOF } cmd_abc() { cat << 'EOF' === ABC/XYZ Inventory Analysis === --- ABC Analysis (Value-Based) --- Classifies SKUs by their contribution to total revenue or cost. Class A: Top 80% of revenue, typically 10-20% of SKUs Highest value items — manage tightly Frequent cycle counts, accurate forecasts Premium warehouse locations (golden zone) Class B: Next 15% of revenue, typically 20-30% of SKUs Moderate value — standard management Regular cycle counts, periodic review Class C: Bottom 5% of revenue, typically 50-70% of SKUs Low value — simplified management Infrequent counts, higher stock levels (carrying cost is low) Candidates for rationalization Calculation: 1. List all SKUs with annual revenue (units × price) 2. Sort descending by revenue 3. Calculate cumulative percentage 4. Assign: cumulative 0-80% = A, 80-95% = B, 95-100% = C --- XYZ Analysis (Variability-Based) --- Classifies SKUs by demand predictability. Class X: Stable demand (CV < 0.5) Easy to forecast, low safety stock needed Examples: staple foods, consumables, utilities Class Y: Moderate variability (CV 0.5-1.0) Seasonal patterns, moderate forecast accuracy Examples: fashion basics, some electronics Class Z: Highly variable demand (CV > 1.0) Unpredictable, hard to forecast Examples: new products, luxury, project-based CV = Coefficient of Variation = Standard Deviation / Mean --- Combined ABC-XYZ Matrix --- X (Stable) Y (Variable) Z (Unpredictable) A AX: Auto-replenish AY: Forecast AZ: Make-to-order High value, easy High value, High value, JIT delivery safety stock respond to demand B BX: Standard BY: Review BZ: Case-by-case reorder point frequently evaluate stocking C CX: Min/max CY: Periodic CZ: Don't stock auto-manage order order on demand only --- Actions by Class --- AX: Automate completely, minimize stock, frequent delivery AZ: Don't forecast — respond to orders, consider make-to-order CX: Set generous min/max, don't waste time optimizing CZ: Consider dropping — low value + unpredictable = waste EOF } cmd_lifecycle() { cat << 'EOF' === SKU Lifecycle Management === --- Lifecycle Stages --- 1. Introduction New product launched, SKU created Tasks: - Assign SKU code following naming convention - Set up in all systems (ERP, WMS, POS, website) - Assign barcode (UPC/EAN if retail) - Set initial inventory levels - Create product images, descriptions - Assign to category hierarchy - Set pricing, cost, and margin targets 2. Growth Sales increasing, gaining market traction Tasks: - Expand distribution (more locations) - Optimize reorder points based on actual demand - Negotiate better supplier pricing at volume - Expand variant range if successful (new colors, sizes) 3. Maturity Sales stable, well-understood demand patterns Tasks: - Fine-tune inventory levels (minimize excess) - Run promotions to maintain interest - Monitor for market shifts - Automate replenishment 4. Decline Sales dropping, market moving on Tasks: - Reduce order quantities - Consolidate to fewer locations - Plan clearance pricing - Identify replacement products 5. End of Life (EOL) Decision to discontinue Tasks: - Stop reordering - Sell through remaining inventory (markdown strategy) - Remove from active catalog/website - Archive SKU data (DO NOT delete) - Transfer warranty/support obligations - Notify affected customers/channels --- SKU Status Codes --- ACTIVE Available for sale and replenishment HOLD Temporarily blocked (quality issue, legal) CLEARANCE Selling remaining stock, no reorder DISCONTINUED Last units being sold, will not return ARCHIVED No longer sold, data retained for history --- Never Delete a SKU --- Why: historical orders reference it, financial records need it, returns may arrive years later, warranty claims need lookup Instead: mark as ARCHIVED with end date Some systems: "soft delete" with is_active flag EOF } cmd_rationalization() { cat << 'EOF' === SKU Rationalization === SKU rationalization is the process of identifying and eliminating underperforming products to reduce complexity and cost. --- Why Rationalize --- Too many SKUs = higher costs: Warehouse space for slow-moving inventory More purchase orders, more suppliers to manage Demand forecasting harder (diluted across variants) Pick complexity increases in warehouse Marketing budget spread thin Shelf space wasted on non-performers Typical findings: 20% of SKUs generate 80% of revenue (Pareto) 30-40% of SKUs contribute < 1% each to revenue 10-15% of SKUs haven't sold in 6+ months --- Rationalization Criteria --- Revenue threshold: Drop SKUs with < $X annual revenue Typical: bottom 5-10% by revenue contribution Velocity threshold: Drop SKUs with < N units sold per month Consider turns: if turns < 1/year, question it Margin threshold: Drop SKUs with negative gross margin Or gross margin below minimum acceptable (e.g., < 15%) Strategic value: Some low-revenue SKUs are strategic: - Completes a product line (customers expect it) - Required by key accounts - New product in growth phase - Regulatory requirement Always check before cutting --- Rationalization Process --- Step 1: Data Analysis Pull 12-24 months of sales data by SKU Calculate: revenue, margin, turns, velocity Run ABC analysis Flag: zero-movers, negative margin, declining trend Step 2: Cross-Reference Check with sales team: "Why do we carry this?" Check with key accounts: "Do you need this?" Check supplier MOQs: "Can we exit gracefully?" Check substitution: "What replaces this?" Step 3: Decision Cut: remove from catalog, sell through inventory Keep: strategic justification documented Modify: change pack size, combine variants, re-source Step 4: Execute Markdown remaining inventory Update all systems (ERP, WMS, website, catalogs) Notify affected customers/channels Set end dates for orders Step 5: Monitor Track results: did total revenue hold? Did margin improve? Did warehouse efficiency improve? Repeat annually EOF } cmd_metrics() { cat << 'EOF' === SKU Performance Metrics === --- Inventory Turns --- Formula: COGS ÷ Average Inventory Value Or: Units Sold ÷ Average Units in Stock Benchmarks: Fast-moving consumer goods: 8-12 turns/year Retail (general): 4-6 turns/year Industrial/B2B: 3-5 turns/year Fashion: 4-8 turns/year (seasonal) Higher turns = healthier inventory (money not sitting on shelves) Exception: strategic stock, long lead time items --- Days of Supply (DOS) --- Formula: Current Inventory ÷ Average Daily Demand Or: 365 ÷ Inventory Turns Example: 500 units in stock, sell 10/day → 50 days of supply Target depends on lead time + safety stock requirement --- Fill Rate --- Formula: Orders Fulfilled Complete ÷ Total Orders × 100% By SKU: what % of demand was met from stock? Target: 95-99% for A items, 90-95% for B, 85-90% for C 100% fill rate is NOT the goal — cost of last 1% is enormous --- Stockout Rate --- Formula: Days Out of Stock ÷ Total Days × 100% Or: Stockout Events ÷ Total Demand Events × 100% A items: target < 1% stockout C items: target < 5% stockout --- GMROI (Gross Margin Return on Inventory Investment) --- Formula: Gross Margin ÷ Average Inventory Cost Example: $50,000 gross margin ÷ $25,000 avg inventory = 2.0 Interpretation: every $1 in inventory generates $2 in gross margin Benchmark: > 3.0 is excellent, < 1.0 is underperforming --- Velocity --- Units sold per time period (day, week, month) Used to assign warehouse locations: High velocity → pick face, ground level, near shipping Low velocity → upper rack, reserve storage --- Sell-Through Rate --- Formula: Units Sold ÷ (Units Sold + Units in Stock) × 100% Period: typically monthly or seasonal Target: 80%+ by end of season (retail) Below 50% → potential markdown/clearance candidate --- Dead Stock --- Inventory with zero sales for 6-12 months Industry average: 20-30% of SKUs are dead stock Costs: warehousing, insurance, depreciation, opportunity cost Action: clearance, donation, recycling, or write-off EOF } show_help() { cat << EOF sku v$VERSION — SKU Management Reference Usage: script.sh <command> Commands: intro SKU concepts and relationship to other identifiers naming SKU naming conventions and best practices hierarchy Product hierarchy design and data modeling barcodes UPC, EAN, GTIN, and barcode systems abc ABC/XYZ inventory analysis and classification lifecycle SKU lifecycle from introduction to end-of-life rationalization Identifying and eliminating underperforming SKUs metrics Key performance metrics: turns, fill rate, GMROI help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; naming) cmd_naming ;; hierarchy) cmd_hierarchy ;; barcodes) cmd_barcodes ;; abc) cmd_abc ;; lifecycle) cmd_lifecycle ;; rationalization) cmd_rationalization ;; metrics) cmd_metrics ;; help|--help|-h) show_help ;; version|--version|-v) echo "sku v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
RFID technology reference — tag types, frequency bands, read ranges, EPC standards, inventory tracking. Use when designing RFID systems, selecting tags/reade...
--- name: "rfid" version: "1.0.0" description: "RFID technology reference — tag types, frequency bands, read ranges, EPC standards, inventory tracking. Use when designing RFID systems, selecting tags/readers, or implementing warehouse tracking solutions." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [rfid, nfc, epc, tag, reader, inventory, tracking, logistics] category: "logistics" --- # RFID — Radio-Frequency Identification Reference Quick-reference skill for RFID technology, standards, and implementation. ## When to Use - Selecting RFID tags and readers for warehouse or retail - Understanding frequency bands and read range trade-offs - Implementing EPC/SGTIN encoding for supply chain - Designing RFID read zones and antenna placement - Comparing RFID vs barcode for inventory management ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of RFID — how it works, components, active vs passive. ### `frequencies` ```bash scripts/script.sh frequencies ``` Frequency bands — LF, HF, UHF, microwave, read range, use cases. ### `tags` ```bash scripts/script.sh tags ``` Tag types — passive, semi-passive, active, inlays, hard tags, form factors. ### `standards` ```bash scripts/script.sh standards ``` Standards — EPC Gen2, ISO 18000, NFC (ISO 14443/15693), GS1 encoding. ### `readers` ```bash scripts/script.sh readers ``` Readers and antennas — fixed, handheld, portal, sensitivity, protocols. ### `applications` ```bash scripts/script.sh applications ``` Applications — retail, warehouse, asset tracking, access control, healthcare. ### `challenges` ```bash scripts/script.sh challenges ``` Challenges — metal/liquid interference, collision, privacy, cost analysis. ### `checklist` ```bash scripts/script.sh checklist ``` RFID implementation planning checklist. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `RFID_DIR` | Data directory (default: ~/.rfid/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # rfid — RFID Technology Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === RFID — Radio-Frequency Identification === RFID uses electromagnetic fields to automatically identify and track tags attached to objects. Unlike barcodes, RFID does NOT require line-of-sight — tags can be read through packaging, pallets, and even walls. How It Works: 1. Reader emits radio waves from antenna 2. Tag antenna receives energy (passive) or responds (active) 3. Tag's IC modulates signal with stored data 4. Reader captures reflected/transmitted signal 5. Reader decodes data and sends to host system System Components: Tag (Transponder): - IC chip (stores data, 96-512 bits typical) - Antenna (receives energy, transmits data) - Substrate (material tag is built on) Reader (Interrogator): - Transmitter (sends RF energy) - Receiver (captures tag response) - Controller (manages protocol/timing) - Antenna(s) (one or more, various patterns) Middleware/Software: - Filters and deduplicates reads - Maps tag IDs to business data - Integrates with WMS, ERP, POS systems Tag Types: Passive: No battery — powered by reader RF energy Range: cm to ~15m (UHF) Cost: $0.03-0.50 per tag Life: 20+ years (no battery to die) Semi-Passive (BAP — Battery-Assisted Passive): Battery powers IC, reader provides communication energy Range: up to 30m Cost: $1-10 Life: 3-7 years (battery) Active: Battery powers both IC and transmitter Range: up to 100-300m Cost: $10-100+ Life: 3-10 years (battery) Use: vehicle tracking, large assets, RTLS RFID vs Barcode: Feature RFID Barcode Line of sight Not required Required Read speed 100s/second 1 at a time Read range cm to 100m+ cm to 1m Data capacity 96-8K bits ~100 characters Read/Write Both Read only Durability High Low (damage=unreadable) Cost per tag $0.03-100 $0.001 Simultaneous Yes No EOF } cmd_frequencies() { cat << 'EOF' === RFID Frequency Bands === Low Frequency (LF): 125-134 kHz Range: 1-10 cm (contact to near-field) Data rate: Low (~1 kbps) Penetration: Excellent through water, tissue, metal Standards: ISO 11784/85 (animal ID) Use cases: Animal tracking (ear tags, implants) Access control (proximity cards) Car immobilizer keys Laundry tracking (survives wash) Pros: Works near metal/water, mature technology Cons: Very short range, slow read, one tag at a time High Frequency (HF): 13.56 MHz Range: 1 cm - 1 m (typically 10-30 cm) Data rate: Medium (~25 kbps) Standards: ISO 14443 (NFC), ISO 15693 (vicinity) NFC: Near Field Communication (subset of HF RFID) Phone-readable, secure payment (Apple Pay, etc.) Use cases: Payment cards (contactless/NFC) Library books (ISO 15693) Pharmaceutical anti-counterfeiting Smart posters / NFC tags Access badges (MIFARE, DESFire) Pros: Global frequency, NFC ecosystem, anti-collision Cons: Limited range, moderate cost Ultra-High Frequency (UHF): 860-960 MHz Range: 1-15 m (passive), up to 30m (BAP) Data rate: High (~640 kbps) Regional: EU: 865-868 MHz | US: 902-928 MHz | China: 920-925 MHz Standards: EPC Gen2 (ISO 18000-63) Use cases: Supply chain / logistics (pallets, cases, items) Retail inventory (item-level tagging) Warehouse management Toll collection Race timing Pros: Long range, fast multi-tag read, low cost tags Cons: Degraded by water/metal, regional frequency differences Microwave: 2.45 GHz / 5.8 GHz Range: 1-10 m (passive), 100m+ (active) Data rate: Very high Use cases: Vehicle toll collection (active) Real-time location systems (RTLS) Industrial automation Pros: Very small antennas, high data rate Cons: Expensive, poor penetration, regulatory limits Frequency Selection Guide: Near metal/water/body? → LF or HF Need NFC/phone? → HF (13.56 MHz) Supply chain/retail? → UHF (860-960 MHz) Long range tracking? → UHF (passive) or Active (2.45 GHz) Animal identification? → LF (125-134 kHz) EOF } cmd_tags() { cat << 'EOF' === RFID Tag Types & Form Factors === Passive UHF Tags (Most Common): Inlay (Wet/Dry): Thin, flexible — IC + antenna on substrate Wet inlay: has adhesive backing Dry inlay: no adhesive (for converting into labels) Size: typically 25×25mm to 100×15mm Cost: $0.03-0.15 in volume Use: item-level tagging, labels, tickets Label/Smart Label: Inlay laminated into paper/plastic label Printable surface for barcode + human-readable text Dual technology: RFID + barcode on same label Cost: $0.05-0.30 Hard Tag: Rugged enclosure (ABS plastic, epoxy, ceramic) Survives extreme environments (heat, impact, chemicals) Mount: screw, rivet, adhesive, cable tie Cost: $1-20 Use: asset tracking, IT equipment, tools, containers On-Metal Tag: Special design with spacer/ferrite layer Works directly on metal surfaces (standard tags don't!) Types: ceramic patch, foam spacer, flex-metal mount Cost: $1-15 Use: metal containers, vehicles, equipment Laundry Tag: Encapsulated in silicone or fabric pouch Survives 200+ wash/dry cycles at 85°C Autoclave-resistant versions for healthcare Cost: $0.50-2.00 NFC Tags (HF): NTAG213: 144 bytes user memory, most common for NFC NTAG215: 504 bytes (Nintendo Amiibo format) NTAG216: 888 bytes MIFARE Classic: 1K/4K memory, access control MIFARE DESFire: AES encryption, transit/payment Cost: $0.10-1.00 Tag Selection Criteria: 1. What surface? (metal, plastic, cardboard, skin) 2. Read range needed? (contact to 15m) 3. Environment? (temperature, moisture, chemicals) 4. Memory size? (96 bits EPC standard, up to 8KB) 5. Read/write needs? (read-only vs rewritable) 6. Volume and budget? (per-tag cost at quantity) 7. Form factor? (label, hard tag, embedded) 8. Standards? (EPC Gen2, NFC, ISO) Tag Memory Structure (EPC Gen2): Reserved: Kill password (32 bits) + Access password (32 bits) EPC: Electronic Product Code (96-496 bits) TID: Tag Identifier (unique IC serial, read-only) User: Optional user data (varies: 0-512+ bits) EOF } cmd_standards() { cat << 'EOF' === RFID Standards === EPC Gen2 (EPCglobal UHF Class 1 Gen 2): Full name: ISO 18000-63 The dominant standard for supply chain RFID Key features: - Anti-collision: can read 1,000+ tags/second - Dense reader mode: multiple readers without interference - 96-bit EPC number (expandable to 496) - Session management (4 sessions for inventory flags) - Kill command (permanently disable tag) - Lock command (protect memory from overwrite) EPC Number Structure: Header | Filter | Partition | Company Prefix | Item Ref | Serial Example SGTIN-96 (serialized product): Header: 8 bits Filter: 3 bits (case, pallet, unit) Partition: 3 bits (defines prefix/item split) Company Prefix: 20-40 bits (GS1 assigned) Item Ref: 4-24 bits (product identifier) Serial: 38 bits (unique serial number) SGTIN-96 URI example: urn:epc:tag:sgtin-96:3.0614141.812345.6789 EPC Tag Data Standard (TDS): SGTIN: Serialized Global Trade Item Number (products) SSCC: Serial Shipping Container Code (pallets/cases) GRAI: Global Returnable Asset Identifier (reusable assets) GIAI: Global Individual Asset Identifier (fixed assets) SGLN: Serialized Global Location Number (locations) GSRN: Global Service Relation Number (relationships) ISO Standards: ISO 14443: NFC Type A/B (contactless smart cards, payment) ISO 15693: Vicinity cards (library, access — longer range HF) ISO 18000-2: LF RFID (below 135 kHz) ISO 18000-3: HF RFID (13.56 MHz) ISO 18000-63: UHF RFID (860-960 MHz) = EPC Gen2 ISO 11784/85: Animal identification (LF) ISO 17363-67: Supply chain RFID data encoding GS1 & EPCIS: GS1: global standards body for barcodes and RFID EPCIS: EPC Information Services Captures WHAT, WHERE, WHEN, WHY of RFID events Event types: Object, Aggregation, Transaction, Transformation Data sharing across supply chain partners XML or JSON-LD format Enables track-and-trace from factory to consumer EOF } cmd_readers() { cat << 'EOF' === RFID Readers & Antennas === Reader Types: Fixed Reader: Permanently mounted (dock door, conveyor, portal) 1-8 antenna ports High power: 30-33 dBm (1-2 watts EIRP) Connectivity: Ethernet, WiFi, serial Examples: Zebra FX9600, Impinj R700, Alien ALR-F800 Cost: $1,000-5,000 Handheld Reader: Portable gun-style or sled (phone attachment) Built-in antenna, battery operated Power: 20-30 dBm Range: 1-10m depending on tag Examples: Zebra MC3330R, Chainway C72 Cost: $1,000-3,000 Integrated Reader: Reader + antenna in single enclosure Simple installation (one device) Lower power but sufficient for many applications Cost: $500-2,000 USB Desktop Reader: Connect to PC for encoding/reading tags Short range (10-30 cm) Used for: tag programming, registration, POS Cost: $200-800 Antenna Types: Circular Polarized: Reads tags in any orientation ~3 dB loss vs linear (shorter range) Best for: portals, conveyors (random tag orientation) Linear Polarized: Higher gain, longer range Tag must be oriented within ~45° of antenna polarization Best for: controlled tag orientation (labels on boxes) Near-Field: Very short range (<10 cm) Precise read zone — reads only what you intend Best for: point-of-sale, item encoding, serialization Antenna Specifications: Gain: 6-12 dBi (higher = more focused, longer range) Beamwidth: 30-70° (narrower = more directional) VSWR: <1.5:1 (impedance matching quality) Polarization: Circular or Linear Size: Larger antenna = higher gain = longer range Read Zone Design: Portal (dock door): 2-4 antennas surrounding door opening Circular polarized for random pallet/case orientation Stagger antennas to minimize blind spots Test with actual tagged goods before deployment Conveyor: Antenna above, below, or both sides Trigger: photoeye or motion sensor starts read cycle Speed: 200-600 ft/min typical conveyor speed Ensure tag exposure time > 100ms Shelf/Cabinet: Near-field antennas on each shelf Low power to avoid reading adjacent shelves Multiplexer to cycle through antenna positions Power Regulations: US (FCC): 4W EIRP max (36 dBm) EU (ETSI): 2W ERP max (33 dBm), listen-before-talk China (MIIT): 2W EIRP (33 dBm) Indoor vs outdoor regulations may differ EOF } cmd_applications() { cat << 'EOF' === RFID Applications === Retail Inventory: Item-level tagging: each garment/product gets UHF RFID tag Benefits: - Inventory accuracy: 65% → 98%+ (industry data) - Count entire store in 2 hours vs 2 days (barcode) - Real-time stock visibility (omnichannel fulfillment) - Automated replenishment triggers - Loss prevention (EAS + RFID combined) ROI: 2-8% sales increase from inventory accuracy Adoption: Walmart, Zara, Uniqlo, Nike, Decathlon mandates Warehouse / Distribution: Pallet and case-level tracking through supply chain Receiving: read all pallets passing through dock door Put-away: verify correct location Picking: confirm correct items picked Shipping: automated manifest verification Benefits: 25-30% labor savings in receiving, near-zero ship errors Asset Tracking: IT assets: laptops, servers, monitors (hard tags) Manufacturing: tools, fixtures, molds, dies Healthcare: wheelchairs, pumps, ventilators Benefits: locate assets in real-time, automate audits Typical: 15-30% reduction in asset loss/replacement Healthcare: Patient wristbands: ID verification for medication/procedures Specimen tracking: blood samples, pathology Equipment tracking: RTLS for infusion pumps, beds Pharmaceutical: anti-counterfeiting (serialized drug packages) Surgical instruments: autoclave-safe tags for sterilization tracking Access Control: HF/NFC badges: office access, secure areas Vehicle tags: parking, toll collection (E-ZPass) Ski passes: UHF wristbands for lift access Events: NFC wristbands for concerts, festivals (+ payment) Supply Chain Compliance: Walmart: Item-level RFID mandate (apparel → expanding) US DoD: MIL-STD-129 RFID marking on shipments FDA DSCSA: Drug serialization (indirect RFID impact) EU MDR: Medical device UDI (RFID-compatible) EOF } cmd_challenges() { cat << 'EOF' === RFID Challenges === Metal Interference: Problem: metal reflects RF energy, detunes tag antenna Result: tag on metal surface → no read or very short range Solution: on-metal tags (spacer + ferrite absorber) Alternative: mount tag on standoff away from metal surface Cost impact: on-metal tags 3-10× more expensive Liquid Interference: Problem: water absorbs UHF energy (resonant frequency) Result: tags on liquid containers → reduced range Solution: tag placement away from liquid surface Solution: use HF or LF (less affected by water) Test: read range with actual product (not empty containers) Tag Collision: Problem: many tags responding simultaneously Solution: anti-collision protocols (EPC Gen2 uses Q algorithm) Capacity: 1,000+ tags/second with modern readers Dense environments may need session management tuning Dense reader mode prevents reader-to-reader interference Read Reliability: Problem: not 100% read rate in real-world conditions Causes: orientation, distance, interference, tag quality Target: >99.5% read rate for automated processes Mitigation: multiple antennas, redundant read points Testing: test with ACTUAL products in ACTUAL environment Never trust lab results alone — always field test Privacy Concerns: Problem: tags can be read without owner's knowledge Retail: tags should be killed or deactivated at point of sale EPC Gen2: kill command permanently disables tag Regulation: US states have RFID privacy laws (varies) EU GDPR: RFID data linked to individuals = personal data Cost Analysis: Component UHF (per unit) Deployment Passive label $0.05-0.15 Per item Hard tag $2-15 Per asset Fixed reader $1,500-5,000 Per read point Antenna $200-500 Per antenna Handheld reader $1,500-3,000 Per worker Software/middleware $10,000-100,000+ Per site Installation $5,000-50,000 Per site Break-even analysis: Labor savings from automated counting/tracking + Inventory accuracy improvement (reduced lost sales) + Theft reduction − Tag cost × volume − Infrastructure cost Typical retail ROI: 12-18 months Environmental Factors: Temperature: Standard tags: -20°C to 65°C High-temp tags: up to 250°C (autoclave, industrial) Humidity: Condensation can affect adhesive and antenna UV exposure: Degrades label face stock (not typically the IC) Chemicals: Solvent exposure can damage tag components EOF } cmd_checklist() { cat << 'EOF' === RFID Implementation Checklist === Requirements Definition: [ ] What objects will be tagged? (items, cases, pallets, assets) [ ] Required read range defined [ ] Read rate target established (reads/second) [ ] Environmental conditions documented (temp, moisture, metal) [ ] Integration requirements with existing systems (WMS, ERP, POS) [ ] ROI / business case approved Tag Selection: [ ] Surface material evaluated (metal, plastic, cardboard, fabric) [ ] Form factor chosen (label, hard tag, laundry, on-metal) [ ] Memory requirements defined (EPC only vs user memory) [ ] Tag samples tested on actual products [ ] Read range verified with chosen reader/antenna [ ] Encoding scheme defined (SGTIN, SSCC, GRAI, custom) [ ] Tag placement location standardized Infrastructure: [ ] Reader type selected (fixed, handheld, integrated) [ ] Antenna type and quantity determined per read point [ ] Read zones designed and diagrammed [ ] Network connectivity planned (Ethernet, WiFi) [ ] Power requirements calculated [ ] Cable routing planned (antenna cables, network) [ ] Reader software/firmware version confirmed Software: [ ] Middleware selected for event filtering/routing [ ] Integration with WMS/ERP/POS designed [ ] EPCIS event capture planned (if supply chain) [ ] Data storage and retention policy defined [ ] Dashboard/reporting requirements specified Testing: [ ] Lab testing completed with tag samples [ ] Pilot site identified for field test [ ] Read rate benchmark established (>99.5% target) [ ] Interference testing completed (metal, liquid, other RF) [ ] Stress testing (maximum tag density, conveyor speed) [ ] User acceptance testing with operations team Deployment: [ ] Installation schedule and downtime planned [ ] Staff trained on new processes [ ] Standard operating procedures documented [ ] Support escalation path defined [ ] Tag ordering/supply chain established [ ] Rollback plan documented (if issues arise) EOF } show_help() { cat << EOF rfid v$VERSION — RFID Technology Reference Usage: script.sh <command> Commands: intro RFID overview, components, passive vs active frequencies LF, HF, UHF, microwave — ranges and use cases tags Tag types, form factors, memory structure standards EPC Gen2, ISO 18000, NFC, GS1/EPCIS readers Fixed, handheld, antennas, power regulations applications Retail, warehouse, healthcare, access control challenges Metal/liquid issues, collision, privacy, cost checklist RFID implementation planning checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; frequencies) cmd_frequencies ;; tags) cmd_tags ;; standards) cmd_standards ;; readers) cmd_readers ;; applications) cmd_applications ;; challenges) cmd_challenges ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "rfid v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Mediation and ADR reference — dispute resolution processes, mediator techniques, caucus strategy, settlement agreements. Use when preparing for mediation ses...
--- name: "mediation" version: "1.0.0" description: "Mediation and ADR reference — dispute resolution processes, mediator techniques, caucus strategy, settlement agreements. Use when preparing for mediation sessions, drafting settlement terms, or choosing between ADR methods." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [mediation, adr, dispute-resolution, arbitration, negotiation, settlement, legal] category: "legal" --- # Mediation — Alternative Dispute Resolution Reference Quick-reference skill for mediation processes, techniques, and settlement practices. ## When to Use - Preparing for a mediation session as party or counsel - Choosing between mediation, arbitration, and litigation - Understanding mediator techniques and caucus strategy - Drafting enforceable settlement agreements - Evaluating when mediation is appropriate or inappropriate ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of mediation — definition, principles, comparison with litigation and arbitration. ### `process` ```bash scripts/script.sh process ``` Mediation process stages — opening, joint session, caucus, negotiation, closure. ### `techniques` ```bash scripts/script.sh techniques ``` Mediator techniques — reframing, reality testing, BATNA analysis, anchoring. ### `types` ```bash scripts/script.sh types ``` ADR spectrum — negotiation, mediation, med-arb, arbitration, early neutral evaluation. ### `preparation` ```bash scripts/script.sh preparation ``` Mediation preparation — position statements, BATNA/WATNA, authority, documents. ### `settlement` ```bash scripts/script.sh settlement ``` Settlement agreements — essential terms, enforceability, tax implications. ### `ethics` ```bash scripts/script.sh ethics ``` Mediator ethics — neutrality, confidentiality, self-determination, conflicts. ### `checklist` ```bash scripts/script.sh checklist ``` Mediation readiness checklist for parties and counsel. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `MEDIATION_DIR` | Data directory (default: ~/.mediation/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # mediation — Alternative Dispute Resolution Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Mediation & Alternative Dispute Resolution === Mediation is a structured negotiation process in which a neutral third party (the mediator) assists disputing parties in reaching a voluntary, mutually acceptable resolution. Key Principles: Voluntary: Parties choose to participate and can leave Confidential: Discussions cannot be used in court Self-determination: Parties control the outcome (not the mediator) Neutral: Mediator has no stake and no decision-making power Interest-based: Focuses on needs, not legal positions Mediation vs Litigation vs Arbitration: Feature Mediation Arbitration Litigation Decision-maker Parties Arbitrator Judge/Jury Binding? If settled Yes Yes Confidential? Yes Usually No (public) Cost $ $$ $$$ Duration Days-weeks Months Years Relationship Preserved Strained Adversarial Flexibility High Medium Low Appeal N/A Very limited Yes Success Rates: Commercial mediation: 70-85% settlement rate Employment disputes: 60-75% Personal injury: 80-90% Family/divorce: 50-70% Construction: 75-85% When Mediation Works Best: - Ongoing relationship (business partners, neighbors, family) - Both parties want resolution (not precedent) - Issues are negotiable (money, terms, future conduct) - Power imbalance is manageable - Emotions need to be acknowledged and processed When Mediation May NOT Work: - One party needs a legal precedent - Domestic violence or extreme power imbalance - Party is not attending in good faith - Criminal matters (though victim-offender mediation exists) - Injunctive relief needed urgently EOF } cmd_process() { cat << 'EOF' === Mediation Process Stages === Stage 1 — Pre-Mediation: - Mediator selected (agreed by both parties) - Confidentiality agreement signed - Mediation agreement signed (ground rules) - Position statements exchanged (optional) - Documents/evidence shared in advance - Logistics: date, venue, participants, authority to settle Stage 2 — Opening Statement (Mediator): - Welcome and introductions - Explain mediation process and ground rules - Emphasize confidentiality and voluntariness - Clarify mediator's role (facilitator, not judge) - Set agenda and time expectations Duration: 10-15 minutes Stage 3 — Party Opening Statements: - Each party presents their perspective uninterrupted - Not legal arguments — tell the story, express impact - Mediator listens actively, takes notes - Other party listens (no interruptions, no rebuttal yet) Duration: 10-30 minutes per party Stage 4 — Joint Discussion: - Mediator identifies common ground and key issues - Parties respond to each other (facilitated) - Clarify misunderstandings - Begin exploring interests behind positions Duration: 30-60 minutes Stage 5 — Caucus (Private Sessions): - Mediator meets each party separately - Confidential — mediator only shares what party permits - Reality testing: "What happens if you don't settle?" - Explore flexibility, hidden interests, bottom lines - Multiple rounds of caucus typical Duration: 20-45 minutes per caucus, multiple rounds Stage 6 — Negotiation/Bargaining: - Exchange proposals (shuttle diplomacy via mediator) - Bracket negotiation: narrow the gap incrementally - Package deals: trade across issues - Mediator's proposal: last resort suggestion Duration: varies widely Stage 7 — Agreement/Closure: If settled: - Draft settlement terms in writing - Both parties and counsel review - Sign memorandum of understanding - Formal agreement drafted by attorneys afterward If impasse: - Mediator summarizes progress made - Identify remaining barriers - Schedule follow-up session or next steps - Mediation can be reconvened later EOF } cmd_techniques() { cat << 'EOF' === Mediator Techniques === Active Listening: - Paraphrase: "So what I hear you saying is..." - Reflect emotions: "It sounds like you feel frustrated by..." - Summarize: consolidate key points periodically - Open questions: "Can you tell me more about...?" - Silence: let parties fill the space (powerful tool) Reframing: Transform negative/adversarial statements into neutral/positive Before: "They deliberately cheated us on the contract!" After: "You feel the contract terms weren't honored as expected." Before: "He's impossible to work with." After: "It sounds like communication has been challenging." Purpose: reduce emotional charge, open exploration Reality Testing: Challenge unrealistic expectations in caucus: "What do you think a court would award?" "How long would litigation take?" "What would legal fees cost through trial?" "What's your best evidence on this point?" "If the judge rules against you, what happens?" Purpose: move parties from positions to realistic ranges BATNA/WATNA Analysis: BATNA: Best Alternative To a Negotiated Agreement "If you don't settle today, what's your best outcome?" WATNA: Worst Alternative To a Negotiated Agreement "What's the worst that could happen in court?" MLATNA: Most Likely Alternative "Realistically, what would probably happen?" Purpose: help parties evaluate settlement against alternatives Bracketing: Narrow the negotiation range systematically: Round 1: P demands $1M, D offers $100K (range: $900K) Round 2: P drops to $750K, D raises to $250K (range: $500K) Round 3: P drops to $600K, D raises to $350K (range: $250K) Round 4: Settle at $475K Mediator helps each side make proportional moves Mediator's Proposal: Last-resort technique when parties are close but stuck Mediator privately proposes same number to both sides Each party says yes or no confidentially If both say yes: deal done If one says no: neither party knows the other's answer Preserves face — no one "gives in" Interest Exploration: Position: "I want $500,000" Interest: "I need to cover medical bills and lost wages" Deeper interest: "I want to feel made whole and acknowledged" Technique: "Why is that important to you?" When interests are uncovered, creative solutions emerge EOF } cmd_types() { cat << 'EOF' === ADR Spectrum === From least to most formal: 1. Negotiation: Direct discussion between parties (no third party) Cheapest, fastest, most private Works when: relationship is functional, stakes manageable Risk: power imbalance, emotional escalation 2. Mediation: Neutral facilitator, non-binding, voluntary Evaluative: mediator gives opinions on merits Facilitative: mediator facilitates, no opinion Transformative: focuses on empowerment and recognition Settlement rate: 70-85% 3. Med-Arb (Mediation-Arbitration): Start with mediation, switch to arbitration if no deal Same neutral or different neutral for each phase Pros: guaranteed resolution in one process Cons: parties may withhold info in mediation (fear of arb) 4. Early Neutral Evaluation (ENE): Expert gives non-binding assessment of case merits Usually 1-2 hour hearing, advisory opinion Helps parties calibrate expectations early Common in: patent, construction, medical cases 5. Mini-Trial: Abbreviated presentation of each side's best case Decision-makers (senior execs) observe Then negotiate based on what they saw Common in: large commercial disputes 6. Arbitration: Quasi-judicial process, binding decision Arbitrator chosen by parties (or institution) Limited discovery, streamlined procedure Very limited appeal (vacate only for fraud, bias, misconduct) Institutions: AAA, JAMS, ICC, LCIA 7. Online Dispute Resolution (ODR): Technology-assisted ADR (video, AI, platforms) Examples: eBay Resolution Center, Modria, ICANN UDRP Growing rapidly for e-commerce and small claims AI-assisted triage and initial resolution Choosing the Right Method: Need precedent? → Litigation Need binding decision? → Arbitration Need relationship? → Mediation Need speed + low cost? → Mediation > Arbitration International dispute? → Arbitration (enforceable globally) Consumer/small claim? → ODR EOF } cmd_preparation() { cat << 'EOF' === Mediation Preparation === For Parties/Counsel — Before Mediation Day: 1. Analyze Your Case: Strengths: what evidence/law favors you Weaknesses: what the other side will argue Best case outcome (BATNA): what you'd likely get at trial Worst case outcome (WATNA): what you'd get if you lose Realistic outcome (MLATNA): most probable trial result Litigation cost estimate: attorney fees through trial 2. Define Your Interests: Why do you want what you want? (beyond money) What non-monetary outcomes would help? What would closure look like? Are there ongoing relationship considerations? 3. Prepare Position Statement (if requested): 1-3 pages typically Brief factual background Key issues in dispute Your position and supporting reasons What you think a fair resolution looks like Confidential section: for mediator's eyes only 4. Gather Documents: Contract/agreement in dispute Key correspondence (emails, letters) Financial documents (damages calculation) Expert reports (if any) Prior settlement discussions (summary only) 5. Authority: Ensure decision-maker is present (not just lawyer) If corporate: get settlement authority range in advance Insurance: adjuster with authority to settle "Full authority" means ability to say yes at any reasonable number 6. Logistics: Confirm date, time, venue Separate rooms for caucuses Bring multiple copies of key documents Plan for a full day (don't schedule hard stops) Bring calculator, authority documents, checkbook Mediation Brief Outline: I. Introduction (1 paragraph) II. Factual Background (1-2 pages) III. Legal Issues (1 page) IV. Damages/Claims (with calculations) V. Settlement Efforts to Date VI. Desired Outcome VII. Confidential Section (bottom line, flexibility) EOF } cmd_settlement() { cat << 'EOF' === Settlement Agreements === A mediated settlement agreement is a binding contract once signed. It must contain all essential terms to be enforceable. Essential Elements: 1. Parties (full legal names) 2. Recitals ("WHEREAS..." — background of dispute) 3. Settlement terms (specific, measurable obligations) 4. Payment terms (amount, schedule, method) 5. Mutual releases (scope of claims released) 6. Confidentiality clause 7. Non-disparagement clause (optional but common) 8. Representations and warranties 9. Breach/default provisions 10. Governing law and jurisdiction 11. Signatures and date Payment Structures: Lump sum: Full payment within 15-30 days Installments: Monthly/quarterly over defined period Structured: Annuity purchased for long-term payments Combination: Initial lump sum + installments Key clause: "Time is of the essence" for payment deadlines Default clause: if payment missed, full amount accelerates Enforceability: Most jurisdictions: settlement = enforceable contract Some states: can be entered as court judgment (if pending case) International: Singapore Convention on Mediation (2020) Allows cross-border enforcement of mediated settlements Similar to New York Convention for arbitration awards Tax Considerations: Physical injury: generally tax-free (IRC §104) Emotional distress: taxable unless linked to physical injury Lost wages/income: taxable as ordinary income Punitive damages: always taxable Attorney fees: complex — may be deductible Interest: taxable 1099 reporting: settlement payments >$600 reported Allocation: specify what each dollar is for in the agreement Confidentiality: Standard clause: parties agree not to disclose terms Exception: may disclose to attorneys, accountants, tax advisors Exception: may disclose if required by law/subpoena Remedy for breach: liquidated damages clause recommended Note: existence of settlement may be public even if terms are not Common Pitfalls: - Vague language ("reasonable" without defining) - Missing deadlines for performance - No default/breach remedy specified - Failing to address all claims (related and unrelated) - Not specifying who pays mediator/legal fees - Forgetting tax allocation - No integration clause (prior agreements superseded) EOF } cmd_ethics() { cat << 'EOF' === Mediator Ethics === Core Ethical Standards (Model Standards of Conduct — ABA/AAA/ACR): 1. Self-Determination: Parties make their own decisions Mediator cannot impose a solution Mediator cannot coerce or unduly influence If party seems unable to participate → address or terminate Informed consent: parties understand process and options 2. Impartiality: No favoritism, bias, or prejudice Disclose any potential conflicts of interest If bias develops during mediation → withdraw Equal time and attention to both parties Perception matters — avoid even appearance of bias 3. Conflicts of Interest: Prior relationship with any party → disclose Financial interest in outcome → disclose Former representation of party → disclose Ongoing professional relationship → disclose When in doubt: disclose. Let parties decide. 4. Confidentiality: Everything said in mediation is confidential Caucus communications: confidential unless permission given Mediator cannot be compelled to testify about mediation Exceptions: threats of harm, child abuse, court order Document retention: clarify policy in advance 5. Quality of the Process: Maintain competence through training and practice Only mediate within areas of competence Ensure parties understand the process Promote honest communication End mediation if it becomes inappropriate 6. Fees and Billing: Disclose fee structure before mediation Reasonable and clearly stated Typically split 50/50 between parties Contingency fees prohibited (creates outcome bias) Pro bono obligation recognized Ethical Dilemmas: Scenario: One party clearly doesn't understand their legal rights Response: Suggest they consult an attorney (don't give legal advice) Scenario: You suspect fraud in the settlement Response: May withdraw; cannot facilitate fraudulent agreement Scenario: Party threatens violence Response: Terminate immediately, ensure safety, may report Scenario: Child custody — child's interests not represented Response: Suggest independent representation for the child Mediator Certification: No universal license required (varies by jurisdiction) Common training: 40-hour basic mediation course Advanced: 100+ hours for family, commercial, etc. Court-approved mediator panels: state-specific requirements Organizations: ACR, IMI, CEDR, Singapore Mediation Centre EOF } cmd_checklist() { cat << 'EOF' === Mediation Readiness Checklist === Pre-Mediation: [ ] Mediator selected and agreed by both parties [ ] Mediation agreement reviewed and signed [ ] Confidentiality agreement executed [ ] Date, time, venue confirmed [ ] Separate caucus rooms arranged [ ] Position statement prepared and submitted [ ] Key documents assembled and organized Case Analysis: [ ] BATNA calculated (best alternative to settlement) [ ] WATNA calculated (worst alternative) [ ] MLATNA estimated (most likely alternative) [ ] Litigation cost estimated (through trial) [ ] Timeline to trial estimated [ ] Risk assessment completed (probability × impact) Authority & Team: [ ] Decision-maker will attend in person [ ] Settlement authority range approved [ ] Insurance carrier notified (if applicable) [ ] Adjuster with authority attending (if applicable) [ ] Expert available by phone (if needed) [ ] All necessary parties included Negotiation Strategy: [ ] Opening demand/offer planned [ ] Concession strategy mapped (how many rounds, how much per) [ ] Package deal options identified [ ] Non-monetary creative solutions brainstormed [ ] Bottom line defined (with reasoning) [ ] Walk-away point determined Documentation Ready: [ ] Contract/agreement in dispute [ ] Damages calculation with supporting docs [ ] Key emails/correspondence [ ] Expert reports [ ] Prior offers/demands chronology [ ] Settlement agreement template Day-Of: [ ] Arrive early, settle into room [ ] Mobile phones silenced [ ] Opening statement prepared (3-5 minutes) [ ] Focus on interests, not just positions [ ] Listen more than talk in joint session [ ] Be candid with mediator in caucus [ ] Stay until mediator calls the session EOF } show_help() { cat << EOF mediation v$VERSION — Alternative Dispute Resolution Reference Usage: script.sh <command> Commands: intro Mediation overview, principles, comparison process Mediation stages from opening to closure techniques Reframing, reality testing, BATNA, bracketing types ADR spectrum: negotiation to arbitration preparation How to prepare for a mediation session settlement Settlement agreement terms and enforceability ethics Mediator ethical standards and dilemmas checklist Mediation readiness checklist help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; process) cmd_process ;; techniques) cmd_techniques ;; types) cmd_types ;; preparation) cmd_preparation ;; settlement) cmd_settlement ;; ethics) cmd_ethics ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "mediation v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Fertigation reference — injecting fertilizers through irrigation systems, nutrient scheduling, injection methods, and crop-specific programs. Use when design...
--- name: "fertigation" version: "1.0.0" description: "Fertigation reference — injecting fertilizers through irrigation systems, nutrient scheduling, injection methods, and crop-specific programs. Use when designing fertigation systems, calculating nutrient rates, or managing drip/sprinkler fertilizer delivery." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [fertigation, irrigation, fertilizer, agriculture, nutrients, drip] category: "agriculture" --- # Fertigation — Fertigation Systems Reference Quick-reference skill for fertigation techniques, nutrient management, and injection system design. ## When to Use - Designing fertigation systems for drip or sprinkler irrigation - Calculating fertilizer injection rates and concentrations - Selecting injection equipment (Venturi, positive displacement, proportional) - Planning nutrient schedules for different crop growth stages - Troubleshooting fertigation uniformity and compatibility issues ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of fertigation — principles, advantages, and system components. ### `methods` ```bash scripts/script.sh methods ``` Injection methods — Venturi, diaphragm pump, piston pump, proportional dosing. ### `nutrients` ```bash scripts/script.sh nutrients ``` Fertilizer types for fertigation — solubility, compatibility, and stock solutions. ### `scheduling` ```bash scripts/script.sh scheduling ``` Nutrient scheduling by crop growth stage — vegetative, flowering, fruiting. ### `calculations` ```bash scripts/script.sh calculations ``` Injection rate calculations — ppm, EC targets, dilution ratios, flow rates. ### `drip` ```bash scripts/script.sh drip ``` Drip fertigation specifics — emitter clogging prevention, acid injection, flushing. ### `monitoring` ```bash scripts/script.sh monitoring ``` Monitoring fertigation — EC, pH, runoff analysis, sensor placement. ### `problems` ```bash scripts/script.sh problems ``` Common fertigation problems — precipitates, uneven distribution, salt buildup. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `FERTIGATION_DIR` | Data directory (default: ~/.fertigation/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # fertigation — Fertigation Systems Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Fertigation === Fertigation is the injection of fertilizers and soil amendments into an irrigation system, delivering nutrients directly to the root zone with irrigation water. Advantages Over Broadcast Fertilization: Nutrient efficiency +30-50% uptake (nutrients delivered to roots) Water savings Precise delivery, less runoff and leaching Labor reduction Automated application, no spreading equipment Flexibility Adjust nutrients daily based on crop stage Uniformity Even distribution if irrigation is uniform Reduced compaction No tractor passes through the field System Components: Water Source → Filter → Injection Point → Distribution → Emitters 1. Water Source Well, reservoir, canal, municipal supply Water quality affects fertigation (pH, alkalinity, dissolved minerals) 2. Filtration Sand media filter: removes organic matter (100-200 mesh) Disc filter: removes particles (120-200 mesh) Screen filter: basic particle removal (80-150 mesh) Always filter BEFORE injection point to protect injector Always filter AFTER injection if precipitates are possible 3. Injection Equipment Venturi injector, diaphragm pump, piston pump, proportional doser (see 'methods' command for details) 4. Distribution System Drip tape/tubing: most common for fertigation Micro-sprinklers: good for tree crops Center pivot: large-scale field crops Sprinkler: possible but less efficient 5. Control System Timer-based: simple, fixed schedule Sensor-based: EC/pH sensors drive injection rate Computer-controlled: most precise, logs everything Key Terms: EC Electrical Conductivity — measures total dissolved salts (dS/m or mS/cm) ppm Parts per million — concentration of specific nutrient pH Acidity/alkalinity of solution (target: 5.5-6.5 for most crops) Stock Solution Concentrated fertilizer mix for injection EOF } cmd_methods() { cat << 'EOF' === Fertigation Injection Methods === --- Venturi Injector --- How: Water flows through a constriction, creating suction that draws concentrate from a tank Cost: $20-200 (cheapest option) Pros: No electricity needed, simple, reliable Cons: Creates 15-30% pressure drop, variable injection rate Rate changes with pressure/flow fluctuations Best for: small farms, gravity-fed systems, backup injection Sizing: match to system flow rate (GPM rating) --- Diaphragm Pump (Positive Displacement) --- How: Electric motor drives diaphragm, pumps fixed volume per stroke Cost: $500-3,000 Pros: Constant injection rate regardless of system pressure Precise dosing, handles concentrated solutions Cons: Requires electricity, moving parts wear out Chemical compatibility of diaphragm material Best for: medium operations, acidification, precise nutrient programs Materials: Viton (acids), EPDM (general), Teflon (aggressive chemicals) --- Piston Pump --- How: Motor-driven piston delivers precise volume per stroke Cost: $1,000-10,000 Pros: Very precise, handles high pressures, durable Cons: Expensive, requires maintenance, crystallization risk Best for: large operations, high-pressure systems --- Proportional Doser --- How: Water flow drives injection mechanism proportionally Fixed ratio (e.g., 1:100, 1:200) regardless of flow rate Cost: $200-2,000 Pros: No electricity, self-adjusting to flow, consistent concentration Cons: Ratio is fixed (or manually adjustable), limited flow range Best for: greenhouse, nursery, consistent dilution ratio operations Example: Dosatron, MixRite --- Injection Point Location --- Rule: inject AFTER the pump, AFTER the main filter If using acid + fertilizer: separate injection points (acid first, then fertilizer downstream) Minimum distance between injection points: 10× pipe diameter Check valve required between tank and injection point (prevents irrigation water backflowing into tank) --- Anti-Siphon / Backflow Prevention --- MANDATORY — prevents fertilizer from contaminating water supply Types: Air gap: physical gap between supply and tank Check valve: one-way flow device Reduced pressure backflow preventer: most reliable Required by law in most jurisdictions EOF } cmd_nutrients() { cat << 'EOF' === Fertigation Nutrient Sources === --- Nitrogen (N) Sources --- Calcium Nitrate Ca(NO3)2: 15.5-0-0 + 19% Ca Most common fertigation N source, fully soluble Alkaline reaction, raises pH slightly ⚠ Do NOT mix with sulfate or phosphate fertilizers (precipitates) Potassium Nitrate KNO3: 13-0-44 Dual-purpose N + K, fully soluble Clean, no residue Ammonium Nitrate NH4NO3: 34-0-0 Highly soluble, acidifying effect Security concerns (explosive), restricted in some areas UAN (Urea Ammonium Nitrate): 32-0-0 Liquid, convenient, widely available ⚠ Biuret content can damage through drip systems Ammonium Sulfate (NH4)2SO4: 21-0-0 + 24% S Strongly acidifying, good for high-pH soils Lower solubility — prepare dilute stock solutions --- Phosphorus (P) Sources --- Phosphoric Acid H3PO4: 0-52-0 Dual purpose: P fertilizer + pH control (acidification) Excellent for drip — helps prevent calcium carbonate clogging ⚠ Corrosive — handle with care MAP (Mono-Ammonium Phosphate): 12-61-0 Highly soluble, slight acidifying effect ⚠ Do NOT mix with calcium fertilizers (precipitates) --- Potassium (K) Sources --- Potassium Chloride KCl: 0-0-60 Cheapest K source, good solubility ⚠ Chloride-sensitive crops: avoid (strawberry, lettuce, beans) Potassium Sulfate K2SO4: 0-0-50 + 18% S For chloride-sensitive crops Lower solubility — dissolve in warm water Potassium Nitrate KNO3: 13-0-44 Premium source, no chloride, fully soluble --- Compatibility Chart --- ✓ Compatible ✗ Precipitates ⚠ Mix with caution Ca(NO3)2 KNO3 MAP KCl K2SO4 MgSO4 Ca(NO3)2 - ✓ ✗ ✓ ✗ ✗ KNO3 ✓ - ✓ ✓ ✓ ✓ MAP ✗ ✓ - ✓ ✓ ✓ KCl ✓ ✓ ✓ - ✓ ✓ K2SO4 ✗ ✓ ✓ ✓ - ✓ MgSO4 ✗ ✓ ✓ ✓ ✓ - KEY RULE: Never mix calcium with sulfate or phosphate in same tank! Use two stock tanks: Tank A (calcium) and Tank B (phosphate/sulfate) EOF } cmd_scheduling() { cat << 'EOF' === Fertigation Scheduling === --- General Crop Stage Nutrient Ratios (N:P:K) --- Seedling/Transplant: 1 : 2 : 1 High P for root development Low total concentration (EC 0.5-1.0 dS/m) Vegetative Growth: 3 : 1 : 2 High N for leaf and stem growth Moderate EC (1.5-2.5 dS/m) Flowering/Fruit Set: 1 : 1 : 3 Reduce N, increase K for fruit quality P for flower development EC 2.0-3.0 dS/m Fruiting/Maturation: 1 : 0.5 : 4 High K for fruit sizing and quality Low N to prevent excessive vegetative growth Add Ca for fruit firmness (tomato, pepper) Late Season/Harvest: 0 : 0 : 1 Reduce or stop N 2-4 weeks before harvest K only for final quality --- Frequency Guidelines --- Sandy soil: fertigate every irrigation (frequent, low concentration) Loam soil: fertigate 2-3× per week Clay soil: fertigate 1-2× per week (higher concentration) Hydroponics: continuous fertigation Container/pot: every irrigation --- Pulse Fertigation --- Most efficient method for drip systems: Phase 1: Water only (5-10 min to wet soil) Phase 2: Fertigation (inject nutrients with water) Phase 3: Water only (5-10 min to flush lines and push nutrients into root zone) This prevents fertilizer from sitting in lines and clogging emitters. Also pushes nutrients below surface where roots are. --- Seasonal Adjustments --- Summer/hot: increase frequency, decrease concentration (more water needed, same nutrients per day) Winter/cool: decrease frequency, increase concentration (less water, same nutrients) Rain events: skip fertigation, check soil EC Drought: water first, then fertigate (never on dry soil) EOF } cmd_calculations() { cat << 'EOF' === Fertigation Calculations === --- PPM from Fertilizer Weight --- ppm = (fertilizer weight in mg) / (water volume in liters) ppm = (fertilizer weight in grams × 1,000,000) / (water volume in liters × 1,000,000) Example: Dissolve 100g KNO3 (13-0-44) in 1000L water N = 100g × 0.13 = 13g N in 1000L = 13 ppm N K₂O = 100g × 0.44 = 44g K₂O = 44 ppm K₂O K = 44 × 0.83 = 36.5 ppm K (elemental) --- Stock Solution Concentration --- Common dilution ratios: 1:100 → 1 liter concentrate per 100 liters water 1:200 → 1 liter concentrate per 200 liters water To achieve 150 ppm N from 1:100 dilution: Need 150 ppm in final solution Stock must be 100× concentrated = 15,000 ppm N Using calcium nitrate (15.5% N): 15,000 ppm ÷ 155,000 ppm per g/L = 0.097 g/mL = 97 grams per liter of stock solution --- Injection Rate --- Injection rate (L/hr) = System flow (L/hr) × Desired concentration (ppm) ÷ Stock concentration (ppm) Example: 5000 L/hr system, want 100 ppm N, stock = 50,000 ppm N Rate = 5000 × 100 / 50,000 = 10 L/hr injection rate --- EC Estimation --- Rule of thumb: 1 dS/m EC ≈ 640-700 ppm total dissolved salts For fertilizer solutions: EC increase ≈ 0.001 per ppm of nutrients Target EC by crop (in irrigation water): Lettuce, strawberry: 1.0-1.5 dS/m Tomato, pepper, cucumber: 2.0-3.5 dS/m Rose, gerbera: 1.5-2.5 dS/m --- Water Quality Adjustment --- Source water EC 0.5 dS/m → only add 1.0-2.5 dS/m from fertilizer Source water EC 1.5 dS/m → analyze composition, credit existing nutrients High bicarbonate water (>3 meq/L) → add acid to lower pH and alkalinity Acid injection rate: determined by titration of source water EOF } cmd_drip() { cat << 'EOF' === Drip Fertigation Specifics === Drip irrigation is the ideal delivery method for fertigation: - Precise root zone delivery - No leaf wetting (reduces disease) - Highest efficiency (90-95% of water reaches roots) - Best fertilizer uniformity when properly designed --- Emitter Clogging Prevention --- #1 issue in drip fertigation. Three types of clogging: Physical (particles): Prevention: 120-200 mesh filtration (120 micron) Fix: flush lines at high velocity quarterly Chemical (precipitates): Cause: calcium + sulfate = gypsum crystals calcium + phosphate = calcium phosphate iron + oxygen = iron oxide (rusty deposits) Prevention: - Keep pH < 7.0 in irrigation water - Never mix incompatible fertilizers - Inject acid (phosphoric or sulfuric) to maintain pH - Flush with acid solution (pH 2.0) quarterly Biological (algae, bacteria): Cause: organic matter + nutrients + sunlight = biofilm Prevention: - Chlorination: 1-2 ppm free chlorine continuously or 10-20 ppm shock treatment monthly - Hydrogen peroxide: 30-50 ppm periodically - Keep fertilizer tanks covered (no light) --- Line Flushing Protocol --- Frequency: monthly minimum, weekly in problem areas Method: 1. Open flush valves at end of laterals 2. Run water at maximum velocity (>0.5 m/s) 3. Flush until water runs clear (2-5 minutes) 4. Close valves starting from farthest lateral After fertigation: always flush with clear water (10-15 min) --- Drip System Design for Fertigation --- Emission uniformity target: >90% (EU = q_min / q_avg) Lateral length: shorter = more uniform (follow manufacturer specs) Pressure regulation: pressure-compensating emitters recommended Mainline sizing: adequate for peak flow + injection pressure drop Injection point: after filter, before first zone valve EOF } cmd_monitoring() { cat << 'EOF' === Fertigation Monitoring === --- EC (Electrical Conductivity) --- What: measures total dissolved salts in solution Units: dS/m (deciSiemens/meter) or mS/cm (same thing) Measurement points: Source water: background EC before fertilizer After injection: EC of fertigation solution Soil/root zone: EC of soil solution (1:2 extract or pour-through) Drainage/runoff: EC of leachate Interpretation: Irrigation EC < root zone EC → salt accumulating (reduce fertilizer or increase leaching) Drainage EC ≈ irrigation EC → nutrients passing through (reduce rate) Drainage EC > 1.5× irrigation EC → salt stress risk (leach with clear water) --- pH Monitoring --- Target: 5.5-6.5 for most crops (nutrient availability optimal) pH too high (>7.0): Iron, manganese, zinc become unavailable Calcium phosphate precipitates in lines Fix: inject acid (phosphoric, sulfuric, or nitric) pH too low (<5.0): Aluminum and manganese toxicity risk Calcium and magnesium deficiency Fix: reduce acid injection, add potassium bicarbonate --- Sensor Placement --- Inline sensors (after injection): EC sensor: verify injection is occurring and at correct rate pH sensor: verify acid injection maintaining target Flow meter: calculate total volume applied Soil sensors: Tensiometer or soil moisture sensor: at 30cm and 60cm depth Soil EC sensor: at root zone depth Place at representative locations (not at edge of bed) --- Runoff/Leachate Analysis --- Collect drainage water from beneath root zone Frequency: weekly during active fertigation season Test for: EC, pH, N (NO3 + NH4), P, K, Ca, Mg Purpose: verify nutrient uptake, detect imbalances --- Record Keeping --- Log daily: Injection rate and duration Fertilizer type and concentration EC and pH of solution Irrigation volume Weather conditions Log weekly: Soil EC and moisture readings Runoff EC and pH Visual crop assessment Log monthly: Full nutrient analysis of soil and drainage Equipment calibration checks Filter cleaning and line flushing dates EOF } cmd_problems() { cat << 'EOF' === Common Fertigation Problems === 1. Precipitate Formation (White Deposits) Cause: Calcium + sulfate or phosphate mixing in concentrated solution Symptoms: white crystite in lines, clogged emitters, reduced flow Fix: Use separate stock tanks (A: calcium, B: sulfate/phosphate) Inject from each tank at separate points Flush system after each fertigation event Prevention: NEVER mix calcium nitrate with potassium sulfate, magnesium sulfate, or MAP in the same tank 2. Uneven Nutrient Distribution Cause: poor irrigation uniformity, pressure variation, clogged emitters Symptoms: nutrient deficiency in some areas, excess in others Fix: check emission uniformity (EU), clean/replace clogged emitters, install pressure regulators, reduce lateral length Goal: EU > 90% for fertigation to be effective 3. Salt Buildup in Soil Cause: insufficient leaching, high EC fertigation, low rainfall Symptoms: white salt crust on soil surface, leaf tip burn, declining yields, high soil EC readings Fix: leaching irrigation (apply 20-30% more water than ET) reduce fertilizer concentration switch to lower-salt fertilizer sources (nitrate vs chloride) 4. pH Drift Cause: alkaline source water neutralizes acid injection, ammonium fertilizers acidify soil over time Symptoms: nutrient lockout (iron chlorosis at high pH), toxicity symptoms at low pH Fix: regular pH testing of irrigation solution and soil, adjust acid injection rate, use appropriate N source 5. Injector Malfunction Cause: worn diaphragm, check valve failure, air lock, clogged suction line Symptoms: EC doesn't change when injection should be occurring, fertilizer tank level not dropping Fix: check suction strainer, verify check valve, bleed air, replace diaphragm/seals on schedule 6. Over-Fertilization Cause: injection rate too high, wrong stock concentration, timer malfunction Symptoms: leaf burn, wilting (osmotic stress), high EC runoff Fix: immediately flush with clear water for extended period reduce injection rate, verify calculations install EC alarm/cutoff on injection system 7. Algae in Fertilizer Tanks Cause: light + nutrients + warm temperature Symptoms: green/brown growth in tanks, clogged suction line Fix: use opaque tanks, keep covered, add chlorine or peroxide clean tanks between batches 8. Nutrient Antagonism Cause: excess of one nutrient blocking uptake of another Examples: Excess K → blocks Ca and Mg uptake Excess NH4 → blocks Ca, Mg, K uptake Excess P → blocks Zn and Fe uptake Fix: maintain balanced nutrient ratios, test tissue regularly, adjust individual nutrient sources as needed EOF } show_help() { cat << EOF fertigation v$VERSION — Fertigation Systems Reference Usage: script.sh <command> Commands: intro Fertigation principles and system components methods Injection methods: Venturi, pump, proportional nutrients Fertilizer types, solubility, compatibility scheduling Nutrient scheduling by crop growth stage calculations Injection rate and concentration math drip Drip-specific issues: clogging, flushing, design monitoring EC, pH, sensors, and runoff analysis problems Common problems and troubleshooting help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; methods) cmd_methods ;; nutrients) cmd_nutrients ;; scheduling) cmd_scheduling ;; calculations) cmd_calculations ;; drip) cmd_drip ;; monitoring) cmd_monitoring ;; problems) cmd_problems ;; help|--help|-h) show_help ;; version|--version|-v) echo "fertigation v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
COPPA compliance reference — children's online privacy, parental consent, data collection rules, FTC enforcement. Use when building apps for children under 1...
--- name: "coppa" version: "1.0.0" description: "COPPA compliance reference — children's online privacy, parental consent, data collection rules, FTC enforcement. Use when building apps for children under 13 or reviewing COPPA obligations." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [coppa, privacy, children, ftc, parental-consent, online-safety, legal] category: "legal" --- # COPPA — Children's Online Privacy Protection Act Reference Quick-reference skill for COPPA compliance, parental consent mechanisms, and FTC enforcement guidelines. ## When to Use - Building websites or apps directed at children under 13 - Reviewing data collection practices for COPPA compliance - Implementing verifiable parental consent mechanisms - Understanding FTC enforcement actions and penalties - Auditing third-party SDKs for child-directed services ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of COPPA — history, purpose, scope, and the FTC's role. ### `scope` ```bash scripts/script.sh scope ``` Who COPPA applies to — operators, child-directed services, mixed-audience sites, and actual knowledge standard. ### `data` ```bash scripts/script.sh data ``` Personal information defined under COPPA — what counts as PI for children. ### `consent` ```bash scripts/script.sh consent ``` Verifiable Parental Consent (VPC) methods approved by the FTC. ### `notice` ```bash scripts/script.sh notice ``` Privacy notice requirements — what must be disclosed and how. ### `safeharbor` ```bash scripts/script.sh safeharbor ``` COPPA Safe Harbor programs and self-regulatory frameworks. ### `enforcement` ```bash scripts/script.sh enforcement ``` FTC enforcement actions, penalties, and notable COPPA cases. ### `checklist` ```bash scripts/script.sh checklist ``` COPPA compliance checklist for app and website developers. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `COPPA_DIR` | Data directory (default: ~/.coppa/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # coppa — COPPA Compliance Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === COPPA — Children's Online Privacy Protection Act === The Children's Online Privacy Protection Act (COPPA) is a U.S. federal law enacted in 1998 (effective April 2000) that imposes requirements on operators of websites and online services directed at children under 13. Enforcing Agency: Federal Trade Commission (FTC) Statute: 15 U.S.C. §§ 6501–6506 Rule: 16 CFR Part 312 (COPPA Rule) Key Dates: 1998 COPPA signed into law 2000 FTC COPPA Rule takes effect 2013 Major amendments — mobile apps, geolocation, photos/video added 2024 FTC proposes further updates (ed-tech, targeted ads) Core Requirements: 1. Post a clear, comprehensive privacy policy 2. Provide direct notice to parents before collecting data 3. Obtain verifiable parental consent (VPC) before collection 4. Allow parents to review/delete their child's data 5. Allow parents to revoke consent 6. Maintain confidentiality, security, and integrity of data 7. Retain data only as long as needed 8. Do not condition participation on unnecessary data collection Penalties: - Up to $50,120 per violation (2024 adjusted amount) - FTC can seek injunctions, civil penalties, and consent decrees - No private right of action (only FTC enforces) EOF } cmd_scope() { cat << 'EOF' === COPPA Scope — Who Must Comply === COPPA applies to: 1. Operators of Commercial Websites/Online Services - Directed to children under 13, OR - Have actual knowledge they collect PI from children under 13 2. "Directed to Children" Factors (FTC totality test): - Subject matter (kid-friendly content) - Visual content (animated characters, bright colors) - Use of child-oriented language - Music and audio content targeting children - Age of models/actors on the site - Presence of child celebrities or characters - Ads for/on the service targeting children - Competent empirical evidence about age of audience 3. Mixed-Audience Sites: - Sites that attract BOTH adults and children - May use age-screening to identify child users - COPPA applies only to users identified as under 13 - Age gate must not encourage false age entry 4. "Actual Knowledge" Standard: - Non-child-directed sites that learn a user is under 13 - Triggered by: age disclosure, parental complaint, chat content - Once triggered, must comply for that user 5. Third-Party Operators: - Ad networks, plug-ins, analytics SDKs on child-directed sites - Share COPPA obligations with the site operator - Can be independently liable for collecting child PI NOT Covered: - Non-commercial sites (nonprofits under certain conditions) - Sites directed to general audience with no child focus - Offline data collection - Children 13 and older (see state laws like CCPA for teens) EOF } cmd_data() { cat << 'EOF' === Personal Information Under COPPA === COPPA defines "personal information" broadly for children under 13: Covered Data Types: 1. Full name (first + last) 2. Home or physical address (including street name and city/town) 3. Online contact info (email, IM identifier) 4. Screen name / username (if used as online contact info) 5. Telephone number 6. Social Security number 7. Persistent identifier (cookie, IP, device ID, processor serial) — when used to recognize a user over time/across sites 8. Photo, video, or audio file containing child's image or voice 9. Geolocation info (precise enough to identify street/city) 10. Any combination of info that permits physical or online contact 2013 Amendments Added: - Photos/video/audio with child's image or voice - Geolocation information - Persistent identifiers used for behavioral advertising - Screen names that function as online contact information What's NOT Personal Information: - Aggregated, de-identified data (properly anonymized) - Persistent identifiers used solely for internal operations: • Maintaining or analyzing site function • Performing network communications • Serving contextual ads (not behavioral) • Capping ad frequency • Protecting security/integrity • Legal compliance Internal Operations Exception: Operators may collect persistent identifiers WITHOUT consent IF used solely for "support for internal operations" AND no personal information is otherwise collected. This allows basic analytics without parental consent. EOF } cmd_consent() { cat << 'EOF' === Verifiable Parental Consent (VPC) Methods === Before collecting PI from a child under 13, operators must obtain verifiable parental consent using one of these FTC-approved methods: Approved Methods: 1. Signed Consent Form (mail/fax/scan) - Parent prints, signs, and returns a physical form - Most burdensome; rarely used for digital services 2. Credit Card Transaction - Parent provides credit card for a purchase or fee - Notify parent that card is being used for consent verification - Transaction must be monetary (not just card number) 3. Toll-Free Phone Call - Parent calls a toll-free number to provide consent - Trained personnel must verify caller is parent - Must maintain records 4. Video Conference - Parent connects via video call - Operator verifies parent's identity visually - Must match to a form of ID 5. Government-Issued ID Check - Parent submits copy of government ID - Operator verifies and deletes ID after verification - Cross-reference with database, then delete 6. Knowledge-Based Authentication - Parent answers questions from a database - Questions must be sufficiently difficult - Not easily guessable by a child 7. "Email Plus" (limited use only) - Parent provides consent via email - PLUS operator sends a delayed confirmation email - Only for internal use — NOT for disclosing data to third parties Consent Must Include: - Types of PI being collected - How PI will be used - Whether PI will be disclosed to third parties - Parent's right to refuse and still let child use service - Link to online privacy policy Consent Is NOT Required When: - Collecting email solely to respond one time to a child - Collecting email for safety/security purposes - Collecting persistent identifiers for internal operations only EOF } cmd_notice() { cat << 'EOF' === COPPA Notice Requirements === Two Types of Notice Required: 1. ONLINE PRIVACY POLICY (posted on website/app) Must Include: □ Name, address, phone, email of all operators collecting data □ Description of PI collected from children □ Description of how PI is used □ Whether PI is disclosed to third parties and for what purpose □ Parent's right to: - Review child's PI - Delete child's PI - Refuse further collection/use □ Procedures for parent to exercise rights □ Statement that operator cannot condition participation on collection of more PI than reasonably necessary Placement: - Homepage link: clear, prominent ("Privacy Policy" or "Children's Privacy") - Each area where PI is collected must link to policy - Must be legible and clearly written (no legal jargon overload) 2. DIRECT NOTICE TO PARENTS (before collecting data) Must Include: □ That the site is collecting PI from their child □ That parental consent is required □ Specific PI being collected □ How the PI will be used □ Whether PI will be shared with third parties □ Link to the full online privacy policy □ How parent can provide consent □ That if parent doesn't consent within reasonable time, operator will delete PI collected from the child Format: - Email to parent (child provides parent's email) - Must be clear and not buried in other content - Must be in language parent can understand EOF } cmd_safeharbor() { cat << 'EOF' === COPPA Safe Harbor Programs === Safe Harbor allows industry groups to submit self-regulatory guidelines to the FTC for approval. Members who comply with approved guidelines are deemed in compliance with COPPA. Benefits of Safe Harbor Membership: - Compliance presumption (burden shifts to FTC to disprove) - Industry-specific guidance tailored to sector - Monitoring and accountability framework - Reduced regulatory risk FTC-Approved Safe Harbor Programs: 1. kidSAFE Seal Program - For child-directed websites and apps - Covers digital products, games, educational tools - Provides kidSAFE, kidSAFE+, and COPPA+ seals 2. CARU (Children's Advertising Review Unit) - Part of BBB National Programs - Focus on advertising practices directed at children - Monitors national child-directed advertising 3. Aristotle Inc. (COPPA Certification) - Age/identity verification specialist - Provides parental consent verification services - Focuses on age-gating and identity tech 4. ESRB Privacy Certified - Entertainment Software Rating Board program - Focus on games, apps, and digital entertainment - Well-known in gaming industry 5. PRIVO (Privacy Vaults Online) - Age verification and parental consent platform - Ed-tech and kids' app focused - Provides SDK/API for consent management Requirements to Maintain Safe Harbor: - Subject to self-regulatory program's oversight - Regular audits and assessments - Breach notification obligations - Annual reporting to FTC - FTC can revoke Safe Harbor status EOF } cmd_enforcement() { cat << 'EOF' === COPPA Enforcement — FTC Actions === The FTC has brought 40+ enforcement actions since COPPA's enactment. Notable Cases: Epic Games / Fortnite (2022) Fine: $275 million (largest COPPA penalty ever) Violation: Collected PI from children without parental consent, enabled live voice/text chat with strangers by default, used dark patterns to trick users into purchases. Google / YouTube (2019) Fine: $170 million Violation: Collected persistent identifiers from child viewers for behavioral advertising without parental consent. Led to YouTube creating "YouTube Kids" and restricting data collection on child-directed channels. Musical.ly / TikTok (2019) Fine: $5.7 million Violation: Collected PI (names, emails, bios, location) from children under 13 with actual knowledge of their age. App required to delete underage accounts. VTech Electronics (2018) Fine: $650,000 Violation: Collected PI from children through kids' tablets and learning apps without proper parental notice/consent. Yelp (2014) Fine: $450,000 Violation: App registration collected birthdates showing users were under 13, but continued collecting PI anyway. Common Violation Patterns: - Failing to post compliant privacy policies - Collecting data without parental consent - Inadequate data security for children's PI - Using persistent identifiers for behavioral ads on kid sites - Third-party SDKs collecting data from child-directed apps - Not providing parents with access/deletion rights - Using dark patterns to circumvent age gates EOF } cmd_checklist() { cat << 'EOF' === COPPA Compliance Checklist === Threshold Assessment: [ ] Determine if site/app is "directed to children" under 13 [ ] If mixed-audience, implement age-screening mechanism [ ] Identify all points where PI is collected [ ] Inventory all third-party SDKs/plug-ins and their data practices Privacy Policy: [ ] Policy is prominently linked from homepage [ ] Lists all operators collecting PI [ ] Describes types of PI collected [ ] Explains how PI is used and shared [ ] Describes parental rights (review, delete, revoke) [ ] States operator won't condition access on excess collection [ ] Policy is clear, readable, and up-to-date Parental Consent: [ ] VPC mechanism implemented (FTC-approved method) [ ] Direct notice sent to parent before collection [ ] Notice describes PI collected and how it's used [ ] Parent can decline and child can still use basic features [ ] Consent records maintained Data Practices: [ ] Collect only PI reasonably necessary [ ] PI retained only as long as needed [ ] Reasonable security measures for child PI [ ] Child PI not disclosed to unauthorized third parties [ ] Third-party recipients maintain adequate protections Parental Rights: [ ] Parents can request review of child's PI [ ] Parents can request deletion of child's PI [ ] Parents can revoke consent for future collection [ ] Respond to parent requests in reasonable timeframe Third-Party Compliance: [ ] Audit all SDKs for COPPA compliance [ ] Disable behavioral advertising on child-directed content [ ] Contractual obligations for third parties handling child PI [ ] Regular monitoring of third-party data practices Age Verification (if mixed-audience): [ ] Age gate does not encourage falsification [ ] Age gate uses neutral date entry (not "are you 13?") [ ] Under-13 users routed to COPPA-compliant experience [ ] Age information not stored as persistent identifier EOF } show_help() { cat << EOF coppa v$VERSION — COPPA Compliance Reference Usage: script.sh <command> Commands: intro COPPA overview — history, purpose, and core requirements scope Who COPPA applies to — operators, sites, and thresholds data Personal information defined under COPPA consent Verifiable Parental Consent (VPC) approved methods notice Privacy notice requirements for parents safeharbor COPPA Safe Harbor programs and self-regulation enforcement FTC enforcement actions and notable cases checklist COPPA compliance checklist for developers help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; scope) cmd_scope ;; data) cmd_data ;; consent) cmd_consent ;; notice) cmd_notice ;; safeharbor) cmd_safeharbor ;; enforcement) cmd_enforcement ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "coppa v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Project scaffolding reference — boilerplate generation, directory structures, template engines, and init patterns. Use when bootstrapping new projects or gen...
--- name: "create" version: "1.0.0" description: "Project scaffolding reference — boilerplate generation, directory structures, template engines, and init patterns. Use when bootstrapping new projects or generating starter code." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [create, scaffold, boilerplate, init, template, generator, devtools] category: "devtools" --- # Create — Project Scaffolding Reference Quick-reference skill for project scaffolding, boilerplate generation, and initialization patterns. ## When to Use - Bootstrapping a new project from scratch - Generating directory structures and boilerplate files - Understanding popular scaffolding tools and templates - Setting up project conventions (linting, testing, CI/CD) - Creating custom project generators ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of project scaffolding — why, when, and how. ### `structures` ```bash scripts/script.sh structures ``` Standard directory structures for common project types. ### `tools` ```bash scripts/script.sh tools ``` Popular scaffolding tools — create-react-app, cookiecutter, yeoman, etc. ### `templates` ```bash scripts/script.sh templates ``` Template engine patterns — variable substitution, conditionals, loops. ### `configs` ```bash scripts/script.sh configs ``` Essential config files every project needs — .gitignore, .editorconfig, CI, etc. ### `conventions` ```bash scripts/script.sh conventions ``` Project conventions — naming, versioning, commit messages, changelog. ### `monorepo` ```bash scripts/script.sh monorepo ``` Monorepo scaffolding — workspaces, nx, turborepo, lerna. ### `checklist` ```bash scripts/script.sh checklist ``` New project checklist — from idea to first commit. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `CREATE_DIR` | Data directory (default: ~/.create/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # create — Project Scaffolding Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Project Scaffolding Overview === Scaffolding is the automated generation of project boilerplate — directory structures, config files, starter code, and build setup. Why Scaffold? - Consistency across team projects - Reduce setup time (hours → minutes) - Enforce best practices from day one - Include security defaults (gitignore, env handling) - Standardize toolchain (linter, formatter, test runner) When to Scaffold: ✓ Starting a new microservice ✓ Creating a new library/package ✓ Spinning up a prototype ✓ Onboarding a new project type ✗ One-off scripts (just create the file) ✗ Modifying existing projects (use codemods) Scaffolding Approaches: 1. CLI Tools npm create, cargo init, django-admin startproject 2. Template Repos GitHub template repositories, degit 3. Generators Yeoman, Cookiecutter, Hygen 4. Custom Scripts Company-specific init scripts 5. IDE Integration VS Code snippets, IntelliJ project wizards Generation Strategies: Copy-based Copy template files, replace placeholders AST-based Parse and modify code programmatically Prompt-based Ask questions, generate based on answers Composition Combine multiple smaller templates AI-assisted LLM generates project based on description EOF } cmd_structures() { cat << 'EOF' === Standard Directory Structures === --- Node.js / TypeScript --- project/ ├── src/ │ ├── index.ts │ ├── routes/ │ ├── middleware/ │ ├── services/ │ ├── models/ │ └── utils/ ├── tests/ │ ├── unit/ │ └── integration/ ├── docs/ ├── scripts/ ├── .github/workflows/ ├── package.json ├── tsconfig.json ├── .eslintrc.json ├── .prettierrc ├── .gitignore ├── .env.example ├── Dockerfile └── README.md --- Python --- project/ ├── src/ │ └── project_name/ │ ├── __init__.py │ ├── main.py │ ├── models/ │ ├── services/ │ └── utils/ ├── tests/ │ ├── conftest.py │ ├── test_main.py │ └── fixtures/ ├── docs/ ├── scripts/ ├── pyproject.toml ├── requirements.txt (or Pipfile / poetry.lock) ├── .flake8 / ruff.toml ├── .gitignore ├── .env.example ├── Dockerfile ├── Makefile └── README.md --- Go --- project/ ├── cmd/ │ └── server/ │ └── main.go ├── internal/ │ ├── handler/ │ ├── service/ │ ├── repository/ │ └── model/ ├── pkg/ (public libraries) ├── api/ (OpenAPI specs, protobuf) ├── configs/ ├── scripts/ ├── go.mod ├── go.sum ├── Makefile ├── Dockerfile └── README.md --- Rust --- project/ ├── src/ │ ├── main.rs (or lib.rs) │ ├── config.rs │ └── handlers/ ├── tests/ ├── benches/ ├── examples/ ├── Cargo.toml ├── .gitignore └── README.md EOF } cmd_tools() { cat << 'EOF' === Popular Scaffolding Tools === Language-Specific: Node.js: npm create vite@latest my-app -- --template react-ts npx create-react-app my-app --template typescript npx create-next-app@latest my-app npm init fastify -- my-app npx nuxi init my-app Python: django-admin startproject myproject flask init (via cookiecutter-flask) poetry new my-package cookiecutter gh:audreyfeldroy/cookiecutter-pypackage uv init my-project Go: go mod init github.com/user/project gonew golang.org/x/example/hello my-project Rust: cargo init my-project cargo new my-library --lib cargo generate --git https://github.com/user/template Java: mvn archetype:generate spring init --dependencies=web my-app (Spring Boot) gradle init --type java-application Cross-Language Generators: Cookiecutter (Python-based): cookiecutter gh:user/template Supports: Jinja2 templates, prompts, hooks Ecosystem: 10,000+ templates on GitHub Yeoman (Node-based): yo generator-name Supports: prompts, file transforms, composition Ecosystem: 8,000+ generators on npm Hygen (Node-based): hygen component new --name MyComponent Template-based, lives in project (_templates/) Good for adding to existing projects degit (lightweight): npx degit user/repo my-project Downloads repo without git history Perfect for template repositories EOF } cmd_templates() { cat << 'EOF' === Template Engine Patterns === Variable Substitution: {{project_name}} → my-awesome-app {{author}} → Jane Doe {{license}} → MIT {{year}} → 2024 {{description}} → A web application for... Common Template Engines: Jinja2 (Cookiecutter): {{ cookiecutter.project_name }} {% if cookiecutter.use_docker == "y" %} Dockerfile content here {% endif %} EJS (Yeoman): <%= projectName %> <% if (useTypeScript) { %> tsconfig.json content <% } %> Handlebars (Hygen): {{name}} {{#if typescript}} TypeScript setup {{/if}} Go Templates (gonew): {{.ProjectName}} {{if .EnableAuth}} Auth middleware {{end}} Conditional File Generation: # Include Dockerfile only if docker option selected # Include CI config based on provider choice (GitHub, GitLab, etc.) # Include test setup based on framework choice Cookiecutter hooks (pre/post generation): hooks/ ├── pre_gen_project.py # Validate inputs └── post_gen_project.py # Clean up, git init, install deps Dynamic Filename Templates: {{cookiecutter.project_slug}}/ → my-project/ {{cookiecutter.module_name}}.py → app.py Best Practices: 1. Keep templates minimal — don't over-generate 2. Include .env.example, never .env 3. Provide sensible defaults for all prompts 4. Include README explaining the generated structure 5. Run linter/formatter as post-generation hook 6. Validate inputs (project name format, license choices) 7. Version your templates (tag releases) EOF } cmd_configs() { cat << 'EOF' === Essential Config Files === .gitignore (must have): # OS .DS_Store Thumbs.db # IDE .idea/ .vscode/ *.swp # Environment .env .env.local # Dependencies node_modules/ __pycache__/ venv/ # Build output dist/ build/ *.egg-info/ # Logs *.log .editorconfig (cross-IDE consistency): root = true [*] indent_style = space indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.md] trim_trailing_whitespace = false [*.py] indent_size = 4 .env.example (document required env vars): DATABASE_URL=postgresql://user:pass@localhost:5432/dbname API_KEY=your-api-key-here NODE_ENV=development PORT=3000 CI/CD Config: .github/workflows/ci.yml (GitHub Actions) .gitlab-ci.yml (GitLab CI) Jenkinsfile (Jenkins) .circleci/config.yml (CircleCI) Docker: Dockerfile Multi-stage build .dockerignore Exclude node_modules, .git, etc. docker-compose.yml Local dev services Code Quality: .eslintrc.json / .eslintrc.js (JS/TS linting) .prettierrc (JS/TS formatting) ruff.toml / pyproject.toml (Python linting) .golangci.yml (Go linting) rustfmt.toml (Rust formatting) Security: .npmrc (registry config) .nvmrc / .python-version / .tool-versions (runtime versions) renovate.json / dependabot.yml (dependency updates) EOF } cmd_conventions() { cat << 'EOF' === Project Conventions === Naming Conventions: Repository: kebab-case (my-awesome-project) Package: kebab-case (npm) or snake_case (Python/Rust) Module: snake_case (Python), camelCase (JS/TS) Class: PascalCase (universal) Function: camelCase (JS/TS/Java), snake_case (Python/Rust/Go) Constant: UPPER_SNAKE_CASE (universal) CSS class: kebab-case or BEM (block__element--modifier) Versioning (SemVer): MAJOR.MINOR.PATCH MAJOR Breaking changes (incompatible API changes) MINOR New features (backward-compatible) PATCH Bug fixes (backward-compatible) Pre-release: 1.0.0-alpha.1, 1.0.0-beta.2, 1.0.0-rc.1 Build meta: 1.0.0+build.123 Conventional Commits: feat: New feature → bumps MINOR fix: Bug fix → bumps PATCH docs: Documentation only style: Code style (no logic change) refactor: Code change (no feature/fix) perf: Performance improvement test: Adding/fixing tests chore: Build process, tooling ci: CI/CD changes Breaking change: add ! after type feat!: remove deprecated API endpoint Examples: feat(auth): add OAuth2 login support fix(api): handle null response from payment gateway docs: update installation instructions for v2 Changelog (Keep a Changelog format): ## [1.2.0] - 2024-01-15 ### Added - OAuth2 login support (#123) ### Fixed - Null response handling in payment API (#456) ### Changed - Updated Node.js requirement to >= 18 Branch Strategy: main / master Production-ready code develop Integration branch feature/xxx New features fix/xxx Bug fixes release/x.x.x Release preparation hotfix/xxx Production hotfixes EOF } cmd_monorepo() { cat << 'EOF' === Monorepo Scaffolding === What Is a Monorepo? Single repository containing multiple projects/packages. Shared tooling, consistent versioning, atomic changes across packages. Directory Structure: monorepo/ ├── apps/ │ ├── web/ (Next.js frontend) │ ├── api/ (Express backend) │ └── mobile/ (React Native) ├── packages/ │ ├── ui/ (Shared component library) │ ├── utils/ (Shared utilities) │ ├── config/ (Shared ESLint, TS configs) │ └── types/ (Shared TypeScript types) ├── tools/ ├── package.json (Root with workspaces) ├── turbo.json (Turborepo config) └── pnpm-workspace.yaml Workspace Managers: npm workspaces: "workspaces": ["packages/*", "apps/*"] pnpm workspaces: pnpm-workspace.yaml yarn workspaces: "workspaces": ["packages/*"] Build Orchestration: Turborepo: npx create-turbo@latest turbo run build --filter=web # Caches builds, runs tasks in parallel # Understands dependency graph Nx: npx create-nx-workspace@latest nx build web nx affected --target=test # Computation caching, affected detection # Rich plugin ecosystem Lerna (legacy, now Nx-powered): npx lerna init lerna run build lerna publish Cross-Package References: # package.json in apps/web { "dependencies": { "@myorg/ui": "workspace:*", "@myorg/utils": "workspace:*" } } Benefits: ✓ Atomic cross-package changes ✓ Shared tooling and configs ✓ Single CI/CD pipeline ✓ Easier dependency management ✓ Code reuse without publishing Challenges: ✗ Large repo size over time ✗ CI complexity (need smart task running) ✗ Permission management (everyone sees everything) ✗ Tooling must support workspaces EOF } cmd_checklist() { cat << 'EOF' === New Project Checklist === Initialization: [ ] Choose project name (check npm/PyPI/crates.io availability) [ ] Initialize version control (git init) [ ] Create directory structure [ ] Choose license (MIT, Apache-2.0, GPL-3.0) [ ] Write initial README.md Code Setup: [ ] Initialize package manager (npm init, cargo init, etc.) [ ] Set up TypeScript / type checking [ ] Configure linter (ESLint, ruff, golangci-lint) [ ] Configure formatter (Prettier, black, rustfmt) [ ] Set up test framework (Jest, pytest, go test) [ ] Create .editorconfig Git Setup: [ ] Create comprehensive .gitignore [ ] Set up commit hooks (husky, pre-commit) [ ] Configure conventional commits (commitlint) [ ] Create PR/MR template [ ] Set up branch protection rules Environment: [ ] Create .env.example with all required variables [ ] Document environment setup in README [ ] Pin runtime version (.nvmrc, .python-version) [ ] Set up local development scripts (npm run dev, make dev) CI/CD: [ ] Set up CI pipeline (lint, test, build) [ ] Configure automated dependency updates (Dependabot, Renovate) [ ] Set up code coverage reporting [ ] Configure security scanning (Snyk, CodeQL) Documentation: [ ] README: what, why, how to install, how to use [ ] CONTRIBUTING.md: how to contribute [ ] LICENSE file [ ] CHANGELOG.md (start with ## [Unreleased]) [ ] API documentation setup (if applicable) Docker (if applicable): [ ] Multi-stage Dockerfile [ ] .dockerignore [ ] docker-compose.yml for local development [ ] Health check endpoint First Commit: [ ] git add -A [ ] git commit -m "feat: initial project scaffold" [ ] Create remote repository [ ] git push -u origin main EOF } show_help() { cat << EOF create v$VERSION — Project Scaffolding Reference Usage: script.sh <command> Commands: intro Scaffolding overview — why, when, approaches structures Standard directory structures by language tools Popular scaffolding tools and generators templates Template engine patterns and best practices configs Essential config files every project needs conventions Naming, versioning, commits, branching monorepo Monorepo scaffolding with Turborepo, Nx, workspaces checklist New project checklist — idea to first commit help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; structures) cmd_structures ;; tools) cmd_tools ;; templates) cmd_templates ;; configs) cmd_configs ;; conventions) cmd_conventions ;; monorepo) cmd_monorepo ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "create v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Freight consolidation reference — LCL groupage, milk runs, cross-docking, and shipment merging strategies. Use when optimizing shipping costs, planning conso...
--- name: "consolidation" version: "1.0.0" description: "Freight consolidation reference — LCL groupage, milk runs, cross-docking, and shipment merging strategies. Use when optimizing shipping costs, planning consolidated loads, or reducing freight spend." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [consolidation, freight, shipping, logistics, lcl, groupage, cross-dock] category: "logistics" --- # Consolidation — Freight Consolidation Reference Quick-reference skill for shipment consolidation strategies, cost optimization, and logistics planning. ## When to Use - Combining multiple small shipments into full container loads - Planning LCL (Less than Container Load) groupage - Designing cross-dock and merge-in-transit operations - Calculating consolidation savings vs direct shipping - Implementing milk run and zone-skip strategies ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of freight consolidation — concepts, types, and economics. ### `lcl` ```bash scripts/script.sh lcl ``` LCL groupage — how ocean freight consolidation works from CFS to CFS. ### `crossdock` ```bash scripts/script.sh crossdock ``` Cross-docking operations — receive, sort, and ship without storage. ### `milkrun` ```bash scripts/script.sh milkrun ``` Milk run pickup routes — collecting from multiple suppliers in one trip. ### `savings` ```bash scripts/script.sh savings ``` Consolidation economics — cost calculations and break-even analysis. ### `methods` ```bash scripts/script.sh methods ``` Consolidation methods: zone-skip, pool distribution, merge-in-transit. ### `planning` ```bash scripts/script.sh planning ``` Consolidation planning — order windows, weight breaks, and timing. ### `risks` ```bash scripts/script.sh risks ``` Consolidation risks and mitigation: delays, damage, customs complications. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `CONSOLIDATION_DIR` | Data directory (default: ~/.consolidation/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # consolidation — Freight Consolidation Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Freight Consolidation === Consolidation combines multiple smaller shipments into a single larger shipment to reduce per-unit transportation costs. Core Economics: Shipping cost per unit decreases as shipment size increases. A full truckload (FTL) costs ~$2/mile regardless of weight. Two half-loads shipped separately = 2× the cost. Consolidating them into one FTL cuts transport cost by ~50%. Types of Consolidation: Inventory Consolidation Hold orders in warehouse until enough volume for full load Trade-off: lower freight cost vs longer delivery time Vehicle Consolidation Combine orders for multiple destinations onto one truck Driver makes multiple stops (multi-stop truckload) Terminal Consolidation Small shipments collected at hub, sorted, re-loaded by destination How LTL (Less Than Truckload) carriers operate Buyer Consolidation Multiple purchase orders from same buyer combined Common in retail: weekly order windows Pool Distribution Full truckload to regional hub, then local delivery Combines linehaul efficiency with last-mile reach Key Metrics: Cube utilization % of vehicle volume used (target: >85%) Weight utilization % of vehicle weight capacity used Stop density Deliveries per route mile Consolidation ratio Orders combined per shipment Cost per unit Total freight ÷ units shipped Container Sizes (Ocean): 20' (TEU) 33 CBM, 21,700 kg max payload 40' (FEU) 67 CBM, 26,500 kg max payload 40' HC 76 CBM, 26,270 kg max payload Truck Sizes (North America): Sprinter Van 10-12 pallets, 4,500 kg Straight Truck 12-16 pallets, 9,000 kg 53' Trailer 26-30 pallets, 19,500 kg EOF } cmd_lcl() { cat << 'EOF' === LCL (Less than Container Load) Groupage === LCL consolidation combines cargo from multiple shippers into one ocean container, sharing the cost proportionally. How It Works: 1. Shippers deliver cargo to origin CFS (Container Freight Station) 2. CFS operator groups compatible cargo by destination port 3. Consolidated container shipped as FCL (Full Container Load) 4. At destination CFS, container is deconsolidated (de-stuffed) 5. Each shipper's cargo is held for pickup or delivered Cost Structure: LCL rates quoted per CBM (cubic meter) or per ton (W/M) W/M = Whichever is greater: volume weight or actual weight 1 CBM = 1,000 kg for ocean freight density calculation Typical LCL surcharges: CFS charge (origin) $50-100 per shipment CFS charge (destination) $50-100 per shipment Documentation fee $25-50 Handling/warehousing $5-15 per CBM When LCL Makes Sense: Volume < 15 CBM → LCL is usually cheaper Volume > 15 CBM → FCL 20' may be cheaper (get quotes for both) Volume > 25 CBM → FCL 20' almost certainly cheaper LCL Transit Time: Add 3-7 days vs FCL for the same route Origin CFS handling 1-3 days (wait for container to fill) Destination CFS 1-2 days (deconsolidation + availability) Customs clearance 1-2 days (shared container inspection risk) Consolidator Types: NVOCC (Non-Vessel Operating Common Carrier) Books FCL space, fills with LCL cargo from multiple shippers Issues own house bill of lading (HBL) Master bill of lading (MBL) in NVOCC name Co-loader Consolidates cargo from freight forwarders (not direct shippers) Multiple HBLs under one MBL LCL Restrictions: - Hazardous goods: limited or not accepted - Temperature-controlled: only if reefer consolidation available - Oversized cargo: may not fit standard container - High-value: consider insurance, FCL may be safer EOF } cmd_crossdock() { cat << 'EOF' === Cross-Docking Operations === Cross-docking receives inbound shipments and ships them outbound with minimal or zero storage time. Product crosses the dock, never enters inventory. Types: Pre-Distributed Cross-Dock Supplier pre-labels each case with destination store Cross-dock just sorts and loads onto outbound trucks Fastest method, minimal handling Used by: Walmart, Amazon FC-to-delivery station Post-Distributed Cross-Dock Inbound goods received in bulk Cross-dock breaks bulk, allocates to destinations based on orders More flexible but requires more labor Used by: grocery distribution, fashion retail Merge-in-Transit Components from multiple suppliers meet at cross-dock Merged into single customer delivery Used by: Dell (monitor from A + PC from B → customer) Physical Layout: ┌──────────────────────────────┐ │ Inbound dock doors (left) │ │ ┌──────────────────────┐ │ │ │ Sorting area │ │ │ │ (staging lanes by │ │ │ │ destination) │ │ │ └──────────────────────┘ │ │ Outbound dock doors (right) │ └──────────────────────────────┘ I-shape: inbound one side, outbound opposite (simplest) L-shape: inbound on two adjacent sides T-shape: inbound on one side, outbound on two H-shape: two parallel dock buildings Success Factors: Timing Inbound must arrive within narrow window Visibility Real-time ASN (Advance Ship Notice) critical Volume Need enough outbound volume to fill trucks quickly IT WMS with cross-dock planning module Layout Minimal travel distance between dock doors Performance Metrics: Dock-to-dock time Target: < 2 hours Dock utilization Target: > 80% of door hours used Touches Target: ≤ 2 (unload → sort → load) On-time departure Target: > 95% of outbound trucks EOF } cmd_milkrun() { cat << 'EOF' === Milk Run Logistics === A milk run is a circular pickup/delivery route that visits multiple locations in a single trip, like a milkman visiting houses on a route. How It Works: Instead of: 5 suppliers each send one small truck → factory Milk run: 1 truck visits all 5 suppliers → returns full to factory Before (direct): After (milk run): S1 ──→ Factory S1 → S2 → S3 → S4 → S5 S2 ──→ Factory ↓ S3 ──→ Factory → Factory (full load) S4 ──→ Factory S5 ──→ Factory 5 trucks, partially loaded 1 truck, fully loaded Benefits: Transport cost -30% to -50% (fewer trucks, higher utilization) Inventory Lower (smaller, more frequent deliveries) Emissions Fewer truck-miles Supplier docks Less congestion (scheduled windows) Quality Problems caught faster (smaller batches) Milk Run Design: 1. Cluster suppliers geographically Rule: max 50km radius for urban, 150km for regional Same-direction routes (no backtracking) 2. Set pickup schedule Fixed days/times for each supplier Example: Mon/Wed/Fri route A, Tue/Thu route B 3. Calculate vehicle sizing Sum of all supplier volumes per run Leave 10-15% capacity buffer for variation Match truck type to total volume 4. Define time windows Window per supplier: 15-30 minutes Total route time: < 8 hours (driver hours regulation) Latest arrival at factory: before production start Toyota's Milk Run System: - Trucks leave factory with empty containers - Visit suppliers in sequence, swap full for empty containers - Return to factory with parts for that day's production - 4-6 runs per day, suppliers within 100km radius - Achieved 50% transport cost reduction vs direct delivery Key Success Factors: ✓ Reliable supplier readiness (cargo staged on time) ✓ Consistent volumes (predictable production schedule) ✓ Geographic clustering (suppliers near each other) ✓ Standardized packaging (pallets, containers stack efficiently) ✓ Good communication (delays cascade through the route) EOF } cmd_savings() { cat << 'EOF' === Consolidation Economics === --- Cost Comparison: LTL vs Consolidated FTL --- Scenario: 5 shipments, each 5 pallets, same origin → same destination LTL (each shipped separately): 5 × $800 per shipment = $4,000 total 5 × separate pickup/delivery Transit: 3-5 days each Consolidated FTL (all 25 pallets on one truck): 1 × $2,200 per truck = $2,200 total 1 pickup, 1 delivery Transit: 1-2 days Savings: $1,800 (45%) --- Weight Break Analysis --- LTL carriers use weight breaks — price drops at thresholds: Minimum charge: 500 lbs $45/cwt 1,000 lb break: 1,000 lbs $35/cwt 2,000 lb break: 2,000 lbs $28/cwt 5,000 lb break: 5,000 lbs $22/cwt 10,000 lb break: 10,000 lbs $18/cwt 20,000 lb break: 20,000 lbs $15/cwt A 1,800 lb shipment at $35/cwt = $630 A 2,000 lb shipment at $28/cwt = $560 Declaring 2,000 lbs is CHEAPER despite more weight! Always check the next weight break. --- Break-Even: LCL vs FCL (Ocean) --- LCL rate: $65/CBM FCL 20' rate: $1,800 all-in FCL capacity: 33 CBM usable Break-even: $1,800 ÷ $65 = 27.7 CBM Below 27 CBM → LCL cheaper Above 28 CBM → FCL cheaper Factor in CFS charges: real break-even often ~20 CBM --- Zone Skip Savings --- Direct parcel: Ship from warehouse → each customer Zone skip: Consolidate parcels by region → trailer to regional hub → inject into local postal/carrier network Example (1,000 parcels/day to Zone 8): Direct ship: 1,000 × $12.50 = $12,500 Zone skip: Trailer to Zone 8 hub: $1,500 Local delivery: 1,000 × $6.00 = $6,000 Total: $7,500 Savings: $5,000/day (40%) --- Consolidation ROI Formula --- Savings = (Direct_Cost - Consolidated_Cost) - Holding_Cost Where: Direct_Cost = sum of individual shipment costs Consolidated_Cost = fewer, fuller shipments Holding_Cost = warehouse cost for holding orders while consolidating If Savings > 0, consolidation is worthwhile EOF } cmd_methods() { cat << 'EOF' === Consolidation Methods === --- Zone Skipping --- Bypass intermediate carrier sort facilities by trucking directly to a destination zone, then injecting into local delivery network. Flow: Shipper → Sort by zone → FTL to zone hub → Local carrier Works with: USPS (DDU/SCF injection), UPS, FedEx SmartPost Best for: high-volume parcel shippers (500+ parcels/day/zone) Savings: 20-40% vs standard parcel rates --- Pool Distribution --- Ship full truckload to a pool point near destination cluster, then use local carriers for last-mile delivery. Flow: Shipper → FTL to pool point → LTL/local delivery Pool points: carrier terminals, 3PL cross-docks, shared warehouses Best for: national distribution to sparse regions Savings: 25-35% vs direct LTL to each customer --- Merge-in-Transit --- Components from different origins converge at a merge point, are combined into a single delivery to the customer. Flow: Supplier A → ┐ Supplier B → ├→ Merge Point → Customer Supplier C → ┘ Requirements: - Precise timing coordination - Real-time visibility into all shipments - Fallback plan if one shipment is late Best for: multi-component orders (furniture, electronics, industrial) --- Buyer Consolidation --- Retail buyer groups multiple purchase orders into one shipment. Example: Retailer places 5 POs this week to same supplier Instead of 5 separate shipments → supplier ships once Uses order windows: "All orders by Wednesday ship Friday" --- Multi-Stop Truckload (MSTL) --- Single truck makes 2-4 deliveries on a route. Cheaper than FTL to each, faster than LTL network. Pricing: FTL rate + stop charges ($50-150 per stop) Constraints: - Each stop adds 1-2 hours - Driver hours limit total stops - Unloading sequence must match route order --- Collaborative Consolidation --- Non-competing companies share truck space on same lanes. Company A ships Mon/Wed (half truck), Company B ships Tue/Thu (half truck) Combined: daily full trucks at lower cost for both. Platforms: Convoy, Transfix, Flexport, collaborative TMS EOF } cmd_planning() { cat << 'EOF' === Consolidation Planning === --- Order Windows --- Define cutoff times for orders to be included in consolidated shipment. Example schedule: Monday 12:00 PM → Cutoff for Wednesday shipment Wednesday 12:00 PM → Cutoff for Friday shipment Friday 12:00 PM → Cutoff for Monday shipment Window sizing: Shorter windows (daily) → faster delivery, less consolidation Longer windows (weekly) → better consolidation, slower delivery Balance: 2-3 day windows give good consolidation without long delays --- Weight/Volume Optimization --- Step 1: Sort pending orders by destination zone Step 2: For each zone, sum weight and cube Step 3: Compare against vehicle capacities: If weight > 10,000 lbs OR cube > 1,000 ft³ → Book FTL If weight > 5,000 lbs → Use 5,000 lb LTL break If weight > 2,000 lbs → Use 2,000 lb LTL break If weight < 2,000 lbs → Ship as standard LTL or hold for next window Step 4: Check if FTL price < sum of individual LTL prices Step 5: Verify delivery windows still met --- Pallet Optimization --- Standard pallet: 48" × 40" (North America) Truck floor: 8 pallets wide × 3 deep per row = 24 floor positions (53' trailer) Double-stacked: up to 48 pallets if weight and product allow Loading priority: 1. Heaviest pallets on bottom, near axles 2. Same-destination pallets together (for multi-stop) 3. Last delivery loaded first (LIFO sequence) 4. Fill vertical space — air is wasted money --- TMS Consolidation Logic --- Good TMS (Transportation Management System) features: Auto-consolidation engine: Groups orders by: destination zone, service level, ship date Evaluates: FTL vs LTL vs parcel for each group Considers: weight breaks, min charges, stop-off fees What-if simulation: "If I hold these orders 1 more day, can I fill a truck?" Shows cost of holding vs cost of partial shipment Dynamic routing: Re-optimizes as new orders arrive Alerts when consolidation opportunity exists Integrates carrier rate tables for real-time comparison EOF } cmd_risks() { cat << 'EOF' === Consolidation Risks & Mitigation === 1. Delivery Delays Risk: Holding orders for consolidation delays individual shipments Impact: Customer dissatisfaction, SLA violations, penalty fees Mitigation: - Set maximum hold time (e.g., never exceed 48 hours) - Priority/expedite orders bypass consolidation - Communicate expected delivery windows to customers - Track consolidation hold time as a KPI 2. Damage from Mixed Cargo Risk: Different products in same container may be incompatible Examples: heavy items crush light ones, chemicals near food Mitigation: - Cargo compatibility matrix (what can ship together) - Proper blocking and bracing between shipments - Clear labeling with handling instructions - Insurance per shipper within consolidated load 3. Customs Complications (International) Risk: Consolidated container with goods from multiple shippers Issues: - One shipper's goods held → entire container detained - Different HS codes, different duty rates - Fumigation or inspection delays all cargo Mitigation: - Use separate commercial invoices per shipper - CFS bond for partial release where available - Avoid mixing regulated goods (food, chemicals, restricted items) - Factor customs risk into LCL transit time estimates 4. Liability Allocation Risk: Damage discovered at deconsolidation — who is responsible? Issues: Carrier vs CFS vs shipper vs consignee Mitigation: - Photo documentation at origin CFS before loading - Tally sheets signed by each party at each handoff - Cargo insurance per shipper (not just per container) - Clear terms in consolidation agreement 5. Capacity Mismatch Risk: Not enough volume to fill consolidated load efficiently Results in: paying for partial truck = worse than LTL Mitigation: - Minimum volume threshold to trigger consolidation - Collaborative shipping with non-competing partners - Flexible cutoff windows that adapt to volume - Fallback to LTL if threshold not met by cutoff 6. Complexity Overhead Risk: Consolidation planning requires TMS, staff, processes Small shipper impact: cost of planning > savings from consolidation Mitigation: - Use 3PL consolidation services (they do the planning) - Start simple: consolidate same-destination, same-day orders only - Automate with TMS rules, don't rely on manual decisions - Break-even analysis: savings must exceed planning cost EOF } show_help() { cat << EOF consolidation v$VERSION — Freight Consolidation Reference Usage: script.sh <command> Commands: intro Freight consolidation concepts and economics lcl LCL ocean freight groupage operations crossdock Cross-docking receive-sort-ship operations milkrun Milk run supplier pickup routes savings Cost calculations and break-even analysis methods Zone-skip, pool distribution, merge-in-transit planning Order windows, weight breaks, TMS logic risks Consolidation risks and mitigation strategies help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; lcl) cmd_lcl ;; crossdock) cmd_crossdock ;; milkrun) cmd_milkrun ;; savings) cmd_savings ;; methods) cmd_methods ;; planning) cmd_planning ;; risks) cmd_risks ;; help|--help|-h) show_help ;; version|--version|-v) echo "consolidation v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Drawdown analysis reference — maximum drawdown, peak-to-trough, recovery time, risk metrics. Use when evaluating portfolio risk, stress-testing strategies, o...
--- name: "drawdown" version: "1.0.0" description: "Drawdown analysis reference — maximum drawdown, peak-to-trough, recovery time, risk metrics. Use when evaluating portfolio risk, stress-testing strategies, or measuring downside exposure." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [drawdown, risk, portfolio, maximum-drawdown, recovery, finance, volatility] category: "finance" --- # Drawdown — Drawdown Analysis & Risk Measurement Reference Quick-reference skill for understanding, calculating, and applying drawdown metrics in portfolio management and risk analysis. ## When to Use - Measuring maximum drawdown of a portfolio or strategy - Comparing risk profiles of different investments - Setting stop-loss levels based on historical drawdowns - Stress-testing strategies against worst-case scenarios - Evaluating fund manager performance through drawdown lens ## Commands ### `intro` ```bash scripts/script.sh intro ``` Overview of drawdown — definition, significance, and types. ### `calculate` ```bash scripts/script.sh calculate ``` How to calculate drawdown — formulas, step-by-step, and time series methods. ### `metrics` ```bash scripts/script.sh metrics ``` Key drawdown metrics — MDD, Calmar ratio, Ulcer Index, pain index. ### `historical` ```bash scripts/script.sh historical ``` Major historical drawdowns — market crashes, recovery timelines. ### `management` ```bash scripts/script.sh management ``` Drawdown management — position sizing, stop-losses, risk budgeting. ### `recovery` ```bash scripts/script.sh recovery ``` Recovery analysis — math of recovery, time to recover, asymmetry of losses. ### `comparison` ```bash scripts/script.sh comparison ``` Drawdown vs other risk measures — volatility, VaR, CVaR, Sortino. ### `examples` ```bash scripts/script.sh examples ``` Worked examples with calculations and strategy evaluation. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `DRAWDOWN_DIR` | Data directory (default: ~/.drawdown/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # drawdown — Drawdown Analysis & Risk Measurement Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Drawdown Analysis === A drawdown is the decline from a historical peak in the value of a portfolio, fund, or asset. It measures how much you've lost from the highest point before a new high is reached. Definition: Drawdown(t) = [Peak(t) - Value(t)] / Peak(t) Where Peak(t) = maximum value from inception to time t Key Concepts: Peak The highest portfolio value achieved so far Trough The lowest point during a drawdown period Drawdown The percentage decline from peak to current value Max Drawdown The largest peak-to-trough decline ever observed Recovery The period from trough back to previous peak Underwater The total time spent below the previous peak Why Drawdown Matters: 1. Captures REAL investor pain (not abstract volatility) 2. Shows worst-case scenario (what you'd have actually lived through) 3. Accounts for path dependency (order of returns matters) 4. Sticky: a 50% loss requires a 100% gain to recover 5. Behavioral: investors abandon strategies during drawdowns Types of Drawdown: Maximum Drawdown (MDD) Largest ever peak-to-trough decline Average Drawdown Mean of all drawdown periods Current Drawdown How far below the current peak right now Longest Drawdown Maximum time spent underwater Conditional Drawdown Expected drawdown in worst X% of cases EOF } cmd_calculate() { cat << 'EOF' === Calculating Drawdown === Step-by-Step Algorithm: 1. Track running peak: Peak(t) = max(Value(0), ..., Value(t)) 2. At each time t: DD(t) = [Peak(t) - Value(t)] / Peak(t) 3. Maximum Drawdown = max(DD(t)) for all t Example: Day Value Peak Drawdown 1 100 100 0.0% 2 105 105 0.0% 3 98 105 -6.7% ← drawdown begins 4 92 105 -12.4% 5 88 105 -16.2% ← trough 6 95 105 -9.5% ← recovering 7 103 105 -1.9% 8 108 108 0.0% ← new peak (drawdown ends) 9 102 108 -5.6% ← new drawdown begins Maximum Drawdown = 16.2% (day 2 peak → day 5 trough) Drawdown Duration = 6 days (day 3 to day 8) Recovery Time = 3 days (day 5 to day 8) In Dollar Terms: MDD$ = Peak$ - Trough$ Example: $105 - $88 = $17 per unit Annualized Maximum Drawdown: Not commonly annualized — MDD is typically reported as-is Longer track records naturally show larger MDDs Rolling Drawdown: Calculate MDD over a rolling window (e.g., 12 months) Shows how worst-case loss evolves over time Useful for detecting regime changes in risk Drawdown Series: Plot DD(t) as a time series → "underwater curve" Shows how long the portfolio spends below each peak Deeper/wider underwater periods = more investor pain EOF } cmd_metrics() { cat << 'EOF' === Drawdown-Based Risk Metrics === Maximum Drawdown (MDD): MDD = max peak-to-trough decline over entire period Simple, intuitive, worst-case measure Limitation: single worst event, doesn't capture frequency Calmar Ratio: = Annualized Return / Maximum Drawdown Higher = better risk-adjusted return per unit of worst loss Example: 12% return / 20% MDD = 0.60 Benchmarks: < 0.5 Poor 0.5-1.0 Acceptable 1.0-2.0 Good > 2.0 Excellent (rare, often unsustainable) Sterling Ratio: = Annualized Return / (Average Annual MDD - 10%) The -10% is a "risk-free" adjustment (somewhat arbitrary) Modified Sterling: just use Average Annual MDD Ulcer Index (UI): = sqrt(mean(DD(t)²)) Like standard deviation, but only for downside Captures both depth and duration of drawdowns Martin Ratio = (Return - Rᶠ) / Ulcer Index Pain Index: = mean(|DD(t)|) Average depth of the underwater curve Pain Ratio = (Return - Rᶠ) / Pain Index Burke Ratio: = (Return - Rᶠ) / sqrt(Σ DD²ᵢ) Uses sum of squared drawdowns (penalizes frequent drawdowns) Conditional Drawdown at Risk (CDaR): Average of the worst X% of drawdowns Like CVaR (Expected Shortfall) but for drawdowns Example: CDaR(95%) = average of top 5% worst drawdowns Comparison: MDD Single worst event CDaR(95%) Average of worst 5% (more robust) Ulcer Index Ongoing pain measure (depth × duration) Pain Index Average underwater depth EOF } cmd_historical() { cat << 'EOF' === Major Historical Drawdowns === US Stock Market (S&P 500): 1929-1932 Great Depression -86% Recovery: 25 years (1954) 1937-1942 WWII Bear Market -60% Recovery: 6 years 1973-1974 Oil Crisis/Stagflation -48% Recovery: 7 years 1987 Black Monday -34% Recovery: 2 years 2000-2002 Dot-com Bust -49% Recovery: 7 years 2007-2009 Global Financial Crisis -57% Recovery: 5.5 years 2020 COVID Crash -34% Recovery: 5 months 2022 Rate Hike Bear -25% Recovery: ~2 years Key Observations: - Average bear market drawdown: ~35% - Average recovery time: 3-5 years - Deeper drawdowns have disproportionately longer recoveries - The 1929 crash took 25 YEARS to recover (in nominal terms) Other Markets: Japan Nikkei 225 1989-2009 -82% (30+ years to recover, 2024) NASDAQ 2000-2002 -78% Recovery: 15 years Bitcoin 2017-2018 -83% Recovery: 3 years Bitcoin 2021-2022 -77% Recovery: ~2 years Gold 1980-1999 -70% Recovery: 28 years US Bonds (AGG) 2020-2023 -18% Worst bond drawdown in decades Lessons: 1. 50%+ drawdowns happen roughly once per generation 2. Diversification reduces drawdown but doesn't eliminate it 3. Leverage amplifies drawdowns (LTCM: -92% in months) 4. Timing recoveries is nearly impossible 5. Having cash during drawdowns is the best opportunity EOF } cmd_management() { cat << 'EOF' === Drawdown Management === Position Sizing by Drawdown Budget: Max acceptable drawdown = your risk budget Position size = Risk Budget / Expected Worst Drawdown Example: Risk budget: 15% portfolio drawdown max Strategy expected MDD: 30% Max allocation = 15% / 30% = 50% of portfolio Kelly-adjusted: Half-Kelly (conservative) is standard Full Kelly maximizes growth but has ~50% MDD typically Stop-Loss Strategies: Fixed Stop: Sell if down X% from entry (e.g., -8%) Trailing Stop: Sell if down X% from highest price since entry Time Stop: Sell if no recovery within N months Volatility Stop: Stop distance = X × ATR (average true range) Tradeoffs: Tight stops: limit drawdowns but increase whipsaws Wide stops: fewer false signals but deeper drawdowns No stops: full drawdowns but no whipsaw cost Risk Budgeting: Allocate total risk budget across strategies Example: 20% max DD budget across 4 strategies Strategy A: 5% budget (low vol, 10% expected MDD at 50% alloc) Strategy B: 5% budget (medium vol) Strategy C: 5% budget (medium vol) Strategy D: 5% budget (high vol, 25% expected MDD at 20% alloc) Drawdown Circuit Breakers: Reduce position size as drawdown deepens: 0-5% DD: Full position (100%) 5-10% DD: Reduce to 75% 10-15% DD: Reduce to 50% 15-20% DD: Reduce to 25% >20% DD: Flat (reassess strategy) Benefit: limits max loss Cost: slower recovery (you reduce exposure near the bottom) EOF } cmd_recovery() { cat << 'EOF' === Recovery Analysis === The Asymmetry of Losses: Loss Gain Needed to Recover -10% +11.1% -20% +25.0% -30% +42.9% -40% +66.7% -50% +100.0% ← must DOUBLE to recover -60% +150.0% -70% +233.3% -80% +400.0% -90% +900.0% Formula: Required gain = Loss / (1 - Loss) This is why drawdown prevention is more important than maximizing returns Recovery Time Factors: 1. Depth of drawdown (deeper = exponentially longer) 2. Expected return going forward 3. Volatility during recovery (drag on compound returns) 4. Continued contributions (dollar-cost averaging helps) 5. Market regime (V-shape vs L-shape recovery) Time to Recover (simplified): T = -ln(1 - DD) / ln(1 + r) Where DD = drawdown fraction, r = expected annual return Example: 50% drawdown, 8% annual return T = -ln(0.5) / ln(1.08) = 0.693 / 0.077 = 9 years Recovery Patterns: V-shape: Sharp decline, sharp recovery (COVID 2020) U-shape: Decline, extended bottom, gradual recovery L-shape: Decline, no meaningful recovery for years (Japan) W-shape: False recovery, second decline, then real recovery Impact of Volatility on Recovery: "Volatility drag" slows compound growth: Arithmetic return: (50% + -50%) / 2 = 0% Actual return: $100 → $150 → $75 = -25% Higher volatility during recovery = slower actual recovery This is why reducing volatility matters, not just returns EOF } cmd_comparison() { cat << 'EOF' === Drawdown vs Other Risk Measures === Volatility (Standard Deviation): Pros: mathematically clean, widely understood, symmetric Cons: penalizes upside equally, doesn't capture tail risk vs DD: volatility says "how bumpy," drawdown says "how painful" Value at Risk (VaR): "With 95% confidence, loss won't exceed X% in one day/month" Pros: simple probability statement, regulatory standard Cons: says nothing about what happens BEYOND VaR vs DD: VaR is a point estimate, drawdown is a path measure Conditional VaR (CVaR / Expected Shortfall): Average loss in the worst X% of scenarios Pros: captures tail risk, coherent risk measure Cons: still single-period, needs distribution assumptions vs DD: CVaR captures tail depth, drawdown captures duration too Sortino Ratio: = (Return - Target) / Downside Deviation Pros: only penalizes downside volatility Cons: still deviation-based, doesn't capture max loss vs DD: Sortino is a ratio, MDD is the actual worst experience Comparison Table: Measure Captures Time Aware? Intuitive? Path Dependent? Volatility Dispersion No Moderate No VaR Tail risk No Yes No CVaR Tail avg No Moderate No Sortino Downside No Moderate No MDD Worst loss Yes Very Yes Ulcer Index Ongoing pain Yes Moderate Yes Calmar Return/MDD Yes Yes Yes Recommendation: Use multiple measures together: - Volatility for day-to-day risk - VaR/CVaR for tail risk budgeting - MDD for worst-case scenarios - Calmar/Ulcer for risk-adjusted performance EOF } cmd_examples() { cat << 'EOF' === Drawdown Worked Examples === --- Example 1: Calculate MDD from Return Series --- Month Return Value Peak Drawdown 0 — 1000 1000 0.0% 1 +5.0% 1050 1050 0.0% 2 -3.0% 1018.5 1050 -3.0% 3 -7.0% 947.2 1050 -9.8% 4 -4.0% 909.3 1050 -13.4% ← MDD 5 +8.0% 982.1 1050 -6.5% 6 +6.0% 1041.0 1050 -0.9% 7 +2.0% 1061.8 1061.8 0.0% ← recovered MDD = 13.4% (month 1 peak to month 4 trough) Recovery time = 3 months (month 4 to month 7) Underwater period = 5 months (month 2 to month 7) --- Example 2: Calmar Ratio Comparison --- Fund A: 15% annual return, 25% MDD → Calmar = 0.60 Fund B: 10% annual return, 12% MDD → Calmar = 0.83 Fund C: 20% annual return, 40% MDD → Calmar = 0.50 Fund B has the best risk-adjusted return per worst loss Fund C has highest return but worst drawdown experience --- Example 3: Position Sizing --- Risk budget: 10% max portfolio drawdown Strategy X has 30% historical MDD Max allocation = 10% / 30% = 33.3% Allocate 33% to Strategy X, rest to cash/bonds With leverage consideration: 2x leveraged: expected MDD ≈ 60% Max allocation = 10% / 60% = 16.7% --- Example 4: Recovery Time --- Portfolio drops 40% during a crisis Expected going-forward return: 10%/year T = -ln(0.60) / ln(1.10) = 0.511 / 0.0953 = 5.4 years With 7% return: T = 0.511 / 0.0677 = 7.5 years EOF } show_help() { cat << EOF drawdown v$VERSION — Drawdown Analysis & Risk Measurement Reference Usage: script.sh <command> Commands: intro Drawdown overview — definition, types, significance calculate How to calculate drawdown step-by-step metrics Key metrics — MDD, Calmar, Ulcer Index, Pain Index historical Major market drawdowns and recovery timelines management Position sizing, stop-losses, risk budgeting recovery Math of recovery, loss asymmetry, recovery patterns comparison Drawdown vs volatility, VaR, CVaR, Sortino examples Worked calculations and strategy comparisons help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; calculate) cmd_calculate ;; metrics) cmd_metrics ;; historical) cmd_historical ;; management) cmd_management ;; recovery) cmd_recovery ;; comparison) cmd_comparison ;; examples) cmd_examples ;; help|--help|-h) show_help ;; version|--version|-v) echo "drawdown v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Mood and emotional wellness reference — mood science, regulation strategies, journaling techniques, emotional literacy. Use when understanding emotional patt...
--- name: "mood" version: "1.0.0" description: "Mood and emotional wellness reference — mood science, regulation strategies, journaling techniques, emotional literacy. Use when understanding emotional patterns, designing mood tracking systems, or improving emotional regulation." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [mood, emotions, wellness, mental-health, emotional-regulation, journaling, psychology] category: "general" --- # Mood — Mood & Emotional Wellness Reference Quick-reference skill for understanding mood science, emotional regulation, and wellness practices. ## When to Use - Understanding the science of moods and emotions - Learning emotional regulation techniques - Designing mood tracking or journaling systems - Identifying mood patterns and triggers - Building emotional literacy and resilience ## Commands ### `intro` ```bash scripts/script.sh intro ``` Mood science fundamentals — emotions vs moods, affect theory, neuroscience basics. ### `wheel` ```bash scripts/script.sh wheel ``` Emotion taxonomy — Plutchik's wheel, granular emotion vocabulary, intensity levels. ### `regulation` ```bash scripts/script.sh regulation ``` Emotional regulation strategies — CBT techniques, reappraisal, grounding, distress tolerance. ### `triggers` ```bash scripts/script.sh triggers ``` Mood triggers — HALT framework, environmental factors, cognitive distortions. ### `journaling` ```bash scripts/script.sh journaling ``` Mood journaling techniques — structured prompts, tracking patterns, gratitude practice. ### `lifestyle` ```bash scripts/script.sh lifestyle ``` Lifestyle factors — sleep, exercise, nutrition, social connection, nature exposure. ### `tracking` ```bash scripts/script.sh tracking ``` Mood tracking systems — scales, frequency, pattern recognition, data visualization. ### `resilience` ```bash scripts/script.sh resilience ``` Building emotional resilience — stress inoculation, growth mindset, social support. ### `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 # mood — Mood & Emotional Wellness Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Mood Science Fundamentals === EMOTIONS vs MOODS: Emotions: - Brief (seconds to minutes) - Triggered by specific event - Identifiable cause - Intense, focused - Example: Fear when a car swerves toward you Moods: - Longer lasting (hours to days) - Often no single trigger - Background state, diffuse - Less intense, more pervasive - Example: Feeling irritable all afternoon Affect: - Umbrella term for all feeling states - Includes emotions, moods, and sentiments CORE AFFECT MODEL (Russell's Circumplex): Two dimensions map all emotional states: High Energy (Arousal) │ Anxious │ Excited Stressed │ Enthusiastic ─────────┼────────── Sad │ Content Bored │ Calm │ Low Energy (Arousal) Negative ←──────→ Positive (Valence) (Valence) NEUROSCIENCE BASICS: Key brain regions for mood: Amygdala Threat detection, fear, emotional memory Prefrontal cortex Regulation, decision-making, planning Hippocampus Memory, context for emotions Insula Body awareness, feeling states Anterior cingulate Conflict monitoring, error detection Key neurotransmitters: Serotonin Mood stability, well-being, sleep Dopamine Reward, motivation, pleasure anticipation Norepinephrine Alertness, energy, stress response GABA Calm, relaxation, anxiety reduction Endorphins Pain relief, runner's high, euphoria EMOTIONAL LITERACY: The ability to identify, understand, and express emotions effectively. Research shows people who can name emotions precisely experience better regulation and mental health outcomes. "Name it to tame it" — Dan Siegel Expanding your emotion vocabulary is itself therapeutic. EOF } cmd_wheel() { cat << 'EOF' === Emotion Taxonomy === PLUTCHIK'S WHEEL OF EMOTIONS (8 primary emotions): Primary Opposite Intensity Levels ─────── ──────── ────────────────── Joy ↔ Sadness Ecstasy → Joy → Serenity Trust ↔ Disgust Admiration → Trust → Acceptance Fear ↔ Anger Terror → Fear → Apprehension Surprise ↔ Anticipation Amazement → Surprise → Distraction Combined emotions (dyads): Joy + Trust = Love Joy + Anticipation = Optimism Trust + Fear = Submission Fear + Surprise = Awe Surprise + Sadness = Disapproval Sadness + Disgust = Remorse Disgust + Anger = Contempt Anger + Anticipation = Aggressiveness GRANULAR EMOTION VOCABULARY: Happy spectrum: Mild: content, pleased, satisfied, comfortable Moderate: happy, cheerful, joyful, delighted, grateful Intense: ecstatic, euphoric, elated, blissful, thrilled Sad spectrum: Mild: disappointed, let down, melancholy, wistful Moderate: sad, unhappy, sorrowful, gloomy, heartbroken Intense: devastated, despairing, grief-stricken, anguished Angry spectrum: Mild: annoyed, irritated, frustrated, bothered Moderate: angry, resentful, indignant, furious Intense: enraged, livid, seething, wrathful Anxious spectrum: Mild: uneasy, worried, nervous, restless Moderate: anxious, apprehensive, tense, stressed Intense: panicked, terrified, overwhelmed, dread Calm spectrum: Mild: okay, fine, neutral, unbothered Moderate: calm, peaceful, relaxed, serene Intense: blissful, transcendent, deeply at peace MICRO-EMOTIONS (subtle states worth noticing): Ennui Listless dissatisfaction, existential boredom Saudade Nostalgic longing for something lost Schadenfreude Pleasure at another's misfortune Hygge Cozy contentment (Danish) Ikigai Purposeful fulfillment (Japanese) Flow Absorbed engagement in a challenging task Frisson Pleasurable shiver from music/beauty Awe Vastness + accommodation (mind expanding) EOF } cmd_regulation() { cat << 'EOF' === Emotional Regulation Strategies === COGNITIVE REAPPRAISAL (most effective long-term): Reframe the situation to change the emotional response. Not: "This presentation will be a disaster" But: "This is a chance to practice speaking, and some nervousness means I care about doing well" Steps: 1. Notice the emotion and the thought behind it 2. Ask: "Is there another way to see this?" 3. Generate 2-3 alternative interpretations 4. Choose the most balanced one (not fake positive) GROUNDING TECHNIQUES (for acute distress): 5-4-3-2-1 Sensory Grounding: Name: 5 things you SEE 4 things you TOUCH/FEEL 3 things you HEAR 2 things you SMELL 1 thing you TASTE Box Breathing (4-4-4-4): Inhale 4 seconds → Hold 4 seconds → Exhale 4 seconds → Hold 4 seconds → Repeat Cold Exposure: Splash cold water on face (activates dive reflex) Hold ice cube in hand Cold shower burst → Triggers parasympathetic nervous system DISTRESS TOLERANCE (DBT — Marsha Linehan): TIPP Skills: T — Temperature (cold water on face) I — Intense exercise (5-10 min burst) P — Paced breathing (long exhale) P — Progressive muscle relaxation ACCEPTS (distraction): Activities, Contributing, Comparisons, Emotions (opposite), Pushing away, Thoughts (replace), Sensations PROCESS MODEL (Gross): 5 points to intervene in emotional response: 1. Situation selection Avoid/approach situations 2. Situation modification Change the situation 3. Attention deployment Redirect attention 4. Cognitive change Reappraise meaning 5. Response modulation Manage the response itself Earlier intervention = more effective and less effortful HEALTHY vs UNHEALTHY REGULATION: Healthy: Reappraisal, problem-solving, acceptance, social support, exercise, mindfulness, journaling Unhealthy: Suppression, avoidance, rumination, substance use, emotional eating, self-harm Key: Suppressing emotions doesn't reduce them — it intensifies them and impairs memory, social connection, and health. EOF } cmd_triggers() { cat << 'EOF' === Mood Triggers === HALT FRAMEWORK (check these first): H — Hungry? Low blood sugar → irritability, brain fog A — Angry? Unresolved anger → mood degradation L — Lonely? Social isolation → sadness, anxiety T — Tired? Sleep deprivation → emotional dysregulation Extended: HALTS S — Stressed? Chronic stress → baseline mood drops S — Sick? Illness → mood changes, reduced coping ENVIRONMENTAL TRIGGERS: Light: Seasonal Affective Disorder (SAD), blue light exposure Noise: Chronic noise → stress, irritability Clutter: Cluttered space → elevated cortisol Weather: Rain, gray skies → lower mood (for some people) Air quality: Poor air → fatigue, cognitive impairment Temperature: Too hot/cold → irritability, discomfort SOCIAL TRIGGERS: Conflict: Arguments, criticism, rejection Social media: Comparison, FOMO, doom scrolling Loneliness: Isolation, lack of meaningful connection Crowding: Overstimulation, loss of personal space Positive: Connection, laughter, kindness received COGNITIVE DISTORTIONS (Beck): All-or-Nothing: "If it's not perfect, it's a failure" Catastrophizing: "This will definitely be a disaster" Mind Reading: "They think I'm stupid" Personalization: "It's my fault they're upset" Should Statements: "I should be happy" → guilt for feeling bad Filtering: Focus only on negatives, ignore positives Overgeneralization: "This ALWAYS happens to me" Emotional Reasoning: "I feel stupid, so I must BE stupid" Fix: Notice the distortion → challenge it with evidence → generate balanced thought PHYSIOLOGICAL TRIGGERS: Hormonal cycles: Menstrual cycle, testosterone fluctuations Medication: Side effects, withdrawal Caffeine: Anxiety, sleep disruption Alcohol: Depressant (next-day mood drop) Blood sugar: Hypoglycemia → irritability ("hangry") Chronic pain: Persistent pain → mood depression Gut health: Microbiome affects serotonin production (90% in gut) EOF } cmd_journaling() { cat << 'EOF' === Mood Journaling Techniques === BASIC MOOD LOG: Time: _______________ Mood: _______________ (1-10 scale) Feeling: _______________ (specific emotion word) Trigger: What happened right before? Thought: What went through my mind? Body: Where do I feel this in my body? Action: What did I do in response? CBT THOUGHT RECORD: 1. Situation: What happened? (objective facts) 2. Emotions: What did I feel? (name + intensity 0-100%) 3. Automatic thought: What went through my mind? 4. Evidence FOR: What supports this thought? 5. Evidence AGAINST: What contradicts this thought? 6. Balanced thought: More realistic perspective 7. Outcome: How do I feel now? (re-rate 0-100%) GRATITUDE JOURNALING: Daily: Write 3 things you're grateful for Be specific: Not "family" but "Mom's phone call that made me laugh" Why it works: Shifts attention from threats to blessings Research: 10 weeks of gratitude journaling → 25% happier (Emmons) Avoid: Don't make it a chore — genuine > routine EXPRESSIVE WRITING (Pennebaker Method): Write for 20 minutes about deepest thoughts and feelings About a difficult experience or strong emotion No editing, no grammar concerns, just write Repeat 3-4 days on the same topic Research: improved immune function, lower depression, better grades, fewer doctor visits PROMPT IDEAS: Morning: "How do I want to feel today? What would support that?" Evening: "What was the emotional highlight and lowlight of today?" Weekly: "What patterns am I noticing in my mood this week?" Stuck: "If my emotion could speak, what would it say?" Growth: "What did I handle better this time than last time?" TRACKING PATTERNS: After 2-4 weeks of daily logging, look for: - Time-of-day patterns (morning vs evening mood) - Day-of-week patterns (weekend vs weekday) - Trigger patterns (same situations → same emotions) - Sleep-mood correlation - Exercise-mood correlation - Social-mood correlation Visual: Plot mood ratings over time → identify trends EOF } cmd_lifestyle() { cat << 'EOF' === Lifestyle Factors Affecting Mood === SLEEP (most impactful): Duration: 7-9 hours for adults (less = emotional dysregulation) Quality: Deep sleep + REM critical for emotional processing Consistency: Same sleep/wake time (±30 min) even weekends Sleep deprivation effects on mood: 1 night poor sleep → 60% increase in emotional reactivity Chronic poor sleep → similar symptoms to depression REM deprivation → impaired emotional memory processing Sleep hygiene essentials: - No screens 1 hour before bed (or use blue light filter) - Cool room (65-68°F / 18-20°C) - Consistent schedule - Caffeine cutoff 8-10 hours before bed - Dark room (blackout curtains or sleep mask) EXERCISE (most reliable mood booster): Acute: Single session improves mood for 4-6 hours Chronic: Regular exercise = as effective as antidepressants for mild-moderate depression Minimum effective dose: 20 minutes moderate activity, 3x/week Optimal: 150 min moderate OR 75 min vigorous per week Best for mood: Aerobic (running, cycling, swimming) → endorphins, serotonin Yoga → GABA increase, stress reduction Strength training → confidence, mastery, testosterone Nature walks → combines exercise + nature (double benefit) NUTRITION: Mediterranean diet: associated with 33% lower depression risk Omega-3 fatty acids: anti-inflammatory, mood-supporting Gut health: fermented foods, fiber → serotonin production Blood sugar stability: regular meals, complex carbs, protein Mood-damaging: Excessive sugar → energy crashes → irritability Ultra-processed food → inflammation → mood decline Excessive alcohol → disrupts sleep, depressant Excessive caffeine → anxiety, sleep disruption SOCIAL CONNECTION: Loneliness is as harmful as smoking 15 cigarettes/day (Holt-Lunstad) Meaningful conversations (not small talk) boost mood Physical touch releases oxytocin Minimum: 2-3 close relationships for emotional buffer Quality > quantity: one deep friendship > many acquaintances NATURE EXPOSURE: 20 minutes in nature → cortisol drops measurably "Forest bathing" (Shinrin-yoku) → lower stress hormones Even houseplants and nature photos have mild benefits Sunlight → vitamin D + serotonin + circadian alignment Target: some outdoor time daily, ideally morning sunlight EOF } cmd_tracking() { cat << 'EOF' === Mood Tracking Systems === SCALES: Simple (1-5): 1 = Very bad 2 = Bad 3 = Okay 4 = Good 5 = Great Best for: daily quick check-in, minimal friction Numerical (1-10): More granular, better for detecting trends Anchor points: 1 = worst ever, 5 = neutral, 10 = best ever Visual Analog Scale (VAS): Slider from "worst" to "best" More nuanced, less categorical bias Good for apps and digital tracking Emoji Scale: 😢 😟 😐 🙂 😄 Low barrier, universal, culturally inclusive Less precise but higher compliance Circumplex (2D): Rate both valence (negative↔positive) AND arousal (low↔high) More informative: "calm-positive" vs "excited-positive" FREQUENCY: 3x daily: Morning, afternoon, evening (best for pattern detection) 2x daily: Morning + evening (good balance) 1x daily: End of day reflection (minimum recommended) Event-based: Log when something notable happens (less systematic) Weekly: Too infrequent for pattern detection Best practice: Start with 1x daily, increase if engaged WHAT TO TRACK ALONGSIDE MOOD: Sleep hours and quality (previous night) Exercise (type, duration) Meals (quality, timing) Social interaction (alone, small group, crowd) Weather and light exposure Menstrual cycle (if applicable) Medication adherence Significant events or stressors Screen time / social media Caffeine and alcohol intake PATTERN RECOGNITION: After 2-4 weeks, analyze: Correlation: mood × sleep (usually strong) Correlation: mood × exercise Time patterns: morning person? Evening dip? Weekly patterns: Sunday scaries? Friday relief? Trigger patterns: meetings → anxiety? Nature → calm? Visualization: Line chart: mood over time (trend, cycles) Heat map: mood by day/time (weekly patterns) Scatter plot: mood vs sleep hours (correlation) Calendar view: color-coded days (at-a-glance month) APPS: Daylio Simple, visual, no writing required Pixels Year-in-pixels calendar view Bearable Correlates mood with health factors Moodfit CBT-based tools + tracking How We Feel Research-backed, circumplex model EOF } cmd_resilience() { cat << 'EOF' === Building Emotional Resilience === WHAT IS RESILIENCE: Not: never feeling bad or being unaffected by adversity Is: the ability to recover from difficulties and adapt Resilience is a skill that can be developed, not a fixed trait THE RESILIENCE FRAMEWORK (APA): 1. CONNECTIONS Build and maintain supportive relationships Don't isolate during difficult times Accept help and support Prioritize relationships proactively 2. WELLNESS Take care of your body (sleep, exercise, nutrition) Practice mindfulness or meditation Avoid unhealthy coping (substances, avoidance) Rest is not laziness — it's recovery 3. HEALTHY THINKING Keep perspective (this too shall pass) Accept that change is part of life Maintain a hopeful outlook (realistic, not delusional) Learn from adversity (post-traumatic growth) 4. MEANING Set meaningful goals (direction during chaos) Look for opportunities in challenges Help others (shifts focus, builds purpose) Connect to values and purpose 5. PROACTIVE STEPS Don't wait for problems — build capacity Face fears gradually (exposure therapy principle) Develop problem-solving skills before crises Create routines that support well-being STRESS INOCULATION (Meichenbaum): Train resilience by graduated exposure to stress: 1. Education: understand stress response (it's normal, adaptive) 2. Skills: learn coping techniques (breathing, reappraisal) 3. Application: practice in low-stress situations first 4. Graduation: apply in progressively challenging situations Like a vaccine: small doses build immunity GROWTH MINDSET (Dweck): Fixed mindset: "I failed, I'm a failure" Growth mindset: "I failed, I can learn from this" Reframes: "I can't do this" → "I can't do this YET" "This is too hard" → "This will take effort and practice" "I made a mistake" → "Mistakes help me learn" POST-TRAUMATIC GROWTH: Some people report positive changes after adversity: - Greater appreciation for life - More meaningful relationships - Increased personal strength - Recognition of new possibilities - Spiritual or existential deepening Not guaranteed, not expected — but possible. Growth and suffering can coexist. DAILY RESILIENCE PRACTICES: Morning: Set intention, brief meditation (5 min) Midday: Check in with HALT (Hungry, Angry, Lonely, Tired?) Evening: Gratitude practice, wind-down routine Weekly: Social connection, nature time, reflection Monthly: Review patterns, adjust strategies, celebrate progress EOF } show_help() { cat << EOF mood v$VERSION — Mood & Emotional Wellness Reference Usage: script.sh <command> Commands: intro Mood science, emotions vs moods, neuroscience basics wheel Emotion taxonomy, Plutchik's wheel, vocabulary regulation Regulation strategies — reappraisal, grounding, DBT triggers Mood triggers — HALT, cognitive distortions, environment journaling Journaling techniques, CBT thought records, gratitude lifestyle Sleep, exercise, nutrition, social connection, nature tracking Mood scales, tracking frequency, pattern recognition resilience Building resilience, stress inoculation, growth mindset help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; wheel) cmd_wheel ;; regulation) cmd_regulation ;; triggers) cmd_triggers ;; journaling) cmd_journaling ;; lifestyle) cmd_lifestyle ;; tracking) cmd_tracking ;; resilience) cmd_resilience ;; help|--help|-h) show_help ;; version|--version|-v) echo "mood v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Reward system design reference — behavioral reinforcement, loyalty programs, gamification, incentive structures. Use when designing reward programs, loyalty...
--- name: "reward" version: "1.0.0" description: "Reward system design reference — behavioral reinforcement, loyalty programs, gamification, incentive structures. Use when designing reward programs, loyalty systems, or behavioral incentive mechanisms." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [reward, incentive, loyalty, gamification, behavioral-design, motivation, reinforcement] category: "life" --- # Reward — Reward System Design Reference Quick-reference skill for designing effective reward systems, loyalty programs, and behavioral incentives. ## When to Use - Designing loyalty or points-based reward programs - Understanding behavioral reinforcement principles - Creating gamification systems for apps or teams - Evaluating incentive structures for effectiveness - Building habit-forming product experiences ## Commands ### `intro` ```bash scripts/script.sh intro ``` Reward system fundamentals — behavioral science, reinforcement theory, types of rewards. ### `schedules` ```bash scripts/script.sh schedules ``` Reinforcement schedules — fixed/variable ratio and interval, optimal engagement patterns. ### `loyalty` ```bash scripts/script.sh loyalty ``` Loyalty program design — points, tiers, coalition models, ROI metrics. ### `gamification` ```bash scripts/script.sh gamification ``` Gamification mechanics — badges, leaderboards, progress bars, streaks, challenges. ### `intrinsic` ```bash scripts/script.sh intrinsic ``` Intrinsic rewards — autonomy, mastery, purpose, flow states, meaningful work. ### `pitfalls` ```bash scripts/script.sh pitfalls ``` Common reward design mistakes and unintended consequences. ### `workplace` ```bash scripts/script.sh workplace ``` Workplace incentives — recognition programs, bonus structures, team rewards. ### `metrics` ```bash scripts/script.sh metrics ``` Measuring reward effectiveness — engagement, retention, satisfaction, ROI. ### `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 # reward — Reward System Design Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Reward System Fundamentals === A reward system is any structured mechanism that delivers positive outcomes in response to desired behaviors, driving engagement, loyalty, and habit formation. BEHAVIORAL SCIENCE FOUNDATIONS: Operant Conditioning (BF Skinner): Behavior is shaped by its consequences. Positive reinforcement: Add something pleasant → repeat behavior Negative reinforcement: Remove something unpleasant → repeat behavior Punishment: Add something unpleasant → reduce behavior Extinction: Remove reinforcement → behavior fades Dopamine & Anticipation: The brain's reward circuit releases dopamine not just at reward, but during ANTICIPATION of reward. Uncertainty amplifies this. → Variable rewards are more engaging than predictable ones → The journey to the reward matters as much as the reward itself TYPES OF REWARDS: Tangible Money, gifts, products, discounts Social Recognition, status, praise, titles Experiential Access, exclusive events, early access, VIP treatment Informational Feedback, progress data, achievement unlock Autonomy Freedom, choice, self-direction opportunities REWARD DESIGN PRINCIPLES: 1. Timely Reward close to the behavior (immediacy matters) 2. Proportional Value matches effort (don't over or under reward) 3. Meaningful Aligns with recipient's values and desires 4. Variable Some unpredictability maintains engagement 5. Visible Others can see the reward (social proof) 6. Achievable Goals feel reachable (not impossibly distant) 7. Progressive Rewards grow with sustained engagement 8. Authentic Feels genuine, not manipulative EOF } cmd_schedules() { cat << 'EOF' === Reinforcement Schedules === How rewards are timed fundamentally determines behavior patterns. FIXED RATIO (FR): Reward after every N actions. Example: "Buy 10 coffees, get 1 free" (FR-10) Behavior: Steady effort, brief pause after reward (post-reinforcement pause) Use for: Simple loyalty programs, piecework compensation Pro: Predictable, easy to understand Con: Engagement drops right after reward, then ramps back up VARIABLE RATIO (VR): Reward after unpredictable number of actions. Example: Slot machines, gacha games, fishing, loot drops Behavior: High, steady response rate — MOST RESISTANT TO EXTINCTION Use for: Games, engagement hooks, social media likes Pro: Highest engagement, persistent behavior Con: Can become addictive, ethical concerns ⚠️ The most powerful and most dangerous schedule FIXED INTERVAL (FI): Reward available after fixed time period. Example: Daily login bonus, weekly paycheck, monthly subscription box Behavior: Low activity early, increases as reward time approaches Use for: Recurring engagement, retention tools Pro: Regular return visits, predictable costs Con: Activity clusters around reward time, dead periods VARIABLE INTERVAL (VI): Reward available after unpredictable time period. Example: Random pop-up sales, surprise bonus, "mystery" daily reward Behavior: Steady, moderate response rate Use for: Maintaining consistent checking behavior Pro: Reduces dead periods, steady engagement Con: Harder to plan/budget, may frustrate users COMPOUND SCHEDULES (real-world combinations): Season pass: Fixed interval (season) + Fixed ratio (XP per level) Loot boxes: Variable ratio (drop rate) + fixed interval (daily free one) Social media: Variable interval (when friends post) + variable ratio (likes) OPTIMAL ENGAGEMENT PATTERN: 1. Start with Fixed Ratio (low threshold) → quick wins, teach the loop 2. Graduate to Variable Ratio → sustained engagement 3. Layer Fixed Interval → daily return habit 4. Add Variable surprises → delight and discovery EOF } cmd_loyalty() { cat << 'EOF' === Loyalty Program Design === PROGRAM MODELS: Points-Based: Earn points per dollar/action, redeem for rewards Examples: Airline miles, credit card points, Starbucks Stars Design: 1 point per $1 spent, redeem at $0.01-0.02/point value Key: Points must feel valuable and be easy to redeem Tiered: Status levels unlock better benefits Examples: Hotel programs (Silver → Gold → Platinum → Diamond) Design: 3-5 tiers, clear qualification criteria Key: Each tier must feel meaningfully different Paid/Subscription: Pay upfront for better rewards Examples: Amazon Prime, Costco membership, airline status match Design: Annual fee < perceived annual benefit Key: Must deliver obvious, immediate value Coalition: Multiple brands share one loyalty currency Examples: Aeroplan (Canada), Nectar (UK), Tmall Points Design: Common currency, brand-specific bonuses Key: Wide earn/burn options increase perceived value Cashback: Simple percentage back on purchases Examples: Credit card cashback, Rakuten, Ibotta Design: 1-5% standard, category bonuses 5-10% Key: Simplicity is the appeal TIER DESIGN BEST PRACTICES: Entry tier: Easy to reach (~80% of members), basic benefits Middle tier: Meaningful effort (~15%), noticeable upgrade Top tier: Aspirational (~5%), exclusive experiences Re-qualification: Annual cycle, slightly lower than initial qualification Status matching: Acquire competitors' high-value customers EARN RATE GUIDELINES: Too stingy: Customer gives up ("I'll never earn enough") Too generous: Unsustainable liability, devaluation risk Sweet spot: First meaningful reward achievable in 3-5 transactions Show progress: "You're 70% to your next reward!" LOYALTY METRICS: Enrollment rate: % eligible customers who join Active rate: % members with activity in last 90 days Redemption rate: Points redeemed / points earned Breakage: Points earned but never redeemed (revenue) Incremental revenue: Additional spend from members vs non-members CLV lift: Customer lifetime value increase from program EOF } cmd_gamification() { cat << 'EOF' === Gamification Mechanics === CORE MECHANICS: Points: Quantified progress currency Types: experience (XP), currency (coins), karma, reputation Best practice: Clear earning rules, visible balance, multiple uses Badges/Achievements: Visual markers of accomplishment Types: milestone (100 purchases), skill (first review), special (event) Best practice: Mix easy + hard, surprise + known, limited editions Leaderboards: Competitive ranking among peers Types: global, friends-only, weekly reset, category-specific ⚠️ Risk: Demotivates bottom 90% who can never compete Fix: Segmented boards (top 100, your percentile, friends) Progress Bars: Visual completion indicator Endowed progress effect: Start at 20% → feels achievable Best practice: Break into segments, show % and absolute numbers Streaks: Consecutive activity counter Examples: Duolingo daily streak, Snapchat streaks Power: Loss aversion — don't want to lose the streak ⚠️ Risk: Stressful, punishing for legitimate breaks Fix: Streak freezes, grace periods, streak recovery items Challenges/Quests: Time-bound goals with specific rewards Daily challenges: low effort, small reward (login habit) Weekly challenges: medium effort, better reward Special events: limited-time, exclusive rewards (FOMO) Levels: Progressive difficulty and status markers XP curve: typically exponential (each level takes more) Best practice: Level 1-5 quick (hook), then gradual increase Prestige system: reset and do it again with bonuses OCTALYSIS FRAMEWORK (Yu-kai Chou): 8 core drives of gamification: 1. Epic Meaning "I'm part of something bigger" 2. Development "I'm getting better/stronger" 3. Empowerment "I can be creative and get feedback" 4. Ownership "I own and want to improve this" 5. Social Influence "Others are doing it / watching me" 6. Scarcity "I can't get this easily, I want it more" 7. Unpredictability "I wonder what happens next" 8. Avoidance "I don't want to lose my progress" White hat (1-3): feel great, sustainable, intrinsic Black hat (6-8): urgent, addictive, potentially harmful Best design: primarily white hat with strategic black hat elements EOF } cmd_intrinsic() { cat << 'EOF' === Intrinsic Rewards === Intrinsic rewards come from the activity itself, not external incentives. They are more sustainable and create deeper engagement than extrinsic rewards. SELF-DETERMINATION THEORY (Deci & Ryan): Three innate needs that drive intrinsic motivation: AUTONOMY — "I choose this" Let people decide HOW to complete tasks Offer meaningful choices, not just yes/no Self-directed goals > assigned goals Example: 20% time (Google), flexible work arrangements COMPETENCE — "I'm growing" Clear feedback on performance Challenges that match skill level (flow) Visible progress and mastery indicators Example: Skill trees, mastery badges, performance dashboards RELATEDNESS — "I belong" Connection to others and community Shared purpose and collaborative goals Social recognition from peers (not just managers) Example: Team achievements, community contributions, mentoring FLOW STATE (Csikszentmihalyi): Optimal experience when challenge matches skill: Challenge too high → anxiety Challenge too low → boredom Challenge = skill → FLOW Flow conditions: 1. Clear goals for each step 2. Immediate feedback 3. Balance between challenge and skill 4. Merger of action and awareness 5. Sense of control 6. Loss of self-consciousness 7. Altered sense of time MEANINGFUL WORK: Connect tasks to impact: "Who benefits from what I do?" Purpose: work serves something larger than self Craft: pride in quality of work itself Connection: relationships formed through work Progress: visible forward movement (Teresa Amabile's research) THE OVERJUSTIFICATION EFFECT: ⚠️ Adding external rewards to intrinsically motivated behavior can DECREASE intrinsic motivation! Classic study: Children who loved drawing were paid to draw. Result: They drew LESS when payment stopped. Lesson: Use extrinsic rewards for unenjoyable tasks. For naturally enjoyable tasks, enhance intrinsic rewards instead. If you must use extrinsic: make them unexpected, informational, and tied to competence (not just completion). EOF } cmd_pitfalls() { cat << 'EOF' === Reward Design Pitfalls === 1. COBRA EFFECT (Perverse Incentives): Reward creates the opposite of desired behavior. Example: Bounty on cobra snakes → people breed cobras for bounty Example: Reward for bug fixes → developers introduce bugs to fix Fix: Reward outcomes, not outputs. Measure what matters. 2. GAMING THE SYSTEM: People optimize for the reward metric, not the intent. Example: Call center rewards "calls per hour" → hang up on hard calls Example: Lines of code reward → bloated, verbose code Fix: Multiple balanced metrics, qualitative review, spirit-of-the-law clauses 3. CROWDING OUT INTRINSIC MOTIVATION: External rewards can kill internal motivation. Example: Paying volunteers → they feel like cheap labor, not helpers Example: Giving grades for reading → kids read less for fun Fix: Use extrinsic rewards sparingly, prefer recognition over cash 4. ENTITLEMENT ESCALATION: Rewards become expected, then demanded, then insufficient. Example: Annual bonus → employees see it as part of salary Example: Loyalty discount → customers won't buy at full price Fix: Variable rewards, surprise bonuses, clear framing as extra 5. INEQUITY PERCEPTION: If rewards feel unfair, they demotivate EVERYONE. Example: Sales commission structure favors legacy accounts Example: Top performer bonus too close to average performer bonus Fix: Transparent criteria, differentiated rewards, perceived fairness 6. SHORT-TERM FOCUS: Rewards for short-term metrics sacrifice long-term value. Example: Quarterly sales bonus → end-of-quarter discounting Example: Daily active user rewards → low-quality sessions Fix: Balance immediate rewards with long-term incentives 7. REWARD INFLATION: Need bigger rewards over time for same effect (habituation). Example: First discount email gets 20% open rate, 50th gets 2% Fix: Vary reward types, intermittent schedules, meaningful > big 8. EXCLUDING THE MAJORITY: Top-performer-only rewards demotivate everyone else. Example: "Employee of the Month" → same 3 people rotate Fix: Tiered recognition, effort-based + outcome-based, team rewards EOF } cmd_workplace() { cat << 'EOF' === Workplace Incentives === RECOGNITION PROGRAMS: Peer-to-Peer Recognition: Platform: Bonusly, Kudos, Nectar, Motivosity How: Employees give micro-bonuses/points to each other Budget: $20-50/employee/month to distribute Impact: 14% better engagement than manager-only recognition Spot Awards: Immediate recognition for exceptional work Manager can award on-the-spot (gift card, bonus, time off) Budget: $50-500 per award Key: Timely, specific, public when appropriate Service Awards: Milestone-based: 1, 3, 5, 10, 15, 20+ years Modern approach: experience catalog (choose your reward) Old approach: generic plaque/pin (low impact) BONUS STRUCTURES: Individual Performance Bonus: Tied to personal KPIs/OKRs Typical: 5-20% of base salary Risk: Competition over collaboration Mitigate: Include team metrics (30% team, 70% individual) Team/Group Bonus: Shared pool based on team achievement Promotes collaboration, knowledge sharing Risk: Free-rider problem (some coast on others' work) Mitigate: Peer evaluation component, minimum individual standard Profit Sharing: Percentage of company profit distributed to employees Typical: 2-10% of profits Creates ownership mentality Risk: Employees can't control profitability individually Equity/Stock Options: Long-term alignment with company success Vesting schedule: typically 4 years with 1-year cliff Most powerful for early-stage companies NON-MONETARY REWARDS (often more impactful): Flexible work hours / remote work options Extra paid time off (birthday off, mental health days) Learning budget ($1000-5000/year for courses) Conference attendance Lunch with leadership Project choice (pick your next assignment) Title upgrade Public presentation opportunity Mentoring from senior leader EOF } cmd_metrics() { cat << 'EOF' === Measuring Reward Effectiveness === ENGAGEMENT METRICS: Participation rate: % of eligible people engaging with program Active rate: % with activity in last 30/60/90 days Frequency: Average interactions per user per period Session depth: How deeply users engage per visit Benchmarks: Good participation: >60% of eligible Good active rate: >40% monthly active Warning sign: participation dropping month-over-month RETENTION METRICS: Churn rate: % of members who disengage per period Retention curve: % remaining at day 1, 7, 30, 90, 365 Cohort analysis: Compare retention across signup periods Reactivation rate: % of churned members who return Program Impact: Members vs non-members retention comparison Target: 20-40% better retention for program members SATISFACTION METRICS: NPS (Net Promoter Score): "Would you recommend this program?" CSAT (Customer Satisfaction): "How satisfied are you with rewards?" CES (Customer Effort Score): "How easy was it to earn/redeem?" Survey at key moments: After first reward earned After first redemption At program anniversary After tier upgrade/downgrade FINANCIAL METRICS: Incremental revenue: Additional spend attributable to program Cost per member: Total program cost / active members ROI: (Incremental revenue - program cost) / program cost Breakage rate: % of earned rewards never redeemed Liability: Outstanding unredeemed points value Calculation example: Members spend $150/month vs non-members $100/month Incremental: $50/month × 10,000 members = $500,000/month Program cost: $100,000/month ROI: ($500,000 - $100,000) / $100,000 = 400% BEHAVIORAL METRICS: Desired behavior change: Did the target behavior increase? Unintended behaviors: Any gaming or perverse outcomes? Habit formation: Does behavior persist without reward? Referral rate: Do members bring others in? REPORTING CADENCE: Daily: Participation, earn/burn activity Weekly: Engagement trends, anomaly detection Monthly: ROI, retention, satisfaction scores Quarterly: Program review, strategy adjustment Annually: Full program audit, competitive benchmark EOF } show_help() { cat << EOF reward v$VERSION — Reward System Design Reference Usage: script.sh <command> Commands: intro Behavioral science, reinforcement theory, reward types schedules Reinforcement schedules — fixed/variable ratio/interval loyalty Loyalty program models, tiers, earn rates, metrics gamification Badges, leaderboards, streaks, progress, Octalysis intrinsic Autonomy, mastery, purpose, flow, meaningful work pitfalls Cobra effect, gaming, crowding out, entitlement workplace Recognition programs, bonuses, non-monetary rewards metrics Engagement, retention, satisfaction, ROI measurement help Show this help version Show version Powered by BytesAgain | bytesagain.com EOF } CMD="-help" case "$CMD" in intro) cmd_intro ;; schedules) cmd_schedules ;; loyalty) cmd_loyalty ;; gamification) cmd_gamification ;; intrinsic) cmd_intrinsic ;; pitfalls) cmd_pitfalls ;; workplace) cmd_workplace ;; metrics) cmd_metrics ;; help|--help|-h) show_help ;; version|--version|-v) echo "reward v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Generate popover UI elements and design assets. Use when building interfaces, creating visual components, or styling web pages.
--- name: "popover" version: "1.0.0" description: "Generate popover UI elements and design assets. Use when building interfaces, creating visual components, or styling web pages." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [popover, frontend, cli, tool] category: "frontend" --- # popover Generate popover UI elements and design assets. Use when building interfaces, creating visual components, or styling web pages. ## 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 | |----------|-------------| | `POPOVER_DIR` | Data directory (default: ~/.popover/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # popover -- Generate popover UI elements and design assets. Use when building interfaces, creating visual components, or styling web pages. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.popover" _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 popover v$VERSION -- Generate popover UI elements and design assets. Use when building interfaces, creating visual components, or styling web pages. Usage: popover <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 "=== popover 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: popover 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 "=== Popover 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: popover 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: popover 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="popover-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 "=== Popover 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 "popover v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: popover help"; exit 1 ;; esac
Calculate ledger financial metrics and business data. Use when tracking expenses, analyzing investments, or generating financial reports.
--- name: "ledger" version: "1.0.0" description: "Calculate ledger financial metrics and business data. Use when tracking expenses, analyzing investments, or generating financial reports." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [ledger, finance, cli, tool] category: "finance" --- # ledger Calculate ledger financial metrics and business data. Use when tracking expenses, analyzing investments, or generating financial reports. ## 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 | |----------|-------------| | `LEDGER_DIR` | Data directory (default: ~/.ledger/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # ledger -- Calculate ledger financial metrics and business data. Use when tracking expenses, analyzing investments, or generating financial reports. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.ledger" _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 ledger v$VERSION -- Calculate ledger financial metrics and business data. Use when tracking expenses, analyzing investments, or generating financial reports. Usage: ledger <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 "=== ledger 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: ledger 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 "=== Ledger 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: ledger 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: ledger 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="ledger-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 "=== Ledger 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 "ledger v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: ledger help"; exit 1 ;; esac
Robot gripper reference — jaw types, force calculation, pneumatic vs electric, and end-effector selection. Use when designing gripping systems, selecting act...
--- name: "gripper" version: "1.0.0" description: "Robot gripper reference — jaw types, force calculation, pneumatic vs electric, and end-effector selection. Use when designing gripping systems, selecting actuators, or sizing grippers for robotic applications." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [gripper, robotics, end-effector, pneumatic, actuator, industrial] category: "industrial" --- # Gripper — Robot Gripper Reference Quick-reference skill for gripper types, force calculations, actuator selection, and end-effector design. ## When to Use - Selecting a gripper type for a robot application - Calculating required gripping force for a payload - Choosing between pneumatic, electric, and vacuum grippers - Designing custom jaw geometry for specific parts - Troubleshooting grip failures in production ## Commands ### `intro` ```bash scripts/script.sh intro ``` Gripper fundamentals — types, actuation methods, key specifications. ### `types` ```bash scripts/script.sh types ``` Gripper types: parallel, angular, three-jaw, vacuum, magnetic, soft, adaptive. ### `force` ```bash scripts/script.sh force ``` Grip force calculation — formulas, safety factors, friction coefficients. ### `pneumatic` ```bash scripts/script.sh pneumatic ``` Pneumatic grippers — cylinders, valves, air prep, circuit design. ### `electric` ```bash scripts/script.sh electric ``` Electric grippers — servo, stepper, advantages over pneumatic. ### `vacuum` ```bash scripts/script.sh vacuum ``` Vacuum grippers — suction cups, venturi generators, cup selection. ### `applications` ```bash scripts/script.sh applications ``` Gripper applications by industry: automotive, electronics, food, pharma. ### `checklist` ```bash scripts/script.sh checklist ``` Gripper selection and commissioning checklist. ### `help` ```bash scripts/script.sh help ``` ### `version` ```bash scripts/script.sh version ``` ## Configuration | Variable | Description | |----------|-------------| | `GRIPPER_DIR` | Data directory (default: ~/.gripper/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # gripper — Robot Gripper Reference # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" cmd_intro() { cat << 'EOF' === Robot Gripper Fundamentals === A gripper is an end-effector mounted on a robot arm that grasps, holds, and releases workpieces. It's the robot's "hand." Actuation Methods: Pneumatic Compressed air drives piston/cylinder + Fast, simple, high force-to-size ratio - Binary (open/close), needs air supply, noisy Electric Servo or stepper motor drives mechanism + Precise position/force control, programmable - Slower, more expensive, complex control Hydraulic Oil pressure drives piston + Very high force, smooth motion - Heavy, messy, expensive, maintenance-heavy Vacuum Negative pressure holds via suction cups + Gentle, handles flat/smooth objects well - Porous/irregular surfaces don't seal Key Specifications: Gripping Force Force applied to workpiece (N) Stroke Opening/closing distance (mm) Closing Time Time to fully close (ms) Repeat Accuracy Position repeatability (mm) Weight Gripper mass (affects robot payload) IP Rating Dust/water ingress protection Finger Length Distance from jaw pivot to contact point Major Manufacturers: Schunk Market leader, parallel/centric grippers SMC Pneumatic grippers, wide range Festo Pneumatic + adaptive/soft grippers Zimmer Versatile, GEP/GPP series Robotiq Collaborative robot grippers (2F/3F) OnRobot Electric grippers + sensors for cobots SCHMALZ Vacuum gripping systems Destaco Toggle clamps and grippers EOF } cmd_types() { cat << 'EOF' === Gripper Types === Parallel Jaw Gripper: Fingers move in parallel (linear motion) Most common industrial gripper 2-finger (external/internal grip) Good for: prismatic parts, cylinders, boxes Brands: Schunk PGN-plus, SMC MHZ2 Angular Gripper: Fingers pivot around a point (arc motion) Wider opening with compact design Good for: larger parts, limited-space applications Angle: typically 30°-180° per jaw Brands: Schunk MPC, SMC MHC2 Three-Jaw (Centric) Gripper: Three fingers close simultaneously to center Self-centering for round/irregular parts Good for: cylindrical parts, rings, shafts Brands: Schunk PZN-plus, Festo DHPS Vacuum Gripper: Suction cups on frame/tooling plate Single or multi-cup arrays Good for: flat objects (sheets, glass, boxes, PCBs) Needs: vacuum generator (venturi or pump) Magnetic Gripper: Electro-permanent or electromagnetic No moving parts, instant grip/release Good for: ferrous metal sheets, stamped parts Limitation: ferrous materials only Soft / Adaptive Gripper: Compliant fingers conform to object shape Fin Ray, pneumatic bladder, or elastomer designs Good for: variable products, food, fragile items Brands: Soft Robotics, Festo DHEF, Robotiq Needle Gripper: Fine needles penetrate soft material Good for: textiles, foam, carbon fiber preforms Low damage to material surface Tool Changer: Not a gripper itself — swaps end-effectors Allows robot to use multiple gripper types Brands: ATI, Schunk SWS, Stäubli Pneumatic/electric/manual coupling EOF } cmd_force() { cat << 'EOF' === Grip Force Calculation === Basic Formula (vertical lift, gravity opposing grip): F_grip = m × g × S / (μ × n) Where: F_grip = required gripping force per finger (N) m = workpiece mass (kg) g = gravity (9.81 m/s²) S = safety factor (typically 2-4) μ = friction coefficient n = number of gripping surfaces (usually 2) Safety Factor Guidelines: S = 2 Static handling (pick and place, low speed) S = 3 Dynamic with acceleration (conveyor loading) S = 4 High speed, vibration, uncertain conditions Friction Coefficients (μ): Steel on steel (dry) 0.15-0.20 Steel on rubber jaw 0.50-0.80 Aluminum on rubber 0.40-0.60 Plastic on rubber 0.40-0.60 Cardboard on rubber 0.50-0.70 Glass on rubber (suction) 0.50-0.70 Oily metal on metal 0.05-0.10 Serrated jaw on metal 0.30-0.50 Dynamic Forces to Consider: Acceleration: F = m × a (add to gravity load) Centrifugal: F = m × ω² × r (rotation at speed) Impact: sudden stop multiplies force 2-5× Example Calculation: Part: 2 kg steel cylinder, rubber jaws Motion: pick up vertically, moderate speed F_grip = 2 × 9.81 × 3 / (0.6 × 2) F_grip = 58.86 / 1.2 F_grip = 49.1 N per finger Select gripper rated ≥ 50N per finger Vacuum Force: F = (P_vacuum × A_cup × n) / S P_vacuum = vacuum level (typically -0.6 to -0.85 bar) A_cup = suction cup area (m²) n = number of cups Bellows cups: better on curved surfaces Flat cups: higher force, smooth surfaces only EOF } cmd_pneumatic() { cat << 'EOF' === Pneumatic Grippers === Air Supply Requirements: Pressure: typically 4-6 bar (60-90 psi) Clean, dry air (ISO 8573-1 Class 4 or better) Filter-Regulator-Lubricator (FRL) unit required Flow: depends on cylinder bore and cycle rate Cylinder Types: Single-acting: spring return, air on one side + Simpler, fail-safe (spring opens/closes on air loss) - Lower force in one direction Double-acting: air on both sides + Full force both directions, adjustable speed - Needs 2 air lines, no fail-safe position Valve Selection: 5/2 valve: double-acting cylinders (2 positions) 5/3 valve: center position options: - Center closed: holds position on air loss - Center exhaust: releases on air loss - Center pressure: maintains force on air loss Solenoid voltage: 24VDC (most common industrial) Circuit Design: Air supply → FRL → Directional valve → Gripper Add flow controls (meter-out) for speed adjustment Add quick-exhaust for faster closing Proximity sensors on cylinder for position feedback Speed Adjustment: Flow control valves (needle valves) Meter-out preferred (controls exhaust, smoother) Typical close time: 30-100ms Shock absorbers for high-speed applications Sensors: Magnetic reed switches on cylinder barrel Detect open and closed positions PNP (sourcing) or NPN (sinking) output Hall-effect for higher reliability than reed EOF } cmd_electric() { cat << 'EOF' === Electric Grippers === Advantages Over Pneumatic: - Programmable position (not just open/close) - Adjustable grip force (gentle for fragile parts) - No air supply needed (cleaner, simpler install) - Quieter operation - Energy efficient (no compressor) - Position and force feedback built-in - Multiple grip positions in one program Motor Types: Servo motor: precise position + velocity control Stepper motor: open-loop, simpler, lower cost Brushless DC: compact, long life Linear motor: direct drive, no mechanism backlash Drive Mechanisms: Lead screw: high force, compact, self-locking Ball screw: smoother, higher efficiency, higher speed Rack and pinion: simple, parallel motion Linkage: force multiplication, compact Belt drive: long stroke, lightweight Key Parameters: Stroke: 5-150mm typical Gripping force: 5-1000N+ depending on size Close speed: 50-500mm/s Repeatability: 0.01-0.05mm Communication: IO-Link, EtherCAT, Profinet, Modbus Popular Electric Grippers: Schunk EGP/EGH Parallel/centric, IO-Link Robotiq 2F-85/140 Adaptive, cobot-ready OnRobot RG2/RG6 Easy setup, force sensing Festo EHPS Parallel, servo-pneumatic hybrid Zimmer GEH6000 Heavy-duty electric When to Choose Electric: - Force/position control needed (fragile/variable parts) - Cleanroom or food-grade (no air contamination) - Collaborative robot (cobot) applications - Energy savings matter (no compressor running 24/7) - Complex grip sequences (multiple widths per cycle) EOF } cmd_vacuum() { cat << 'EOF' === Vacuum Grippers === Vacuum Generation: Venturi (ejector): Compressed air creates vacuum via Bernoulli effect + Simple, no moving parts, fast response - Consumes compressed air, limited vacuum level Typical: -0.6 to -0.85 bar vacuum Vacuum pump (electric): Mechanical pump creates vacuum + Higher vacuum, more efficient for multi-cup - Slower response, maintenance, noise Types: rotary vane, diaphragm, regenerative blower Suction Cup Types: Flat Cup: Best for: smooth, flat surfaces (glass, metal sheets) Highest force per area, fastest response Materials: NBR, silicone, Viton, polyurethane Bellows Cup (1.5-3.5 folds): Best for: curved, uneven, or flexible surfaces Compensates height differences 1.5 fold: slight curves 2.5 fold: moderate unevenness 3.5 fold: significant height variation Oval Cup: Best for: narrow, elongated workpieces Profiles, beams, rails Foam Seal Cup: Best for: textured, rough, or porous surfaces Closed-cell foam creates seal on irregular surfaces Cardboard boxes, wood panels, stone Cup Sizing: F_hold = P_vac × A_cup × n_cups P_vac = vacuum pressure (Pa, typically 60,000-85,000 Pa) A_cup = cup area (m²), diameter × π/4 Rule of thumb: select cups so total force ≥ 4× payload weight Common diameters: 10, 20, 30, 40, 50, 60, 80mm Material temp ranges: NBR: -30 to +70°C (general purpose) Silicone: -40 to +200°C (hot parts, food-grade) Viton: -20 to +200°C (chemical resistance) PU: -20 to +60°C (wear resistance) Vacuum Level Monitoring: Vacuum switch: confirms grip before robot moves Analog sensor: measures actual vacuum level Leak detection: if vacuum drops during move → alarm Important: always verify grip before lifting! EOF } cmd_applications() { cat << 'EOF' === Gripper Applications by Industry === Automotive: Body-in-white: magnetic grippers for steel panels Engine assembly: multi-finger for complex shapes Glass installation: large vacuum cup arrays Trim/clips: needle or soft grippers Typical: high speed (< 1s cycle), heavy loads Electronics: PCB handling: ESD-safe vacuum cups, gentle force Chip placement: micro-grippers, ±0.01mm accuracy Cable assembly: soft grippers for flexible parts Display handling: non-marking cups (silicone) Typical: high precision, cleanroom compatible Food & Beverage: Bakery: soft grippers (Fin Ray, bladder type) Meat/fish: needle grippers, food-safe material Bottles: parallel jaw with V-shaped fingers Boxes/cartons: vacuum with foam seal cups Requirements: FDA/EU food contact, washdown (IP67+) Pharma & Medical: Syringe handling: precision parallel grippers Vial capping: torque-controlled electric grippers Blister pack: vacuum cup arrays Requirements: cleanroom, stainless steel, no lubricants Logistics / E-commerce: Box picking: large vacuum grippers (multi-cup) Depalletizing: fork or clamp style Bin picking: 3D vision + adaptive grippers Variable products: AI-guided grip planning Challenge: huge variety of shapes, sizes, weights Metal Fabrication: Sheet handling: magnetic (ferrous) or vacuum (non-ferrous) Stamped parts: custom jaw profiles CNC machine tending: hydraulic or pneumatic Welding: clamp-and-hold fixtures EOF } cmd_checklist() { cat << 'EOF' === Gripper Selection & Commissioning Checklist === Part Analysis: [ ] Part weight (including worst-case tolerance) [ ] Part dimensions and shape (flat, round, irregular?) [ ] Surface finish (smooth, rough, oily, porous?) [ ] Material (steel, plastic, glass, food, fragile?) [ ] Temperature at time of gripping [ ] Part-to-part variation (one SKU or many?) Application Requirements: [ ] Cycle time requirement (picks per minute) [ ] Robot speed and acceleration (dynamic forces) [ ] Orientation changes during handling (tilt, rotate) [ ] Accuracy needed (placement tolerance) [ ] Environment (clean, dirty, wet, hot, cold?) [ ] Cleanroom / food-grade / ESD requirements Gripper Sizing: [ ] Grip force calculated with safety factor (≥ 2×) [ ] Stroke covers full range of part sizes [ ] Gripper weight within robot payload budget [ ] Mounting interface compatible with robot flange [ ] Finger/jaw length sized for part geometry Installation: [ ] Air supply connected, FRL unit installed (pneumatic) [ ] Electrical connections: power, signal, communication [ ] Position sensors wired and tested (open/close detect) [ ] Gripper mounted square to robot flange [ ] TCP (Tool Center Point) calibrated in robot controller Commissioning: [ ] Manual jog test: open/close at low speed [ ] Grip force verified (force gauge or crush test) [ ] Cycle time measured and meets target [ ] Grip confirmed before robot moves (sensor/vacuum check) [ ] Emergency stop releases part safely (fail mode) [ ] Run 100+ cycles, check for slip or misalignment [ ] Document: gripper model, jaw design, settings, spares EOF } show_help() { cat << EOF gripper v$VERSION — Robot Gripper Reference Usage: script.sh <command> Commands: intro Gripper fundamentals, actuation, specifications types Gripper types: parallel, angular, vacuum, soft force Grip force calculation and safety factors pneumatic Pneumatic gripper systems and circuits electric Electric gripper advantages and selection vacuum Vacuum grippers, cups, and sizing applications Industry applications: auto, food, electronics checklist Gripper selection and commissioning 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 ;; force) cmd_force ;; pneumatic) cmd_pneumatic ;; electric) cmd_electric ;; vacuum) cmd_vacuum ;; applications) cmd_applications ;; checklist) cmd_checklist ;; help|--help|-h) show_help ;; version|--version|-v) echo "gripper v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: script.sh help"; exit 1 ;; esac
Personal protective equipment tracker. Use when json ppe tasks, csv ppe tasks, checking ppe status.
--- name: "ppe" version: "1.0.0" description: "Personal protective equipment tracker. Use when json ppe tasks, csv ppe tasks, checking ppe status." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [ppe, safety, cli, tool] category: "safety" --- # ppe Personal protective equipment tracker. Use when json ppe tasks, csv ppe tasks, checking ppe 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 | |----------|-------------| | `PPE_DIR` | Data directory (default: ~/.ppe/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # ppe -- Personal protective equipment tracker # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.ppe" _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 ppe v$VERSION -- Personal protective equipment tracker Usage: ppe <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 "=== ppe 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: ppe 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 "=== Ppe 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: ppe 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: ppe 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="ppe-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 "=== Ppe 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 "ppe v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: ppe help"; exit 1 ;; esac
Switchgear specification manager. Use when json switchgear tasks, csv switchgear tasks, checking switchgear status.
--- name: "switchgear" version: "1.0.0" description: "Switchgear specification manager. Use when json switchgear tasks, csv switchgear tasks, checking switchgear status." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [switchgear, electrical, cli, tool] category: "electrical" --- # switchgear Switchgear specification manager. Use when json switchgear tasks, csv switchgear tasks, checking switchgear 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 | |----------|-------------| | `SWITCHGEAR_DIR` | Data directory (default: ~/.switchgear/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # switchgear -- Switchgear specification manager # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.switchgear" _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 switchgear v$VERSION -- Switchgear specification manager Usage: switchgear <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 "=== switchgear 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: switchgear 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 "=== Switchgear 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: switchgear 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: switchgear 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="switchgear-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 "=== Switchgear 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 "switchgear v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: switchgear help"; exit 1 ;; esac
Rectifier circuit design calculator. Use when json rectifier tasks, csv rectifier tasks, checking rectifier status.
--- name: "rectifier" version: "1.0.0" description: "Rectifier circuit design calculator. Use when json rectifier tasks, csv rectifier tasks, checking rectifier status." author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [rectifier, electrical, cli, tool] category: "electrical" --- # rectifier Rectifier circuit design calculator. Use when json rectifier tasks, csv rectifier tasks, checking rectifier 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 | |----------|-------------| | `RECTIFIER_DIR` | Data directory (default: ~/.rectifier/) | --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # rectifier -- Rectifier circuit design calculator # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.rectifier" _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 rectifier v$VERSION -- Rectifier circuit design calculator Usage: rectifier <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 "=== rectifier 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: rectifier 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 "=== Rectifier 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: rectifier 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: rectifier 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="rectifier-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 "=== Rectifier 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 "rectifier v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: rectifier help"; exit 1 ;; esac
Enterprise asset management tracker
--- name: "eam" version: "1.0.0" description: "Enterprise asset management tracker" author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [eam, industrial, cli, tool] category: "industrial" --- # eam Enterprise asset management tracker ## 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 | Required | Description | |----------|----------|-------------| | `EAM_DIR` | No | Data directory (default: ~/.eam/) | ## Data Storage All data stored in `~/.eam/` using JSONL format (one JSON object per line). ## Output Structured output to stdout. Exit code 0 on success, 1 on error. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # eam -- Enterprise asset management tracker # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.eam" _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 eam v$VERSION -- Enterprise asset management tracker Usage: eam <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 "=== eam 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: eam 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 "=== Eam 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: eam 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: eam 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="eam-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 "=== Eam 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 "eam v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: eam help"; exit 1 ;; esac
Boiler efficiency and sizing tool
--- name: "boiler" version: "1.0.0" description: "Boiler efficiency and sizing tool" author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [boiler, industrial, cli, tool] category: "industrial" --- # boiler Boiler efficiency and sizing tool ## 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 | Required | Description | |----------|----------|-------------| | `BOILER_DIR` | No | Data directory (default: ~/.boiler/) | ## Data Storage All data stored in `~/.boiler/` using JSONL format (one JSON object per line). ## Output Structured output to stdout. Exit code 0 on success, 1 on error. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # boiler -- Boiler efficiency and sizing tool # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.boiler" _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 boiler v$VERSION -- Boiler efficiency and sizing tool Usage: boiler <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 "=== boiler 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: boiler 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 "=== Boiler 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: boiler 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: boiler 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="boiler-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 "=== Boiler 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 "boiler v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: boiler help"; exit 1 ;; esac
Use when calculating gear ratios, converting RPM between shafts, computing torque output, analyzing drivetrain configurations, or selecting motors for mechan...
--- name: "Gear Ratio & Mechanical Drive Calculator" description: "Use when calculating gear ratios, converting RPM between shafts, computing torque output, analyzing drivetrain configurations, or selecting motors for mechanical systems." version: "2.0.0" author: "BytesAgain" homepage: https://bytesagain.com source: https://github.com/bytesagain/ai-skills tags: ["gear", "mechanical", "engineering", "torque", "drivetrain", "motor", "calculator"] --- # Gear Ratio & Mechanical Drive Calculator Calculate gear ratios, convert RPM, compute torque, analyze multi-stage drivetrains, and get motor selection guidance for mechanical systems. ## Commands ### ratio Calculate gear ratio from tooth counts or diameters. ```bash bash scripts/script.sh ratio 20 60 ``` ### speed Convert RPM through a gear ratio. ```bash bash scripts/script.sh speed 1800 3.5 ``` ### torque Compute output torque given input torque and gear ratio. ```bash bash scripts/script.sh torque 10 3.5 0.95 ``` ### drivetrain Analyze a multi-stage gear train. ```bash bash scripts/script.sh drivetrain "20:60,15:45,18:72" ``` ### motor-select Motor selection helper based on load requirements. ```bash bash scripts/script.sh motor-select 50 300 ``` ### help Show all commands. ```bash bash scripts/script.sh help ``` ## Output - Gear ratios with speed/torque multipliers - Multi-stage drivetrain analysis - Motor specification recommendations ## Feedback https://bytesagain.com/feedback/ Powered by BytesAgain | bytesagain.com FILE:scripts/script.sh #!/usr/bin/env bash # gear — Gear Ratio & Mechanical Drive Calculator # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="2.0.0" cmd_ratio() { local driving="-" local driven="-" if [ -z "$driving" ] || [ -z "$driven" ]; then cat <<'EOF' ═══════════════════════════════════════════════════ Gear Ratio Calculator ═══════════════════════════════════════════════════ Usage: bash scripts/script.sh ratio <driving_teeth> <driven_teeth> Arguments: driving_teeth Number of teeth on driving gear (pinion) driven_teeth Number of teeth on driven gear (wheel) Examples: bash scripts/script.sh ratio 20 60 → 1:3 (speed reduction) bash scripts/script.sh ratio 48 16 → 3:1 (speed increase) bash scripts/script.sh ratio 40 40 → 1:1 (direct drive) 【Gear Ratio Fundamentals】 Ratio = Driven Teeth / Driving Teeth Ratio > 1 → Speed reduction, torque multiplication Ratio < 1 → Speed increase, torque reduction Ratio = 1 → Direct drive 【Common Gear Types & Typical Ratios】 Spur Gear 1:1 to 1:6 per stage (parallel shafts) Helical Gear 1:1 to 1:10 per stage (quieter, parallel) Bevel Gear 1:1 to 1:5 (perpendicular shafts) Worm Gear 5:1 to 100:1 (right angle, self-lock) Planetary 3:1 to 10:1 per stage (compact, inline) Harmonic 30:1 to 320:1 (zero backlash) 📖 More skills: bytesagain.com EOF return 0 fi DRIVING="$driving" DRIVEN="$driven" python3 -u <<'PYEOF' import os driving = float(os.environ["DRIVING"]) driven = float(os.environ["DRIVEN"]) ratio = driven / driving inv_ratio = driving / driven speed_mult = 1 / ratio torque_mult = ratio print("═" * 50) print(" ⚙️ Gear Ratio Calculation") print("═" * 50) print(f""" Driving Gear (Pinion): {driving:.0f} teeth Driven Gear (Wheel): {driven:.0f} teeth Gear Ratio: 1:{ratio:.4f} ({driving:.0f}:{driven:.0f}) Inverse Ratio: {inv_ratio:.4f}:1 Speed Multiplier: ×{speed_mult:.4f} Torque Multiplier: ×{torque_mult:.4f} """) if ratio > 1: print(" Type: SPEED REDUCTION / TORQUE MULTIPLICATION") print(f" → Output shaft runs {ratio:.2f}× slower") print(f" → Output torque is {ratio:.2f}× higher (before losses)") elif ratio < 1: print(" Type: SPEED INCREASE / TORQUE REDUCTION") print(f" → Output shaft runs {1/ratio:.2f}× faster") print(f" → Output torque is {1/ratio:.2f}× lower") else: print(" Type: DIRECT DRIVE (1:1)") print(" → No speed or torque change") # Module/pitch guidance print(""" 【Minimum Teeth Recommendations (to avoid undercutting)】 Standard spur (20° pressure angle): min 17 teeth Helical gear: min 14 teeth With profile shift: can go as low as 12 【Efficiency Estimates】 Spur/Helical pair: 97-99% per stage Bevel pair: 95-98% per stage Worm gear: 40-90% (depends on lead angle) Planetary stage: 96-98% per stage """) print("📖 More skills: bytesagain.com") PYEOF } cmd_speed() { local input_rpm="-" local ratio="-" if [ -z "$input_rpm" ] || [ -z "$ratio" ]; then cat <<'EOF' ═══════════════════════════════════════════════════ RPM / Speed Conversion ═══════════════════════════════════════════════════ Usage: bash scripts/script.sh speed <input_rpm> <gear_ratio> Arguments: input_rpm Input shaft speed in RPM gear_ratio Gear ratio (driven/driving) Examples: bash scripts/script.sh speed 1800 3.5 → 514.3 RPM output bash scripts/script.sh speed 3600 0.5 → 7200 RPM output bash scripts/script.sh speed 1450 7.2 → 201.4 RPM output 【Speed Formulas】 Output RPM = Input RPM / Gear Ratio Output Angular Velocity (rad/s) = Output RPM × 2π / 60 Output Linear Velocity = ω × r (at gear pitch radius) 【Common Motor Speeds (at 60 Hz)】 2-pole: 3600 RPM (synchronous), ~3450 RPM (induction) 4-pole: 1800 RPM (synchronous), ~1750 RPM (induction) 6-pole: 1200 RPM (synchronous), ~1150 RPM (induction) 8-pole: 900 RPM (synchronous), ~875 RPM (induction) 📖 More skills: bytesagain.com EOF return 0 fi RPM="$input_rpm" RATIO="$ratio" python3 -u <<'PYEOF' import os, math rpm_in = float(os.environ["RPM"]) ratio = float(os.environ["RATIO"]) rpm_out = rpm_in / ratio omega_in = rpm_in * 2 * math.pi / 60 omega_out = rpm_out * 2 * math.pi / 60 print("═" * 50) print(" 🔄 Speed Conversion Through Gear Ratio") print("═" * 50) print(f""" Input Speed: {rpm_in:.1f} RPM ({omega_in:.2f} rad/s) Gear Ratio: 1:{ratio:.4f} Output Speed: {rpm_out:.1f} RPM ({omega_out:.2f} rad/s) Speed Change: {abs(1 - 1/ratio)*100:.1f}% {'reduction' if ratio > 1 else 'increase'} """) # Surface speed table for common gear sizes print("【Surface Speed at Output (Pitch Diameter)】") print(f" {'Diameter':>10} {'Surface Speed':>14} {'ft/min':>10}") print(f" {'─'*10} {'─'*14} {'─'*10}") for d_mm in [50, 100, 150, 200, 300]: v_ms = omega_out * (d_mm / 1000) / 2 v_ftmin = v_ms * 196.85 print(f" {d_mm:>7} mm {v_ms:>11.2f} m/s {v_ftmin:>7.0f}") print(f""" 【Speed Limits by Gear Type】 Spur gear: < 20 m/s pitch line velocity Helical gear: < 40 m/s pitch line velocity Bevel gear: < 20 m/s pitch line velocity Worm gear: < 30 m/s sliding velocity """) print("📖 More skills: bytesagain.com") PYEOF } cmd_torque() { local input_torque="-" local ratio="-" local efficiency="-0.97" if [ -z "$input_torque" ] || [ -z "$ratio" ]; then cat <<'EOF' ═══════════════════════════════════════════════════ Torque Calculator ═══════════════════════════════════════════════════ Usage: bash scripts/script.sh torque <input_Nm> <gear_ratio> [efficiency] Arguments: input_Nm Input torque in Newton-meters gear_ratio Gear ratio (driven/driving teeth) efficiency Mesh efficiency 0-1 (default: 0.97) Examples: bash scripts/script.sh torque 10 3.5 → 33.95 Nm bash scripts/script.sh torque 10 3.5 0.95 → 33.25 Nm bash scripts/script.sh torque 50 7.2 0.92 → 331.2 Nm 【Torque Formulas】 T_out = T_in × Ratio × Efficiency Power = Torque × Angular Velocity = T × (2π × RPM / 60) P (watts) = T (Nm) × ω (rad/s) P (HP) = T (lb·ft) × RPM / 5252 【Unit Conversions】 1 Nm = 0.7376 lb·ft 1 Nm = 8.851 lb·in 1 kgf·cm = 0.0981 Nm 1 oz·in = 0.00706 Nm 📖 More skills: bytesagain.com EOF return 0 fi T_IN="$input_torque" RATIO="$ratio" EFF="$efficiency" python3 -u <<'PYEOF' import os t_in = float(os.environ["T_IN"]) ratio = float(os.environ["RATIO"]) eff = float(os.environ["EFF"]) t_out = t_in * ratio * eff t_out_ideal = t_in * ratio t_loss = t_out_ideal - t_out print("═" * 50) print(" 🔧 Torque Calculation") print("═" * 50) print(f""" Input Torque: {t_in:.2f} Nm ({t_in * 0.7376:.2f} lb·ft) Gear Ratio: 1:{ratio:.4f} Mesh Efficiency: {eff*100:.1f}% Output Torque: {t_out:.2f} Nm ({t_out * 0.7376:.2f} lb·ft) Ideal (no loss): {t_out_ideal:.2f} Nm Friction Loss: {t_loss:.2f} Nm ({(1-eff)*100:.1f}%) """) # Power equivalence at various RPMs print("【Power at Various Input Speeds】") print(f" {'Input RPM':>10} {'Power (W)':>10} {'Power (HP)':>10} {'Out Torque':>11}") print(f" {'─'*10} {'─'*10} {'─'*10} {'─'*11}") import math for rpm in [500, 1000, 1450, 1800, 3600]: omega = 2 * math.pi * rpm / 60 power_w = t_in * omega power_hp = power_w / 745.7 print(f" {rpm:>10} {power_w:>8.1f} W {power_hp:>7.3f} HP {t_out:>8.2f} Nm") print(f""" 【Torque Design Factors】 Service Factor (typical): Uniform load: 1.00 Moderate shock: 1.25 – 1.50 Heavy shock: 1.75 – 2.00 Design Torque = Output Torque × Service Factor For {t_out:.1f} Nm with moderate shock: {t_out * 1.25:.1f} – {t_out * 1.50:.1f} Nm """) print("📖 More skills: bytesagain.com") PYEOF } cmd_drivetrain() { local stages="-" if [ -z "$stages" ]; then cat <<'EOF' ═══════════════════════════════════════════════════ Multi-Stage Drivetrain Analyzer ═══════════════════════════════════════════════════ Usage: bash scripts/script.sh drivetrain "<stage1>,<stage2>,..." Each stage: driving_teeth:driven_teeth Separate stages with commas. Examples: bash scripts/script.sh drivetrain "20:60,15:45,18:72" bash scripts/script.sh drivetrain "12:48,16:64" bash scripts/script.sh drivetrain "24:72" 【Multi-Stage Gear Train Rules】 Total Ratio = Stage1 × Stage2 × Stage3 × ... Total Efficiency = η₁ × η₂ × η₃ × ... Each intermediate shaft is both output and input 【Why Multiple Stages?】 • Single spur gear pair: practical limit ~1:6 • Two stages: up to 1:36 • Three stages: up to 1:216 • Planetary gearbox: compact multi-stage in one unit • More stages = more losses, more cost, more size 📖 More skills: bytesagain.com EOF return 0 fi STAGES="$stages" python3 -u <<'PYEOF' import os stages_str = os.environ["STAGES"] pairs = stages_str.split(",") print("═" * 50) print(" 🔗 Multi-Stage Drivetrain Analysis") print("═" * 50) print() total_ratio = 1.0 total_eff = 1.0 stage_eff = 0.97 # assumed per spur/helical stage for i, pair in enumerate(pairs, 1): parts = pair.strip().split(":") driving = float(parts[0]) driven = float(parts[1]) ratio = driven / driving total_ratio *= ratio total_eff *= stage_eff print(f" Stage {i}: {driving:.0f}T → {driven:.0f}T") print(f" Ratio: 1:{ratio:.3f} | Speed: ÷{ratio:.2f} | Torque: ×{ratio:.2f}") print() print(" " + "─" * 46) print(f""" Total Gear Ratio: 1:{total_ratio:.3f} Overall Efficiency: {total_eff*100:.1f}% (at {stage_eff*100:.0f}%/stage) Number of Stages: {len(pairs)} If Input = 1800 RPM, 10 Nm: Output Speed: {1800/total_ratio:.1f} RPM Output Torque: {10 * total_ratio * total_eff:.1f} Nm Power: {10 * 1800 * 2 * 3.14159 / 60:.0f} W (constant minus losses) """) print("📖 More skills: bytesagain.com") PYEOF } cmd_motor_select() { local torque_nm="-" local rpm="-" if [ -z "$torque_nm" ] || [ -z "$rpm" ]; then cat <<'EOF' ═══════════════════════════════════════════════════ Motor Selection Helper ═══════════════════════════════════════════════════ Usage: bash scripts/script.sh motor-select <required_torque_Nm> <required_rpm> Arguments: required_torque_Nm Load torque requirement in Nm required_rpm Required output speed in RPM Examples: bash scripts/script.sh motor-select 50 300 bash scripts/script.sh motor-select 5 1500 bash scripts/script.sh motor-select 200 60 【Motor Types Overview】 AC Induction — Robust, cheap, 50/60 Hz, needs VFD for speed control Brushless DC — Efficient, precise speed, good for servo applications Stepper — Precise positioning, no feedback needed, limited speed Servo (AC/DC) — High performance, closed-loop, expensive Universal — AC/DC capable, high speed, short life (power tools) 📖 More skills: bytesagain.com EOF return 0 fi TORQUE="$torque_nm" RPM="$rpm" python3 -u <<'PYEOF' import os, math torque = float(os.environ["TORQUE"]) rpm = float(os.environ["RPM"]) omega = 2 * math.pi * rpm / 60 power_w = torque * omega power_kw = power_w / 1000 power_hp = power_w / 745.7 print("═" * 50) print(" 🏭 Motor Selection Guide") print("═" * 50) print(f""" Required Torque: {torque:.1f} Nm Required Speed: {rpm:.0f} RPM Required Power: {power_w:.0f} W ({power_kw:.2f} kW / {power_hp:.2f} HP) """) # Add safety margin design_power = power_kw * 1.25 print(f" Design Power (×1.25 SF): {design_power:.2f} kW / {design_power/0.7457:.2f} HP") print() # Motor + gearbox combinations print("【Recommended Motor + Gearbox Combinations】") print() motor_speeds = [ ("4-pole AC Induction (1750 RPM)", 1750, 0.88), ("2-pole AC Induction (3500 RPM)", 3500, 0.90), ("BLDC Motor (3000 RPM)", 3000, 0.92), ("Servo Motor (2000 RPM)", 2000, 0.95), ] for name, motor_rpm, motor_eff in motor_speeds: gear_ratio = motor_rpm / rpm if gear_ratio < 1: continue motor_torque = torque / gear_ratio / 0.97 # gear eff motor_power = motor_torque * (2 * math.pi * motor_rpm / 60) print(f" {name}") print(f" Gear ratio needed: 1:{gear_ratio:.2f}") print(f" Motor torque: {motor_torque:.2f} Nm") print(f" Motor power: {motor_power:.0f} W ({motor_power/745.7:.2f} HP)") print(f" Motor efficiency: ~{motor_eff*100:.0f}%") print() print("""【Motor Frame Size Guide (IEC)】 Power Range Frame Size ──────────────────────────── 0.12 – 0.37 kW 56 – 71 0.37 – 1.1 kW 71 – 90 1.1 – 4.0 kW 90 – 112 4.0 – 11 kW 132 – 160 11 – 30 kW 160 – 200 30 – 75 kW 225 – 280 """) print("📖 More skills: bytesagain.com") PYEOF } cmd_help() { cat <<EOF Gear vVERSION — Gear Ratio & Mechanical Drive Calculator Commands: ratio <driving> <driven> Calculate gear ratio from tooth counts speed <rpm> <ratio> Convert RPM through a gear ratio torque <Nm> <ratio> [eff] Compute output torque (default eff: 0.97) drivetrain "<stages>" Analyze multi-stage gear train motor-select <Nm> <rpm> Motor selection helper help Show this help version Show version Usage: bash scripts/script.sh ratio 20 60 bash scripts/script.sh speed 1800 3.5 bash scripts/script.sh torque 10 3.5 0.95 bash scripts/script.sh drivetrain "20:60,15:45" bash scripts/script.sh motor-select 50 300 Related skills: clawhub install cam clawhub install bearing Browse all: bytesagain.com Powered by BytesAgain | bytesagain.com EOF } case "-help" in ratio) shift; cmd_ratio "$@" ;; speed) shift; cmd_speed "$@" ;; torque) shift; cmd_torque "$@" ;; drivetrain) shift; cmd_drivetrain "$@" ;; motor-select) shift; cmd_motor_select "$@" ;; version) echo "gear vVERSION" ;; help|*) cmd_help ;; esac
servo
--- name: "servo" version: "2.0.0" description: "servo" author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [servo, reference] category: "devtools" --- # Servo servo. No API keys or credentials required — outputs reference documentation only. ## Commands | Command | Description | |---------|-------------| | `intro` | intro reference | | `quickstart` | quickstart reference | | `patterns` | patterns reference | | `debugging` | debugging reference | | `performance` | performance reference | | `security` | security reference | | `migration` | migration reference | | `cheatsheet` | cheatsheet reference | ## Output Format All commands output plain-text reference documentation via heredoc. No external API calls, no credentials needed, no network access. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # servo — Servo reference tool. Use when working with servo in devtools contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="2.0.0" show_help() { cat << 'HELPEOF' servo v$VERSION — Servo Reference Tool Usage: servo <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' # Servo — Overview ## What is Servo? Servo (servo) is a specialized tool/concept in the devtools domain. It provides essential capabilities for professionals working with servo. ## Key Concepts - Core servo principles and fundamentals - How servo fits into the broader devtools ecosystem - Essential terminology every practitioner should know ## Why Servo Matters Understanding servo is critical for: - Improving efficiency in devtools workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic servo concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Servo — Quick Start Guide ## Prerequisites - Basic understanding of devtools concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the servo 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' # Servo — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for servo 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' # Servo — 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' # Servo — 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' # Servo — 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' # Servo — 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' # Servo — 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 "servo v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: servo help"; exit 1 ;; esac
Distributed control system manager
--- name: "dcs" version: "1.0.0" description: "Distributed control system manager" author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [dcs, industrial, cli, tool] category: "industrial" --- # dcs Distributed control system manager ## 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 | Required | Description | |----------|----------|-------------| | `DCS_DIR` | No | Data directory (default: ~/.dcs/) | ## Data Storage All data stored in `~/.dcs/` using JSONL format (one JSON object per line). ## Output Structured output to stdout. Exit code 0 on success, 1 on error. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # dcs -- Distributed control system manager # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="1.0.0" DATA_DIR="-$HOME/.dcs" _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 dcs v$VERSION -- Distributed control system manager Usage: dcs <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 "=== dcs 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: dcs 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 "=== Dcs 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: dcs 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: dcs 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="dcs-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 "=== Dcs 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 "dcs v$VERSION -- Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: dcs help"; exit 1 ;; esac
flip reference tool
--- name: "flip" version: "2.0.0" description: "flip reference tool" author: "BytesAgain" homepage: "https://bytesagain.com" source: "https://github.com/bytesagain/ai-skills" tags: [flip, reference] category: "devtools" --- # Flip flip reference tool. No API keys or credentials required — outputs reference documentation only. ## Commands | Command | Description | |---------|-------------| | `intro` | intro reference | | `quickstart` | quickstart reference | | `patterns` | patterns reference | | `debugging` | debugging reference | | `performance` | performance reference | | `security` | security reference | | `migration` | migration reference | | `cheatsheet` | cheatsheet reference | ## Output Format All commands output plain-text reference documentation via heredoc. No external API calls, no credentials needed, no network access. --- *Powered by BytesAgain | bytesagain.com | [email protected]* FILE:scripts/script.sh #!/usr/bin/env bash # flip — Flip reference tool. Use when working with flip in devtools contexts. # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail VERSION="2.0.0" show_help() { cat << 'HELPEOF' flip v$VERSION — Flip Reference Tool Usage: flip <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' # Flip — Overview ## What is Flip? Flip (flip) is a specialized tool/concept in the devtools domain. It provides essential capabilities for professionals working with flip. ## Key Concepts - Core flip principles and fundamentals - How flip fits into the broader devtools ecosystem - Essential terminology every practitioner should know ## Why Flip Matters Understanding flip is critical for: - Improving efficiency in devtools workflows - Reducing errors and downtime - Meeting industry standards and compliance requirements - Enabling better decision-making with accurate data ## Getting Started 1. Understand the basic flip concepts 2. Learn the standard tools and interfaces 3. Practice with common scenarios 4. Review safety and compliance requirements EOF } cmd_quickstart() { cat << 'EOF' # Flip — Quick Start Guide ## Prerequisites - Basic understanding of devtools concepts - Required tools and access credentials - System meeting minimum requirements ## Installation 1. Download or clone the flip 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' # Flip — Common Patterns & Best Practices ## Design Patterns 1. **Standard Pattern**: The most common approach for flip 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' # Flip — 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' # Flip — 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' # Flip — 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' # Flip — 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' # Flip — 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 "flip v$VERSION — Powered by BytesAgain" ;; *) echo "Unknown: $CMD"; echo "Run: flip help"; exit 1 ;; esac
Serve spec-driven dev tools via MCP for AI-assisted workflows. Use when adding tasks, planning iterations, tracking completion, reviewing quality.
--- name: Spec Workflow Mcp description: "Serve spec-driven dev tools via MCP for AI-assisted workflows. Use when adding tasks, planning iterations, tracking completion, reviewing quality." version: "1.0.0" license: GPL-3.0 runtime: python3 --- # Spec Workflow MCP Spec Workflow MCP v2.0.0 — a productivity toolkit for spec-driven development workflows served via the Model Context Protocol (MCP). Manage tasks, plan sprints, track progress, review deliverables, set reminders, prioritize work, and run weekly reviews — all from the command line with timestamped log entries. ## Commands The script (`scripts/script.sh`) exposes the following commands via a `case` dispatcher: | Command | Description | |---------|-------------| | `add <input>` | Add a new spec/task entry. Without args, shows the 20 most recent add entries. | | `plan <input>` | Record a planning entry (sprint planning, iteration goals). Without args, lists recent plans. | | `track <input>` | Track progress on a task or deliverable. Without args, lists recent tracking entries. | | `review <input>` | Record a review note (code review, spec review). Without args, lists recent reviews. | | `streak <input>` | Log a streak entry (daily consistency tracking). Without args, lists recent streaks. | | `remind <input>` | Set a reminder or log a reminder note. Without args, lists recent reminders. | | `prioritize <input>` | Record a prioritization decision. Without args, lists recent prioritizations. | | `archive <input>` | Archive a completed item. Without args, lists recent archive entries. | | `tag <input>` | Tag or categorize an entry. Without args, lists recent tags. | | `timeline <input>` | Record a timeline/milestone entry. Without args, lists recent timeline entries. | | `report <input>` | Generate or log a report entry. Without args, lists recent reports. | | `weekly-review <input>` | Record a weekly review summary. Without args, lists recent weekly reviews. | | `stats` | Show summary statistics across all log files (entry counts per type, total, disk usage). | | `export <fmt>` | Export all data in `json`, `csv`, or `txt` format to `$DATA_DIR/export.<fmt>`. | | `search <term>` | Search all log files for a term (case-insensitive grep). | | `recent` | Show the 20 most recent lines from `history.log`. | | `status` | Health check — shows version, data directory, total entries, disk usage, last activity. | | `help` | Display the full help/usage message. | | `version` | Print `spec-workflow-mcp v2.0.0`. | ## How Each Entry Command Works 1. If called **without arguments**, it tails the last 20 lines of `<command>.log`. 2. If called **with arguments**, it: - Timestamps the input (`YYYY-MM-DD HH:MM|<input>`) - Appends it to `$DATA_DIR/<command>.log` - Prints confirmation with the current total count - Logs the action to `history.log` ## Data Storage All data is stored as plain-text log files under: ``` ~/.local/share/spec-workflow-mcp/ ├── add.log ├── plan.log ├── track.log ├── review.log ├── streak.log ├── remind.log ├── prioritize.log ├── archive.log ├── tag.log ├── timeline.log ├── report.log ├── weekly-review.log └── history.log # unified activity log ``` Each log line uses pipe-delimited format: `YYYY-MM-DD HH:MM|<value>` The `history.log` uses: `MM-DD HH:MM <command>: <value>` ## Requirements - **Bash** 4.0+ (uses `local` variables, `set -euo pipefail`) - **coreutils**: `date`, `wc`, `du`, `tail`, `cat`, `basename`, `grep`, `sed` - No external dependencies, API keys, or network access required - Works on Linux and macOS ## When to Use 1. **Sprint planning** — use `plan` to record iteration goals, then `track` to log progress against them throughout the sprint 2. **Task management** — use `add` to capture new specs or tasks, `prioritize` to rank them, and `archive` when complete 3. **Daily standups** — use `streak` to maintain consistency tracking and `recent` to review what happened yesterday 4. **Code/spec reviews** — use `review` to log review notes and decisions for future reference 5. **Weekly retrospectives** — use `weekly-review` to capture weekly summaries, then `export` to generate reports for stakeholders ## Examples ### Add a task and plan a sprint ```bash # Add a new spec bash scripts/script.sh add "API rate limiting — sliding window implementation" # Plan the sprint bash scripts/script.sh plan "Sprint 8: rate limiter, caching layer, monitoring" ``` ### Track progress and review ```bash # Track completion bash scripts/script.sh track "rate limiter: Redis backend done, unit tests passing" # Log a review bash scripts/script.sh review "rate limiter PR #87: approved, added integration tests" ``` ### Set reminders and manage priorities ```bash # Set a reminder bash scripts/script.sh remind "demo prep for Friday stakeholder meeting" # Prioritize bash scripts/script.sh prioritize "P1: cache invalidation edge case in multi-region" ``` ### Weekly review and export ```bash # Record weekly summary bash scripts/script.sh weekly-review "shipped rate limiter, started caching layer, blocked on Redis cluster config" # Export all data as CSV bash scripts/script.sh export csv ``` ### Search and view timeline ```bash # Find all entries mentioning "cache" bash scripts/script.sh search "cache" # Log a milestone bash scripts/script.sh timeline "v2.1 release candidate tagged" # View overall statistics bash scripts/script.sh stats ``` ## Configuration Set the `DATA_DIR` variable (or modify it in the script) to change the storage directory. Default: `~/.local/share/spec-workflow-mcp/` ## Output All commands print to stdout. Redirect to a file as needed: ```bash bash scripts/script.sh weekly-review > retro-notes.txt ``` --- Powered by BytesAgain | bytesagain.com | [email protected] FILE:scripts/script.sh #!/usr/bin/env bash # Spec Workflow Mcp — productivity tool # Powered by BytesAgain | bytesagain.com | [email protected] set -euo pipefail DATA_DIR="HOME/.local/share/spec-workflow-mcp" mkdir -p "$DATA_DIR" _log() { echo "$(date '+%m-%d %H:%M') $1: $2" >> "$DATA_DIR/history.log"; } _version() { echo "spec-workflow-mcp v2.0.0"; } _help() { echo "Spec Workflow Mcp v2.0.0 — productivity toolkit" echo "" echo "Usage: spec-workflow-mcp <command> [args]" echo "" echo "Commands:" echo " add Add" echo " plan Plan" echo " track Track" echo " review Review" echo " streak Streak" echo " remind Remind" echo " prioritize Prioritize" echo " archive Archive" echo " tag Tag" echo " timeline Timeline" echo " report Report" echo " weekly-review Weekly Review" echo " stats Summary statistics" echo " export <fmt> Export (json|csv|txt)" echo " search <term> Search entries" echo " recent Recent activity" echo " status Health check" echo " help Show this help" echo " version Show version" echo "" echo "Data: $DATA_DIR" } _stats() { echo "=== Spec Workflow Mcp Stats ===" local total=0 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) local c=$(wc -l < "$f") total=$((total + c)) echo " $name: $c entries" done echo " ---" echo " Total: $total entries" echo " Data size: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" } _export() { local fmt="-json" local out="$DATA_DIR/export.$fmt" case "$fmt" in json) echo "[" > "$out" local first=1 for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do [ $first -eq 1 ] && first=0 || echo "," >> "$out" printf ' {"type":"%s","time":"%s","value":"%s"}' "$name" "$ts" "$val" >> "$out" done < "$f" done echo "\n]" >> "$out" ;; csv) echo "type,time,value" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local name=$(basename "$f" .log) while IFS='|' read -r ts val; do echo "$name,$ts,$val" >> "$out"; done < "$f" done ;; txt) echo "=== Spec Workflow Mcp Export ===" > "$out" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue echo "--- $(basename "$f" .log) ---" >> "$out" cat "$f" >> "$out" done ;; *) echo "Formats: json, csv, txt"; return 1 ;; esac echo "Exported to $out ($(wc -c < "$out") bytes)" } _status() { echo "=== Spec Workflow Mcp Status ===" echo " Version: v2.0.0" echo " Data dir: $DATA_DIR" echo " Entries: $(cat "$DATA_DIR"/*.log 2>/dev/null | wc -l) total" echo " Disk: $(du -sh "$DATA_DIR" 2>/dev/null | cut -f1)" echo " Last: $(tail -1 "$DATA_DIR/history.log" 2>/dev/null || echo never)" echo " Status: OK" } _search() { local term="?Usage: spec-workflow-mcp search <term>" echo "Searching for: $term" for f in "$DATA_DIR"/*.log; do [ -f "$f" ] || continue local m=$(grep -i "$term" "$f" 2>/dev/null || true) if [ -n "$m" ]; then echo " --- $(basename "$f" .log) ---" echo "$m" | sed 's/^/ /' fi done } _recent() { echo "=== Recent Activity ===" tail -20 "$DATA_DIR/history.log" 2>/dev/null | sed 's/^/ /' || echo " No activity yet." } case "-help" in add) shift if [ $# -eq 0 ]; then echo "Recent add entries:" tail -20 "$DATA_DIR/add.log" 2>/dev/null || echo " No entries yet. Use: spec-workflow-mcp add <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/add.log" local total=$(wc -l < "$DATA_DIR/add.log") echo " [Spec Workflow Mcp] add: $input" echo " Saved. Total add entries: $total" _log "add" "$input" fi ;; plan) shift if [ $# -eq 0 ]; then echo "Recent plan entries:" tail -20 "$DATA_DIR/plan.log" 2>/dev/null || echo " No entries yet. Use: spec-workflow-mcp plan <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/plan.log" local total=$(wc -l < "$DATA_DIR/plan.log") echo " [Spec Workflow Mcp] plan: $input" echo " Saved. Total plan entries: $total" _log "plan" "$input" fi ;; track) shift if [ $# -eq 0 ]; then echo "Recent track entries:" tail -20 "$DATA_DIR/track.log" 2>/dev/null || echo " No entries yet. Use: spec-workflow-mcp track <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/track.log" local total=$(wc -l < "$DATA_DIR/track.log") echo " [Spec Workflow Mcp] track: $input" echo " Saved. Total track entries: $total" _log "track" "$input" fi ;; review) shift if [ $# -eq 0 ]; then echo "Recent review entries:" tail -20 "$DATA_DIR/review.log" 2>/dev/null || echo " No entries yet. Use: spec-workflow-mcp review <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/review.log" local total=$(wc -l < "$DATA_DIR/review.log") echo " [Spec Workflow Mcp] review: $input" echo " Saved. Total review entries: $total" _log "review" "$input" fi ;; streak) shift if [ $# -eq 0 ]; then echo "Recent streak entries:" tail -20 "$DATA_DIR/streak.log" 2>/dev/null || echo " No entries yet. Use: spec-workflow-mcp streak <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/streak.log" local total=$(wc -l < "$DATA_DIR/streak.log") echo " [Spec Workflow Mcp] streak: $input" echo " Saved. Total streak entries: $total" _log "streak" "$input" fi ;; remind) shift if [ $# -eq 0 ]; then echo "Recent remind entries:" tail -20 "$DATA_DIR/remind.log" 2>/dev/null || echo " No entries yet. Use: spec-workflow-mcp remind <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/remind.log" local total=$(wc -l < "$DATA_DIR/remind.log") echo " [Spec Workflow Mcp] remind: $input" echo " Saved. Total remind entries: $total" _log "remind" "$input" fi ;; prioritize) shift if [ $# -eq 0 ]; then echo "Recent prioritize entries:" tail -20 "$DATA_DIR/prioritize.log" 2>/dev/null || echo " No entries yet. Use: spec-workflow-mcp prioritize <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/prioritize.log" local total=$(wc -l < "$DATA_DIR/prioritize.log") echo " [Spec Workflow Mcp] prioritize: $input" echo " Saved. Total prioritize entries: $total" _log "prioritize" "$input" fi ;; archive) shift if [ $# -eq 0 ]; then echo "Recent archive entries:" tail -20 "$DATA_DIR/archive.log" 2>/dev/null || echo " No entries yet. Use: spec-workflow-mcp archive <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/archive.log" local total=$(wc -l < "$DATA_DIR/archive.log") echo " [Spec Workflow Mcp] archive: $input" echo " Saved. Total archive entries: $total" _log "archive" "$input" fi ;; tag) shift if [ $# -eq 0 ]; then echo "Recent tag entries:" tail -20 "$DATA_DIR/tag.log" 2>/dev/null || echo " No entries yet. Use: spec-workflow-mcp tag <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/tag.log" local total=$(wc -l < "$DATA_DIR/tag.log") echo " [Spec Workflow Mcp] tag: $input" echo " Saved. Total tag entries: $total" _log "tag" "$input" fi ;; timeline) shift if [ $# -eq 0 ]; then echo "Recent timeline entries:" tail -20 "$DATA_DIR/timeline.log" 2>/dev/null || echo " No entries yet. Use: spec-workflow-mcp timeline <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/timeline.log" local total=$(wc -l < "$DATA_DIR/timeline.log") echo " [Spec Workflow Mcp] timeline: $input" echo " Saved. Total timeline entries: $total" _log "timeline" "$input" fi ;; report) shift if [ $# -eq 0 ]; then echo "Recent report entries:" tail -20 "$DATA_DIR/report.log" 2>/dev/null || echo " No entries yet. Use: spec-workflow-mcp report <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/report.log" local total=$(wc -l < "$DATA_DIR/report.log") echo " [Spec Workflow Mcp] report: $input" echo " Saved. Total report entries: $total" _log "report" "$input" fi ;; weekly-review) shift if [ $# -eq 0 ]; then echo "Recent weekly-review entries:" tail -20 "$DATA_DIR/weekly-review.log" 2>/dev/null || echo " No entries yet. Use: spec-workflow-mcp weekly-review <input>" else local input="$*" local ts=$(date '+%Y-%m-%d %H:%M') echo "$ts|$input" >> "$DATA_DIR/weekly-review.log" local total=$(wc -l < "$DATA_DIR/weekly-review.log") echo " [Spec Workflow Mcp] weekly-review: $input" echo " Saved. Total weekly-review entries: $total" _log "weekly-review" "$input" fi ;; stats) _stats ;; export) shift; _export "$@" ;; search) shift; _search "$@" ;; recent) _recent ;; status) _status ;; help|--help|-h) _help ;; version|--version|-v) _version ;; *) echo "Unknown: $1 — run 'spec-workflow-mcp help'" exit 1 ;; esac