{
  "schemaVersion": "1.0",
  "item": {
    "slug": "email-formatter-skill",
    "name": "Cerbug45 Email Formatter",
    "source": "tencent",
    "type": "skill",
    "category": "开发工具",
    "sourceUrl": "https://clawhub.ai/cerbug45/email-formatter-skill",
    "canonicalUrl": "https://clawhub.ai/cerbug45/email-formatter-skill",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/email-formatter-skill",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=email-formatter-skill",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "README.md",
      "SKILL.md",
      "grammar_check.py",
      "install.sh",
      "readability.py",
      "security_scan.py"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-04-30T16:55:25.780Z",
      "expiresAt": "2026-05-07T16:55:25.780Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
        "contentDisposition": "attachment; filename=\"network-1.0.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null
      },
      "scope": "source",
      "summary": "Source download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this source.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/email-formatter-skill"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/email-formatter-skill",
    "agentPageUrl": "https://openagent3.xyz/skills/email-formatter-skill/agent",
    "manifestUrl": "https://openagent3.xyz/skills/email-formatter-skill/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/email-formatter-skill/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "Prerequisites Check",
        "body": "Before using this skill, verify the environment has required capabilities:\n\n# Check if bash is available\nwhich bash\n\n# Check Python version (3.8+ required)\npython3 --version\n\n# Check Node.js (optional, for advanced features)\nnode --version"
      },
      {
        "title": "Auto-Installation Script",
        "body": "For AI Agents: Run this installation check at first use\n\n#!/bin/bash\n# Email Formatter Skill - Auto Setup\n# This script installs required dependencies\n\necho \"🔧 Email Formatter Skill - Installation Starting...\"\n\n# Create skill workspace\nSKILL_DIR=\"$HOME/.email-formatter-skill\"\nmkdir -p \"$SKILL_DIR\"\ncd \"$SKILL_DIR\"\n\n# Install Python dependencies\necho \"📦 Installing Python packages...\"\npip3 install --break-system-packages --quiet \\\n    language-tool-python \\\n    textstat \\\n    spacy 2>/dev/null || pip3 install --user --quiet \\\n    language-tool-python \\\n    textstat \\\n    spacy\n\n# Download language model for grammar checking\necho \"📚 Downloading language model...\"\npython3 -m spacy download en_core_web_sm --quiet 2>/dev/null || true\n\n# Create helper scripts directory\nmkdir -p \"$SKILL_DIR/scripts\"\n\n# Test installation\nif python3 -c \"import language_tool_python; import textstat; import spacy\" 2>/dev/null; then\n    echo \"✅ Email Formatter Skill installed successfully!\"\n    echo \"📍 Installed at: $SKILL_DIR\"\n    exit 0\nelse\n    echo \"⚠️  Some dependencies failed. Skill will work with reduced features.\"\n    exit 0\nfi"
      },
      {
        "title": "Manual Installation (if auto-install fails)",
        "body": "# Minimal setup - no external dependencies\n# The skill will use built-in Python capabilities only\nmkdir -p ~/.email-formatter-skill/scripts\necho \"✅ Basic setup complete\""
      },
      {
        "title": "Verify Installation",
        "body": "# Quick verification\npython3 -c \"print('Email Formatter: Ready ✅')\""
      },
      {
        "title": "Required (Always Available)",
        "body": "Python 3.7+ (standard library only for minimal mode)\nBash shell"
      },
      {
        "title": "Optional (Enhanced Features)",
        "body": "language-tool-python: Advanced grammar checking\ntextstat: Readability analysis\nspacy: NLP for tone detection\n\nNote for AI Agents: The skill works in degraded mode without optional dependencies. Install them only if environment allows."
      },
      {
        "title": "Overview",
        "body": "This skill transforms rough email drafts into polished, professional communication by improving grammar, adjusting tone, enhancing clarity, and applying proper formatting. It handles everything from quick fixes to complete rewrites while preserving the sender's intent."
      },
      {
        "title": "⚠️ CRITICAL SECURITY & SAFETY REQUIREMENTS",
        "body": "This skill MUST enforce these non-negotiable safety rules at all times:"
      },
      {
        "title": "SECURITY LEVEL: MAXIMUM - Multi-Layer Validation Required",
        "body": "MANDATORY PRE-PROCESSING SECURITY CHECKS:\nEvery email MUST pass ALL security layers before any formatting occurs:\n\nLayer 1: Content Classification (BLOCK IMMEDIATELY)\n\n❌ Illegal Activities: Fraud, scams, phishing, money laundering, tax evasion, bribery\n❌ Violence & Threats: Physical threats, intimidation, stalking, doxxing, revenge threats\n❌ Impersonation: Government officials, company executives, IT/support staff, law enforcement\n❌ Financial Fraud: Wire transfers, cryptocurrency scams, investment fraud, Ponzi schemes\n❌ Identity Theft: SSN requests, password sharing, credential phishing, fake verification\n❌ Misinformation: Health fraud, election interference, conspiracy theories, fake news\n❌ Child Safety: ANY content involving minors in inappropriate context\n❌ Hate Speech: Racism, sexism, homophobia, religious hatred, ethnic slurs\n❌ Sexual Content: Harassment, explicit content, unwanted advances, grooming\n❌ Workplace Violations: Discrimination, harassment, retaliation, hostile environment\n❌ Academic Fraud: Plagiarism, cheating, fake credentials, assignment ghostwriting\n❌ Medical Fraud: Fake prescriptions, unlicensed advice, miracle cures, dangerous treatments\n❌ Legal Violations: Contract fraud, perjury, witness tampering, obstruction\n❌ Privacy Violations: Sharing private info without consent, surveillance, stalking\n❌ Malware/Hacking: Phishing links, malicious attachments, system exploits\n❌ Extortion: Blackmail, ransomware, threats for money, coercion\n\nLayer 2: Pattern Recognition (RED FLAGS)\n\nScan for suspicious patterns that indicate malicious intent:\n\nFinancial Red Flags:\n\nUrgent payment requests\nWire transfer instructions\nGift card purchases\nCryptocurrency transactions\n\"Keep this confidential\" + money\nBypassing normal approval process\nUnusual account changes\nTax refund scams\nInheritance scams\nLottery/prize scams\n\nAuthority Impersonation Red Flags:\n\n\"I'm from IT/HR/Legal/Management\"\n\"CEO needs you to...\"\n\"Urgent request from [authority]\"\n\"Don't tell anyone\"\nBypassing email/domain verification\nUnusual requests from superiors\nFake emergency scenarios\n\nCredential Harvesting Red Flags:\n\n\"Verify your password\"\n\"Confirm your account\"\n\"Click to prevent suspension\"\n\"Unusual login detected\"\nLinks to login pages\nFake security alerts\nAccount expiration warnings\n\nSocial Engineering Red Flags:\n\nArtificial urgency\nEmotional manipulation\nToo good to be true\nRequests for secrecy\nUnusual sender behavior\nPressure tactics\nFear-based messaging\n\nLayer 3: Sentiment & Tone Analysis (WARN OR BLOCK)\n\n⚠️ Aggressive/Hostile: Insulting, demeaning, threatening language\n⚠️ Manipulative: Guilt-tripping, gaslighting, emotional blackmail\n⚠️ Coercive: Power imbalance exploitation, quid pro quo\n⚠️ Deceptive: Half-truths, misleading statements, omissions\n⚠️ Discriminatory: Based on protected characteristics\n⚠️ Retaliatory: Punishment for protected actions\n\nLayer 4: Context Validation (VERIFY LEGITIMACY)\n\n✓ Sender-Recipient Relationship: Does this match their normal communication?\n✓ Request Reasonability: Is this a normal business request?\n✓ Communication Channel: Should this be email or in-person/phone?\n✓ Timing: Why is this urgent? Is urgency justified?\n✓ Information Sensitivity: Should this data be in email?\n✓ Authorization: Does sender have authority for this request?\n\nLayer 5: Privacy & Data Protection (GDPR/CCPA COMPLIANCE)\n\n🔒 PII Detection: Name, address, phone, email, SSN, DOB, photos\n🔒 Financial Data: Credit cards, bank accounts, tax IDs, salary info\n🔒 Health Data: Medical records, diagnoses, prescriptions, HIPAA data\n🔒 Credentials: Passwords, API keys, tokens, security questions\n🔒 Proprietary Data: Trade secrets, confidential business info, NDA material\n🔒 Children's Data: ANY data about individuals under 18\n\nACTION REQUIRED: If PII detected, warn user about:\n\nEmail is not encrypted by default\nData breach risks\nRegulatory compliance (GDPR, CCPA, HIPAA)\nSuggest secure alternatives (encrypted email, secure portal, in-person)"
      },
      {
        "title": "ZERO TOLERANCE BLOCKING - Immediate Rejection",
        "body": "If ANY of these detected, REFUSE IMMEDIATELY WITHOUT FORMATTING:\n\nZERO_TOLERANCE_PATTERNS = [\n    # Credential Requests\n    r'(send|give|provide).{0,20}(password|credential|login)',\n    r'verify.{0,20}(password|account|identity)',\n    \n    # Financial Fraud\n    r'wire transfer.{0,30}(urgent|immediately|today)',\n    r'gift card.{0,20}(purchase|buy|get)',\n    r'(bitcoin|crypto).{0,20}(send|transfer|wallet)',\n    \n    # Impersonation\n    r\"i'?m.{0,10}(from|with|calling from).{0,20}(IT|HR|legal|IRS|FBI)\",\n    r'(this is|i am).{0,20}(CEO|CFO|president|director)',\n    \n    # Threats\n    r'(or else|otherwise).{0,30}(fire|sue|report|punish)',\n    r'you (will|better).{0,20}(regret|pay|suffer)',\n    \n    # Illegal Activities\n    r'(launder|hide|conceal).{0,20}money',\n    r'(fake|forged|fraudulent).{0,20}(document|invoice|receipt)',\n    \n    # Child Safety\n    r'(minor|child|kid|underage).{0,50}(sexual|romantic|date|meet)',\n    \n    # Malware/Phishing\n    r'(click|download).{0,20}(attachment|link|file).{0,20}(urgent|immediately)',\n    r'account.{0,20}(suspend|lock|close|expire).{0,20}(unless|until)',\n    \n    # Harassment\n    r'(stupid|idiot|incompetent|worthless).{0,20}(you|employee|coworker)',\n    r\"i'?ll make sure you (never|don't|can't)\",\n]"
      },
      {
        "title": "Enhanced Security Response Protocol",
        "body": "When prohibited content detected:\n\n1. STOP - Do not process further\n2. LOG - Record violation type (no content)\n3. INFORM - Tell user specifically what rule was violated\n4. EDUCATE - Explain why it's harmful/illegal\n5. REDIRECT - Suggest legitimate alternatives\n6. REPORT - Flag for review if severe (threats, child safety, fraud)\n\nExample Response Template:\n\n🛑 SECURITY BLOCK: Email Formatting Refused\n\nREASON: [Specific violation - e.g., \"Credential request detected\"]\n\nWHY THIS IS BLOCKED:\n[Explanation - e.g., \"Legitimate organizations never ask for \npasswords via email. This matches phishing attack patterns.\"]\n\nWHAT YOU SHOULD DO:\n[Alternative - e.g., \"If you need to reset a password, use \nthe official password reset link on the company website.\"]\n\nTHIS SKILL CANNOT:\n- Help with fraudulent communications\n- Bypass security protocols\n- Facilitate illegal activities\n- Enable harassment or threats"
      },
      {
        "title": "Helper Scripts & Tools",
        "body": "The skill includes utility scripts for AI agents to use. Create these in ~/.email-formatter-skill/scripts/:"
      },
      {
        "title": "1. Grammar Checker (grammar_check.py)",
        "body": "#!/usr/bin/env python3\n\"\"\"\nBasic grammar and spell checker\nUsage: python3 grammar_check.py \"email text here\"\n\"\"\"\nimport sys\nimport re\n\ndef basic_grammar_check(text):\n    \"\"\"Basic grammar checks without external dependencies\"\"\"\n    issues = []\n    \n    # Common spelling errors\n    typos = {\n        'recieve': 'receive', 'occured': 'occurred', 'seperate': 'separate',\n        'definately': 'definitely', 'accomodate': 'accommodate',\n        'tommorow': 'tomorrow', 'untill': 'until', 'truely': 'truly'\n    }\n    \n    for wrong, right in typos.items():\n        if wrong in text.lower():\n            issues.append(f\"Spelling: '{wrong}' → '{right}'\")\n    \n    # Basic grammar patterns\n    if re.search(r'\\bi\\s', text):  # lowercase 'i'\n        issues.append(\"Grammar: 'i' should be capitalized to 'I'\")\n    \n    if re.search(r'\\s{2,}', text):\n        issues.append(\"Formatting: Multiple spaces detected\")\n    \n    if re.search(r'[.!?]\\s*[a-z]', text):\n        issues.append(\"Grammar: Sentence should start with capital letter\")\n    \n    # Double punctuation\n    if re.search(r'[.!?]{2,}', text):\n        issues.append(\"Punctuation: Multiple punctuation marks\")\n    \n    return issues\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Usage: python3 grammar_check.py 'text'\")\n        sys.exit(1)\n    \n    text = sys.argv[1]\n    issues = basic_grammar_check(text)\n    \n    if issues:\n        for issue in issues:\n            print(f\"⚠️  {issue}\")\n    else:\n        print(\"✅ No basic issues found\")"
      },
      {
        "title": "2. Tone Analyzer (tone_analyzer.py)",
        "body": "#!/usr/bin/env python3\n\"\"\"\nAnalyze email tone\nUsage: python3 tone_analyzer.py \"email text\"\n\"\"\"\nimport sys\nimport re\n\ndef analyze_tone(text):\n    \"\"\"Detect tone indicators in email text\"\"\"\n    \n    # Formal indicators\n    formal_words = ['pursuant', 'hereby', 'aforementioned', 'regarding', \n                   'sincerely', 'respectfully', 'cordially']\n    \n    # Casual indicators  \n    casual_words = ['hey', 'gonna', 'wanna', 'yeah', 'yep', 'nope',\n                   'btw', 'fyi', 'lol', 'omg', 'tbh']\n    \n    # Aggressive indicators\n    aggressive_words = ['immediately', 'must', 'unacceptable', 'ridiculous',\n                       'obviously', 'clearly', 'need to', 'have to']\n    \n    # Polite indicators\n    polite_words = ['please', 'kindly', 'would you', 'could you',\n                   'appreciate', 'thank', 'grateful']\n    \n    text_lower = text.lower()\n    \n    formal_count = sum(1 for w in formal_words if w in text_lower)\n    casual_count = sum(1 for w in casual_words if w in text_lower)\n    aggressive_count = sum(1 for w in aggressive_words if w in text_lower)\n    polite_count = sum(1 for w in polite_words if w in text_lower)\n    \n    # Exclamation marks\n    exclamations = len(re.findall(r'!', text))\n    \n    # ALL CAPS detection\n    caps_words = len(re.findall(r'\\b[A-Z]{2,}\\b', text))\n    \n    # Determine primary tone\n    tones = []\n    if formal_count >= 2:\n        tones.append(\"FORMAL\")\n    if casual_count >= 2:\n        tones.append(\"CASUAL\")\n    if aggressive_count >= 2 or caps_words >= 2:\n        tones.append(\"AGGRESSIVE\")\n    if polite_count >= 2:\n        tones.append(\"POLITE\")\n    if exclamations >= 3:\n        tones.append(\"ENTHUSIASTIC/URGENT\")\n    \n    if not tones:\n        tones.append(\"NEUTRAL\")\n    \n    return {\n        'primary_tone': tones[0],\n        'all_tones': tones,\n        'formal_score': formal_count,\n        'casual_score': casual_count,\n        'aggressive_score': aggressive_count,\n        'polite_score': polite_count,\n        'exclamations': exclamations,\n        'caps_words': caps_words\n    }\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Usage: python3 tone_analyzer.py 'text'\")\n        sys.exit(1)\n    \n    result = analyze_tone(sys.argv[1])\n    print(f\"📊 Primary Tone: {result['primary_tone']}\")\n    print(f\"🎯 All Tones: {', '.join(result['all_tones'])}\")\n    print(f\"📈 Scores - Formal:{result['formal_score']} Casual:{result['casual_score']} \"\n          f\"Aggressive:{result['aggressive_score']} Polite:{result['polite_score']}\")\n    \n    if result['aggressive_score'] >= 2:\n        print(\"⚠️  WARNING: Email may sound aggressive\")\n    if result['exclamations'] >= 3:\n        print(\"⚠️  WARNING: Too many exclamation marks\")\n    if result['caps_words'] >= 2:\n        print(\"⚠️  WARNING: Excessive capitalization detected\")"
      },
      {
        "title": "3. Readability Scorer (readability.py)",
        "body": "#!/usr/bin/env python3\n\"\"\"\nCalculate email readability\nUsage: python3 readability.py \"email text\"\n\"\"\"\nimport sys\nimport re\n\ndef count_syllables(word):\n    \"\"\"Simple syllable counter\"\"\"\n    word = word.lower()\n    vowels = 'aeiouy'\n    syllable_count = 0\n    previous_was_vowel = False\n    \n    for char in word:\n        is_vowel = char in vowels\n        if is_vowel and not previous_was_vowel:\n            syllable_count += 1\n        previous_was_vowel = is_vowel\n    \n    # Adjust for silent 'e'\n    if word.endswith('e'):\n        syllable_count -= 1\n    \n    # Every word has at least one syllable\n    if syllable_count == 0:\n        syllable_count = 1\n        \n    return syllable_count\n\ndef flesch_reading_ease(text):\n    \"\"\"Calculate Flesch Reading Ease score\"\"\"\n    sentences = len(re.findall(r'[.!?]+', text)) or 1\n    words = len(text.split())\n    syllables = sum(count_syllables(word) for word in text.split())\n    \n    if words == 0:\n        return 0\n    \n    score = 206.835 - 1.015 * (words / sentences) - 84.6 * (syllables / words)\n    return round(score, 1)\n\ndef analyze_readability(text):\n    \"\"\"Analyze email readability\"\"\"\n    words = text.split()\n    sentences = len(re.findall(r'[.!?]+', text)) or 1\n    \n    avg_word_length = sum(len(w) for w in words) / len(words) if words else 0\n    avg_sentence_length = len(words) / sentences\n    \n    flesch_score = flesch_reading_ease(text)\n    \n    # Interpret score\n    if flesch_score >= 90:\n        level = \"Very Easy (5th grade)\"\n    elif flesch_score >= 80:\n        level = \"Easy (6th grade)\"\n    elif flesch_score >= 70:\n        level = \"Fairly Easy (7th grade)\"\n    elif flesch_score >= 60:\n        level = \"Standard (8-9th grade)\"\n    elif flesch_score >= 50:\n        level = \"Fairly Difficult (10-12th grade)\"\n    elif flesch_score >= 30:\n        level = \"Difficult (College)\"\n    else:\n        level = \"Very Difficult (Graduate)\"\n    \n    return {\n        'flesch_score': flesch_score,\n        'level': level,\n        'avg_word_length': round(avg_word_length, 1),\n        'avg_sentence_length': round(avg_sentence_length, 1),\n        'total_words': len(words),\n        'total_sentences': sentences\n    }\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Usage: python3 readability.py 'text'\")\n        sys.exit(1)\n    \n    result = analyze_readability(sys.argv[1])\n    print(f\"📖 Flesch Reading Ease: {result['flesch_score']}\")\n    print(f\"📚 Reading Level: {result['level']}\")\n    print(f\"📊 Stats: {result['total_words']} words, {result['total_sentences']} sentences\")\n    print(f\"📏 Avg: {result['avg_word_length']} chars/word, {result['avg_sentence_length']} words/sentence\")\n    \n    # Recommendations\n    if result['flesch_score'] < 60:\n        print(\"💡 TIP: Simplify language for better clarity\")\n    if result['avg_sentence_length'] > 20:\n        print(\"💡 TIP: Break long sentences into shorter ones\")"
      },
      {
        "title": "4. Security Scanner (security_scan.py)",
        "body": "#!/usr/bin/env python3\n\"\"\"\nULTRA-SECURE Email Scanner - Multi-Layer Threat Detection\nUsage: python3 security_scan.py \"email text\"\nExit codes: 0=safe, 1=warning, 2=critical_block, 3=report_required\n\"\"\"\nimport sys\nimport re\nimport json\nfrom datetime import datetime\n\nclass SecurityScanner:\n    \"\"\"Military-grade email security scanner\"\"\"\n    \n    def __init__(self):\n        self.threat_level = 0  # 0=safe, 1=warning, 2=critical, 3=report\n        self.violations = []\n        self.warnings = []\n        \n    def scan(self, text):\n        \"\"\"Run all security checks\"\"\"\n        # Layer 1: Zero Tolerance Patterns\n        self.check_zero_tolerance(text)\n        \n        # Layer 2: Financial Fraud\n        self.check_financial_fraud(text)\n        \n        # Layer 3: Impersonation\n        self.check_impersonation(text)\n        \n        # Layer 4: Credential Harvesting\n        self.check_credential_harvesting(text)\n        \n        # Layer 5: Threats & Violence\n        self.check_threats(text)\n        \n        # Layer 6: Harassment & Discrimination\n        self.check_harassment(text)\n        \n        # Layer 7: Privacy & PII\n        self.check_privacy_violations(text)\n        \n        # Layer 8: Social Engineering\n        self.check_social_engineering(text)\n        \n        # Layer 9: Child Safety\n        self.check_child_safety(text)\n        \n        # Layer 10: Malicious Patterns\n        self.check_malicious_patterns(text)\n        \n        return self.generate_report()\n    \n    def check_zero_tolerance(self, text):\n        \"\"\"Critical patterns that immediately block\"\"\"\n        text_lower = text.lower()\n        \n        critical_patterns = [\n            # Credentials\n            (r'(send|give|provide|email).{0,30}(password|pwd|credential|login|passphrase)',\n             'CREDENTIAL_REQUEST', 3),\n            (r'verify.{0,20}(password|account|identity|credential)',\n             'FAKE_VERIFICATION', 3),\n            (r'(username|user id).{0,20}(and|&|\\\\+).{0,20}password',\n             'CREDENTIAL_PAIR_REQUEST', 3),\n            \n            # Financial\n            (r'wire transfer.{0,30}(urgent|immediate|asap|now|today)',\n             'URGENT_WIRE_TRANSFER', 3),\n            (r'(gift card|itunes|steam|amazon card).{0,30}(buy|purchase|get|send)',\n             'GIFT_CARD_SCAM', 3),\n            (r'(bitcoin|btc|crypto|ethereum|eth).{0,30}(wallet|address|send|transfer)',\n             'CRYPTO_SCAM', 3),\n            (r'(bank account|routing number|swift code).{0,30}(provide|send|give)',\n             'BANKING_INFO_REQUEST', 3),\n            \n            # Impersonation\n            (r\"i'?m.{0,10}(from|with|calling from).{0,30}(IT|support|tech|help desk)\",\n             'IT_IMPERSONATION', 3),\n            (r\"(this is|i am|i'm).{0,20}(CEO|CFO|president|director|executive)\",\n             'EXECUTIVE_IMPERSONATION', 3),\n            (r\"(IRS|FBI|police|government|immigration).{0,30}(contact|reach out|notice)\",\n             'AUTHORITY_IMPERSONATION', 3),\n            \n            # Threats\n            (r'(or else|otherwise).{0,30}(fire|terminate|sue|report|arrest)',\n             'THREAT_DETECTED', 3),\n            (r\"(you|i)'?(ll| will).{0,30}(regret|pay|suffer|sorry)\",\n             'THREAT_LANGUAGE', 3),\n            \n            # Child Safety\n            (r'(child|minor|kid|teen|underage).{0,50}(meet|date|relationship|romantic)',\n             'CHILD_SAFETY_VIOLATION', 3),\n            \n            # Malware\n            (r'(click|open|download).{0,20}(attachment|link|file).{0,20}(urgent|expire|suspend)',\n             'PHISHING_LINK', 3),\n        ]\n        \n        for pattern, violation_type, severity in critical_patterns:\n            if re.search(pattern, text_lower):\n                self.add_violation(violation_type, severity, pattern)\n    \n    def check_financial_fraud(self, text):\n        \"\"\"Detect financial scam patterns\"\"\"\n        text_lower = text.lower()\n        \n        fraud_indicators = [\n            (r'(won|winner|prize|lottery).{0,30}(\\$|dollar|money|claim)',\n             'LOTTERY_SCAM', 2),\n            (r'(inheritance|beneficiary|estate).{0,50}(million|claim|transfer)',\n             'INHERITANCE_SCAM', 2),\n            (r'(tax|irs).{0,30}(refund|owe|pay immediately)',\n             'TAX_SCAM', 2),\n            (r'(invoice|payment).{0,20}(overdue|urgent|immediate|final notice)',\n             'FAKE_INVOICE', 2),\n            (r'(suspended|frozen|locked).{0,30}account',\n             'ACCOUNT_SUSPENSION_SCAM', 2),\n            (r'(refund|reimbursement).{0,30}(click|verify|confirm)',\n             'REFUND_SCAM', 2),\n            (r'(investment|opportunity|profit).{0,50}(guaranteed|risk-free|double)',\n             'INVESTMENT_FRAUD', 2),\n        ]\n        \n        for pattern, violation_type, severity in fraud_indicators:\n            if re.search(pattern, text_lower):\n                self.add_violation(violation_type, severity, pattern)\n    \n    def check_impersonation(self, text):\n        \"\"\"Detect impersonation attempts\"\"\"\n        text_lower = text.lower()\n        \n        impersonation_patterns = [\n            (r'(on behalf of|representing).{0,30}(company|organization|government)',\n             'UNAUTHORIZED_REPRESENTATION', 2),\n            (r\"(i'?m|this is).{0,20}(calling|writing|reaching out).{0,20}(from|regarding)\",\n             'SUSPICIOUS_INTRODUCTION', 1),\n            (r'(verify|confirm).{0,20}(you are|your identity|who you are)',\n             'IDENTITY_VERIFICATION_REQUEST', 2),\n        ]\n        \n        for pattern, violation_type, severity in impersonation_patterns:\n            if re.search(pattern, text_lower):\n                self.add_violation(violation_type, severity, pattern)\n    \n    def check_credential_harvesting(self, text):\n        \"\"\"Detect credential theft attempts\"\"\"\n        text_lower = text.lower()\n        \n        patterns = [\n            (r'(account|access).{0,30}(expire|suspend|lock|disable)',\n             'FAKE_EXPIRATION', 2),\n            (r'(security|unusual|suspicious).{0,30}activity',\n             'FAKE_SECURITY_ALERT', 2),\n            (r'(update|verify|confirm).{0,30}(payment|billing) (method|information)',\n             'PAYMENT_INFO_PHISHING', 2),\n            (r'(reset|recover|change).{0,20}password.{0,20}(click|link|here)',\n             'PASSWORD_RESET_SCAM', 2),\n        ]\n        \n        for pattern, violation_type, severity in patterns:\n            if re.search(pattern, text_lower):\n                self.add_violation(violation_type, severity, pattern)\n    \n    def check_threats(self, text):\n        \"\"\"Detect threats and violent language\"\"\"\n        text_lower = text.lower()\n        \n        threat_words = [\n            'kill', 'hurt', 'harm', 'destroy', 'eliminate', 'punish',\n            'revenge', 'retaliate', 'get back at', 'make you pay'\n        ]\n        \n        for word in threat_words:\n            if word in text_lower:\n                self.add_violation('THREAT_LANGUAGE', 3, f\"Threat word: {word}\")\n        \n        # Physical threat patterns\n        if re.search(r'(come after|find you|know where you)', text_lower):\n            self.add_violation('PHYSICAL_THREAT', 3, 'Physical threat implied')\n    \n    def check_harassment(self, text):\n        \"\"\"Detect harassment and hostile language\"\"\"\n        text_lower = text.lower()\n        \n        hostile_words = [\n            'stupid', 'idiot', 'moron', 'incompetent', 'worthless',\n            'pathetic', 'useless', 'loser', 'failure', 'trash'\n        ]\n        \n        count = sum(1 for word in hostile_words if word in text_lower)\n        if count >= 2:\n            self.add_violation('HARASSMENT', 2, f'{count} hostile terms detected')\n        elif count == 1:\n            self.add_warning('POTENTIALLY_HOSTILE', 'Hostile language detected')\n        \n        # Discriminatory patterns\n        protected_characteristics = [\n            (r'(because|since).{0,20}(you\\'?re|you are).{0,20}(woman|female|girl)',\n             'GENDER_DISCRIMINATION'),\n            (r'(because|since).{0,20}(you\\'?re|you are).{0,20}(old|young|age)',\n             'AGE_DISCRIMINATION'),\n            (r'(people like you|your kind|you people)', 'DISCRIMINATORY_LANGUAGE'),\n        ]\n        \n        for pattern, violation_type in protected_characteristics:\n            if re.search(pattern, text_lower):\n                self.add_violation(violation_type, 3, pattern)\n    \n    def check_privacy_violations(self, text):\n        \"\"\"Detect PII and privacy issues\"\"\"\n        \n        # SSN pattern\n        if re.search(r'\\b\\d{3}-\\d{2}-\\d{4}\\b', text):\n            self.add_violation('SSN_DETECTED', 2, 'Social Security Number found')\n        \n        # Credit card pattern\n        if re.search(r'\\b\\d{4}[\\s-]?\\d{4}[\\s-]?\\d{4}[\\s-]?\\d{4}\\b', text):\n            self.add_violation('CREDIT_CARD_DETECTED', 2, 'Credit card number found')\n        \n        # Email addresses (multiple)\n        emails = re.findall(r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b', text)\n        if len(emails) > 3:\n            self.add_warning('MULTIPLE_EMAILS', f'{len(emails)} email addresses found')\n        \n        # Phone numbers (multiple)\n        phones = re.findall(r'\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b', text)\n        if len(phones) > 2:\n            self.add_warning('MULTIPLE_PHONES', f'{len(phones)} phone numbers found')\n        \n        # Home address pattern\n        if re.search(r'\\d+\\s+\\w+\\s+(street|st|avenue|ave|road|rd|drive|dr)', text.lower()):\n            self.add_warning('ADDRESS_DETECTED', 'Physical address found')\n    \n    def check_social_engineering(self, text):\n        \"\"\"Detect social engineering tactics\"\"\"\n        text_lower = text.lower()\n        \n        # Urgency indicators\n        urgency_words = ['urgent', 'immediate', 'asap', 'right now', 'immediately',\n                        'emergency', 'critical', 'time-sensitive']\n        urgency_count = sum(1 for word in urgency_words if word in text_lower)\n        \n        if urgency_count >= 3:\n            self.add_violation('ARTIFICIAL_URGENCY', 2, f'{urgency_count} urgency indicators')\n        elif urgency_count >= 2:\n            self.add_warning('URGENCY_DETECTED', 'Multiple urgency indicators')\n        \n        # Secrecy requests\n        if re.search(r\"(don't tell|keep (this )?secret|confidential|between us)\", text_lower):\n            self.add_violation('SECRECY_REQUEST', 2, 'Requesting secrecy')\n        \n        # Authority bypass\n        if re.search(r'(bypass|skip|ignore).{0,20}(normal|usual|standard) (process|procedure)', text_lower):\n            self.add_violation('PROCESS_BYPASS', 2, 'Attempting to bypass normal procedures')\n        \n        # Too good to be true\n        if re.search(r'(free|win|won|winner|selected|chosen).{0,30}(prize|money|gift|\\$)', text_lower):\n            self.add_warning('TOO_GOOD_TO_BE_TRUE', 'Unrealistic offer detected')\n    \n    def check_child_safety(self, text):\n        \"\"\"Critical: Child safety violations\"\"\"\n        text_lower = text.lower()\n        \n        child_terms = ['child', 'minor', 'kid', 'teen', 'teenager', 'underage', 'student', 'pupil']\n        inappropriate_context = ['date', 'dating', 'romantic', 'relationship', 'meet in person',\n                                'alone', 'secret', 'don\\'t tell', 'special friend']\n        \n        has_child_term = any(term in text_lower for term in child_terms)\n        has_inappropriate = any(term in text_lower for term in inappropriate_context)\n        \n        if has_child_term and has_inappropriate:\n            self.add_violation('CHILD_SAFETY_CRITICAL', 3, 'Child safety violation - REPORT REQUIRED')\n    \n    def check_malicious_patterns(self, text):\n        \"\"\"Detect malware and hacking patterns\"\"\"\n        text_lower = text.lower()\n        \n        malicious_patterns = [\n            (r'(click|open).{0,20}attachment.{0,20}(urgent|important|invoice)',\n             'MALICIOUS_ATTACHMENT', 2),\n            (r'(download|install|run).{0,20}(software|program|tool|update)',\n             'UNAUTHORIZED_SOFTWARE', 2),\n            (r'(disable|turn off).{0,20}(antivirus|firewall|security)',\n             'SECURITY_BYPASS', 3),\n            (r'(admin|administrator|root).{0,20}(access|password|privileges)',\n             'PRIVILEGE_ESCALATION', 3),\n        ]\n        \n        for pattern, violation_type, severity in malicious_patterns:\n            if re.search(pattern, text_lower):\n                self.add_violation(violation_type, severity, pattern)\n    \n    def add_violation(self, violation_type, severity, pattern):\n        \"\"\"Record a security violation\"\"\"\n        self.violations.append({\n            'type': violation_type,\n            'severity': severity,\n            'pattern': pattern,\n            'timestamp': datetime.now().isoformat()\n        })\n        if severity > self.threat_level:\n            self.threat_level = severity\n    \n    def add_warning(self, warning_type, message):\n        \"\"\"Record a warning\"\"\"\n        self.warnings.append({\n            'type': warning_type,\n            'message': message\n        })\n        if self.threat_level == 0:\n            self.threat_level = 1\n    \n    def generate_report(self):\n        \"\"\"Generate security scan report\"\"\"\n        return {\n            'threat_level': self.threat_level,\n            'status': self.get_status(),\n            'violations': self.violations,\n            'warnings': self.warnings,\n            'summary': self.get_summary()\n        }\n    \n    def get_status(self):\n        \"\"\"Get security status\"\"\"\n        if self.threat_level >= 3:\n            return 'CRITICAL_BLOCK_AND_REPORT'\n        elif self.threat_level == 2:\n            return 'BLOCK'\n        elif self.threat_level == 1:\n            return 'WARNING'\n        else:\n            return 'SAFE'\n    \n    def get_summary(self):\n        \"\"\"Get human-readable summary\"\"\"\n        if self.threat_level >= 3:\n            return f\"🚨 CRITICAL: {len(self.violations)} severe violations detected. DO NOT SEND. REPORT REQUIRED.\"\n        elif self.threat_level == 2:\n            return f\"🛑 BLOCKED: {len(self.violations)} violations detected. Cannot format this email.\"\n        elif self.threat_level == 1:\n            return f\"⚠️  WARNING: {len(self.warnings)} potential issues detected. Review carefully.\"\n        else:\n            return \"✅ No security issues detected.\"\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Usage: python3 security_scan.py 'email text'\")\n        sys.exit(1)\n    \n    scanner = SecurityScanner()\n    report = scanner.scan(sys.argv[1])\n    \n    # Print report\n    print(f\"\\n{'='*60}\")\n    print(f\"SECURITY SCAN REPORT\")\n    print(f\"{'='*60}\")\n    print(f\"Status: {report['status']}\")\n    print(f\"Threat Level: {report['threat_level']}/3\")\n    print(f\"\\n{report['summary']}\\n\")\n    \n    if report['violations']:\n        print(\"VIOLATIONS:\")\n        for v in report['violations']:\n            severity_icon = \"🚨\" if v['severity'] >= 3 else \"🛑\"\n            print(f\"  {severity_icon} {v['type']}\")\n            print(f\"      Pattern: {v['pattern'][:50]}...\")\n    \n    if report['warnings']:\n        print(\"\\nWARNINGS:\")\n        for w in report['warnings']:\n            print(f\"  ⚠️  {w['type']}: {w['message']}\")\n    \n    print(f\"\\n{'='*60}\\n\")\n    \n    # Return appropriate exit code\n    sys.exit(report['threat_level'])"
      },
      {
        "title": "Usage Workflow for AI Agents",
        "body": "MANDATORY SECURITY-FIRST WORKFLOW:\n\n#!/bin/bash\n# Email Formatter - Secure Processing Pipeline\n# This workflow is REQUIRED for every email formatting request\n\nset -e  # Exit on any error\n\nEMAIL_TEXT=\"$1\"\nTEMP_DIR=\"/tmp/email-formatter-$$\"\nmkdir -p \"$TEMP_DIR\"\n\necho \"🔒 Starting Secure Email Processing Pipeline...\"\necho \"================================================\"\n\n# STEP 1: PRE-FLIGHT SECURITY SCAN (CRITICAL)\necho \"Step 1/7: Running security scan...\"\npython3 ~/.email-formatter-skill/scripts/security_scan.py \"$EMAIL_TEXT\"\nSECURITY_EXIT=$?\n\nif [ $SECURITY_EXIT -eq 3 ]; then\n    echo \"\"\n    echo \"🚨🚨🚨 CRITICAL SECURITY VIOLATION 🚨🚨🚨\"\n    echo \"This email contains SEVERE violations that must be reported.\"\n    echo \"Formatting REFUSED. Potential illegal activity detected.\"\n    echo \"\"\n    echo \"ACTIONS REQUIRED:\"\n    echo \"1. Do NOT send this email\"\n    echo \"2. Document the incident\"\n    echo \"3. Report to appropriate authorities if applicable\"\n    echo \"4. Inform user of violation\"\n    exit 3\n\nelif [ $SECURITY_EXIT -eq 2 ]; then\n    echo \"\"\n    echo \"🛑 SECURITY BLOCK\"\n    echo \"This email violates safety policies and cannot be formatted.\"\n    echo \"Review the security report above for specific violations.\"\n    echo \"\"\n    echo \"SUGGESTED ACTIONS:\"\n    echo \"1. Identify the specific violation\"\n    echo \"2. Explain to user why it's blocked\"\n    echo \"3. Suggest legitimate alternatives\"\n    echo \"4. Offer to help rewrite with appropriate content\"\n    exit 2\n\nelif [ $SECURITY_EXIT -eq 1 ]; then\n    echo \"\"\n    echo \"⚠️  SECURITY WARNING\"\n    echo \"Potential issues detected. Proceeding with caution...\"\n    echo \"Will re-scan after formatting to ensure no issues introduced.\"\n    echo \"\"\nfi\n\n# STEP 2: CONTENT ANALYSIS\necho \"\"\necho \"Step 2/7: Analyzing content...\"\necho \"$EMAIL_TEXT\" > \"$TEMP_DIR/original.txt\"\n\n# Word count\nWORD_COUNT=$(echo \"$EMAIL_TEXT\" | wc -w)\necho \"   📊 Word count: $WORD_COUNT\"\n\nif [ $WORD_COUNT -gt 500 ]; then\n    echo \"   ⚠️  Email is very long. Consider breaking into multiple emails.\"\nfi\n\n# STEP 3: TONE ANALYSIS\necho \"\"\necho \"Step 3/7: Analyzing tone...\"\npython3 ~/.email-formatter-skill/scripts/tone_analyzer.py \"$EMAIL_TEXT\" > \"$TEMP_DIR/tone.txt\"\ncat \"$TEMP_DIR/tone.txt\"\n\n# Check if tone is aggressive\nif grep -q \"AGGRESSIVE\" \"$TEMP_DIR/tone.txt\"; then\n    echo \"\"\n    echo \"   ⚠️  AGGRESSIVE TONE DETECTED\"\n    echo \"   Recommendation: Suggest user wait 24 hours before sending\"\n    echo \"   Offer to rewrite in professional, constructive tone\"\n    echo \"\"\n    read -p \"   Continue anyway? (yes/no): \" CONTINUE\n    if [ \"$CONTINUE\" != \"yes\" ]; then\n        echo \"   Formatting cancelled by tone check.\"\n        exit 1\n    fi\nfi\n\n# STEP 4: GRAMMAR CHECK\necho \"\"\necho \"Step 4/7: Checking grammar...\"\npython3 ~/.email-formatter-skill/scripts/grammar_check.py \"$EMAIL_TEXT\"\n\n# STEP 5: READABILITY ANALYSIS\necho \"\"\necho \"Step 5/7: Analyzing readability...\"\npython3 ~/.email-formatter-skill/scripts/readability.py \"$EMAIL_TEXT\" > \"$TEMP_DIR/readability.txt\"\ncat \"$TEMP_DIR/readability.txt\"\n\n# STEP 6: FORMAT THE EMAIL\necho \"\"\necho \"Step 6/7: Formatting email...\"\necho \"   [Agent applies formatting rules based on guidelines]\"\n# ... AI agent performs formatting here ...\n# FORMATTED_EMAIL=\"...\"\n\n# STEP 7: POST-FORMATTING SECURITY RE-SCAN (CRITICAL)\necho \"\"\necho \"Step 7/7: Final security validation...\"\npython3 ~/.email-formatter-skill/scripts/security_scan.py \"$FORMATTED_EMAIL\"\nFINAL_SECURITY=$?\n\nif [ $FINAL_SECURITY -ne 0 ]; then\n    echo \"\"\n    echo \"🚨 POST-FORMATTING SECURITY FAILURE\"\n    echo \"Formatted version introduced security issues!\"\n    echo \"This should never happen - formatting logic has a bug.\"\n    echo \"Reverting to original and blocking output.\"\n    exit 2\nfi\n\n# SUCCESS\necho \"\"\necho \"✅ All security checks passed\"\necho \"✅ Email formatted successfully\"\necho \"\"\necho \"================================================\"\necho \"FORMATTED EMAIL READY FOR REVIEW\"\necho \"================================================\"\n\n# Cleanup\nrm -rf \"$TEMP_DIR\""
      },
      {
        "title": "Critical Enforcement Rules for AI Agents",
        "body": "NEVER SKIP SECURITY SCANS:\n\nSecurity scan must run BEFORE any formatting\nSecurity scan must run AFTER formatting\nBoth scans must pass (exit 0) for email to be delivered\nExit codes 1, 2, 3 MUST stop the pipeline\n\nDOUBLE-CHECK MECHANISM:\n\n# Before presenting formatted email to user\ndef final_validation(formatted_email):\n    # Re-run all security checks\n    security_clear = run_security_scan(formatted_email)\n    \n    if not security_clear:\n        # NEVER show formatted email\n        return {\n            'status': 'BLOCKED',\n            'message': 'Formatting introduced security issues',\n            'action': 'Report bug in formatting logic'\n        }\n    \n    # Additional checks\n    if contains_pii(formatted_email):\n        return {\n            'status': 'WARNING',\n            'message': 'PII detected in formatted email',\n            'action': 'Warn user about sending sensitive data via email'\n        }\n    \n    return {\n        'status': 'APPROVED',\n        'formatted_email': formatted_email\n    }\n\nLogging & Audit Trail (Privacy-Safe):\n\n# Log violations only (NO content)\ndef log_security_event(violation_type, severity, timestamp):\n    \"\"\"\n    Log security events for monitoring\n    NEVER log actual email content\n    \"\"\"\n    log_entry = {\n        'timestamp': timestamp,\n        'violation_type': violation_type,\n        'severity': severity,\n        'action_taken': 'BLOCKED',\n        'content': '[REDACTED]'  # Never log content\n    }\n    # Append to secure audit log\n    # This helps improve security detection"
      },
      {
        "title": "When to Use This Skill",
        "body": "Use this skill when the user needs to:\n\nFix grammar, spelling, and punctuation in emails\nAdjust tone (make more formal, casual, friendly, or assertive)\nStructure messy drafts into clear, organized messages\nConvert bullet points or notes into complete emails\nAdd professional greetings and closings\nImprove clarity and conciseness\nPrepare important messages for executives, clients, or stakeholders"
      },
      {
        "title": "Core Principles",
        "body": "Preserve Intent: Never change the core message or facts - only improve how it's communicated\nMatch Context: Adjust formality based on recipient and situation\nEnhance Clarity: Remove ambiguity while maintaining natural voice\nProfessional Standard: Apply business writing best practices\nCultural Awareness: Consider professional norms and communication styles"
      },
      {
        "title": "Step 1: Analyze the Draft",
        "body": "Before formatting, assess:\n\nRecipient relationship: Boss, colleague, client, vendor, team, external?\nPurpose: Request, update, introduction, follow-up, feedback, apology?\nTone needed: Formal, semi-formal, casual, friendly, assertive, diplomatic?\nUrgency: Routine, important, urgent, sensitive?\nCurrent issues: Grammar errors, unclear structure, wrong tone, missing context?"
      },
      {
        "title": "Step 2: Apply Improvements",
        "body": "Grammar & Mechanics:\n\nFix spelling, punctuation, and grammatical errors\nCorrect subject-verb agreement and tense consistency\nRemove run-on sentences and fragments\nFix comma splices and misplaced modifiers\n\nStructure & Organization:\n\nStandard Email Structure:\n1. Greeting (appropriate to relationship)\n2. Opening (context or pleasantry)\n3. Purpose statement (clear and direct)\n4. Body (organized by topic, use paragraphs/bullets)\n5. Call to action (if needed)\n6. Closing (polite sign-off)\n7. Signature\n\nTone Adjustments:\n\nToo Casual → Professional:\n\nBefore: \"Hey! Just wanted to check if u got my last email lol\"\nAfter: \"Hi Sarah, I wanted to follow up on my previous email from Tuesday. Please let me know if you need any additional information.\"\n\nToo Formal → Friendly:\n\nBefore: \"I am writing to inquire whether you have completed the aforementioned task.\"\nAfter: \"Hi John, I wanted to check in on the status of the marketing report. How's it coming along?\"\n\nToo Aggressive → Diplomatic:\n\nBefore: \"You need to fix this immediately. This is unacceptable.\"\nAfter: \"I noticed an issue that requires urgent attention. Could we prioritize resolving this today? I'm happy to help if needed.\"\n\nClarity Enhancements:\n\nReplace vague phrases with specific language\nBreak long paragraphs into digestible chunks\nUse bullet points for lists or multiple items\nAdd context where assumed knowledge might be missing\nRemove redundancy and filler words"
      },
      {
        "title": "Step 3: Polish Details",
        "body": "Subject Line (if provided or needed):\n\nKeep it under 50 characters\nMake it specific and actionable\nUse sentence case (not all caps)\nExamples:\n\n\"Q1 Budget Review Meeting - March 15\"\n\"Quick question about project timeline\"\n\"Following up: Website redesign proposal\"\n\nGreetings:\n\nFormal: \"Dear Dr. Smith,\" or \"Dear Hiring Manager,\"\nProfessional: \"Hi Jennifer,\" or \"Hello Team,\"\nCasual: \"Hey Alex,\" or \"Hi everyone,\"\n\nClosings:\n\nFormal: \"Sincerely,\" \"Respectfully,\" \"Best regards,\"\nProfessional: \"Best,\" \"Thanks,\" \"Looking forward to hearing from you,\"\nCasual: \"Cheers,\" \"Talk soon,\" \"Have a great day,\"\n\nSignature Block:\n\nBest regards,\n[Name]\n[Title]\n[Company]\n[Contact Info - if external]"
      },
      {
        "title": "1. Request Email",
        "body": "Structure:\n- Greeting\n- Context (why you're writing)\n- Specific request\n- Deadline or timeframe (if applicable)\n- Offer of additional info\n- Thanks\n- Closing"
      },
      {
        "title": "2. Follow-Up Email",
        "body": "Structure:\n- Reference previous communication\n- Polite reminder of action needed\n- Make it easy to respond\n- Maintain friendly tone\n- Closing"
      },
      {
        "title": "3. Bad News Email",
        "body": "Structure:\n- Direct but empathetic opening\n- Clear explanation\n- Acknowledge impact\n- Offer alternatives or next steps\n- End on positive note if possible"
      },
      {
        "title": "4. Introduction Email",
        "body": "Structure:\n- Who you are and connection\n- Purpose of introduction\n- What you're offering/requesting\n- Call to action\n- Professional closing"
      },
      {
        "title": "DO:",
        "body": "✅ Keep emails concise (under 200 words when possible)\n✅ Use active voice (\"I will send\" vs \"It will be sent\")\n✅ Break up text with white space\n✅ Put most important info in first paragraph\n✅ Proofread for typos and auto-correct errors\n✅ Use \"Reply All\" judiciously\n✅ Include clear next steps or calls to action\n✅ Match the sender's energy level"
      },
      {
        "title": "DON'T:",
        "body": "❌ Use all caps (seems like shouting)\n❌ Overuse exclamation marks\n❌ Include multiple topics in one email (if complex)\n❌ Use jargon with external recipients\n❌ Write when emotional (flag if email seems angry)\n❌ Assume tone translates (sarcasm, humor can fail)\n❌ Forget attachments referenced in text\n❌ Change factual content or commitments"
      },
      {
        "title": "Tone Guide",
        "body": "Formal (executives, clients, first contact):\n\nComplete sentences\nProfessional vocabulary\nProper titles and full names\n\"I would appreciate\" vs \"Can you\"\n\"Please let me know\" vs \"Let me know\"\n\nSemi-Formal (colleagues, regular contacts):\n\nConversational but professional\nContractions are fine\nFirst names acceptable\n\"Could you\" vs \"Can you\"\nFriendly but respectful\n\nCasual (close colleagues, internal teams):\n\nRelaxed language\nContractions and informal phrases\nQuick greetings\nCan be brief\nEmoji okay if culturally appropriate"
      },
      {
        "title": "Quality Checklist",
        "body": "Before presenting the formatted email, verify:\n\nSECURITY FIRST: Content passes all safety requirements\n No prohibited content: Checked against all safety rules above\n Legal compliance: No fraudulent, harassing, or illegal content\n Ethical standards: Message is honest and appropriate\n Grammar and spelling are correct\n Tone matches relationship and context\n Structure is clear and logical\n Key information is easy to find\n Call to action is clear (if needed)\n Opening and closing are appropriate\n No ambiguity or confusion\n Length is appropriate (concise but complete)\n Professional formatting applied\n Original intent is preserved\n Privacy check: No sensitive data exposed inappropriately\n Reputation check: Sender won't regret sending this"
      },
      {
        "title": "Red Flag Detection",
        "body": "Always scan for these warning signs:\n\nRequests for money, credentials, or personal information\nUrgency combined with financial requests\nImpersonation language (\"I'm calling from...\", \"This is [authority]...\")\nThreats or ultimatums\nAsking recipient to keep communication secret\nBypassing normal procedures\nInconsistent sender information\nRequests to click suspicious links\nGrammar/spelling errors in supposedly official communication\nToo-good-to-be-true offers\nEmotional manipulation tactics\nDiscriminatory language\nFalse information\nHostile or aggressive tone toward protected groups"
      },
      {
        "title": "Incident Response Protocol",
        "body": "When Critical Violations Detected (Threat Level 3):\n\nIMMEDIATE ACTIONS:\n1. BLOCK - Refuse to format email\n2. DOCUMENT - Record violation type, timestamp\n3. NOTIFY - Inform user of specific violation\n4. EDUCATE - Explain why it's harmful/illegal\n5. REDIRECT - Suggest legitimate alternatives\n6. REPORT - Flag for review if:\n   - Child safety violations\n   - Credible threats of violence\n   - Large-scale fraud attempts\n   - Illegal activities\n\nResponse Template for Critical Violations:\n\n🚨 CRITICAL SECURITY VIOLATION DETECTED\n\nVIOLATION TYPE: [Specific type - e.g., \"Credential Phishing Attempt\"]\n\nSEVERITY: CRITICAL - This email cannot be formatted\n\nWHAT WAS DETECTED:\n[Specific pattern - e.g., \"Email requests password and account \ncredentials, matching known phishing attack patterns\"]\n\nWHY THIS IS SERIOUS:\n[Impact - e.g., \"This could lead to:\n- Identity theft\n- Unauthorized account access  \n- Financial fraud\n- Legal liability for sender\"]\n\nWHAT YOU SHOULD KNOW:\n- Legitimate organizations NEVER ask for passwords via email\n- This pattern is used in 95% of credential phishing attacks\n- Sending this email could violate anti-fraud laws\n\nRECOMMENDED ACTIONS:\n1. If you received a similar email: Report it as phishing\n2. If you need password help: Use official password reset tools\n3. If suspicious: Contact IT/security team directly\n\nALTERNATIVE APPROACH:\n[Legitimate way to accomplish goal if applicable]\n\n---\nThis email has been blocked to protect you and recipients.\nFor questions about this decision, review security guidelines."
      },
      {
        "title": "Security Metrics & Monitoring",
        "body": "Track these metrics (content-free):\n\nSECURITY_METRICS = {\n    'total_scans': 0,\n    'threats_blocked': {\n        'level_1_warnings': 0,\n        'level_2_blocks': 0,\n        'level_3_critical': 0\n    },\n    'violation_types': {\n        'phishing': 0,\n        'fraud': 0,\n        'threats': 0,\n        'harassment': 0,\n        'impersonation': 0,\n        'pii_exposure': 0,\n        'malware': 0,\n        'child_safety': 0\n    },\n    'false_positives_reported': 0,\n    'scan_performance_ms': []\n}\n\nRegular Security Audits:\n\nReview blocked emails (patterns only, no content)\nUpdate detection patterns based on new threats\nTune sensitivity to reduce false positives\nImprove educational messages\nAdd new threat categories as they emerge"
      },
      {
        "title": "Privacy & Data Protection Compliance",
        "body": "GDPR/CCPA/HIPAA Compliance:\n\nDATA_PROTECTION_RULES = {\n    'data_minimization': 'Process only what's needed for formatting',\n    'purpose_limitation': 'Use data ONLY for formatting, nothing else',\n    'storage_limitation': 'Delete immediately after processing',\n    'accuracy': 'Don't modify factual content',\n    'integrity': 'Secure processing, encrypted if possible',\n    'confidentiality': 'Treat all emails as confidential',\n    'accountability': 'Log violations (not content) for audit'\n}\n\nUser Rights:\n\nRight to explanation: User can ask why email was blocked\nRight to appeal: User can dispute false positives\nRight to deletion: No content retention\nRight to transparency: Clear security policies"
      },
      {
        "title": "Continuous Improvement",
        "body": "Security Pattern Updates:\n\n# Periodically update threat patterns\n# Add new scam patterns as they emerge\n# Improve detection accuracy\n# Reduce false positives\n\n# Example: Update security_scan.py\ngit pull origin main  # Get latest threat patterns\npython3 -m pytest tests/test_security.py  # Verify\n\nFeedback Loop:\n\nCollect anonymized violation statistics\nIdentify common false positives\nRefine pattern matching\nAdd context-aware detection\nImprove user education messages"
      },
      {
        "title": "Output Format",
        "body": "Present the formatted email like this:\n\n**Subject:** [Subject line if relevant]\n\n[Formatted email body]\n\n---\n\n**Changes Made:**\n- [Brief list of key improvements]\n- [E.g., \"Corrected grammar errors\"]\n- [E.g., \"Adjusted tone from casual to professional\"]\n- [E.g., \"Restructured for clarity\"]"
      },
      {
        "title": "Special Considerations",
        "body": "Security Edge Cases:\n\nExample 1 - Phishing Attempt:\n\nUser Input: \"Format this: Hi, I'm from IT. Send me your password to verify your account.\"\nResponse: \"I cannot format this email as it requests sensitive credentials, which is a security red flag and potential phishing attempt. Legitimate IT departments never ask for passwords via email.\"\n\nExample 2 - Impersonation:\n\nUser Input: \"Make this sound like it's from the CEO demanding urgent wire transfer.\"\nResponse: \"I cannot help format emails that impersonate others or create urgency around financial transfers, as this matches common fraud patterns.\"\n\nExample 3 - Harassment:\n\nUser Input: \"Polish this email telling my coworker she's incompetent and should quit.\"\nResponse: \"I cannot format this email as it contains hostile language that could constitute workplace harassment. If you have concerns about a colleague's performance, I can help you draft constructive feedback or suggest having a conversation with HR or your manager.\"\n\nExample 4 - Academic Dishonesty:\n\nUser Input: \"Format this email to my professor pretending I was sick when I just forgot the assignment.\"\nResponse: \"I cannot help format emails containing false information. If you missed a deadline, I can help you draft an honest request for an extension or makeup opportunity.\"\n\nExample 5 - Anger/Emotional State:\n\nUser Input: \"Format this angry email to my boss calling them out for being unfair!\"\nResponse: \"⚠️ This email appears to be written in anger. I recommend waiting 24 hours before sending. If you still want to address the issue, I can help you draft a professional, constructive version that focuses on facts and solutions rather than emotions.\"\n\nLegitimate Gray Areas - Advise User:\n\nStrong feedback: Format professionally but warn about tone\nDeclining requests: Help maintain relationships while saying no\nAddressing conflicts: Focus on facts, not blame\nSensitive HR matters: Recommend consulting HR/legal first\n\nReply vs New Message:\n\nReplies: Can be more concise, less formal\nNew messages: Need more context and structure\n\nGroup Emails:\n\nAddress all recipients appropriately\nBe clear about who needs to take action\nAvoid \"Reply All\" clutter\n\nSensitive Topics:\n\nBe extra diplomatic\nAcknowledge feelings/concerns\nStick to facts\nOffer to discuss in person/call if needed\n\nInternational Recipients:\n\nAvoid idioms and colloquialisms\nUse clear, direct language\nBe aware of cultural communication differences\nSpell out dates (avoid 3/4/24 format ambiguity)\n\nMobile Email:\n\nFront-load most important info\nUse shorter paragraphs\nLimit to one topic if possible\nClear subject lines are crucial"
      },
      {
        "title": "Common Mistakes to Avoid",
        "body": "Starting with apologies: \"Sorry to bother you\" → \"I hope this email finds you well\"\nBuried lede: Put main point in first paragraph\nToo many questions: Limit to 1-2 per email\nPassive voice overuse: \"The report was completed\" → \"I completed the report\"\nUnclear next steps: Always specify what happens next\nOver-explaining: Be concise; don't over-justify\nMissing context: Assume recipient doesn't remember previous discussion\nInconsistent tone: Maintain same formality throughout"
      },
      {
        "title": "Advanced Techniques",
        "body": "The BLUF Method (Bottom Line Up Front):\n\nState conclusion/request first\nProvide supporting details after\nIdeal for busy executives\n\nChunking Information:\n\nUse subheadings for long emails\nBullet points for lists\nBold key phrases for scanning\n\nCall to Action Clarity:\n\n\"Please review and approve by Friday EOD\"\n\"Let me know if you have questions\"\n\"I'll send the draft by Thursday for your feedback\"\n\nSoftening Requests:\n\n\"Would you be able to...\" vs \"Can you...\"\n\"I was wondering if...\" vs \"I need...\"\n\"If possible...\" vs \"Please...\""
      },
      {
        "title": "Version History",
        "body": "v1.0.0 (2024): Initial release with core formatting capabilities"
      },
      {
        "title": "License",
        "body": "MIT License - Free to use and modify\n\nPro Tip for Users: For best results, provide context about the recipient relationship and email purpose. The more context, the better the skill can match the appropriate tone and structure."
      }
    ],
    "body": "Email Formatter - Professional Email Enhancement\nInstallation & Setup\nPrerequisites Check\n\nBefore using this skill, verify the environment has required capabilities:\n\n# Check if bash is available\nwhich bash\n\n# Check Python version (3.8+ required)\npython3 --version\n\n# Check Node.js (optional, for advanced features)\nnode --version\n\nAuto-Installation Script\n\nFor AI Agents: Run this installation check at first use\n\n#!/bin/bash\n# Email Formatter Skill - Auto Setup\n# This script installs required dependencies\n\necho \"🔧 Email Formatter Skill - Installation Starting...\"\n\n# Create skill workspace\nSKILL_DIR=\"$HOME/.email-formatter-skill\"\nmkdir -p \"$SKILL_DIR\"\ncd \"$SKILL_DIR\"\n\n# Install Python dependencies\necho \"📦 Installing Python packages...\"\npip3 install --break-system-packages --quiet \\\n    language-tool-python \\\n    textstat \\\n    spacy 2>/dev/null || pip3 install --user --quiet \\\n    language-tool-python \\\n    textstat \\\n    spacy\n\n# Download language model for grammar checking\necho \"📚 Downloading language model...\"\npython3 -m spacy download en_core_web_sm --quiet 2>/dev/null || true\n\n# Create helper scripts directory\nmkdir -p \"$SKILL_DIR/scripts\"\n\n# Test installation\nif python3 -c \"import language_tool_python; import textstat; import spacy\" 2>/dev/null; then\n    echo \"✅ Email Formatter Skill installed successfully!\"\n    echo \"📍 Installed at: $SKILL_DIR\"\n    exit 0\nelse\n    echo \"⚠️  Some dependencies failed. Skill will work with reduced features.\"\n    exit 0\nfi\n\nManual Installation (if auto-install fails)\n# Minimal setup - no external dependencies\n# The skill will use built-in Python capabilities only\nmkdir -p ~/.email-formatter-skill/scripts\necho \"✅ Basic setup complete\"\n\nVerify Installation\n# Quick verification\npython3 -c \"print('Email Formatter: Ready ✅')\"\n\nDependencies\nRequired (Always Available)\nPython 3.7+ (standard library only for minimal mode)\nBash shell\nOptional (Enhanced Features)\nlanguage-tool-python: Advanced grammar checking\ntextstat: Readability analysis\nspacy: NLP for tone detection\n\nNote for AI Agents: The skill works in degraded mode without optional dependencies. Install them only if environment allows.\n\nOverview\n\nThis skill transforms rough email drafts into polished, professional communication by improving grammar, adjusting tone, enhancing clarity, and applying proper formatting. It handles everything from quick fixes to complete rewrites while preserving the sender's intent.\n\n⚠️ CRITICAL SECURITY & SAFETY REQUIREMENTS\n\nThis skill MUST enforce these non-negotiable safety rules at all times:\n\nSECURITY LEVEL: MAXIMUM - Multi-Layer Validation Required\n\nMANDATORY PRE-PROCESSING SECURITY CHECKS: Every email MUST pass ALL security layers before any formatting occurs:\n\nLayer 1: Content Classification (BLOCK IMMEDIATELY)\n\n❌ Illegal Activities: Fraud, scams, phishing, money laundering, tax evasion, bribery ❌ Violence & Threats: Physical threats, intimidation, stalking, doxxing, revenge threats ❌ Impersonation: Government officials, company executives, IT/support staff, law enforcement ❌ Financial Fraud: Wire transfers, cryptocurrency scams, investment fraud, Ponzi schemes ❌ Identity Theft: SSN requests, password sharing, credential phishing, fake verification ❌ Misinformation: Health fraud, election interference, conspiracy theories, fake news ❌ Child Safety: ANY content involving minors in inappropriate context ❌ Hate Speech: Racism, sexism, homophobia, religious hatred, ethnic slurs ❌ Sexual Content: Harassment, explicit content, unwanted advances, grooming ❌ Workplace Violations: Discrimination, harassment, retaliation, hostile environment ❌ Academic Fraud: Plagiarism, cheating, fake credentials, assignment ghostwriting ❌ Medical Fraud: Fake prescriptions, unlicensed advice, miracle cures, dangerous treatments ❌ Legal Violations: Contract fraud, perjury, witness tampering, obstruction ❌ Privacy Violations: Sharing private info without consent, surveillance, stalking ❌ Malware/Hacking: Phishing links, malicious attachments, system exploits ❌ Extortion: Blackmail, ransomware, threats for money, coercion\n\nLayer 2: Pattern Recognition (RED FLAGS)\n\nScan for suspicious patterns that indicate malicious intent:\n\nFinancial Red Flags:\n\nUrgent payment requests\nWire transfer instructions\nGift card purchases\nCryptocurrency transactions\n\"Keep this confidential\" + money\nBypassing normal approval process\nUnusual account changes\nTax refund scams\nInheritance scams\nLottery/prize scams\n\nAuthority Impersonation Red Flags:\n\n\"I'm from IT/HR/Legal/Management\"\n\"CEO needs you to...\"\n\"Urgent request from [authority]\"\n\"Don't tell anyone\"\nBypassing email/domain verification\nUnusual requests from superiors\nFake emergency scenarios\n\nCredential Harvesting Red Flags:\n\n\"Verify your password\"\n\"Confirm your account\"\n\"Click to prevent suspension\"\n\"Unusual login detected\"\nLinks to login pages\nFake security alerts\nAccount expiration warnings\n\nSocial Engineering Red Flags:\n\nArtificial urgency\nEmotional manipulation\nToo good to be true\nRequests for secrecy\nUnusual sender behavior\nPressure tactics\nFear-based messaging\nLayer 3: Sentiment & Tone Analysis (WARN OR BLOCK)\n\n⚠️ Aggressive/Hostile: Insulting, demeaning, threatening language ⚠️ Manipulative: Guilt-tripping, gaslighting, emotional blackmail ⚠️ Coercive: Power imbalance exploitation, quid pro quo ⚠️ Deceptive: Half-truths, misleading statements, omissions ⚠️ Discriminatory: Based on protected characteristics ⚠️ Retaliatory: Punishment for protected actions\n\nLayer 4: Context Validation (VERIFY LEGITIMACY)\n\n✓ Sender-Recipient Relationship: Does this match their normal communication? ✓ Request Reasonability: Is this a normal business request? ✓ Communication Channel: Should this be email or in-person/phone? ✓ Timing: Why is this urgent? Is urgency justified? ✓ Information Sensitivity: Should this data be in email? ✓ Authorization: Does sender have authority for this request?\n\nLayer 5: Privacy & Data Protection (GDPR/CCPA COMPLIANCE)\n\n🔒 PII Detection: Name, address, phone, email, SSN, DOB, photos 🔒 Financial Data: Credit cards, bank accounts, tax IDs, salary info 🔒 Health Data: Medical records, diagnoses, prescriptions, HIPAA data 🔒 Credentials: Passwords, API keys, tokens, security questions 🔒 Proprietary Data: Trade secrets, confidential business info, NDA material 🔒 Children's Data: ANY data about individuals under 18\n\nACTION REQUIRED: If PII detected, warn user about:\n\nEmail is not encrypted by default\nData breach risks\nRegulatory compliance (GDPR, CCPA, HIPAA)\nSuggest secure alternatives (encrypted email, secure portal, in-person)\nZERO TOLERANCE BLOCKING - Immediate Rejection\n\nIf ANY of these detected, REFUSE IMMEDIATELY WITHOUT FORMATTING:\n\nZERO_TOLERANCE_PATTERNS = [\n    # Credential Requests\n    r'(send|give|provide).{0,20}(password|credential|login)',\n    r'verify.{0,20}(password|account|identity)',\n    \n    # Financial Fraud\n    r'wire transfer.{0,30}(urgent|immediately|today)',\n    r'gift card.{0,20}(purchase|buy|get)',\n    r'(bitcoin|crypto).{0,20}(send|transfer|wallet)',\n    \n    # Impersonation\n    r\"i'?m.{0,10}(from|with|calling from).{0,20}(IT|HR|legal|IRS|FBI)\",\n    r'(this is|i am).{0,20}(CEO|CFO|president|director)',\n    \n    # Threats\n    r'(or else|otherwise).{0,30}(fire|sue|report|punish)',\n    r'you (will|better).{0,20}(regret|pay|suffer)',\n    \n    # Illegal Activities\n    r'(launder|hide|conceal).{0,20}money',\n    r'(fake|forged|fraudulent).{0,20}(document|invoice|receipt)',\n    \n    # Child Safety\n    r'(minor|child|kid|underage).{0,50}(sexual|romantic|date|meet)',\n    \n    # Malware/Phishing\n    r'(click|download).{0,20}(attachment|link|file).{0,20}(urgent|immediately)',\n    r'account.{0,20}(suspend|lock|close|expire).{0,20}(unless|until)',\n    \n    # Harassment\n    r'(stupid|idiot|incompetent|worthless).{0,20}(you|employee|coworker)',\n    r\"i'?ll make sure you (never|don't|can't)\",\n]\n\nEnhanced Security Response Protocol\n\nWhen prohibited content detected:\n\n1. STOP - Do not process further\n2. LOG - Record violation type (no content)\n3. INFORM - Tell user specifically what rule was violated\n4. EDUCATE - Explain why it's harmful/illegal\n5. REDIRECT - Suggest legitimate alternatives\n6. REPORT - Flag for review if severe (threats, child safety, fraud)\n\n\nExample Response Template:\n\n🛑 SECURITY BLOCK: Email Formatting Refused\n\nREASON: [Specific violation - e.g., \"Credential request detected\"]\n\nWHY THIS IS BLOCKED:\n[Explanation - e.g., \"Legitimate organizations never ask for \npasswords via email. This matches phishing attack patterns.\"]\n\nWHAT YOU SHOULD DO:\n[Alternative - e.g., \"If you need to reset a password, use \nthe official password reset link on the company website.\"]\n\nTHIS SKILL CANNOT:\n- Help with fraudulent communications\n- Bypass security protocols\n- Facilitate illegal activities\n- Enable harassment or threats\n\nHelper Scripts & Tools\n\nThe skill includes utility scripts for AI agents to use. Create these in ~/.email-formatter-skill/scripts/:\n\n1. Grammar Checker (grammar_check.py)\n#!/usr/bin/env python3\n\"\"\"\nBasic grammar and spell checker\nUsage: python3 grammar_check.py \"email text here\"\n\"\"\"\nimport sys\nimport re\n\ndef basic_grammar_check(text):\n    \"\"\"Basic grammar checks without external dependencies\"\"\"\n    issues = []\n    \n    # Common spelling errors\n    typos = {\n        'recieve': 'receive', 'occured': 'occurred', 'seperate': 'separate',\n        'definately': 'definitely', 'accomodate': 'accommodate',\n        'tommorow': 'tomorrow', 'untill': 'until', 'truely': 'truly'\n    }\n    \n    for wrong, right in typos.items():\n        if wrong in text.lower():\n            issues.append(f\"Spelling: '{wrong}' → '{right}'\")\n    \n    # Basic grammar patterns\n    if re.search(r'\\bi\\s', text):  # lowercase 'i'\n        issues.append(\"Grammar: 'i' should be capitalized to 'I'\")\n    \n    if re.search(r'\\s{2,}', text):\n        issues.append(\"Formatting: Multiple spaces detected\")\n    \n    if re.search(r'[.!?]\\s*[a-z]', text):\n        issues.append(\"Grammar: Sentence should start with capital letter\")\n    \n    # Double punctuation\n    if re.search(r'[.!?]{2,}', text):\n        issues.append(\"Punctuation: Multiple punctuation marks\")\n    \n    return issues\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Usage: python3 grammar_check.py 'text'\")\n        sys.exit(1)\n    \n    text = sys.argv[1]\n    issues = basic_grammar_check(text)\n    \n    if issues:\n        for issue in issues:\n            print(f\"⚠️  {issue}\")\n    else:\n        print(\"✅ No basic issues found\")\n\n2. Tone Analyzer (tone_analyzer.py)\n#!/usr/bin/env python3\n\"\"\"\nAnalyze email tone\nUsage: python3 tone_analyzer.py \"email text\"\n\"\"\"\nimport sys\nimport re\n\ndef analyze_tone(text):\n    \"\"\"Detect tone indicators in email text\"\"\"\n    \n    # Formal indicators\n    formal_words = ['pursuant', 'hereby', 'aforementioned', 'regarding', \n                   'sincerely', 'respectfully', 'cordially']\n    \n    # Casual indicators  \n    casual_words = ['hey', 'gonna', 'wanna', 'yeah', 'yep', 'nope',\n                   'btw', 'fyi', 'lol', 'omg', 'tbh']\n    \n    # Aggressive indicators\n    aggressive_words = ['immediately', 'must', 'unacceptable', 'ridiculous',\n                       'obviously', 'clearly', 'need to', 'have to']\n    \n    # Polite indicators\n    polite_words = ['please', 'kindly', 'would you', 'could you',\n                   'appreciate', 'thank', 'grateful']\n    \n    text_lower = text.lower()\n    \n    formal_count = sum(1 for w in formal_words if w in text_lower)\n    casual_count = sum(1 for w in casual_words if w in text_lower)\n    aggressive_count = sum(1 for w in aggressive_words if w in text_lower)\n    polite_count = sum(1 for w in polite_words if w in text_lower)\n    \n    # Exclamation marks\n    exclamations = len(re.findall(r'!', text))\n    \n    # ALL CAPS detection\n    caps_words = len(re.findall(r'\\b[A-Z]{2,}\\b', text))\n    \n    # Determine primary tone\n    tones = []\n    if formal_count >= 2:\n        tones.append(\"FORMAL\")\n    if casual_count >= 2:\n        tones.append(\"CASUAL\")\n    if aggressive_count >= 2 or caps_words >= 2:\n        tones.append(\"AGGRESSIVE\")\n    if polite_count >= 2:\n        tones.append(\"POLITE\")\n    if exclamations >= 3:\n        tones.append(\"ENTHUSIASTIC/URGENT\")\n    \n    if not tones:\n        tones.append(\"NEUTRAL\")\n    \n    return {\n        'primary_tone': tones[0],\n        'all_tones': tones,\n        'formal_score': formal_count,\n        'casual_score': casual_count,\n        'aggressive_score': aggressive_count,\n        'polite_score': polite_count,\n        'exclamations': exclamations,\n        'caps_words': caps_words\n    }\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Usage: python3 tone_analyzer.py 'text'\")\n        sys.exit(1)\n    \n    result = analyze_tone(sys.argv[1])\n    print(f\"📊 Primary Tone: {result['primary_tone']}\")\n    print(f\"🎯 All Tones: {', '.join(result['all_tones'])}\")\n    print(f\"📈 Scores - Formal:{result['formal_score']} Casual:{result['casual_score']} \"\n          f\"Aggressive:{result['aggressive_score']} Polite:{result['polite_score']}\")\n    \n    if result['aggressive_score'] >= 2:\n        print(\"⚠️  WARNING: Email may sound aggressive\")\n    if result['exclamations'] >= 3:\n        print(\"⚠️  WARNING: Too many exclamation marks\")\n    if result['caps_words'] >= 2:\n        print(\"⚠️  WARNING: Excessive capitalization detected\")\n\n3. Readability Scorer (readability.py)\n#!/usr/bin/env python3\n\"\"\"\nCalculate email readability\nUsage: python3 readability.py \"email text\"\n\"\"\"\nimport sys\nimport re\n\ndef count_syllables(word):\n    \"\"\"Simple syllable counter\"\"\"\n    word = word.lower()\n    vowels = 'aeiouy'\n    syllable_count = 0\n    previous_was_vowel = False\n    \n    for char in word:\n        is_vowel = char in vowels\n        if is_vowel and not previous_was_vowel:\n            syllable_count += 1\n        previous_was_vowel = is_vowel\n    \n    # Adjust for silent 'e'\n    if word.endswith('e'):\n        syllable_count -= 1\n    \n    # Every word has at least one syllable\n    if syllable_count == 0:\n        syllable_count = 1\n        \n    return syllable_count\n\ndef flesch_reading_ease(text):\n    \"\"\"Calculate Flesch Reading Ease score\"\"\"\n    sentences = len(re.findall(r'[.!?]+', text)) or 1\n    words = len(text.split())\n    syllables = sum(count_syllables(word) for word in text.split())\n    \n    if words == 0:\n        return 0\n    \n    score = 206.835 - 1.015 * (words / sentences) - 84.6 * (syllables / words)\n    return round(score, 1)\n\ndef analyze_readability(text):\n    \"\"\"Analyze email readability\"\"\"\n    words = text.split()\n    sentences = len(re.findall(r'[.!?]+', text)) or 1\n    \n    avg_word_length = sum(len(w) for w in words) / len(words) if words else 0\n    avg_sentence_length = len(words) / sentences\n    \n    flesch_score = flesch_reading_ease(text)\n    \n    # Interpret score\n    if flesch_score >= 90:\n        level = \"Very Easy (5th grade)\"\n    elif flesch_score >= 80:\n        level = \"Easy (6th grade)\"\n    elif flesch_score >= 70:\n        level = \"Fairly Easy (7th grade)\"\n    elif flesch_score >= 60:\n        level = \"Standard (8-9th grade)\"\n    elif flesch_score >= 50:\n        level = \"Fairly Difficult (10-12th grade)\"\n    elif flesch_score >= 30:\n        level = \"Difficult (College)\"\n    else:\n        level = \"Very Difficult (Graduate)\"\n    \n    return {\n        'flesch_score': flesch_score,\n        'level': level,\n        'avg_word_length': round(avg_word_length, 1),\n        'avg_sentence_length': round(avg_sentence_length, 1),\n        'total_words': len(words),\n        'total_sentences': sentences\n    }\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Usage: python3 readability.py 'text'\")\n        sys.exit(1)\n    \n    result = analyze_readability(sys.argv[1])\n    print(f\"📖 Flesch Reading Ease: {result['flesch_score']}\")\n    print(f\"📚 Reading Level: {result['level']}\")\n    print(f\"📊 Stats: {result['total_words']} words, {result['total_sentences']} sentences\")\n    print(f\"📏 Avg: {result['avg_word_length']} chars/word, {result['avg_sentence_length']} words/sentence\")\n    \n    # Recommendations\n    if result['flesch_score'] < 60:\n        print(\"💡 TIP: Simplify language for better clarity\")\n    if result['avg_sentence_length'] > 20:\n        print(\"💡 TIP: Break long sentences into shorter ones\")\n\n4. Security Scanner (security_scan.py)\n#!/usr/bin/env python3\n\"\"\"\nULTRA-SECURE Email Scanner - Multi-Layer Threat Detection\nUsage: python3 security_scan.py \"email text\"\nExit codes: 0=safe, 1=warning, 2=critical_block, 3=report_required\n\"\"\"\nimport sys\nimport re\nimport json\nfrom datetime import datetime\n\nclass SecurityScanner:\n    \"\"\"Military-grade email security scanner\"\"\"\n    \n    def __init__(self):\n        self.threat_level = 0  # 0=safe, 1=warning, 2=critical, 3=report\n        self.violations = []\n        self.warnings = []\n        \n    def scan(self, text):\n        \"\"\"Run all security checks\"\"\"\n        # Layer 1: Zero Tolerance Patterns\n        self.check_zero_tolerance(text)\n        \n        # Layer 2: Financial Fraud\n        self.check_financial_fraud(text)\n        \n        # Layer 3: Impersonation\n        self.check_impersonation(text)\n        \n        # Layer 4: Credential Harvesting\n        self.check_credential_harvesting(text)\n        \n        # Layer 5: Threats & Violence\n        self.check_threats(text)\n        \n        # Layer 6: Harassment & Discrimination\n        self.check_harassment(text)\n        \n        # Layer 7: Privacy & PII\n        self.check_privacy_violations(text)\n        \n        # Layer 8: Social Engineering\n        self.check_social_engineering(text)\n        \n        # Layer 9: Child Safety\n        self.check_child_safety(text)\n        \n        # Layer 10: Malicious Patterns\n        self.check_malicious_patterns(text)\n        \n        return self.generate_report()\n    \n    def check_zero_tolerance(self, text):\n        \"\"\"Critical patterns that immediately block\"\"\"\n        text_lower = text.lower()\n        \n        critical_patterns = [\n            # Credentials\n            (r'(send|give|provide|email).{0,30}(password|pwd|credential|login|passphrase)',\n             'CREDENTIAL_REQUEST', 3),\n            (r'verify.{0,20}(password|account|identity|credential)',\n             'FAKE_VERIFICATION', 3),\n            (r'(username|user id).{0,20}(and|&|\\\\+).{0,20}password',\n             'CREDENTIAL_PAIR_REQUEST', 3),\n            \n            # Financial\n            (r'wire transfer.{0,30}(urgent|immediate|asap|now|today)',\n             'URGENT_WIRE_TRANSFER', 3),\n            (r'(gift card|itunes|steam|amazon card).{0,30}(buy|purchase|get|send)',\n             'GIFT_CARD_SCAM', 3),\n            (r'(bitcoin|btc|crypto|ethereum|eth).{0,30}(wallet|address|send|transfer)',\n             'CRYPTO_SCAM', 3),\n            (r'(bank account|routing number|swift code).{0,30}(provide|send|give)',\n             'BANKING_INFO_REQUEST', 3),\n            \n            # Impersonation\n            (r\"i'?m.{0,10}(from|with|calling from).{0,30}(IT|support|tech|help desk)\",\n             'IT_IMPERSONATION', 3),\n            (r\"(this is|i am|i'm).{0,20}(CEO|CFO|president|director|executive)\",\n             'EXECUTIVE_IMPERSONATION', 3),\n            (r\"(IRS|FBI|police|government|immigration).{0,30}(contact|reach out|notice)\",\n             'AUTHORITY_IMPERSONATION', 3),\n            \n            # Threats\n            (r'(or else|otherwise).{0,30}(fire|terminate|sue|report|arrest)',\n             'THREAT_DETECTED', 3),\n            (r\"(you|i)'?(ll| will).{0,30}(regret|pay|suffer|sorry)\",\n             'THREAT_LANGUAGE', 3),\n            \n            # Child Safety\n            (r'(child|minor|kid|teen|underage).{0,50}(meet|date|relationship|romantic)',\n             'CHILD_SAFETY_VIOLATION', 3),\n            \n            # Malware\n            (r'(click|open|download).{0,20}(attachment|link|file).{0,20}(urgent|expire|suspend)',\n             'PHISHING_LINK', 3),\n        ]\n        \n        for pattern, violation_type, severity in critical_patterns:\n            if re.search(pattern, text_lower):\n                self.add_violation(violation_type, severity, pattern)\n    \n    def check_financial_fraud(self, text):\n        \"\"\"Detect financial scam patterns\"\"\"\n        text_lower = text.lower()\n        \n        fraud_indicators = [\n            (r'(won|winner|prize|lottery).{0,30}(\\$|dollar|money|claim)',\n             'LOTTERY_SCAM', 2),\n            (r'(inheritance|beneficiary|estate).{0,50}(million|claim|transfer)',\n             'INHERITANCE_SCAM', 2),\n            (r'(tax|irs).{0,30}(refund|owe|pay immediately)',\n             'TAX_SCAM', 2),\n            (r'(invoice|payment).{0,20}(overdue|urgent|immediate|final notice)',\n             'FAKE_INVOICE', 2),\n            (r'(suspended|frozen|locked).{0,30}account',\n             'ACCOUNT_SUSPENSION_SCAM', 2),\n            (r'(refund|reimbursement).{0,30}(click|verify|confirm)',\n             'REFUND_SCAM', 2),\n            (r'(investment|opportunity|profit).{0,50}(guaranteed|risk-free|double)',\n             'INVESTMENT_FRAUD', 2),\n        ]\n        \n        for pattern, violation_type, severity in fraud_indicators:\n            if re.search(pattern, text_lower):\n                self.add_violation(violation_type, severity, pattern)\n    \n    def check_impersonation(self, text):\n        \"\"\"Detect impersonation attempts\"\"\"\n        text_lower = text.lower()\n        \n        impersonation_patterns = [\n            (r'(on behalf of|representing).{0,30}(company|organization|government)',\n             'UNAUTHORIZED_REPRESENTATION', 2),\n            (r\"(i'?m|this is).{0,20}(calling|writing|reaching out).{0,20}(from|regarding)\",\n             'SUSPICIOUS_INTRODUCTION', 1),\n            (r'(verify|confirm).{0,20}(you are|your identity|who you are)',\n             'IDENTITY_VERIFICATION_REQUEST', 2),\n        ]\n        \n        for pattern, violation_type, severity in impersonation_patterns:\n            if re.search(pattern, text_lower):\n                self.add_violation(violation_type, severity, pattern)\n    \n    def check_credential_harvesting(self, text):\n        \"\"\"Detect credential theft attempts\"\"\"\n        text_lower = text.lower()\n        \n        patterns = [\n            (r'(account|access).{0,30}(expire|suspend|lock|disable)',\n             'FAKE_EXPIRATION', 2),\n            (r'(security|unusual|suspicious).{0,30}activity',\n             'FAKE_SECURITY_ALERT', 2),\n            (r'(update|verify|confirm).{0,30}(payment|billing) (method|information)',\n             'PAYMENT_INFO_PHISHING', 2),\n            (r'(reset|recover|change).{0,20}password.{0,20}(click|link|here)',\n             'PASSWORD_RESET_SCAM', 2),\n        ]\n        \n        for pattern, violation_type, severity in patterns:\n            if re.search(pattern, text_lower):\n                self.add_violation(violation_type, severity, pattern)\n    \n    def check_threats(self, text):\n        \"\"\"Detect threats and violent language\"\"\"\n        text_lower = text.lower()\n        \n        threat_words = [\n            'kill', 'hurt', 'harm', 'destroy', 'eliminate', 'punish',\n            'revenge', 'retaliate', 'get back at', 'make you pay'\n        ]\n        \n        for word in threat_words:\n            if word in text_lower:\n                self.add_violation('THREAT_LANGUAGE', 3, f\"Threat word: {word}\")\n        \n        # Physical threat patterns\n        if re.search(r'(come after|find you|know where you)', text_lower):\n            self.add_violation('PHYSICAL_THREAT', 3, 'Physical threat implied')\n    \n    def check_harassment(self, text):\n        \"\"\"Detect harassment and hostile language\"\"\"\n        text_lower = text.lower()\n        \n        hostile_words = [\n            'stupid', 'idiot', 'moron', 'incompetent', 'worthless',\n            'pathetic', 'useless', 'loser', 'failure', 'trash'\n        ]\n        \n        count = sum(1 for word in hostile_words if word in text_lower)\n        if count >= 2:\n            self.add_violation('HARASSMENT', 2, f'{count} hostile terms detected')\n        elif count == 1:\n            self.add_warning('POTENTIALLY_HOSTILE', 'Hostile language detected')\n        \n        # Discriminatory patterns\n        protected_characteristics = [\n            (r'(because|since).{0,20}(you\\'?re|you are).{0,20}(woman|female|girl)',\n             'GENDER_DISCRIMINATION'),\n            (r'(because|since).{0,20}(you\\'?re|you are).{0,20}(old|young|age)',\n             'AGE_DISCRIMINATION'),\n            (r'(people like you|your kind|you people)', 'DISCRIMINATORY_LANGUAGE'),\n        ]\n        \n        for pattern, violation_type in protected_characteristics:\n            if re.search(pattern, text_lower):\n                self.add_violation(violation_type, 3, pattern)\n    \n    def check_privacy_violations(self, text):\n        \"\"\"Detect PII and privacy issues\"\"\"\n        \n        # SSN pattern\n        if re.search(r'\\b\\d{3}-\\d{2}-\\d{4}\\b', text):\n            self.add_violation('SSN_DETECTED', 2, 'Social Security Number found')\n        \n        # Credit card pattern\n        if re.search(r'\\b\\d{4}[\\s-]?\\d{4}[\\s-]?\\d{4}[\\s-]?\\d{4}\\b', text):\n            self.add_violation('CREDIT_CARD_DETECTED', 2, 'Credit card number found')\n        \n        # Email addresses (multiple)\n        emails = re.findall(r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b', text)\n        if len(emails) > 3:\n            self.add_warning('MULTIPLE_EMAILS', f'{len(emails)} email addresses found')\n        \n        # Phone numbers (multiple)\n        phones = re.findall(r'\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b', text)\n        if len(phones) > 2:\n            self.add_warning('MULTIPLE_PHONES', f'{len(phones)} phone numbers found')\n        \n        # Home address pattern\n        if re.search(r'\\d+\\s+\\w+\\s+(street|st|avenue|ave|road|rd|drive|dr)', text.lower()):\n            self.add_warning('ADDRESS_DETECTED', 'Physical address found')\n    \n    def check_social_engineering(self, text):\n        \"\"\"Detect social engineering tactics\"\"\"\n        text_lower = text.lower()\n        \n        # Urgency indicators\n        urgency_words = ['urgent', 'immediate', 'asap', 'right now', 'immediately',\n                        'emergency', 'critical', 'time-sensitive']\n        urgency_count = sum(1 for word in urgency_words if word in text_lower)\n        \n        if urgency_count >= 3:\n            self.add_violation('ARTIFICIAL_URGENCY', 2, f'{urgency_count} urgency indicators')\n        elif urgency_count >= 2:\n            self.add_warning('URGENCY_DETECTED', 'Multiple urgency indicators')\n        \n        # Secrecy requests\n        if re.search(r\"(don't tell|keep (this )?secret|confidential|between us)\", text_lower):\n            self.add_violation('SECRECY_REQUEST', 2, 'Requesting secrecy')\n        \n        # Authority bypass\n        if re.search(r'(bypass|skip|ignore).{0,20}(normal|usual|standard) (process|procedure)', text_lower):\n            self.add_violation('PROCESS_BYPASS', 2, 'Attempting to bypass normal procedures')\n        \n        # Too good to be true\n        if re.search(r'(free|win|won|winner|selected|chosen).{0,30}(prize|money|gift|\\$)', text_lower):\n            self.add_warning('TOO_GOOD_TO_BE_TRUE', 'Unrealistic offer detected')\n    \n    def check_child_safety(self, text):\n        \"\"\"Critical: Child safety violations\"\"\"\n        text_lower = text.lower()\n        \n        child_terms = ['child', 'minor', 'kid', 'teen', 'teenager', 'underage', 'student', 'pupil']\n        inappropriate_context = ['date', 'dating', 'romantic', 'relationship', 'meet in person',\n                                'alone', 'secret', 'don\\'t tell', 'special friend']\n        \n        has_child_term = any(term in text_lower for term in child_terms)\n        has_inappropriate = any(term in text_lower for term in inappropriate_context)\n        \n        if has_child_term and has_inappropriate:\n            self.add_violation('CHILD_SAFETY_CRITICAL', 3, 'Child safety violation - REPORT REQUIRED')\n    \n    def check_malicious_patterns(self, text):\n        \"\"\"Detect malware and hacking patterns\"\"\"\n        text_lower = text.lower()\n        \n        malicious_patterns = [\n            (r'(click|open).{0,20}attachment.{0,20}(urgent|important|invoice)',\n             'MALICIOUS_ATTACHMENT', 2),\n            (r'(download|install|run).{0,20}(software|program|tool|update)',\n             'UNAUTHORIZED_SOFTWARE', 2),\n            (r'(disable|turn off).{0,20}(antivirus|firewall|security)',\n             'SECURITY_BYPASS', 3),\n            (r'(admin|administrator|root).{0,20}(access|password|privileges)',\n             'PRIVILEGE_ESCALATION', 3),\n        ]\n        \n        for pattern, violation_type, severity in malicious_patterns:\n            if re.search(pattern, text_lower):\n                self.add_violation(violation_type, severity, pattern)\n    \n    def add_violation(self, violation_type, severity, pattern):\n        \"\"\"Record a security violation\"\"\"\n        self.violations.append({\n            'type': violation_type,\n            'severity': severity,\n            'pattern': pattern,\n            'timestamp': datetime.now().isoformat()\n        })\n        if severity > self.threat_level:\n            self.threat_level = severity\n    \n    def add_warning(self, warning_type, message):\n        \"\"\"Record a warning\"\"\"\n        self.warnings.append({\n            'type': warning_type,\n            'message': message\n        })\n        if self.threat_level == 0:\n            self.threat_level = 1\n    \n    def generate_report(self):\n        \"\"\"Generate security scan report\"\"\"\n        return {\n            'threat_level': self.threat_level,\n            'status': self.get_status(),\n            'violations': self.violations,\n            'warnings': self.warnings,\n            'summary': self.get_summary()\n        }\n    \n    def get_status(self):\n        \"\"\"Get security status\"\"\"\n        if self.threat_level >= 3:\n            return 'CRITICAL_BLOCK_AND_REPORT'\n        elif self.threat_level == 2:\n            return 'BLOCK'\n        elif self.threat_level == 1:\n            return 'WARNING'\n        else:\n            return 'SAFE'\n    \n    def get_summary(self):\n        \"\"\"Get human-readable summary\"\"\"\n        if self.threat_level >= 3:\n            return f\"🚨 CRITICAL: {len(self.violations)} severe violations detected. DO NOT SEND. REPORT REQUIRED.\"\n        elif self.threat_level == 2:\n            return f\"🛑 BLOCKED: {len(self.violations)} violations detected. Cannot format this email.\"\n        elif self.threat_level == 1:\n            return f\"⚠️  WARNING: {len(self.warnings)} potential issues detected. Review carefully.\"\n        else:\n            return \"✅ No security issues detected.\"\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Usage: python3 security_scan.py 'email text'\")\n        sys.exit(1)\n    \n    scanner = SecurityScanner()\n    report = scanner.scan(sys.argv[1])\n    \n    # Print report\n    print(f\"\\n{'='*60}\")\n    print(f\"SECURITY SCAN REPORT\")\n    print(f\"{'='*60}\")\n    print(f\"Status: {report['status']}\")\n    print(f\"Threat Level: {report['threat_level']}/3\")\n    print(f\"\\n{report['summary']}\\n\")\n    \n    if report['violations']:\n        print(\"VIOLATIONS:\")\n        for v in report['violations']:\n            severity_icon = \"🚨\" if v['severity'] >= 3 else \"🛑\"\n            print(f\"  {severity_icon} {v['type']}\")\n            print(f\"      Pattern: {v['pattern'][:50]}...\")\n    \n    if report['warnings']:\n        print(\"\\nWARNINGS:\")\n        for w in report['warnings']:\n            print(f\"  ⚠️  {w['type']}: {w['message']}\")\n    \n    print(f\"\\n{'='*60}\\n\")\n    \n    # Return appropriate exit code\n    sys.exit(report['threat_level'])\n\nUsage Workflow for AI Agents\n\nMANDATORY SECURITY-FIRST WORKFLOW:\n\n#!/bin/bash\n# Email Formatter - Secure Processing Pipeline\n# This workflow is REQUIRED for every email formatting request\n\nset -e  # Exit on any error\n\nEMAIL_TEXT=\"$1\"\nTEMP_DIR=\"/tmp/email-formatter-$$\"\nmkdir -p \"$TEMP_DIR\"\n\necho \"🔒 Starting Secure Email Processing Pipeline...\"\necho \"================================================\"\n\n# STEP 1: PRE-FLIGHT SECURITY SCAN (CRITICAL)\necho \"Step 1/7: Running security scan...\"\npython3 ~/.email-formatter-skill/scripts/security_scan.py \"$EMAIL_TEXT\"\nSECURITY_EXIT=$?\n\nif [ $SECURITY_EXIT -eq 3 ]; then\n    echo \"\"\n    echo \"🚨🚨🚨 CRITICAL SECURITY VIOLATION 🚨🚨🚨\"\n    echo \"This email contains SEVERE violations that must be reported.\"\n    echo \"Formatting REFUSED. Potential illegal activity detected.\"\n    echo \"\"\n    echo \"ACTIONS REQUIRED:\"\n    echo \"1. Do NOT send this email\"\n    echo \"2. Document the incident\"\n    echo \"3. Report to appropriate authorities if applicable\"\n    echo \"4. Inform user of violation\"\n    exit 3\n\nelif [ $SECURITY_EXIT -eq 2 ]; then\n    echo \"\"\n    echo \"🛑 SECURITY BLOCK\"\n    echo \"This email violates safety policies and cannot be formatted.\"\n    echo \"Review the security report above for specific violations.\"\n    echo \"\"\n    echo \"SUGGESTED ACTIONS:\"\n    echo \"1. Identify the specific violation\"\n    echo \"2. Explain to user why it's blocked\"\n    echo \"3. Suggest legitimate alternatives\"\n    echo \"4. Offer to help rewrite with appropriate content\"\n    exit 2\n\nelif [ $SECURITY_EXIT -eq 1 ]; then\n    echo \"\"\n    echo \"⚠️  SECURITY WARNING\"\n    echo \"Potential issues detected. Proceeding with caution...\"\n    echo \"Will re-scan after formatting to ensure no issues introduced.\"\n    echo \"\"\nfi\n\n# STEP 2: CONTENT ANALYSIS\necho \"\"\necho \"Step 2/7: Analyzing content...\"\necho \"$EMAIL_TEXT\" > \"$TEMP_DIR/original.txt\"\n\n# Word count\nWORD_COUNT=$(echo \"$EMAIL_TEXT\" | wc -w)\necho \"   📊 Word count: $WORD_COUNT\"\n\nif [ $WORD_COUNT -gt 500 ]; then\n    echo \"   ⚠️  Email is very long. Consider breaking into multiple emails.\"\nfi\n\n# STEP 3: TONE ANALYSIS\necho \"\"\necho \"Step 3/7: Analyzing tone...\"\npython3 ~/.email-formatter-skill/scripts/tone_analyzer.py \"$EMAIL_TEXT\" > \"$TEMP_DIR/tone.txt\"\ncat \"$TEMP_DIR/tone.txt\"\n\n# Check if tone is aggressive\nif grep -q \"AGGRESSIVE\" \"$TEMP_DIR/tone.txt\"; then\n    echo \"\"\n    echo \"   ⚠️  AGGRESSIVE TONE DETECTED\"\n    echo \"   Recommendation: Suggest user wait 24 hours before sending\"\n    echo \"   Offer to rewrite in professional, constructive tone\"\n    echo \"\"\n    read -p \"   Continue anyway? (yes/no): \" CONTINUE\n    if [ \"$CONTINUE\" != \"yes\" ]; then\n        echo \"   Formatting cancelled by tone check.\"\n        exit 1\n    fi\nfi\n\n# STEP 4: GRAMMAR CHECK\necho \"\"\necho \"Step 4/7: Checking grammar...\"\npython3 ~/.email-formatter-skill/scripts/grammar_check.py \"$EMAIL_TEXT\"\n\n# STEP 5: READABILITY ANALYSIS\necho \"\"\necho \"Step 5/7: Analyzing readability...\"\npython3 ~/.email-formatter-skill/scripts/readability.py \"$EMAIL_TEXT\" > \"$TEMP_DIR/readability.txt\"\ncat \"$TEMP_DIR/readability.txt\"\n\n# STEP 6: FORMAT THE EMAIL\necho \"\"\necho \"Step 6/7: Formatting email...\"\necho \"   [Agent applies formatting rules based on guidelines]\"\n# ... AI agent performs formatting here ...\n# FORMATTED_EMAIL=\"...\"\n\n# STEP 7: POST-FORMATTING SECURITY RE-SCAN (CRITICAL)\necho \"\"\necho \"Step 7/7: Final security validation...\"\npython3 ~/.email-formatter-skill/scripts/security_scan.py \"$FORMATTED_EMAIL\"\nFINAL_SECURITY=$?\n\nif [ $FINAL_SECURITY -ne 0 ]; then\n    echo \"\"\n    echo \"🚨 POST-FORMATTING SECURITY FAILURE\"\n    echo \"Formatted version introduced security issues!\"\n    echo \"This should never happen - formatting logic has a bug.\"\n    echo \"Reverting to original and blocking output.\"\n    exit 2\nfi\n\n# SUCCESS\necho \"\"\necho \"✅ All security checks passed\"\necho \"✅ Email formatted successfully\"\necho \"\"\necho \"================================================\"\necho \"FORMATTED EMAIL READY FOR REVIEW\"\necho \"================================================\"\n\n# Cleanup\nrm -rf \"$TEMP_DIR\"\n\nCritical Enforcement Rules for AI Agents\n\nNEVER SKIP SECURITY SCANS:\n\nSecurity scan must run BEFORE any formatting\nSecurity scan must run AFTER formatting\nBoth scans must pass (exit 0) for email to be delivered\nExit codes 1, 2, 3 MUST stop the pipeline\n\nDOUBLE-CHECK MECHANISM:\n\n# Before presenting formatted email to user\ndef final_validation(formatted_email):\n    # Re-run all security checks\n    security_clear = run_security_scan(formatted_email)\n    \n    if not security_clear:\n        # NEVER show formatted email\n        return {\n            'status': 'BLOCKED',\n            'message': 'Formatting introduced security issues',\n            'action': 'Report bug in formatting logic'\n        }\n    \n    # Additional checks\n    if contains_pii(formatted_email):\n        return {\n            'status': 'WARNING',\n            'message': 'PII detected in formatted email',\n            'action': 'Warn user about sending sensitive data via email'\n        }\n    \n    return {\n        'status': 'APPROVED',\n        'formatted_email': formatted_email\n    }\n\n\nLogging & Audit Trail (Privacy-Safe):\n\n# Log violations only (NO content)\ndef log_security_event(violation_type, severity, timestamp):\n    \"\"\"\n    Log security events for monitoring\n    NEVER log actual email content\n    \"\"\"\n    log_entry = {\n        'timestamp': timestamp,\n        'violation_type': violation_type,\n        'severity': severity,\n        'action_taken': 'BLOCKED',\n        'content': '[REDACTED]'  # Never log content\n    }\n    # Append to secure audit log\n    # This helps improve security detection\n\nWhen to Use This Skill\n\nUse this skill when the user needs to:\n\nFix grammar, spelling, and punctuation in emails\nAdjust tone (make more formal, casual, friendly, or assertive)\nStructure messy drafts into clear, organized messages\nConvert bullet points or notes into complete emails\nAdd professional greetings and closings\nImprove clarity and conciseness\nPrepare important messages for executives, clients, or stakeholders\nCore Principles\nPreserve Intent: Never change the core message or facts - only improve how it's communicated\nMatch Context: Adjust formality based on recipient and situation\nEnhance Clarity: Remove ambiguity while maintaining natural voice\nProfessional Standard: Apply business writing best practices\nCultural Awareness: Consider professional norms and communication styles\nFormatting Process\nStep 1: Analyze the Draft\n\nBefore formatting, assess:\n\nRecipient relationship: Boss, colleague, client, vendor, team, external?\nPurpose: Request, update, introduction, follow-up, feedback, apology?\nTone needed: Formal, semi-formal, casual, friendly, assertive, diplomatic?\nUrgency: Routine, important, urgent, sensitive?\nCurrent issues: Grammar errors, unclear structure, wrong tone, missing context?\nStep 2: Apply Improvements\n\nGrammar & Mechanics:\n\nFix spelling, punctuation, and grammatical errors\nCorrect subject-verb agreement and tense consistency\nRemove run-on sentences and fragments\nFix comma splices and misplaced modifiers\n\nStructure & Organization:\n\nStandard Email Structure:\n1. Greeting (appropriate to relationship)\n2. Opening (context or pleasantry)\n3. Purpose statement (clear and direct)\n4. Body (organized by topic, use paragraphs/bullets)\n5. Call to action (if needed)\n6. Closing (polite sign-off)\n7. Signature\n\n\nTone Adjustments:\n\nToo Casual → Professional:\n\nBefore: \"Hey! Just wanted to check if u got my last email lol\"\nAfter: \"Hi Sarah, I wanted to follow up on my previous email from Tuesday. Please let me know if you need any additional information.\"\n\n\nToo Formal → Friendly:\n\nBefore: \"I am writing to inquire whether you have completed the aforementioned task.\"\nAfter: \"Hi John, I wanted to check in on the status of the marketing report. How's it coming along?\"\n\n\nToo Aggressive → Diplomatic:\n\nBefore: \"You need to fix this immediately. This is unacceptable.\"\nAfter: \"I noticed an issue that requires urgent attention. Could we prioritize resolving this today? I'm happy to help if needed.\"\n\n\nClarity Enhancements:\n\nReplace vague phrases with specific language\nBreak long paragraphs into digestible chunks\nUse bullet points for lists or multiple items\nAdd context where assumed knowledge might be missing\nRemove redundancy and filler words\nStep 3: Polish Details\n\nSubject Line (if provided or needed):\n\nKeep it under 50 characters\nMake it specific and actionable\nUse sentence case (not all caps)\nExamples:\n\"Q1 Budget Review Meeting - March 15\"\n\"Quick question about project timeline\"\n\"Following up: Website redesign proposal\"\n\nGreetings:\n\nFormal: \"Dear Dr. Smith,\" or \"Dear Hiring Manager,\"\nProfessional: \"Hi Jennifer,\" or \"Hello Team,\"\nCasual: \"Hey Alex,\" or \"Hi everyone,\"\n\nClosings:\n\nFormal: \"Sincerely,\" \"Respectfully,\" \"Best regards,\"\nProfessional: \"Best,\" \"Thanks,\" \"Looking forward to hearing from you,\"\nCasual: \"Cheers,\" \"Talk soon,\" \"Have a great day,\"\n\nSignature Block:\n\nBest regards,\n[Name]\n[Title]\n[Company]\n[Contact Info - if external]\n\nCommon Email Scenarios\n1. Request Email\nStructure:\n- Greeting\n- Context (why you're writing)\n- Specific request\n- Deadline or timeframe (if applicable)\n- Offer of additional info\n- Thanks\n- Closing\n\n2. Follow-Up Email\nStructure:\n- Reference previous communication\n- Polite reminder of action needed\n- Make it easy to respond\n- Maintain friendly tone\n- Closing\n\n3. Bad News Email\nStructure:\n- Direct but empathetic opening\n- Clear explanation\n- Acknowledge impact\n- Offer alternatives or next steps\n- End on positive note if possible\n\n4. Introduction Email\nStructure:\n- Who you are and connection\n- Purpose of introduction\n- What you're offering/requesting\n- Call to action\n- Professional closing\n\nBest Practices\nDO:\n\n✅ Keep emails concise (under 200 words when possible) ✅ Use active voice (\"I will send\" vs \"It will be sent\") ✅ Break up text with white space ✅ Put most important info in first paragraph ✅ Proofread for typos and auto-correct errors ✅ Use \"Reply All\" judiciously ✅ Include clear next steps or calls to action ✅ Match the sender's energy level\n\nDON'T:\n\n❌ Use all caps (seems like shouting) ❌ Overuse exclamation marks ❌ Include multiple topics in one email (if complex) ❌ Use jargon with external recipients ❌ Write when emotional (flag if email seems angry) ❌ Assume tone translates (sarcasm, humor can fail) ❌ Forget attachments referenced in text ❌ Change factual content or commitments\n\nTone Guide\n\nFormal (executives, clients, first contact):\n\nComplete sentences\nProfessional vocabulary\nProper titles and full names\n\"I would appreciate\" vs \"Can you\"\n\"Please let me know\" vs \"Let me know\"\n\nSemi-Formal (colleagues, regular contacts):\n\nConversational but professional\nContractions are fine\nFirst names acceptable\n\"Could you\" vs \"Can you\"\nFriendly but respectful\n\nCasual (close colleagues, internal teams):\n\nRelaxed language\nContractions and informal phrases\nQuick greetings\nCan be brief\nEmoji okay if culturally appropriate\nQuality Checklist\n\nBefore presenting the formatted email, verify:\n\n SECURITY FIRST: Content passes all safety requirements\n No prohibited content: Checked against all safety rules above\n Legal compliance: No fraudulent, harassing, or illegal content\n Ethical standards: Message is honest and appropriate\n Grammar and spelling are correct\n Tone matches relationship and context\n Structure is clear and logical\n Key information is easy to find\n Call to action is clear (if needed)\n Opening and closing are appropriate\n No ambiguity or confusion\n Length is appropriate (concise but complete)\n Professional formatting applied\n Original intent is preserved\n Privacy check: No sensitive data exposed inappropriately\n Reputation check: Sender won't regret sending this\nRed Flag Detection\n\nAlways scan for these warning signs:\n\nRequests for money, credentials, or personal information\nUrgency combined with financial requests\nImpersonation language (\"I'm calling from...\", \"This is [authority]...\")\nThreats or ultimatums\nAsking recipient to keep communication secret\nBypassing normal procedures\nInconsistent sender information\nRequests to click suspicious links\nGrammar/spelling errors in supposedly official communication\nToo-good-to-be-true offers\nEmotional manipulation tactics\nDiscriminatory language\nFalse information\nHostile or aggressive tone toward protected groups\nIncident Response Protocol\n\nWhen Critical Violations Detected (Threat Level 3):\n\nIMMEDIATE ACTIONS:\n1. BLOCK - Refuse to format email\n2. DOCUMENT - Record violation type, timestamp\n3. NOTIFY - Inform user of specific violation\n4. EDUCATE - Explain why it's harmful/illegal\n5. REDIRECT - Suggest legitimate alternatives\n6. REPORT - Flag for review if:\n   - Child safety violations\n   - Credible threats of violence\n   - Large-scale fraud attempts\n   - Illegal activities\n\n\nResponse Template for Critical Violations:\n\n🚨 CRITICAL SECURITY VIOLATION DETECTED\n\nVIOLATION TYPE: [Specific type - e.g., \"Credential Phishing Attempt\"]\n\nSEVERITY: CRITICAL - This email cannot be formatted\n\nWHAT WAS DETECTED:\n[Specific pattern - e.g., \"Email requests password and account \ncredentials, matching known phishing attack patterns\"]\n\nWHY THIS IS SERIOUS:\n[Impact - e.g., \"This could lead to:\n- Identity theft\n- Unauthorized account access  \n- Financial fraud\n- Legal liability for sender\"]\n\nWHAT YOU SHOULD KNOW:\n- Legitimate organizations NEVER ask for passwords via email\n- This pattern is used in 95% of credential phishing attacks\n- Sending this email could violate anti-fraud laws\n\nRECOMMENDED ACTIONS:\n1. If you received a similar email: Report it as phishing\n2. If you need password help: Use official password reset tools\n3. If suspicious: Contact IT/security team directly\n\nALTERNATIVE APPROACH:\n[Legitimate way to accomplish goal if applicable]\n\n---\nThis email has been blocked to protect you and recipients.\nFor questions about this decision, review security guidelines.\n\nSecurity Metrics & Monitoring\n\nTrack these metrics (content-free):\n\nSECURITY_METRICS = {\n    'total_scans': 0,\n    'threats_blocked': {\n        'level_1_warnings': 0,\n        'level_2_blocks': 0,\n        'level_3_critical': 0\n    },\n    'violation_types': {\n        'phishing': 0,\n        'fraud': 0,\n        'threats': 0,\n        'harassment': 0,\n        'impersonation': 0,\n        'pii_exposure': 0,\n        'malware': 0,\n        'child_safety': 0\n    },\n    'false_positives_reported': 0,\n    'scan_performance_ms': []\n}\n\n\nRegular Security Audits:\n\nReview blocked emails (patterns only, no content)\nUpdate detection patterns based on new threats\nTune sensitivity to reduce false positives\nImprove educational messages\nAdd new threat categories as they emerge\nPrivacy & Data Protection Compliance\n\nGDPR/CCPA/HIPAA Compliance:\n\nDATA_PROTECTION_RULES = {\n    'data_minimization': 'Process only what's needed for formatting',\n    'purpose_limitation': 'Use data ONLY for formatting, nothing else',\n    'storage_limitation': 'Delete immediately after processing',\n    'accuracy': 'Don't modify factual content',\n    'integrity': 'Secure processing, encrypted if possible',\n    'confidentiality': 'Treat all emails as confidential',\n    'accountability': 'Log violations (not content) for audit'\n}\n\n\nUser Rights:\n\nRight to explanation: User can ask why email was blocked\nRight to appeal: User can dispute false positives\nRight to deletion: No content retention\nRight to transparency: Clear security policies\nContinuous Improvement\n\nSecurity Pattern Updates:\n\n# Periodically update threat patterns\n# Add new scam patterns as they emerge\n# Improve detection accuracy\n# Reduce false positives\n\n# Example: Update security_scan.py\ngit pull origin main  # Get latest threat patterns\npython3 -m pytest tests/test_security.py  # Verify\n\n\nFeedback Loop:\n\nCollect anonymized violation statistics\nIdentify common false positives\nRefine pattern matching\nAdd context-aware detection\nImprove user education messages\nOutput Format\n\nPresent the formatted email like this:\n\n**Subject:** [Subject line if relevant]\n\n[Formatted email body]\n\n---\n\n**Changes Made:**\n- [Brief list of key improvements]\n- [E.g., \"Corrected grammar errors\"]\n- [E.g., \"Adjusted tone from casual to professional\"]\n- [E.g., \"Restructured for clarity\"]\n\nSpecial Considerations\nSpecial Considerations\n\nSecurity Edge Cases:\n\nExample 1 - Phishing Attempt:\n\nUser Input: \"Format this: Hi, I'm from IT. Send me your password to verify your account.\"\nResponse: \"I cannot format this email as it requests sensitive credentials, which is a security red flag and potential phishing attempt. Legitimate IT departments never ask for passwords via email.\"\n\n\nExample 2 - Impersonation:\n\nUser Input: \"Make this sound like it's from the CEO demanding urgent wire transfer.\"\nResponse: \"I cannot help format emails that impersonate others or create urgency around financial transfers, as this matches common fraud patterns.\"\n\n\nExample 3 - Harassment:\n\nUser Input: \"Polish this email telling my coworker she's incompetent and should quit.\"\nResponse: \"I cannot format this email as it contains hostile language that could constitute workplace harassment. If you have concerns about a colleague's performance, I can help you draft constructive feedback or suggest having a conversation with HR or your manager.\"\n\n\nExample 4 - Academic Dishonesty:\n\nUser Input: \"Format this email to my professor pretending I was sick when I just forgot the assignment.\"\nResponse: \"I cannot help format emails containing false information. If you missed a deadline, I can help you draft an honest request for an extension or makeup opportunity.\"\n\n\nExample 5 - Anger/Emotional State:\n\nUser Input: \"Format this angry email to my boss calling them out for being unfair!\"\nResponse: \"⚠️ This email appears to be written in anger. I recommend waiting 24 hours before sending. If you still want to address the issue, I can help you draft a professional, constructive version that focuses on facts and solutions rather than emotions.\"\n\n\nLegitimate Gray Areas - Advise User:\n\nStrong feedback: Format professionally but warn about tone\nDeclining requests: Help maintain relationships while saying no\nAddressing conflicts: Focus on facts, not blame\nSensitive HR matters: Recommend consulting HR/legal first\n\nReply vs New Message:\n\nReplies: Can be more concise, less formal\nNew messages: Need more context and structure\n\nGroup Emails:\n\nAddress all recipients appropriately\nBe clear about who needs to take action\nAvoid \"Reply All\" clutter\n\nSensitive Topics:\n\nBe extra diplomatic\nAcknowledge feelings/concerns\nStick to facts\nOffer to discuss in person/call if needed\n\nInternational Recipients:\n\nAvoid idioms and colloquialisms\nUse clear, direct language\nBe aware of cultural communication differences\nSpell out dates (avoid 3/4/24 format ambiguity)\n\nMobile Email:\n\nFront-load most important info\nUse shorter paragraphs\nLimit to one topic if possible\nClear subject lines are crucial\nCommon Mistakes to Avoid\nStarting with apologies: \"Sorry to bother you\" → \"I hope this email finds you well\"\nBuried lede: Put main point in first paragraph\nToo many questions: Limit to 1-2 per email\nPassive voice overuse: \"The report was completed\" → \"I completed the report\"\nUnclear next steps: Always specify what happens next\nOver-explaining: Be concise; don't over-justify\nMissing context: Assume recipient doesn't remember previous discussion\nInconsistent tone: Maintain same formality throughout\nAdvanced Techniques\n\nThe BLUF Method (Bottom Line Up Front):\n\nState conclusion/request first\nProvide supporting details after\nIdeal for busy executives\n\nChunking Information:\n\nUse subheadings for long emails\nBullet points for lists\nBold key phrases for scanning\n\nCall to Action Clarity:\n\n\"Please review and approve by Friday EOD\"\n\"Let me know if you have questions\"\n\"I'll send the draft by Thursday for your feedback\"\n\nSoftening Requests:\n\n\"Would you be able to...\" vs \"Can you...\"\n\"I was wondering if...\" vs \"I need...\"\n\"If possible...\" vs \"Please...\"\nVersion History\nv1.0.0 (2024): Initial release with core formatting capabilities\nLicense\n\nMIT License - Free to use and modify\n\nPro Tip for Users: For best results, provide context about the recipient relationship and email purpose. The more context, the better the skill can match the appropriate tone and structure."
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/cerbug45/email-formatter-skill",
    "publisherUrl": "https://clawhub.ai/cerbug45/email-formatter-skill",
    "owner": "cerbug45",
    "version": "0.1.0",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/email-formatter-skill",
    "downloadUrl": "https://openagent3.xyz/downloads/email-formatter-skill",
    "agentUrl": "https://openagent3.xyz/skills/email-formatter-skill/agent",
    "manifestUrl": "https://openagent3.xyz/skills/email-formatter-skill/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/email-formatter-skill/agent.md"
  }
}