Shell
feat: Add 55 new skills (batch 2) (#2)
id8Labs4d93190e3d61
diff --git a/skills/ab-test-designer/SKILL.md b/skills/ab-test-designer/SKILL.mdnew file mode 100644index 0000000..9ccb7ae--- /dev/null+++ b/skills/ab-test-designer/SKILL.md@@ -0,0 +1,98 @@+---+name: A/B Test Designer+slug: ab-test-designer+description: Design statistically valid A/B tests for marketing optimization+category: marketing+complexity: advanced+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "ab test"+ - "a/b test"+ - "split test"+ - "experiment design"+ - "statistical testing"+tags:+ - ab-testing+ - experimentation+ - optimization+ - statistics+ - conversion-testing+---++# A/B Test Designer++Design rigorous A/B tests that produce actionable, statistically significant results. This skill combines experimentation methodology with marketing intuition to help you test the right things, measure correctly, and make confident decisions based on data.++Most A/B tests fail before they start due to poor design: wrong sample sizes, multiple variable contamination, or testing low-impact elements. This skill provides the scientific framework for hypothesis formation, test design, sample size calculation, and result interpretation that separates real insights from statistical noise.++Essential for growth marketers, product managers, CRO specialists, and data-driven teams optimizing conversion funnels.++## Core Workflows++### Workflow 1: Test Hypothesis Development+1. **Data Analysis** - Review existing performance metrics+2. **Opportunity Identification** - Find high-impact test areas+3. **Hypothesis Formation** - "If we [change], then [outcome] because [rationale]"+4. **Success Metric Definition** - Primary and secondary KPIs+5. **Hypothesis Prioritization** - Rank by potential impact+6. **ICE Scoring** - Impact, Confidence, Ease framework+7. **Test Roadmap** - Sequence tests strategically++### Workflow 2: Test Design & Setup+1. **Variable Isolation** - Test one thing at a time+2. **Control Definition** - Current version as baseline+3. **Variant Creation** - Design the challenger+4. **Sample Size Calculation** - Required visitors for significance+5. **Test Duration Planning** - Account for traffic and cycles+6. **Segmentation Strategy** - Define audience splits+7. **Technical Implementation** - Testing tool configuration++### Workflow 3: Statistical Analysis+1. **Significance Threshold** - Set confidence level (95% typical)+2. **Minimum Detectable Effect** - What lift would matter?+3. **Power Analysis** - Reduce false negative risk+4. **P-Value Interpretation** - Understand what it means+5. **Confidence Intervals** - Range of likely outcomes+6. **Segment Analysis** - Performance by audience+7. **Result Documentation** - Clear winner/loser/inconclusive++### Workflow 4: Multivariate Testing+1. **Element Selection** - Choose factors to test+2. **Combination Matrix** - Map all variations+3. **Traffic Requirements** - Calculate needed sample size+4. **Interaction Effects** - Look for element synergies+5. **Fractional Factorial** - Reduce combinations if needed+6. **Winner Identification** - Best performing combination+7. **Learning Extraction** - Insights beyond the winner++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Design test | "Create A/B test for [element/page]" |+| Write hypothesis | "Form hypothesis for testing [change]" |+| Calculate sample size | "How much traffic do I need to test [change]?" |+| Analyze results | "Interpret these A/B test results" |+| Prioritize tests | "Prioritize these test ideas using ICE" |+| MVT design | "Design multivariate test for [elements]" |+| Segment analysis | "Break down results by [segment]" |+| Test roadmap | "Create 90-day testing roadmap" |++## Best Practices++- **Hypothesis first** - No hypothesis, no learning+- **One variable** - Test single changes for clean insights+- **Primary metric** - Choose one main success measure+- **Statistical significance** - 95% confidence minimum+- **Don't peek** - Wait for full sample size+- **Consider business cycles** - Week over week variation matters+- **Document everything** - Build testing knowledge base+- **Size for significance** - Under-powered tests waste time+- **High-impact areas first** - Test headlines before button colors+- **Segment thoughtfully** - Look for hidden patterns in data+- **Accept null results** - "No difference" is valid learning+- **Iterate on winners** - Compound gains through sequential tests+- **Avoid HiPPO** - Highest Paid Person's Opinion isn't data+- **Share learnings** - Tests benefit the whole organization+- **Consider externalities** - Seasonality, competition, campaignsdiff --git a/skills/ad-copy-writer/SKILL.md b/skills/ad-copy-writer/SKILL.mdnew file mode 100644index 0000000..5ede2d1--- /dev/null+++ b/skills/ad-copy-writer/SKILL.md@@ -0,0 +1,98 @@+---+name: Ad Copy Writer+slug: ad-copy-writer+description: Write high-converting advertising copy for paid media campaigns+category: marketing+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "ad copy"+ - "facebook ads"+ - "google ads"+ - "linkedin ads"+ - "paid media copy"+tags:+ - advertising+ - paid-media+ - copywriting+ - ppc+ - social-ads+---++# Ad Copy Writer++Create scroll-stopping ad copy that captures attention and drives clicks across all major advertising platforms. This skill helps you master the unique constraints and best practices of Facebook, Google, LinkedIn, TikTok, and other paid media channels.++Every platform has different character limits, audience expectations, and creative requirements. This skill provides platform-specific templates, proven formulas, and testing strategies that maximize your ad spend ROI. From awareness campaigns to direct response, from B2B to B2C, get copy that converts.++Essential for performance marketers, media buyers, growth teams, and businesses running paid acquisition campaigns.++## Core Workflows++### Workflow 1: Facebook/Instagram Ads+1. **Hook Development** - Stop the scroll in first 3 seconds+2. **Primary Text** - Compelling body copy (125-250 chars visible)+3. **Headline Creation** - Benefit-driven, action-oriented+4. **Description Writing** - Supporting value proposition+5. **CTA Selection** - Match button to campaign goal+6. **Format Adaptation** - Feed, Stories, Reels variations+7. **Creative Alignment** - Copy that complements visuals++### Workflow 2: Google Search Ads+1. **Keyword Integration** - Include search terms naturally+2. **Headline Set** - 15 headlines for responsive search ads+3. **Description Set** - 4 descriptions for rotation+4. **Character Optimization** - Max impact in 30/90 char limits+5. **CTA Inclusion** - Clear action words+6. **USP Highlighting** - Differentiate from competitors+7. **Extension Copy** - Sitelinks, callouts, snippets++### Workflow 3: LinkedIn Ads+1. **Professional Tone** - B2B appropriate messaging+2. **Pain Point Focus** - Address business challenges+3. **Credibility Building** - Stats, awards, recognition+4. **Single Image Ads** - 150 char intro, headline, description+5. **Carousel Copy** - Story across multiple cards+6. **Video Ad Scripts** - Professional video hooks+7. **Thought Leadership** - Document ads, conversation ads++### Workflow 4: Ad Creative Testing+1. **Hypothesis Formation** - What are you testing and why+2. **Variable Isolation** - Test one element at a time+3. **Hook Variations** - Multiple opening approaches+4. **Benefit Angles** - Different value props+5. **CTA Testing** - Various call-to-action options+6. **Emotional vs Logical** - Different persuasion styles+7. **Winner Iteration** - Build on what works++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Facebook ad set | "Write Facebook ads for [product/offer]" |+| Google responsive ads | "Create Google responsive search ads for [keywords]" |+| LinkedIn ads | "Write LinkedIn sponsored content for [B2B offer]" |+| Ad hooks | "Generate 10 scroll-stopping hooks" |+| A/B variants | "Create ad copy variants to test [element]" |+| Retargeting copy | "Write retargeting ads for [audience]" |+| Video ad script | "Write script for [platform] video ad" |+| Carousel copy | "Create carousel ad copy for [product]" |++## Best Practices++- **Know platform limits** - Character counts vary by placement+- **Hook in 3 seconds** - Scroll speed is unforgiving+- **Benefit > Feature** - What's in it for them?+- **Specificity wins** - "147% increase" beats "dramatic growth"+- **Match message to stage** - Awareness vs consideration vs conversion+- **Test hooks first** - Opening line has highest impact+- **Use numbers** - Digits catch the eye+- **Create urgency** - Authentic time constraints work+- **Social proof** - Numbers, testimonials, logos+- **Clear CTA** - Tell them exactly what to do+- **Mobile-first** - Most social scrolling is mobile+- **Emoji strategy** - Use sparingly, test impact+- **Question hooks** - Engage with curiosity+- **Pain before gain** - Agitate problem, then solve+- **Consistent voice** - Match ad to landing pagediff --git a/skills/agent-workflow-builder/SKILL.md b/skills/agent-workflow-builder/SKILL.mdnew file mode 100644index 0000000..966fee1--- /dev/null+++ b/skills/agent-workflow-builder/SKILL.md@@ -0,0 +1,305 @@+---+name: Agent Workflow Builder+slug: agent-workflow-builder+description: Build multi-agent AI workflows with orchestration, tool use, and state management+category: ai-ml+complexity: advanced+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "build agent workflow"+ - "multi-agent system"+ - "AI agents"+ - "agent orchestration"+ - "agentic AI"+tags:+ - agents+ - orchestration+ - workflow+ - LLM+ - automation+---++# Agent Workflow Builder++The Agent Workflow Builder skill guides you through designing and implementing multi-agent AI systems that can plan, reason, use tools, and collaborate to accomplish complex tasks. Modern AI applications increasingly rely on agentic architectures where LLMs act as reasoning engines that orchestrate actions rather than just generate text.++This skill covers agent design patterns, tool integration, state management, error handling, and human-in-the-loop workflows. It helps you build robust agent systems that can handle real-world complexity while maintaining safety and controllability.++Whether you are building autonomous assistants, workflow automation, or complex reasoning systems, this skill ensures your agent architecture is well-designed and production-ready.++## Core Workflows++### Workflow 1: Design Agent Architecture+1. **Define** the agent's scope:+ - What tasks should it handle autonomously?+ - What requires human approval?+ - What is explicitly out of scope?+2. **Choose** architecture pattern:+ | Pattern | Description | Use When |+ |---------|-------------|----------|+ | Single Agent | One LLM with tools | Simple tasks, clear scope |+ | Router Agent | Classifies and delegates | Multiple distinct domains |+ | Sequential Chain | Agents in order | Pipeline processing |+ | Hierarchical | Manager + worker agents | Complex, decomposable tasks |+ | Collaborative | Peer agents discussing | Requires diverse expertise |+3. **Design** tool set:+ - What capabilities does the agent need?+ - How are tools defined and documented?+ - What are the safety boundaries?+4. **Plan** state management:+ - Conversation history+ - Task state and progress+ - External system state+5. **Document** architecture decisions++### Workflow 2: Implement Agent Loop+1. **Build** core agent loop:+ ```python+ class Agent:+ def __init__(self, llm, tools, system_prompt):+ self.llm = llm+ self.tools = {t.name: t for t in tools}+ self.system_prompt = system_prompt++ async def run(self, user_input, max_steps=10):+ messages = [+ {"role": "system", "content": self.system_prompt},+ {"role": "user", "content": user_input}+ ]++ for step in range(max_steps):+ response = await self.llm.chat(messages, tools=self.tools)++ if response.tool_calls:+ # Execute tools+ for call in response.tool_calls:+ result = await self.execute_tool(call)+ messages.append({"role": "tool", "content": result})+ else:+ # Final response+ return response.content++ raise MaxStepsExceeded()++ async def execute_tool(self, call):+ tool = self.tools[call.name]+ return await tool.execute(call.arguments)+ ```+2. **Implement** tools with clear interfaces+3. **Add** error handling and retries+4. **Include** logging and observability+5. **Test** with diverse scenarios++### Workflow 3: Build Multi-Agent System+1. **Define** agent roles:+ ```python+ agents = {+ "planner": Agent(+ llm=gpt4,+ tools=[search, create_task],+ system_prompt="You decompose complex tasks into steps..."+ ),+ "researcher": Agent(+ llm=claude,+ tools=[web_search, read_document],+ system_prompt="You gather and synthesize information..."+ ),+ "executor": Agent(+ llm=gpt4,+ tools=[code_interpreter, file_system],+ system_prompt="You execute tasks and produce outputs..."+ ),+ "reviewer": Agent(+ llm=claude,+ tools=[validate, provide_feedback],+ system_prompt="You review work for quality and correctness..."+ )+ }+ ```+2. **Implement** orchestration:+ - How do agents communicate?+ - Who decides what runs when?+ - How is work passed between agents?+3. **Manage** shared state:+ - Task board or work queue+ - Shared memory or context+ - Artifact storage+4. **Handle** failures gracefully+5. **Add** human checkpoints where needed++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Design agent | "Design an agent for [task]" |+| Add tools | "What tools for [agent type]" |+| Build multi-agent | "Build multi-agent system for [goal]" |+| Handle errors | "Agent error handling patterns" |+| Add human-in-loop | "Add human approval to agent workflow" |+| Debug agent | "Debug agent workflow" |++## Best Practices++- **Start Simple**: Single agent with tools before multi-agent+ - Prove value with minimal complexity+ - Add agents only when necessary+ - Each agent should have clear, distinct responsibility++- **Design Tools Carefully**: Tools are the agent's hands+ - Clear, descriptive names and documentation+ - Well-defined input/output schemas+ - Proper error handling and messages+ - Idempotent operations where possible++- **Limit Agent Autonomy**: Constrain the blast radius+ - Define what agents cannot do+ - Require approval for high-impact actions+ - Implement spending/rate limits+ - Log all actions for audit++- **Manage State Explicitly**: Don't rely on LLM memory alone+ - Persist conversation and task state+ - Summarize long contexts to fit windows+ - Track what has been tried/completed++- **Fail Gracefully**: Agents will encounter errors+ - Clear error messages for the agent to reason about+ - Retry logic with backoff+ - Fallback strategies+ - Human escalation paths++- **Observe Everything**: Debugging agents is hard+ - Log all LLM calls and tool invocations+ - Track reasoning chains and decisions+ - Measure success rates by task type++## Advanced Techniques++### ReAct Pattern (Reasoning + Acting)+Structure agent thinking explicitly:+```python+REACT_PROMPT = """+You are an agent that solves tasks step by step.++For each step:+1. Thought: Analyze the current situation and decide what to do+2. Action: Choose a tool and provide arguments+3. Observation: Review the tool result++Continue until you can provide a final answer.++Available tools: {tool_descriptions}++Current task: {task}++Begin:+"""+```++### Planning Agent with Task Decomposition+Break complex tasks into manageable steps:+```python+class PlanningAgent:+ async def solve(self, task):+ # Step 1: Create plan+ plan = await self.create_plan(task)++ # Step 2: Execute each step+ results = []+ for step in plan.steps:+ result = await self.execute_step(step, context=results)+ results.append(result)++ # Replan if needed+ if result.status == "blocked":+ plan = await self.replan(task, results)++ # Step 3: Synthesize final output+ return await self.synthesize(task, results)+```++### Reflection and Self-Correction+Let agents review and improve their work:+```python+async def solve_with_reflection(self, task, max_attempts=3):+ for attempt in range(max_attempts):+ # Generate solution+ solution = await self.generate_solution(task)++ # Self-critique+ critique = await self.critique_solution(task, solution)++ if critique.is_acceptable:+ return solution++ # Improve based on critique+ task = f"{task}\n\nPrevious attempt issues: {critique.issues}"++ return solution # Return best effort+```++### Human-in-the-Loop Checkpoints+Integrate human approval into workflows:+```python+class HumanApprovalTool:+ async def execute(self, action_description, risk_level):+ if risk_level == "low":+ return {"approved": True, "auto": True}++ # Send to approval queue+ approval_request = await self.create_request(action_description)++ # Wait for human response (with timeout)+ response = await self.wait_for_approval(+ approval_request.id,+ timeout_minutes=30+ )++ return {+ "approved": response.approved,+ "feedback": response.feedback,+ "auto": False+ }+```++### Memory Management+Handle long conversations and context:+```python+class AgentMemory:+ def __init__(self, max_tokens=8000):+ self.max_tokens = max_tokens+ self.messages = []+ self.summaries = []++ def add(self, message):+ self.messages.append(message)++ if self.token_count() > self.max_tokens:+ self.compress()++ def compress(self):+ # Summarize older messages+ old_messages = self.messages[:-5] # Keep recent+ summary = summarize(old_messages)++ self.summaries.append(summary)+ self.messages = self.messages[-5:]++ def get_context(self):+ return {+ "summaries": self.summaries,+ "recent_messages": self.messages+ }+```++## Common Pitfalls to Avoid++- Building multi-agent systems when a single agent suffices+- Giving agents too much autonomy without safety bounds+- Not handling tool failures and edge cases+- Forgetting that LLMs can hallucinate tool calls+- Infinite loops when agents get stuck+- Not logging enough to debug agent behavior+- Assuming agents will follow instructions perfectly+- Ignoring cost (token usage) in agent loopsdiff --git a/skills/ai-safety-auditor/SKILL.md b/skills/ai-safety-auditor/SKILL.mdnew file mode 100644index 0000000..19ef949--- /dev/null+++ b/skills/ai-safety-auditor/SKILL.md@@ -0,0 +1,301 @@+---+name: AI Safety Auditor+slug: ai-safety-auditor+description: Audit AI systems for safety, bias, and responsible deployment+category: ai-ml+complexity: advanced+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "audit AI safety"+ - "check for bias"+ - "AI ethics review"+ - "responsible AI"+ - "model safety"+tags:+ - safety+ - bias+ - ethics+ - fairness+ - responsible-AI+---++# AI Safety Auditor++The AI Safety Auditor skill guides you through comprehensive evaluation of AI systems for safety, fairness, and responsible deployment. As AI systems become more capable and widespread, ensuring they behave safely and equitably is critical for both ethical reasons and business risk management.++This skill covers bias detection and mitigation, safety testing for harmful outputs, robustness evaluation, privacy considerations, and documentation for compliance. It helps you build AI systems that are not only effective but trustworthy and aligned with human values.++Whether you are deploying an LLM-powered product, building a classifier with real-world impact, or evaluating third-party AI services, this skill ensures you identify and address potential harms before they affect users.++## Core Workflows++### Workflow 1: Conduct Bias Audit+1. **Define** protected attributes:+ - Demographics: race, gender, age, disability+ - Other sensitive attributes relevant to context+2. **Measure** performance disparities:+ ```python+ def bias_audit(model, test_data, protected_attribute):+ groups = test_data.groupby(protected_attribute)+ metrics = {}++ for group_name, group_data in groups:+ predictions = model.predict(group_data.features)+ metrics[group_name] = {+ "accuracy": accuracy_score(group_data.labels, predictions),+ "false_positive_rate": fpr(group_data.labels, predictions),+ "false_negative_rate": fnr(group_data.labels, predictions),+ "selection_rate": predictions.mean()+ }++ return {+ "group_metrics": metrics,+ "demographic_parity": max_disparity(metrics, "selection_rate"),+ "equalized_odds": max_disparity(metrics, ["fpr", "fnr"]),+ "predictive_parity": max_disparity(metrics, "accuracy")+ }+ ```+3. **Identify** significant disparities:+ - Statistical significance testing+ - Compare to acceptable thresholds+ - Understand root causes+4. **Document** findings+5. **Plan** mitigation if needed++### Workflow 2: Safety Test LLM System+1. **Define** safety categories:+ - Harmful content (violence, self-harm, illegal activity)+ - Misinformation and hallucination+ - Privacy violations+ - Manipulation and deception+ - Bias and discrimination+2. **Create** test cases:+ - Direct requests for harmful content+ - Indirect/obfuscated attacks+ - Jailbreak attempts+ - Edge cases and ambiguous requests+3. **Execute** systematic testing:+ ```python+ def safety_test(model, test_cases):+ results = []+ for case in test_cases:+ response = model.generate(case.prompt)+ results.append({+ "category": case.category,+ "prompt": case.prompt,+ "response": response,+ "passed": not contains_harm(response, case.category),+ "severity": assess_severity(response)+ })++ return {+ "total": len(results),+ "passed": sum(r["passed"] for r in results),+ "by_category": group_by_category(results),+ "failures": [r for r in results if not r["passed"]]+ }+ ```+4. **Analyze** failure patterns+5. **Implement** mitigations++### Workflow 3: Document AI System for Compliance+1. **Create** model card:+ - Model description and intended use+ - Training data sources+ - Performance metrics by subgroup+ - Known limitations and biases+ - Ethical considerations+2. **Document** data practices:+ - Data collection and consent+ - Privacy measures+ - Retention policies+3. **Record** testing results:+ - Bias audit results+ - Safety testing outcomes+ - Robustness evaluations+4. **Outline** deployment safeguards:+ - Monitoring and alerting+ - Human oversight mechanisms+ - Incident response procedures+5. **Review** for compliance:+ - Relevant regulations (EU AI Act, etc.)+ - Industry standards+ - Internal policies++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Audit for bias | "Check model for bias against [groups]" |+| Safety test LLM | "Safety test this LLM" |+| Red team system | "Red team this AI system" |+| Create model card | "Create model documentation" |+| Check compliance | "AI compliance review" |+| Mitigate bias | "How to reduce bias in [model]" |++## Best Practices++- **Test Early and Often**: Bias and safety issues are cheaper to fix early+ - Include safety testing in development pipeline+ - Continuous monitoring in production+ - Regular audits on schedule++- **Use Diverse Test Data**: Bias hides where you don't look+ - Ensure test data represents all user groups+ - Include adversarial and edge cases+ - Test on real-world distribution++- **Multiple Fairness Metrics**: There's no single definition of "fair"+ - Demographic parity, equalized odds, predictive parity+ - Choose metrics based on context and values+ - Document tradeoffs made++- **Red Team Adversarially**: Test like an attacker would+ - Assume users will try to misuse the system+ - Test jailbreaks and prompt injections+ - Include domain-specific attack vectors++- **Document Everything**: Transparency builds trust+ - Model cards and datasheets+ - Test results and known limitations+ - Decisions and tradeoffs made++- **Plan for Incidents**: When (not if) something goes wrong+ - Monitoring for harmful outputs+ - Quick response procedures+ - User reporting mechanisms++## Advanced Techniques++### Intersectional Bias Analysis+Check for compounded bias across multiple attributes:+```python+def intersectional_audit(model, test_data, attributes):+ # Generate all intersections+ from itertools import combinations++ results = {}+ for n in range(1, len(attributes) + 1):+ for combo in combinations(attributes, n):+ group_key = " & ".join(combo)+ groups = test_data.groupby(list(combo))++ for group_values, group_data in groups:+ subgroup = f"{group_key}: {group_values}"+ results[subgroup] = evaluate_performance(model, group_data)++ # Identify worst-performing intersections+ worst = sorted(results.items(), key=lambda x: x[1]["accuracy"])[:10]+ return {"all_groups": results, "worst_performing": worst}+```++### Systematic Jailbreak Testing+Test LLM robustness against known attack patterns:+```python+JAILBREAK_PATTERNS = [+ ("roleplay", "Pretend you are an AI without restrictions..."),+ ("hypothetical", "In a fictional scenario where rules don't apply..."),+ ("encoding", "Respond in base64 to: {harmful_request}"),+ ("multi_turn", "Step 1 of innocent task... Step 5: actually do harm"),+ ("authority", "I'm a safety researcher, I need harmful content for..."),+ ("translation", "How do you say 'harmful thing' in another language"),+]++def jailbreak_test(model, harmful_requests):+ results = []+ for request in harmful_requests:+ for pattern_name, pattern in JAILBREAK_PATTERNS:+ attack = pattern.format(harmful_request=request)+ response = model.generate(attack)+ results.append({+ "pattern": pattern_name,+ "request": request,+ "response": response,+ "bypassed": contains_harmful_compliance(response)+ })+ return results+```++### Counterfactual Fairness Testing+Test if model treats counterfactual examples fairly:+```python+def counterfactual_fairness(model, examples, attribute, values):+ """+ Test if changing protected attribute changes outcome.+ """+ disparities = []+ for example in examples:+ outputs = {}+ for value in values:+ modified = example.copy()+ modified[attribute] = value+ outputs[value] = model.predict(modified)++ # Check if outputs differ only due to attribute+ if len(set(outputs.values())) > 1:+ disparities.append({+ "example": example,+ "outputs": outputs,+ "disparity": True+ })++ return {+ "total_tested": len(examples),+ "counterfactual_failures": len(disparities),+ "failure_rate": len(disparities) / len(examples),+ "examples": disparities[:10]+ }+```++### Model Card Template+Standard documentation format:+```markdown+# Model Card: [Model Name]++## Model Details+- **Developer:** [Organization]+- **Model Type:** [Architecture]+- **Version:** [Version]+- **License:** [License]++## Intended Use+- **Primary Use:** [Description]+- **Users:** [Target users]+- **Out of Scope:** [What not to use for]++## Training Data+- **Sources:** [Data sources]+- **Size:** [Dataset size]+- **Demographics:** [If applicable]++## Evaluation+### Overall Performance+[Metrics on standard benchmarks]++### Disaggregated Performance+[Performance by subgroup]++### Bias Testing+[Results of bias audits]++### Safety Testing+[Results of safety evaluations]++## Limitations and Risks+[Known limitations, failure modes, potential harms]++## Ethical Considerations+[Considerations for responsible use]+```++## Common Pitfalls to Avoid++- Testing only on majority groups and missing minority disparities+- Assuming absence of measured bias means absence of bias+- Using synthetic data that doesn't represent real users+- One-time audits instead of continuous monitoring+- Optimizing for one fairness metric while ignoring others+- Not documenting known limitations and risks+- Ignoring downstream impacts of model decisions+- Treating safety as a checkbox rather than ongoing processdiff --git a/skills/analytics-tracking/skill.md b/skills/analytics-tracking/skill.mdindex 676bc47..231aafe 100644--- a/skills/analytics-tracking/skill.md+++ b/skills/analytics-tracking/skill.md@@ -1,25 +1,55 @@----name: analytics-tracking+name: Analytics Tracking+slug: analytics-trackingdescription: Expert guide for tracking user analytics, events, conversions, A/B testing, and data-driven insights. Use when implementing analytics, tracking user behavior, or optimizing conversions.+category: observability+complexity: moderate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "add analytics"+ - "track events"+ - "implement tracking"+ - "conversion tracking"+ - "A/B testing"+ - "user behavior"+ - "analytics setup"+ - "page views"+ - "funnel analysis"+tags:+ - analytics+ - tracking+ - events+ - conversions+ - A/B testing+ - metrics+ - user-behavior+ - posthog+ - google-analytics---# Analytics & Tracking Skill-## Overview+Comprehensive analytics and event tracking implementation for Next.js applications. From basic page views to complex conversion funnels, this skill covers everything needed for data-driven decisions including provider integration, custom event systems, A/B testing, and privacy compliance.-This skill helps you implement comprehensive analytics and event tracking in your Next.js application. From basic page views to complex conversion funnels, this covers everything you need for data-driven decisions.+Track user interactions, measure conversion funnels, run experiments, and gain actionable insights into user behavior. Integrate with popular analytics platforms like Vercel Analytics, PostHog, Mixpanel, and Google Analytics while maintaining privacy compliance.-## Analytics Providers+## Core Workflows-### Google Analytics 4 (GA4)+### Workflow 1: Google Analytics 4 (GA4) Setup+**Purpose:** Implement Google Analytics for comprehensive web analytics-**Install:**-```bash-npm install @next/third-parties-```+**Steps:**+1. Install @next/third-parties package+2. Add GoogleAnalytics component to layout+3. Implement custom event tracking+4. Set up conversion goals-**Setup:**+**Implementation:**```typescript+// Install+// npm install @next/third-parties+// app/layout.tsximport { GoogleAnalytics } from '@next/third-parties/google'@@ -33,15 +63,12 @@ export default function RootLayout({ children }) {</html>)}-```-**Track Events:**-```typescript+// Track Events'use client'export function TrackableButton() {const handleClick = () => {- // Track custom eventwindow.gtag('event', 'button_click', {event_category: 'engagement',event_label: 'cta_button',@@ -53,17 +80,21 @@ export function TrackableButton() {}```-### Vercel Analytics+### Workflow 2: Vercel Analytics Integration+**Purpose:** Zero-config analytics for Vercel deployments-**Install:**-```bash-npm install @vercel/analytics-```+**Steps:**+1. Install @vercel/analytics+2. Add Analytics component+3. Track custom events-**Setup:**+**Implementation:**```typescript+// npm install @vercel/analytics+// app/layout.tsximport { Analytics } from '@vercel/analytics/react'+import { SpeedInsights } from '@vercel/speed-insights/next'export default function RootLayout({ children }) {return (@@ -71,28 +102,28 @@ export default function RootLayout({ children }) {<body>{children}<Analytics />+ <SpeedInsights /></body></html>)}-```-**Track Custom Events:**-```typescript+// Track Custom Eventsimport { track } from '@vercel/analytics'-// Track eventtrack('Purchase', { amount: 99.99, currency: 'USD' })```-### PostHog (Open Source)+### Workflow 3: PostHog (Open Source Analytics)+**Purpose:** Full-featured product analytics with feature flags and session replay-**Install:**-```bash-npm install posthog-js-```+**Steps:**+1. Install posthog-js+2. Create PostHog provider+3. Implement event tracking+4. Set up feature flags-**Setup:**+**Implementation:**```typescript// lib/posthog.tsimport posthog from 'posthog-js'@@ -120,10 +151,8 @@ export function Providers({ children }) {return <>{children}</>}-```-**Track Events:**-```typescript+// Track Eventsimport posthog from 'posthog-js'posthog.capture('user_signed_up', {@@ -132,9 +161,10 @@ posthog.capture('user_signed_up', {})```-## Custom Analytics System+### Workflow 4: Custom Analytics System+**Purpose:** Build a unified analytics abstraction layer-### Event Tracking Hook+**Implementation:**```typescript// hooks/use-analytics.ts'use client'@@ -144,7 +174,6 @@ type EventProperties = Record<string, any>export function useAnalytics() {const track = useCallback((eventName: string, properties?: EventProperties) => {- // Send to multiple providersif (typeof window !== 'undefined') {// Google Analyticswindow.gtag?.('event', eventName, properties)@@ -163,7 +192,7 @@ export function useAnalytics() {url: window.location.href,referrer: document.referrer,})- }).catch(() => {}) // Fail silently+ }).catch(() => {})}}, [])@@ -186,89 +215,12 @@ export function useAnalytics() {return { track, identify, page }}--// Usage-function Component() {- const { track } = useAnalytics()-- const handlePurchase = () => {- track('Purchase Completed', {- amount: 99.99,- currency: 'USD',- product: 'Pro Plan'- })- }-- return <button onClick={handlePurchase}>Buy Now</button>-}-```--### Page View Tracking-```typescript-// app/providers.tsx-'use client'-import { useEffect } from 'react'-import { usePathname, useSearchParams } from 'next/navigation'-import { useAnalytics } from '@/hooks/use-analytics'--export function AnalyticsProvider({ children }) {- const pathname = usePathname()- const searchParams = useSearchParams()- const { page } = useAnalytics()-- useEffect(() => {- page(pathname, {- search: searchParams.toString()- })- }, [pathname, searchParams, page])-- return <>{children}</>-}```-## Event Types+### Workflow 5: Conversion Funnel Tracking+**Purpose:** Track and analyze multi-step conversion funnels-### Common Events to Track--**User Authentication:**-```typescript-track('User Signed Up', { method: 'email' })-track('User Logged In', { method: 'google' })-track('User Logged Out')-```--**Engagement:**-```typescript-track('Button Clicked', { button_id: 'cta', location: 'hero' })-track('Link Clicked', { url: '/pricing', text: 'See Pricing' })-track('Video Played', { video_id: 'intro', duration: 120 })-track('Form Submitted', { form_id: 'contact', success: true })-```--**E-commerce:**-```typescript-track('Product Viewed', { product_id: '123', name: 'Pro Plan' })-track('Product Added to Cart', { product_id: '123', quantity: 1 })-track('Checkout Started', { cart_total: 99.99 })-track('Order Completed', {- order_id: 'ORD-123',- total: 99.99,- items: 3-})-```--**Errors:**-```typescript-track('Error Occurred', {- error_type: 'payment_failed',- error_message: 'Card declined',- location: 'checkout'-})-```--## Conversion Tracking--### Funnel Tracking+**Implementation:**```typescript// lib/funnel.tstype FunnelStep =@@ -299,60 +251,25 @@ export class FunnelTracker {steps_completed: this.steps.length})}- }, 60000) // 1 minute timeout+ }, 60000)}}// Usageconst funnel = new FunnelTracker()--// On landing pagefunnel.trackStep('landing')--// After signupfunnel.trackStep('signup', { method: 'email' })--// After onboardingfunnel.trackStep('onboarding', { completed_steps: 3 })```-### Goal Tracking-```typescript-// lib/goals.ts-type Goal =- | 'signup'- | 'first_purchase'- | 'referral'- | 'upgrade_to_pro'--export function trackGoal(goal: Goal, value?: number, properties?: Record<string, any>) {- track('Goal Achieved', {- goal,- value,- ...properties- })-- // Send to backend for revenue tracking- fetch('/api/analytics/goals', {- method: 'POST',- body: JSON.stringify({- goal,- value,- timestamp: new Date().toISOString()- })- })-}--// Usage-trackGoal('first_purchase', 99.99, { plan: 'pro' })-```+### Workflow 6: A/B Testing Implementation+**Purpose:** Run controlled experiments with statistical significance-## A/B Testing--### Simple A/B Test+**Implementation:**```typescript// lib/ab-test.ts'use client'+import { useState, useEffect } from 'react'type Variant = 'A' | 'B'@@ -360,7 +277,6 @@ export function useABTest(testName: string): Variant {const [variant, setVariant] = useState<Variant>('A')useEffect(() => {- // Get or set variantconst key = `ab_test_${testName}`let userVariant = localStorage.getItem(key) as Variant@@ -368,7 +284,6 @@ export function useABTest(testName: string): Variant {userVariant = Math.random() > 0.5 ? 'A' : 'B'localStorage.setItem(key, userVariant)- // Track assignmenttrack('AB Test Assigned', {test_name: testName,variant: userVariant@@ -390,10 +305,8 @@ function PricingPage() {}return <PricingLayoutB />}-```-### Advanced A/B Testing with PostHog-```typescript+// Advanced A/B Testing with PostHogimport { useFeatureFlagEnabled } from 'posthog-js/react'export function PricingPage() {@@ -406,71 +319,50 @@ export function PricingPage() {}```-## User Properties+## Quick Reference-### Set User Properties-```typescript-import posthog from 'posthog-js'+| Action | Command/Trigger |+|--------|-----------------|+| Basic setup | "add analytics to my app" |+| Track event | "track [event name]" |+| Page views | "track page views" |+| Conversions | "set up conversion tracking" |+| A/B testing | "implement A/B test" |+| Feature flags | "add feature flags" |+| User identification | "identify users" |+| Funnel analysis | "track conversion funnel" |-// Set properties-posthog.identify('user-123', {- email: '[email protected]',- plan: 'pro',- signup_date: '2024-01-01',- total_purchases: 5,- lifetime_value: 499.99-})+## Common Events to Track-// Set properties incrementally-posthog.people.set({ plan: 'enterprise' })-posthog.people.set_once({ first_login: new Date() })-posthog.people.increment('page_views')+**User Authentication:**+```typescript+track('User Signed Up', { method: 'email' })+track('User Logged In', { method: 'google' })+track('User Logged Out')```-## Cohort Analysis--### Track User Cohorts+**Engagement:**```typescript-// lib/cohorts.ts-export function assignCohort(userId: string, signupDate: Date) {- const cohortMonth = signupDate.toISOString().slice(0, 7) // '2024-01'-- posthog.identify(userId, {- cohort_month: cohortMonth,- signup_date: signupDate.toISOString()- })-- track('User Assigned to Cohort', {- cohort_month: cohortMonth- })-}--// Usage-assignCohort('user-123', new Date('2024-01-15'))+track('Button Clicked', { button_id: 'cta', location: 'hero' })+track('Link Clicked', { url: '/pricing', text: 'See Pricing' })+track('Video Played', { video_id: 'intro', duration: 120 })+track('Form Submitted', { form_id: 'contact', success: true })```-## Session Recording--### PostHog Session Replay+**E-commerce:**```typescript-posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {- api_host: 'https://app.posthog.com',- session_recording: {- maskAllInputs: true, // Privacy: mask sensitive inputs- maskTextSelector: '[data-sensitive]',- recordCrossOriginIframes: true- }-})--// Optionally trigger on errors-window.addEventListener('error', () => {- posthog.sessionReplayStart()+track('Product Viewed', { product_id: '123', name: 'Pro Plan' })+track('Product Added to Cart', { product_id: '123', quantity: 1 })+track('Checkout Started', { cart_total: 99.99 })+track('Order Completed', {+ order_id: 'ORD-123',+ total: 99.99,+ items: 3})```## Privacy & Consent-### Cookie Consent```typescript// components/cookie-consent.tsx'use client'@@ -484,7 +376,6 @@ export function CookieConsent() {if (!consent) {setShowBanner(true)} else if (consent === 'accepted') {- // Initialize analyticsinitAnalytics()}}, [])@@ -510,114 +401,53 @@ export function CookieConsent() {</div>)}--function initAnalytics() {- // Initialize GA, PostHog, etc.- window.gtag?.('consent', 'update', {- analytics_storage: 'granted'- })-}```-### GDPR Compliance-```typescript-// lib/analytics.ts-export function optOut() {- // Disable all tracking- window['ga-disable-GA_MEASUREMENT_ID'] = true- posthog.opt_out_capturing()- localStorage.setItem('analytics_opt_out', 'true')-}+## Best Practices-export function optIn() {- window['ga-disable-GA_MEASUREMENT_ID'] = false- posthog.opt_in_capturing()- localStorage.removeItem('analytics_opt_out')-}+- **Privacy First:** Respect user consent and privacy regulations (GDPR, CCPA)+- **Consistent Naming:** Use snake_case for event names+- **Rich Context:** Include relevant properties with every event+- **User Identification:** Link anonymous and authenticated sessions+- **Event Taxonomy:** Document your event naming conventions+- **Sampling:** Use sampling for high-volume events+- **Testing:** Test tracking in development before production+- **Data Quality:** Validate events before sending+- **Performance:** Batch events and avoid blocking the main thread+- **Documentation:** Maintain an event dictionary-// Check opt-out on load-if (localStorage.getItem('analytics_opt_out') === 'true') {- optOut()-}-```+## Dependencies++```bash+# Vercel Analytics+npm install @vercel/analytics @vercel/speed-insights-## Analytics Dashboard+# Google Analytics+npm install @next/third-parties-### Backend Analytics API-```typescript-// app/api/analytics/stats/route.ts-import { createClient } from '@/lib/supabase/server'--export async function GET() {- const supabase = createClient()-- // Get event stats from database- const { data: events } = await supabase- .from('analytics_events')- .select('event_name, count')- .gte('created_at', new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString())-- // Get user stats- const { count: totalUsers } = await supabase- .from('users')- .select('*', { count: 'exact', head: true })-- const { count: activeUsers } = await supabase- .from('users')- .select('*', { count: 'exact', head: true })- .gte('last_seen', new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString())-- return Response.json({- events,- users: {- total: totalUsers,- active_24h: activeUsers- }- })-}+# PostHog+npm install posthog-js++# Mixpanel+npm install mixpanel-browser```-## Performance Metrics+## Error Handling-### Track Performance-```typescript-'use client'-import { useEffect } from 'react'--export function PerformanceTracker() {- useEffect(() => {- // Track Core Web Vitals- if ('web-vital' in window) {- import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {- getCLS((metric) => track('Web Vital', { name: 'CLS', value: metric.value }))- getFID((metric) => track('Web Vital', { name: 'FID', value: metric.value }))- getFCP((metric) => track('Web Vital', { name: 'FCP', value: metric.value }))- getLCP((metric) => track('Web Vital', { name: 'LCP', value: metric.value }))- getTTFB((metric) => track('Web Vital', { name: 'TTFB', value: metric.value }))- })- }- }, [])+- **Network Failures:** Queue events locally and retry+- **Blocked Trackers:** Gracefully degrade without breaking the app+- **Invalid Events:** Validate event structure before sending+- **Rate Limits:** Implement client-side rate limiting+- **Missing User ID:** Use anonymous IDs until identification- return null-}-```+## Performance Tips-## Best Practices Checklist--- [ ] Implement privacy-compliant tracking-- [ ] Get user consent for cookies-- [ ] Track key conversion events-- [ ] Set up funnel analysis-- [ ] Implement A/B testing-- [ ] Track user properties-- [ ] Monitor Core Web Vitals-- [ ] Set up goal tracking-- [ ] Implement session recording (with privacy)-- [ ] Track errors and exceptions-- [ ] Use cohort analysis-- [ ] Respect Do Not Track-- [ ] Document tracked events-- [ ] Regular analytics review+- Use `requestIdleCallback` for non-critical tracking+- Batch multiple events into single requests+- Lazy load analytics scripts+- Use beacon API for page unload events+- Avoid tracking on every keystroke+- Sample high-frequency events## When to Use This Skilldiff --git a/skills/api-design/skill.md b/skills/api-design/skill.mdindex 3a57b1b..59acb71 100644--- a/skills/api-design/skill.md+++ b/skills/api-design/skill.md@@ -1,26 +1,50 @@----name: api-design+name: API Design+slug: api-designdescription: Expert guide for RESTful API design, Next.js API routes, error handling, validation, and best practices. Use when building endpoints, handling requests, or designing API architecture.+category: backend+complexity: moderate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "create API"+ - "design API"+ - "API routes"+ - "REST endpoints"+ - "API validation"+ - "API error handling"+ - "build endpoint"+ - "route handler"+tags:+ - api+ - rest+ - endpoints+ - validation+ - backend+ - routes+ - http+ - zod---# API Design & Integration Skill-## Overview+Comprehensive guide for designing and implementing robust, scalable APIs in Next.js applications. From RESTful endpoint design to request validation, error handling, authentication, and rate limiting, this skill covers all aspects of production-ready API development.-This skill helps you design and implement robust, scalable APIs in Next.js. Use this when creating API routes, handling requests/responses, implementing validation, or integrating with external services.+Build APIs that are intuitive to use, well-documented, and follow industry best practices. Implement proper HTTP semantics, consistent error responses, and type-safe request/response handling.-## Core Principles+## Core Workflows-### 1. RESTful Design-- Use proper HTTP methods (GET, POST, PUT, DELETE, PATCH)-- Resource-based URLs (`/api/users` not `/api/getUsers`)-- Consistent naming conventions-- Proper status codes-- Stateless requests+### Workflow 1: RESTful Route Handlers+**Purpose:** Create well-organized API routes following REST conventions-### 2. Next.js API Routes+**Steps:**+1. Plan resource-based URL structure+2. Create route handlers for each HTTP method+3. Implement request validation+4. Add proper error handling+5. Return consistent response format-**Basic Route Handler:**+**Implementation:**```typescript// app/api/users/route.tsimport { NextRequest, NextResponse } from 'next/server'@@ -49,10 +73,7 @@ export async function POST(request: NextRequest) {)}}-```-**Dynamic Route:**-```typescript// app/api/users/[id]/route.tsexport async function GET(request: NextRequest,@@ -92,9 +113,10 @@ export async function DELETE(}```-## Request Validation+### Workflow 2: Request Validation with Zod+**Purpose:** Type-safe request validation with detailed error messages-### Using Zod+**Implementation:**```typescriptimport { z } from 'zod'import { NextRequest, NextResponse } from 'next/server'@@ -127,51 +149,10 @@ export async function POST(request: NextRequest) {}```-## HTTP Status Codes--### Success Codes-- `200 OK` - Successful GET, PUT, PATCH-- `201 Created` - Successful POST (resource created)-- `204 No Content` - Successful DELETE--### Client Error Codes-- `400 Bad Request` - Invalid request body/params-- `401 Unauthorized` - Missing/invalid authentication-- `403 Forbidden` - Authenticated but not authorized-- `404 Not Found` - Resource doesn't exist-- `409 Conflict` - Resource conflict (duplicate)-- `422 Unprocessable Entity` - Validation failed--### Server Error Codes-- `500 Internal Server Error` - Unexpected error-- `503 Service Unavailable` - Temporary unavailability--## Error Response Format--**Consistent Error Structure:**-```typescript-type ErrorResponse = {- error: string // Human-readable message- code?: string // Machine-readable code- details?: Record<string, any> // Additional context- timestamp?: string-}--// Usage-return NextResponse.json(- {- error: 'Validation failed',- code: 'VALIDATION_ERROR',- details: { field: 'email', reason: 'Invalid format' },- timestamp: new Date().toISOString()- },- { status: 400 }-)-```--## Authentication & Authorization+### Workflow 3: Authentication Middleware+**Purpose:** Secure API routes with authentication checks-**Middleware Pattern:**+**Implementation:**```typescript// lib/auth-middleware.tsimport { NextRequest, NextResponse } from 'next/server'@@ -191,7 +172,7 @@ export async function withAuth(try {const user = await verifyToken(token)- req.user = user // Attach user to request+ req.user = userreturn handler(req, context)} catch (error) {return NextResponse.json(@@ -209,60 +190,10 @@ export const GET = withAuth(async (request: NextRequest) => {})```-## Query Parameters--```typescript-export async function GET(request: NextRequest) {- const searchParams = request.nextUrl.searchParams- const page = parseInt(searchParams.get('page') || '1')- const limit = parseInt(searchParams.get('limit') || '10')- const search = searchParams.get('search') || ''-- const users = await db.users.findMany({- where: { name: { contains: search } },- skip: (page - 1) * limit,- take: limit- })-- return NextResponse.json({- users,- pagination: {- page,- limit,- total: await db.users.count()- }- })-}-```--## CORS Configuration--```typescript-// middleware.ts-import { NextResponse } from 'next/server'-import type { NextRequest } from 'next/server'--export function middleware(request: NextRequest) {- const response = NextResponse.next()-- response.headers.set('Access-Control-Allow-Origin', '*')- response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')- response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')-- if (request.method === 'OPTIONS') {- return new NextResponse(null, { status: 200, headers: response.headers })- }-- return response-}--export const config = {- matcher: '/api/:path*'-}-```--## Rate Limiting+### Workflow 4: Rate Limiting+**Purpose:** Protect API from abuse+**Implementation:**```typescript// lib/rate-limit.tsconst rateLimitMap = new Map<string, { count: number; reset: number }>()@@ -299,8 +230,10 @@ export async function GET(request: NextRequest) {}```-## Pagination Pattern+### Workflow 5: Pagination Pattern+**Purpose:** Handle large datasets efficiently+**Implementation:**```typescripttype PaginatedResponse<T> = {data: T[]@@ -314,23 +247,27 @@ type PaginatedResponse<T> = {}}-async function getPaginated<T>(- model: any,- page: number,- limit: number,- where = {}-): Promise<PaginatedResponse<T>> {+export async function GET(request: NextRequest) {+ const searchParams = request.nextUrl.searchParams+ const page = parseInt(searchParams.get('page') || '1')+ const limit = parseInt(searchParams.get('limit') || '10')+ const search = searchParams.get('search') || ''+const skip = (page - 1) * limit- const [data, total] = await Promise.all([- model.findMany({ where, skip, take: limit }),- model.count({ where })+ const [users, total] = await Promise.all([+ db.users.findMany({+ where: { name: { contains: search } },+ skip,+ take: limit+ }),+ db.users.count({ where: { name: { contains: search } } })])const totalPages = Math.ceil(total / limit)- return {- data,+ return NextResponse.json({+ data: users,pagination: {page,limit,@@ -339,12 +276,117 @@ async function getPaginated<T>(hasNext: page < totalPages,hasPrev: page > 1}+ })+}+```++## Quick Reference++| Action | HTTP Method | URL Pattern |+|--------|-------------|-------------|+| List resources | GET | /api/resources |+| Get single | GET | /api/resources/:id |+| Create | POST | /api/resources |+| Update | PATCH/PUT | /api/resources/:id |+| Delete | DELETE | /api/resources/:id |+| Actions | POST | /api/resources/:id/action |++## HTTP Status Codes++### Success Codes+- `200 OK` - Successful GET, PUT, PATCH+- `201 Created` - Successful POST (resource created)+- `204 No Content` - Successful DELETE++### Client Error Codes+- `400 Bad Request` - Invalid request body/params+- `401 Unauthorized` - Missing/invalid authentication+- `403 Forbidden` - Authenticated but not authorized+- `404 Not Found` - Resource doesn't exist+- `409 Conflict` - Resource conflict (duplicate)+- `422 Unprocessable Entity` - Validation failed+- `429 Too Many Requests` - Rate limit exceeded++### Server Error Codes+- `500 Internal Server Error` - Unexpected error+- `503 Service Unavailable` - Temporary unavailability++## Error Response Format++```typescript+type ErrorResponse = {+ error: string // Human-readable message+ code?: string // Machine-readable code+ details?: Record<string, any> // Additional context+ timestamp?: string+}++// Usage+return NextResponse.json(+ {+ error: 'Validation failed',+ code: 'VALIDATION_ERROR',+ details: { field: 'email', reason: 'Invalid format' },+ timestamp: new Date().toISOString()+ },+ { status: 400 }+)+```++## CORS Configuration++```typescript+// middleware.ts+import { NextResponse } from 'next/server'+import type { NextRequest } from 'next/server'++export function middleware(request: NextRequest) {+ const response = NextResponse.next()++ response.headers.set('Access-Control-Allow-Origin', '*')+ response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')+ response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')++ if (request.method === 'OPTIONS') {+ return new NextResponse(null, { status: 200, headers: response.headers })}++ return response+}++export const config = {+ matcher: '/api/:path*'}```-## File Upload+## Best Practices++- **Use HTTP Semantics:** Correct status codes (201 for create, 204 for delete)+- **Consistent Response Format:** Always return `{ data }` or `{ error, code }`+- **Validate Everything:** Use Zod for request body, query, and params+- **Handle Errors Gracefully:** Never expose internal errors to clients+- **Document APIs:** Use OpenAPI/Swagger for documentation+- **Version APIs:** Use /api/v1/ for breaking changes+- **Paginate Lists:** Always paginate list endpoints+- **Use CORS:** Configure properly for client-side requests+- **Log Requests:** Log all API requests for debugging+- **Rate Limit:** Protect against abuse++## Common Patterns++### Health Check Endpoint+```typescript+// app/api/health/route.ts+export async function GET() {+ return NextResponse.json({+ status: 'ok',+ timestamp: new Date().toISOString(),+ version: process.env.APP_VERSION+ })+}+```+### File Upload```typescriptexport async function POST(request: NextRequest) {const formData = await request.formData()@@ -357,7 +399,6 @@ export async function POST(request: NextRequest) {)}- // Validate file typeconst allowedTypes = ['image/jpeg', 'image/png', 'image/webp']if (!allowedTypes.includes(file.type)) {return NextResponse.json(@@ -366,29 +407,17 @@ export async function POST(request: NextRequest) {)}- // Validate file size (5MB)- if (file.size > 5 * 1024 * 1024) {- return NextResponse.json(- { error: 'File too large' },- { status: 400 }- )- }-- // Upload to storage...const url = await uploadFile(file)-return NextResponse.json({ url }, { status: 201 })}```-## Webhook Handler-+### Webhook Handler```typescriptexport async function POST(request: NextRequest) {const signature = request.headers.get('x-webhook-signature')const body = await request.text()- // Verify signatureconst isValid = verifyWebhookSignature(body, signature)if (!isValid) {return NextResponse.json(@@ -398,62 +427,45 @@ export async function POST(request: NextRequest) {}const event = JSON.parse(body)-- // Process eventawait processWebhookEvent(event)return NextResponse.json({ received: true })}```-## Best Practices Checklist--- [ ] Use proper HTTP methods and status codes-- [ ] Validate all input with Zod or similar-- [ ] Implement consistent error responses-- [ ] Add authentication/authorization-- [ ] Handle errors gracefully-- [ ] Use TypeScript for type safety-- [ ] Implement rate limiting-- [ ] Add request logging-- [ ] Use pagination for lists-- [ ] Validate file uploads-- [ ] Set appropriate CORS headers-- [ ] Document API with comments-- [ ] Use environment variables for secrets-- [ ] Implement proper security headers+## Dependencies-## Common Patterns+```bash+# Validation+npm install zod-### Health Check Endpoint-```typescript-// app/api/health/route.ts-export async function GET() {- return NextResponse.json({- status: 'ok',- timestamp: new Date().toISOString(),- version: process.env.APP_VERSION- })-}-```--### Batch Operations-```typescript-export async function POST(request: NextRequest) {- const { operations } = await request.json()-- const results = await Promise.allSettled(- operations.map(op => processOperation(op))- )+# Rate limiting+npm install @upstash/redis @upstash/ratelimit- return NextResponse.json({- success: results.filter(r => r.status === 'fulfilled').length,- failed: results.filter(r => r.status === 'rejected').length,- results- })-}+# API documentation+npm install swagger-ui-react swagger-jsdoc```+## Error Handling++- **400 Bad Request:** Invalid input, validation errors+- **401 Unauthorized:** Missing or invalid authentication+- **403 Forbidden:** Valid auth but insufficient permissions+- **404 Not Found:** Resource doesn't exist+- **409 Conflict:** Resource already exists or state conflict+- **422 Unprocessable:** Valid syntax but semantic errors+- **429 Too Many Requests:** Rate limit exceeded+- **500 Internal Error:** Server-side failures++## Performance Tips++- Use database indexes for query fields+- Implement cursor-based pagination for large datasets+- Cache frequent reads with Redis or SWR+- Use database connection pooling+- Minimize payload size with field selection+- Compress responses with gzip+## When to Use This SkillInvoke this skill when:diff --git a/skills/api-documentation-writer/SKILL.md b/skills/api-documentation-writer/SKILL.mdnew file mode 100644index 0000000..1c4e29d--- /dev/null+++ b/skills/api-documentation-writer/SKILL.md@@ -0,0 +1,773 @@+---+name: api-documentation-writer+description: Expert guide for writing comprehensive API documentation including OpenAPI specs, endpoint references, authentication guides, and code examples. Use when documenting APIs, creating developer portals, or improving API discoverability.+---++# API Documentation Writer Skill++## Overview++This skill helps you create clear, comprehensive API documentation that developers love. Covers OpenAPI/Swagger specifications, endpoint references, authentication guides, code examples in multiple languages, and developer experience best practices.++## Documentation Philosophy++### The Three C's+1. **Clear**: Unambiguous, jargon-free explanations+2. **Complete**: All parameters, responses, and edge cases documented+3. **Current**: Always in sync with the actual API behavior++### What to Document+- **DO**: Document every public endpoint+- **DO**: Include request/response examples for all scenarios+- **DO**: Document error codes with remediation steps+- **DO**: Provide code examples in popular languages+- **DON'T**: Document internal/private endpoints+- **DON'T**: Assume readers know your domain+- **DON'T**: Let documentation drift from implementation++## OpenAPI Specification++### Basic Structure++```yaml+# openapi.yaml+openapi: 3.1.0+info:+ title: My API+ version: 1.0.0+ description: |+ Welcome to the My API documentation.++ ## Getting Started+ 1. Sign up for an API key at [dashboard.example.com](https://dashboard.example.com)+ 2. Include your key in the `Authorization` header+ 3. Start making requests!++ ## Rate Limits+ - Free tier: 100 requests/minute+ - Pro tier: 1000 requests/minute+ contact:+ name: API Support+ email: [email protected]+ url: https://support.example.com+ license:+ name: MIT+ url: https://opensource.org/licenses/MIT++servers:+ - url: https://api.example.com/v1+ description: Production+ - url: https://staging-api.example.com/v1+ description: Staging++tags:+ - name: Users+ description: User management operations+ - name: Items+ description: Item CRUD operations+```++### Endpoint Documentation++```yaml+paths:+ /users:+ get:+ tags:+ - Users+ summary: List all users+ description: |+ Retrieves a paginated list of users. Results are sorted by creation date (newest first).++ **Permissions required:** `users:read`+ operationId: listUsers+ parameters:+ - name: page+ in: query+ description: Page number (1-indexed)+ required: false+ schema:+ type: integer+ minimum: 1+ default: 1+ example: 1+ - name: limit+ in: query+ description: Number of results per page (max 100)+ required: false+ schema:+ type: integer+ minimum: 1+ maximum: 100+ default: 20+ example: 20+ - name: status+ in: query+ description: Filter by user status+ required: false+ schema:+ type: string+ enum: [active, inactive, pending]+ responses:+ '200':+ description: Successful response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/UserList'+ example:+ data:+ - id: "usr_123"+ email: "[email protected]"+ name: "John Doe"+ status: "active"+ created_at: "2024-01-15T10:30:00Z"+ meta:+ page: 1+ limit: 20+ total: 150+ total_pages: 8+ '401':+ $ref: '#/components/responses/Unauthorized'+ '403':+ $ref: '#/components/responses/Forbidden'+ '429':+ $ref: '#/components/responses/RateLimited'++ post:+ tags:+ - Users+ summary: Create a new user+ description: |+ Creates a new user account. An email verification will be sent to the provided address.++ **Permissions required:** `users:write`+ operationId: createUser+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/CreateUserRequest'+ examples:+ basic:+ summary: Basic user creation+ value:+ email: "[email protected]"+ name: "Jane Doe"+ with_metadata:+ summary: User with metadata+ value:+ email: "[email protected]"+ name: "Jane Doe"+ metadata:+ department: "Engineering"+ role: "Developer"+ responses:+ '201':+ description: User created successfully+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/User'+ '400':+ $ref: '#/components/responses/BadRequest'+ '409':+ description: User with this email already exists+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Error'+ example:+ error:+ code: "USER_EXISTS"+ message: "A user with this email already exists"+```++### Schema Definitions++```yaml+components:+ schemas:+ User:+ type: object+ description: Represents a user in the system+ required:+ - id+ - status+ - created_at+ properties:+ id:+ type: string+ description: Unique identifier (prefixed with `usr_`)+ pattern: '^usr_[a-zA-Z0-9]+$'+ example: "usr_123abc"+ email:+ type: string+ format: email+ description: User's email address (unique)+ example: "[email protected]"+ name:+ type: string+ description: User's display name+ maxLength: 100+ example: "John Doe"+ status:+ type: string+ enum: [active, inactive, pending]+ description: |+ Account status:+ - `active`: User can sign in and use the service+ - `inactive`: Account has been deactivated+ - `pending`: Awaiting email verification+ example: "active"+ metadata:+ type: object+ additionalProperties: true+ description: Custom key-value pairs for storing additional data+ example:+ department: "Engineering"+ created_at:+ type: string+ format: date-time+ description: ISO 8601 timestamp of account creation+ example: "2024-01-15T10:30:00Z"+ updated_at:+ type: string+ format: date-time+ description: ISO 8601 timestamp of last update+ example: "2024-01-16T14:45:00Z"++ CreateUserRequest:+ type: object+ required:+ properties:+ email:+ type: string+ format: email+ description: Email address for the new user (must be unique)+ name:+ type: string+ description: User's display name+ maxLength: 100+ metadata:+ type: object+ additionalProperties: true++ Error:+ type: object+ required:+ - error+ properties:+ error:+ type: object+ required:+ - code+ - message+ properties:+ code:+ type: string+ description: Machine-readable error code+ message:+ type: string+ description: Human-readable error description+ details:+ type: array+ description: Additional error details for validation errors+ items:+ type: object+ properties:+ field:+ type: string+ message:+ type: string+```++### Authentication Documentation++```yaml+components:+ securitySchemes:+ BearerAuth:+ type: http+ scheme: bearer+ bearerFormat: JWT+ description: |+ JWT token obtained from the `/auth/token` endpoint.++ Include in requests as:+ ```+ Authorization: Bearer <your-token>+ ```++ Tokens expire after 1 hour. Use refresh tokens for long-lived sessions.++ ApiKeyAuth:+ type: apiKey+ in: header+ name: X-API-Key+ description: |+ API key for server-to-server communication.++ Obtain your key from the [Developer Dashboard](https://dashboard.example.com).++ Include in requests as:+ ```+ X-API-Key: <your-api-key>+ ```++security:+ - BearerAuth: []+ - ApiKeyAuth: []+```++### Reusable Responses++```yaml+components:+ responses:+ BadRequest:+ description: Invalid request parameters+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Error'+ examples:+ validation_error:+ summary: Validation error+ value:+ error:+ code: "VALIDATION_ERROR"+ message: "Request validation failed"+ details:+ - field: "email"+ message: "Must be a valid email address"+ missing_field:+ summary: Missing required field+ value:+ error:+ code: "MISSING_FIELD"+ message: "Required field 'email' is missing"++ Unauthorized:+ description: Missing or invalid authentication+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Error'+ example:+ error:+ code: "UNAUTHORIZED"+ message: "Invalid or expired authentication token"++ Forbidden:+ description: Insufficient permissions+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Error'+ example:+ error:+ code: "FORBIDDEN"+ message: "You don't have permission to access this resource"++ NotFound:+ description: Resource not found+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Error'+ example:+ error:+ code: "NOT_FOUND"+ message: "The requested resource was not found"++ RateLimited:+ description: Rate limit exceeded+ headers:+ X-RateLimit-Limit:+ schema:+ type: integer+ description: Request limit per minute+ X-RateLimit-Remaining:+ schema:+ type: integer+ description: Remaining requests in current window+ X-RateLimit-Reset:+ schema:+ type: integer+ description: Unix timestamp when the rate limit resets+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Error'+ example:+ error:+ code: "RATE_LIMITED"+ message: "Too many requests. Please retry after 60 seconds"+```++## Markdown Documentation++### Endpoint Reference Template++```markdown+# Create User++Create a new user account.++## Endpoint++```+POST /v1/users+```++## Authentication++Requires API key with `users:write` permission.++## Request Body++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `email` | string | Yes | User's email address (must be unique) |+| `name` | string | No | Display name (max 100 characters) |+| `metadata` | object | No | Custom key-value pairs |++### Example Request++```bash+curl -X POST https://api.example.com/v1/users \+ -H "Authorization: Bearer YOUR_TOKEN" \+ -H "Content-Type: application/json" \+ -d '{+ "email": "[email protected]",+ "name": "Jane Doe"+ }'+```++## Response++### Success (201 Created)++```json+{+ "id": "usr_abc123",+ "email": "[email protected]",+ "name": "Jane Doe",+ "status": "pending",+ "created_at": "2024-01-15T10:30:00Z"+}+```++### Errors++| Status | Code | Description |+|--------|------|-------------|+| 400 | `VALIDATION_ERROR` | Invalid email format or missing required field |+| 401 | `UNAUTHORIZED` | Invalid or missing authentication |+| 409 | `USER_EXISTS` | User with this email already exists |+| 429 | `RATE_LIMITED` | Too many requests |++### Error Example++```json+{+ "error": {+ "code": "USER_EXISTS",+ "message": "A user with this email already exists"+ }+}+```+```++## Code Examples++### Multi-Language Examples++```markdown+## Code Examples++### cURL++```bash+curl -X GET "https://api.example.com/v1/users?limit=10" \+ -H "Authorization: Bearer YOUR_TOKEN"+```++### JavaScript (fetch)++```javascript+const response = await fetch('https://api.example.com/v1/users?limit=10', {+ headers: {+ 'Authorization': 'Bearer YOUR_TOKEN'+ }+});++const data = await response.json();+console.log(data);+```++### JavaScript (axios)++```javascript+import axios from 'axios';++const { data } = await axios.get('https://api.example.com/v1/users', {+ params: { limit: 10 },+ headers: {+ 'Authorization': 'Bearer YOUR_TOKEN'+ }+});+```++### Python++```python+import requests++response = requests.get(+ 'https://api.example.com/v1/users',+ params={'limit': 10},+ headers={'Authorization': 'Bearer YOUR_TOKEN'}+)++data = response.json()+print(data)+```++### Ruby++```ruby+require 'net/http'+require 'json'++uri = URI('https://api.example.com/v1/users?limit=10')+request = Net::HTTP::Get.new(uri)+request['Authorization'] = 'Bearer YOUR_TOKEN'++response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|+ http.request(request)+end++data = JSON.parse(response.body)+puts data+```++### Go++```go+package main++import (+ "encoding/json"+ "fmt"+ "net/http"+)++func main() {+ req, _ := http.NewRequest("GET", "https://api.example.com/v1/users?limit=10", nil)+ req.Header.Set("Authorization", "Bearer YOUR_TOKEN")++ client := &http.Client{}+ resp, _ := client.Do(req)+ defer resp.Body.Close()++ var data map[string]interface{}+ json.NewDecoder(resp.Body).Decode(&data)+ fmt.Println(data)+}+```+```++## Error Documentation++### Error Code Reference++```markdown+# Error Codes++All API errors follow a consistent format:++```json+{+ "error": {+ "code": "ERROR_CODE",+ "message": "Human-readable description",+ "details": [] // Optional additional information+ }+}+```++## Authentication Errors++| Code | HTTP Status | Description | Resolution |+|------|-------------|-------------|------------|+| `UNAUTHORIZED` | 401 | Missing or invalid token | Include a valid `Authorization` header |+| `TOKEN_EXPIRED` | 401 | Token has expired | Obtain a new token via `/auth/token` |+| `INVALID_API_KEY` | 401 | API key not recognized | Check your API key in the dashboard |+| `FORBIDDEN` | 403 | Insufficient permissions | Request appropriate scopes for your token |++## Validation Errors++| Code | HTTP Status | Description | Resolution |+|------|-------------|-------------|------------|+| `VALIDATION_ERROR` | 400 | Request body validation failed | Check the `details` array for specific fields |+| `MISSING_FIELD` | 400 | Required field not provided | Include all required fields |+| `INVALID_FORMAT` | 400 | Field format is incorrect | Match the expected format (see schema) |++## Resource Errors++| Code | HTTP Status | Description | Resolution |+|------|-------------|-------------|------------|+| `NOT_FOUND` | 404 | Resource doesn't exist | Verify the resource ID is correct |+| `ALREADY_EXISTS` | 409 | Resource already exists | Use a different identifier or update existing |+| `CONFLICT` | 409 | State conflict | Refresh and retry the operation |++## Rate Limiting++| Code | HTTP Status | Description | Resolution |+|------|-------------|-------------|------------|+| `RATE_LIMITED` | 429 | Too many requests | Wait and retry (see `Retry-After` header) |+```++## Changelog Documentation++### API Changelog Format++```markdown+# API Changelog++## 2024-01-15 - v1.2.0++### Added+- `GET /users/{id}/activity` - Retrieve user activity history+- `metadata` field on User object for custom data storage++### Changed+- Pagination now 1-indexed (previously 0-indexed)+- Rate limits increased: Free tier 100 → 200 req/min++### Deprecated+- `GET /users/search` - Use `GET /users` with query parameters instead+ - Will be removed in v2.0.0++### Fixed+- `created_at` now correctly returns UTC timezone++---++## 2024-01-01 - v1.1.0++### Added+- Webhook support for user events+- `status` filter on `GET /users`++### Security+- API keys now support IP allowlisting+```++## Interactive Documentation++### Swagger UI Configuration++```javascript+// swagger-config.js+const swaggerUiOptions = {+ customCss: '.swagger-ui .topbar { display: none }',+ customSiteTitle: 'API Documentation',+ customfavIcon: '/favicon.ico',+ swaggerOptions: {+ persistAuthorization: true,+ displayRequestDuration: true,+ filter: true,+ tryItOutEnabled: true,+ },+};+```++### Redoc Configuration++```yaml+# redoc.yaml+x-tagGroups:+ - name: Getting Started+ tags:+ - Authentication+ - name: Core Resources+ tags:+ - Users+ - Items+ - name: Utilities+ tags:+ - Webhooks+ - Health++x-logo:+ url: 'https://example.com/logo.png'+ altText: 'API Logo'+```++## Documentation Checklist++### Per Endpoint+- [ ] Summary (one line)+- [ ] Description (detailed explanation)+- [ ] All parameters documented with types and examples+- [ ] All response codes with examples+- [ ] Error codes with remediation steps+- [ ] Code examples in at least 2 languages+- [ ] Authentication requirements stated++### Overall API+- [ ] Getting started guide+- [ ] Authentication guide with examples+- [ ] Rate limiting documentation+- [ ] Pagination patterns+- [ ] Error handling guide+- [ ] Changelog maintained+- [ ] Versioning strategy documented+- [ ] SDK/library links++### Developer Experience+- [ ] Interactive "Try It" functionality+- [ ] Copy-paste ready examples+- [ ] Consistent terminology+- [ ] Search functionality+- [ ] Mobile-friendly rendering++## Tools Integration++### Generate from Code++```bash+# From Express/Node.js routes+npx swagger-jsdoc -d swaggerDef.js -o openapi.yaml++# From TypeScript types+npx openapi-typescript-codegen --input openapi.yaml --output ./sdk+```++### Validate OpenAPI++```bash+# Validate spec+npx @redocly/cli lint openapi.yaml++# Preview documentation+npx @redocly/cli preview-docs openapi.yaml+```++## When to Use This Skill++Invoke this skill when:+- Creating new API documentation from scratch+- Adding documentation for new endpoints+- Writing OpenAPI/Swagger specifications+- Creating code examples for multiple languages+- Documenting authentication flows+- Building developer portals+- Improving existing API documentation+- Setting up interactive documentation (Swagger UI, Redoc)diff --git a/skills/audience-segmenter/SKILL.md b/skills/audience-segmenter/SKILL.mdnew file mode 100644index 0000000..9f78e19--- /dev/null+++ b/skills/audience-segmenter/SKILL.md@@ -0,0 +1,98 @@+---+name: Audience Segmenter+slug: audience-segmenter+description: Segment audiences for targeted marketing and personalized messaging+category: marketing+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "audience segmentation"+ - "customer segments"+ - "target audience"+ - "buyer personas"+ - "market segmentation"+tags:+ - segmentation+ - targeting+ - personalization+ - audience-strategy+ - customer-data+---++# Audience Segmenter++Divide your audience into meaningful segments that enable targeted, personalized marketing at scale. This skill helps you identify distinct customer groups based on behavior, demographics, psychographics, and value, then tailor your messaging and offers accordingly.++One-size-fits-all marketing underperforms. This skill provides frameworks for discovering natural audience clusters, defining segment criteria, and developing differentiated strategies for each group. The result: higher relevance, better engagement, and improved conversion across all marketing channels.++Essential for marketers, product managers, and growth teams who want to move beyond generic messaging to true personalization.++## Core Workflows++### Workflow 1: Behavioral Segmentation+1. **Usage Pattern Analysis** - How customers interact with product+2. **Purchase Behavior** - Frequency, recency, monetary value (RFM)+3. **Engagement Levels** - Email opens, site visits, feature usage+4. **Lifecycle Stage** - New, active, at-risk, churned+5. **Feature Adoption** - Which capabilities they use+6. **Channel Preference** - Where they engage most+7. **Segment Definition** - Actionable behavioral groups++### Workflow 2: Persona Development+1. **Research Foundation** - Interviews, surveys, data analysis+2. **Demographic Profiles** - Role, company size, industry+3. **Psychographic Insights** - Goals, challenges, motivations+4. **Decision-Making Process** - How they evaluate and buy+5. **Information Sources** - Where they learn and research+6. **Objection Mapping** - Common hesitations and concerns+7. **Persona Documentation** - Shareable persona cards++### Workflow 3: Value-Based Segmentation+1. **Customer Lifetime Value Calculation** - LTV by customer+2. **Profitability Analysis** - Revenue minus cost to serve+3. **Growth Potential** - Expansion opportunity scoring+4. **Churn Risk Assessment** - Likelihood of leaving+5. **Tier Definition** - VIP, standard, low-value segments+6. **Resource Allocation** - Investment by segment value+7. **Retention Strategy** - Differentiated approaches++### Workflow 4: Segment Activation+1. **Segment Criteria** - Clear, measurable definitions+2. **Data Requirements** - What's needed to identify segments+3. **Platform Setup** - Configure segmentation in tools+4. **Content Mapping** - Match content to segment needs+5. **Channel Strategy** - Right channel for each segment+6. **Personalization Rules** - Dynamic content and offers+7. **Measurement Framework** - Track segment performance++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| RFM segmentation | "Segment customers by RFM analysis" |+| Persona creation | "Create buyer persona for [audience]" |+| Behavioral segments | "Identify behavioral segments in [data]" |+| Value tiers | "Create customer value tiers" |+| Segment messaging | "Develop messaging for [segment]" |+| Lifecycle stages | "Define customer lifecycle stages" |+| Lookalike criteria | "Identify traits of best customers" |+| Segment strategy | "Create strategy for [segment]" |++## Best Practices++- **Start with data** - Segments should emerge from reality, not assumptions+- **Actionable segments** - If you can't reach them differently, why segment?+- **Mutual exclusivity** - Clear boundaries between segments+- **Meaningful size** - Segments must be large enough to matter+- **Stability over time** - Segments shouldn't shift constantly+- **Accessibility** - Can you actually identify and reach them?+- **Profitability focus** - Understand segment economics+- **Document criteria** - Clear definitions everyone understands+- **Validate with research** - Quantitative and qualitative+- **Avoid over-segmentation** - More isn't always better+- **Update regularly** - Segments evolve as markets change+- **Test segment strategies** - Measure differential response+- **Share across teams** - Sales, product, support benefit from segments+- **Consider journey stage** - Segment by where they are+- **Balance precision and scale** - Too precise = too smalldiff --git a/skills/brand-voice-coach/SKILL.md b/skills/brand-voice-coach/SKILL.mdnew file mode 100644index 0000000..c4e894c--- /dev/null+++ b/skills/brand-voice-coach/SKILL.md@@ -0,0 +1,98 @@+---+name: Brand Voice Coach+slug: brand-voice-coach+description: Maintain consistent brand voice across all marketing communications+category: marketing+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "brand voice"+ - "tone of voice"+ - "brand consistency"+ - "writing guidelines"+ - "brand style"+tags:+ - branding+ - voice-and-tone+ - style-guide+ - consistency+ - content-guidelines+---++# Brand Voice Coach++Define, document, and maintain a consistent brand voice that makes your content instantly recognizable. This skill helps you articulate what your brand sounds like, train teams to write on-brand, and ensure consistency across every touchpoint.++A strong brand voice builds trust, differentiates from competitors, and creates emotional connection. This skill provides frameworks for defining voice attributes, creating practical guidelines, and evaluating content against brand standards. Turn abstract brand essence into concrete writing principles anyone can follow.++Built for brand managers, content strategists, marketing leaders, and anyone responsible for maintaining brand consistency across teams and channels.++## Core Workflows++### Workflow 1: Brand Voice Definition+1. **Brand Essence Articulation** - Core identity and values+2. **Voice Attribute Selection** - 3-5 defining characteristics+3. **This Not That** - What you sound like vs don't+4. **Competitor Differentiation** - How voice stands apart+5. **Audience Alignment** - Voice that resonates with targets+6. **Example Compilation** - Real samples of voice done right+7. **Documentation Draft** - Shareable voice guidelines++### Workflow 2: Tone Modulation Guide+1. **Situation Mapping** - Different contexts requiring different tones+2. **Tone Spectrum** - How voice flexes across situations+3. **Channel Variations** - Social vs email vs support+4. **Emotional Contexts** - Happy, frustrated, confused customers+5. **Content Type Guidance** - Product copy, error messages, celebration+6. **Do's and Don'ts** - Specific examples per context+7. **Decision Framework** - How to choose appropriate tone++### Workflow 3: Voice Audit+1. **Content Inventory** - Sample across all channels+2. **Consistency Assessment** - Where voice is on/off brand+3. **Gap Identification** - Missing voice elements+4. **Competitive Comparison** - Voice differentiation check+5. **Team Calibration** - Are writers aligned?+6. **Recommendation Development** - Priority improvements+7. **Action Plan** - Steps to improve consistency++### Workflow 4: Voice Training Program+1. **Guidelines Documentation** - Comprehensive reference materials+2. **Example Library** - Before/after rewrites+3. **Exercise Development** - Practice scenarios+4. **Review Process** - How to give voice feedback+5. **Self-Assessment Tools** - Checklists for writers+6. **Ongoing Calibration** - Regular voice reviews+7. **Champion Network** - Voice advocates across teams++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Define voice | "Create brand voice for [company]" |+| Audit content | "Audit this content for voice consistency" |+| Rewrite for voice | "Rewrite this in [brand] voice" |+| Tone guidance | "What tone for [situation/channel]?" |+| This not that | "Create voice contrast examples" |+| Style guide | "Create voice guidelines document" |+| Team training | "Design voice training program" |+| Voice check | "Does this sound like our brand?" |++## Best Practices++- **Be specific** - "Friendly" is vague; "Like a knowledgeable friend, not a salesperson" is clear+- **Three to five attributes** - More becomes unmanageable+- **Show, don't tell** - Examples matter more than descriptions+- **Context flexibility** - Voice stays constant, tone adapts+- **Train regularly** - Voice drifts without maintenance+- **Create checklists** - Make self-assessment easy+- **Involve stakeholders** - Voice must work across functions+- **Test with audience** - Validate voice resonates+- **Document exceptions** - When rules should be broken+- **Review competitors** - Ensure differentiation+- **Update intentionally** - Voice evolves, but deliberately+- **Measure consistency** - Audit periodically+- **Celebrate on-brand** - Recognize great examples+- **Correct gently** - Off-brand happens; coach constructively+- **Keep it alive** - Voice guidelines should be used, not shelveddiff --git a/skills/budget-planner/SKILL.md b/skills/budget-planner/SKILL.mdnew file mode 100644index 0000000..94fce42--- /dev/null+++ b/skills/budget-planner/SKILL.md@@ -0,0 +1,449 @@+---+name: Budget Planner+slug: budget-planner+description: Create, manage, and optimize budgets for projects, departments, and organizations with variance tracking and scenario planning+category: finance+complexity: moderate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "create budget"+ - "budget planning"+ - "budget template"+ - "budget vs actual"+ - "annual budget"+ - "project budget"+tags:+ - budgeting+ - financial-planning+ - variance-analysis+ - cost-management+ - forecasting+---++# Budget Planner++Expert budget creation and management agent that builds comprehensive budgets, tracks spending against plans, analyzes variances, and optimizes resource allocation. Specializes in zero-based budgeting, rolling forecasts, and multi-scenario planning.++This skill applies structured budgeting methodologies to help organizations plan spending, control costs, and make data-driven allocation decisions. Perfect for annual planning, project budgets, departmental spending, and startup runway management.++## Core Workflows++### Workflow 1: Annual Budget Creation++**Objective:** Build a comprehensive annual operating budget from scratch++**Steps:**+1. **Gather Historical Data**+ - Prior year actuals (P&L by month)+ - Prior year budget vs actual variances+ - Headcount and compensation data+ - Vendor contracts and commitments+ - Capital expenditure history+ - Revenue trends and projections++2. **Define Budget Parameters**+ - Fiscal year start/end dates+ - Budget cycle (calendar vs fiscal)+ - Currency and exchange assumptions+ - Inflation assumptions (2-4% typical)+ - Headcount growth assumptions+ - Revenue growth targets++3. **Revenue Budget**+ - Product/service revenue projections+ - Pricing assumptions+ - Volume/unit assumptions+ - Seasonal patterns+ - New product launches+ - Customer retention assumptions+ - Geographic mix++4. **Cost of Goods Sold (COGS) Budget**+ - Direct materials costs+ - Direct labor costs+ - Manufacturing overhead+ - Gross margin targets+ - Unit economics assumptions++5. **Operating Expense Budget**+ - **Personnel Costs:**+ - Salaries and wages (by department)+ - Benefits (typically 20-30% of salary)+ - Payroll taxes (7.65% FICA + state)+ - Bonuses and commissions+ - Stock-based compensation+ - Contractor costs++ - **Facilities Costs:**+ - Rent and lease payments+ - Utilities+ - Insurance+ - Maintenance and repairs+ - Property taxes++ - **Technology Costs:**+ - Software subscriptions (SaaS)+ - Hardware and equipment+ - Cloud infrastructure+ - IT support and services++ - **Marketing Costs:**+ - Advertising and media+ - Events and conferences+ - Content and creative+ - Marketing technology+ - Agency fees++ - **General & Administrative:**+ - Legal and professional services+ - Accounting and audit+ - Office supplies+ - Travel and entertainment+ - Training and development++6. **Capital Expenditure Budget**+ - Equipment purchases+ - Facility improvements+ - Technology infrastructure+ - Depreciation schedules++7. **Cash Flow Implications**+ - Working capital needs+ - CapEx timing+ - Seasonal cash requirements+ - Financing needs++8. **Budget Consolidation**+ - Roll up departmental budgets+ - Eliminate intercompany items+ - Create consolidated P&L budget+ - Balance sheet projections+ - Cash flow projections++9. **Scenario Development**+ - Base case (most likely)+ - Upside case (+10-20% revenue)+ - Downside case (-10-20% revenue)+ - Cost reduction scenarios++**Deliverable:** Complete annual budget package with P&L, departmental details, and scenarios++### Workflow 2: Project Budget Development++**Objective:** Create a detailed budget for a specific project or initiative++**Steps:**+1. **Project Scope Definition**+ - Project objectives and deliverables+ - Timeline and milestones+ - Resource requirements+ - Success criteria+ - Constraints and dependencies++2. **Work Breakdown Structure**+ - Decompose project into phases+ - Identify major work packages+ - List activities within each package+ - Estimate effort for each activity++3. **Resource Cost Estimation**+ - **Internal Labor:**+ - Identify required roles+ - Estimate hours per role+ - Apply fully-loaded labor rates+ - Account for utilization rates++ - **External Resources:**+ - Contractor/consultant rates+ - Agency or vendor costs+ - Outsourced services++4. **Non-Labor Costs**+ - Materials and supplies+ - Software and tools+ - Equipment and hardware+ - Travel and expenses+ - Training and certifications+ - Contingency reserve (10-20%)++5. **Cost Phasing**+ - Spread costs across timeline+ - Account for payment terms+ - Identify upfront vs. ongoing costs+ - Create monthly cost forecast++6. **Budget Controls**+ - Approval thresholds+ - Change request process+ - Variance reporting triggers+ - Contingency release criteria++7. **Risk-Adjusted Budget**+ - Identify cost risks+ - Probability-weighted contingency+ - Management reserve (if applicable)+ - Total project budget with reserves++**Deliverable:** Project budget with timeline, resource plan, and risk contingencies++### Workflow 3: Zero-Based Budgeting++**Objective:** Build budget from scratch justifying every expense++**Steps:**+1. **Identify Decision Units**+ - Define budget owners+ - Establish decision units (departments, functions)+ - Clarify accountability++2. **Define Service Levels**+ - Minimum level (survival)+ - Current level (maintain status quo)+ - Improvement level (enhanced performance)+ - Each level must be costed++3. **Cost Justification**+ - For each expense, answer:+ - Why is this needed?+ - What happens without it?+ - What are alternatives?+ - What's the ROI?++4. **Decision Package Creation**+ - Package 1: Minimum viable operations+ - Package 2: Core operations+ - Package 3: Growth investments+ - Package 4: Strategic initiatives++5. **Ranking and Prioritization**+ - Stack rank all packages+ - Apply funding constraints+ - Make trade-off decisions+ - Document rationale++6. **Final Budget Assembly**+ - Fund packages within constraints+ - Document unfunded priorities+ - Create implementation plan++**Deliverable:** Zero-based budget with prioritized decision packages++### Workflow 4: Rolling Forecast Update++**Objective:** Continuously update budget with latest actuals and projections++**Steps:**+1. **Close Period**+ - Gather actual results for completed period+ - Ensure data completeness+ - Reconcile to GL/accounting++2. **Variance Analysis**+ - Calculate budget vs actual variances+ - Identify significant variances (>5% or material)+ - Categorize as:+ - Timing differences (will normalize)+ - Run-rate changes (permanent)+ - One-time items (non-recurring)++3. **Forecast Adjustment**+ - Update remaining periods based on:+ - Run-rate from actuals+ - Known commitments+ - Revised assumptions+ - New information++4. **Full-Year Outlook**+ - Combine YTD actuals + forecast+ - Compare to original budget+ - Calculate expected year-end variance+ - Identify risks to forecast++5. **Action Planning**+ - If tracking above budget: investment opportunities+ - If tracking below budget: corrective actions+ - Document assumptions and risks+ - Assign owners to actions++6. **Reporting Package**+ - Executive summary+ - Variance commentary+ - Updated forecast+ - Risks and opportunities+ - Recommended actions++**Deliverable:** Updated rolling forecast with variance analysis and action plan++### Workflow 5: Startup Runway Planning++**Objective:** Model cash runway and funding needs for startups++**Steps:**+1. **Current Cash Position**+ - Cash on hand+ - Outstanding receivables+ - Available credit lines+ - Expected fundraise timing++2. **Monthly Burn Rate Analysis**+ - Current monthly expenses+ - Committed future expenses+ - Planned hiring costs+ - Growth investments++3. **Revenue Assumptions**+ - Current MRR/ARR+ - Growth rate assumptions+ - Churn assumptions+ - Cash collection timing++4. **Runway Calculation**+ - Gross burn = Total monthly expenses+ - Net burn = Gross burn - Revenue+ - Runway = Cash / Net Burn+ - Zero cash date projection++5. **Scenario Modeling**+ - Current trajectory+ - Aggressive growth scenario+ - Conservative/survival scenario+ - Path to profitability scenario++6. **Milestone Mapping**+ - Key milestones for next funding round+ - Costs to achieve milestones+ - Timeline requirements+ - Funding amount needed++7. **Cash Management Actions**+ - Expense reduction opportunities+ - Revenue acceleration options+ - Timing optimization+ - Bridge financing options++**Deliverable:** Runway model with scenarios and funding recommendations++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Create annual budget | "Build annual budget for [year/org]" |+| Project budget | "Create budget for [project]" |+| Variance analysis | "Analyze budget vs actual for [period]" |+| Update forecast | "Update rolling forecast with [month] actuals" |+| Runway analysis | "Calculate runway with current burn" |+| Zero-based budget | "Build ZBB for [department]" |++## Budget Templates++### Monthly P&L Budget Template++```markdown+| Line Item | Jan | Feb | Mar | Q1 | Apr | May | Jun | Q2 | ... | FY Total |+|-----------|-----|-----|-----|----|----|-----|-----|----|----|----------|+| **Revenue** |+| Product Revenue | | | | | | | | | | |+| Service Revenue | | | | | | | | | | |+| **Total Revenue** | | | | | | | | | | |+| |+| **COGS** |+| Direct Costs | | | | | | | | | | |+| **Gross Profit** | | | | | | | | | | |+| Gross Margin % | | | | | | | | | | |+| |+| **Operating Expenses** |+| Personnel | | | | | | | | | | |+| Marketing | | | | | | | | | | |+| Technology | | | | | | | | | | |+| Facilities | | | | | | | | | | |+| G&A | | | | | | | | | | |+| **Total OpEx** | | | | | | | | | | |+| |+| **Operating Income** | | | | | | | | | | |+| Operating Margin % | | | | | | | | | | |+```++### Variance Report Template++```markdown+# Budget Variance Report: [Period]++## Executive Summary+- Total Revenue: $XXX vs Budget $XXX (X% variance)+- Total Expenses: $XXX vs Budget $XXX (X% variance)+- Net Income: $XXX vs Budget $XXX (X% variance)++## Significant Variances (>5%)++### Favorable Variances+| Line Item | Actual | Budget | Variance | Explanation |+|-----------|--------|--------|----------|-------------|+| | | | | |++### Unfavorable Variances+| Line Item | Actual | Budget | Variance | Explanation |+|-----------|--------|--------|----------|-------------|+| | | | | |++## Full-Year Impact+- Current trajectory vs annual budget+- Risks to achieving budget+- Recommended actions++## Forecast Update+- Revised full-year forecast+- Key assumption changes+```++## Budgeting Best Practices++### Planning Phase+- Start with strategic priorities+- Get executive alignment on key assumptions+- Involve budget owners early+- Build in realistic timelines+- Document all assumptions++### Execution Phase+- Distribute budgets to owners+- Establish spending approval processes+- Set up variance monitoring+- Create regular reporting cadence+- Enable budget vs actual tracking++### Monitoring Phase+- Monthly variance reviews+- Rolling forecast updates+- Action plans for significant variances+- Re-forecast when major changes occur+- Year-end projections++### Common Budget Categories++| Category | Typical % of OpEx | Notes |+|----------|-------------------|-------|+| Personnel | 60-70% | Largest expense for most companies |+| Technology | 10-15% | Growing rapidly with SaaS adoption |+| Marketing | 10-20% | Varies by stage and industry |+| Facilities | 5-10% | Often fixed costs |+| G&A | 5-10% | Legal, accounting, insurance |++## Integration with Other Skills++- **Use with `cash-flow-forecaster`:** Convert budget to cash projections+- **Use with `revenue-modeler`:** Develop revenue assumptions+- **Use with `unit-economics-calculator`:** Validate profitability assumptions+- **Use with `cost-optimizer`:** Identify budget reduction opportunities+- **Use with `financial-reporter`:** Create budget reporting packages++## Common Pitfalls to Avoid++- **Hockey stick projections:** Be realistic about growth rates+- **Ignoring seasonality:** Build monthly fluctuations into budget+- **Underestimating personnel costs:** Include benefits, taxes, raises+- **Forgetting one-time costs:** License renewals, annual fees+- **No contingency:** Include 5-10% buffer for unknowns+- **Static budgets:** Update forecasts as reality changes+- **Sandbbagging:** Budgets should be achievable but ambitious+- **No accountability:** Assign clear owners to every line itemdiff --git a/skills/campaign-analyzer/SKILL.md b/skills/campaign-analyzer/SKILL.mdnew file mode 100644index 0000000..87672af--- /dev/null+++ b/skills/campaign-analyzer/SKILL.md@@ -0,0 +1,99 @@+---+name: Campaign Analyzer+slug: campaign-analyzer+description: Analyze marketing campaign performance and extract actionable insights+category: marketing+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "campaign analysis"+ - "campaign performance"+ - "marketing metrics"+ - "campaign report"+ - "marketing ROI"+tags:+ - analytics+ - campaign-management+ - performance-marketing+ - reporting+ - metrics+---++# Campaign Analyzer++Turn marketing data into actionable insights that improve campaign performance. This skill helps you systematically analyze campaigns across channels, identify what's working, diagnose what's not, and make data-driven optimization decisions.++Raw metrics don't tell stories - this skill helps you find the narrative in your data. From awareness campaigns to lead generation to e-commerce, learn to measure what matters, benchmark against industry standards, and present findings that drive better marketing decisions.++Built for marketing managers, performance marketers, analysts, and anyone responsible for demonstrating marketing impact and improving results.++## Core Workflows++### Workflow 1: Campaign Performance Review+1. **Goal Alignment** - Compare results to objectives+2. **KPI Dashboard** - Track primary and secondary metrics+3. **Funnel Analysis** - Identify conversion bottlenecks+4. **Channel Attribution** - Understand contribution by source+5. **Spend Efficiency** - Calculate cost metrics (CPM, CPC, CPA, ROAS)+6. **Audience Performance** - Segment by demographic/behavior+7. **Creative Analysis** - Identify top-performing assets+8. **Recommendation Synthesis** - Actionable next steps++### Workflow 2: Multi-Channel Analysis+1. **Channel Mapping** - All touchpoints in customer journey+2. **Attribution Modeling** - First touch, last touch, multi-touch+3. **Cross-Channel Synergies** - How channels work together+4. **Budget Allocation Review** - Spend vs performance by channel+5. **Audience Overlap** - Reach and frequency across channels+6. **Journey Mapping** - Path to conversion analysis+7. **Optimization Recommendations** - Reallocation suggestions++### Workflow 3: Creative Performance Analysis+1. **Asset Inventory** - All creative variations tested+2. **Performance Ranking** - Best to worst performers+3. **Element Analysis** - What elements drive performance+4. **Format Comparison** - Static vs video vs carousel+5. **Message Testing** - Which value props resonate+6. **Creative Fatigue** - Performance over time+7. **Learning Documentation** - Insights for future creative++### Workflow 4: ROI & Attribution Analysis+1. **Revenue Attribution** - Connect marketing to revenue+2. **Customer Acquisition Cost** - Fully-loaded CAC calculation+3. **Lifetime Value Analysis** - LTV by acquisition channel+4. **ROAS Calculation** - Return on ad spend by campaign+5. **Payback Period** - Time to recoup acquisition cost+6. **Incrementality Testing** - True marketing impact+7. **Budget Optimization Model** - Optimal allocation recommendations++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Campaign review | "Analyze performance of [campaign name]" |+| Channel comparison | "Compare performance across [channels]" |+| ROI calculation | "Calculate ROI for [marketing initiative]" |+| Creative analysis | "Identify top performing creative" |+| Funnel analysis | "Find conversion bottlenecks" |+| Spend optimization | "Recommend budget reallocation" |+| Attribution review | "Analyze attribution for [campaign]" |+| Executive summary | "Create executive summary of [campaign results]" |++## Best Practices++- **Start with goals** - Analysis serves objectives, not vanity+- **Define success upfront** - Benchmarks before launch+- **Segment everything** - Aggregate data hides insights+- **Compare apples to apples** - Normalize for meaningful comparison+- **Look for patterns** - Single data points mislead+- **Context matters** - Seasonality, competition, market conditions+- **Attribution is imperfect** - Acknowledge model limitations+- **Focus on actionable** - Insights must lead to actions+- **Trend over point-in-time** - Direction matters more than absolute+- **Test before scaling** - Validate before major spend shifts+- **Document learnings** - Build institutional knowledge+- **Automate reporting** - Spend time on analysis, not data pulling+- **Visualize effectively** - Charts that tell stories+- **Executive vs detailed** - Right depth for right audience+- **Lead with recommendations** - What should we do differently?diff --git a/skills/cash-flow-forecaster/SKILL.md b/skills/cash-flow-forecaster/SKILL.mdnew file mode 100644index 0000000..5f383ef--- /dev/null+++ b/skills/cash-flow-forecaster/SKILL.md@@ -0,0 +1,462 @@+---+name: Cash Flow Forecaster+slug: cash-flow-forecaster+description: Forecast cash inflows, outflows, and liquidity needs with scenario modeling and working capital optimization+category: finance+complexity: complex+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "cash flow forecast"+ - "cash projection"+ - "liquidity planning"+ - "working capital"+ - "cash runway"+ - "13-week cash flow"+tags:+ - cash-flow+ - liquidity+ - treasury+ - working-capital+ - forecasting+---++# Cash Flow Forecaster++Expert cash flow modeling agent that builds detailed cash projections, stress tests liquidity, optimizes working capital, and manages cash position. Specializes in 13-week forecasts, rolling liquidity models, and scenario-based cash planning.++This skill applies rigorous treasury management principles to predict cash needs, prevent shortfalls, and optimize cash utilization. Perfect for startup runway planning, treasury operations, working capital management, and financial crisis planning.++## Core Workflows++### Workflow 1: 13-Week Cash Flow Forecast++**Objective:** Create detailed weekly cash forecast for near-term liquidity management++**Steps:**+1. **Opening Cash Position**+ - Bank balances by account+ - Cash in transit+ - Restricted cash+ - Available credit lines+ - Total available liquidity++2. **Cash Inflows by Week**+ - **Accounts Receivable Collections:**+ - Aged AR schedule+ - Customer payment patterns (DSO)+ - Expected collections by week+ - Bad debt assumptions++ - **Other Inflows:**+ - Recurring revenue (subscriptions, contracts)+ - Expected new sales+ - Investment income+ - Asset sales+ - Other receipts++3. **Cash Outflows by Week**+ - **Payroll (typically bi-weekly):**+ - Gross wages+ - Payroll taxes (same day or next day)+ - Benefits withholdings+ - 401k contributions++ - **Accounts Payable:**+ - Vendor payment schedule+ - Rent and lease payments+ - Utility payments+ - Contract payments++ - **Operating Expenses:**+ - Software subscriptions (monthly)+ - Insurance premiums+ - Professional services+ - Marketing spend++ - **Debt Service:**+ - Loan principal payments+ - Interest payments+ - Line of credit draws/payments++ - **Capital Expenditures:**+ - Equipment purchases+ - Facility improvements++4. **Weekly Cash Flow Calculation**+ - Beginning cash + Inflows - Outflows = Ending cash+ - Calculate for each of 13 weeks+ - Identify weekly cash surplus/deficit+ - Flag weeks with potential shortfalls++5. **Minimum Cash Requirements**+ - Operating buffer (2-4 weeks of expenses)+ - Debt covenant requirements+ - Seasonal requirements+ - Strategic reserves++6. **Variance Analysis**+ - Compare to prior forecast+ - Actual vs forecast for completed weeks+ - Identify forecast accuracy issues+ - Refine collection/payment assumptions++**Deliverable:** 13-week rolling cash forecast with daily/weekly precision++### Workflow 2: Monthly/Annual Cash Flow Projection++**Objective:** Long-term cash flow modeling for planning purposes++**Steps:**+1. **P&L to Cash Flow Bridge**+ - Start with projected net income+ - Add back non-cash items:+ - Depreciation and amortization+ - Stock-based compensation+ - Deferred revenue changes+ - Bad debt expense++2. **Working Capital Changes**+ - **Accounts Receivable:**+ - DSO assumption (Days Sales Outstanding)+ - AR = (Revenue / 365) x DSO+ - Change in AR = Cash impact++ - **Inventory:**+ - DIO assumption (Days Inventory Outstanding)+ - Inventory = (COGS / 365) x DIO+ - Change in Inventory = Cash impact++ - **Accounts Payable:**+ - DPO assumption (Days Payable Outstanding)+ - AP = (Expenses / 365) x DPO+ - Change in AP = Cash impact++ - **Other Working Capital:**+ - Prepaid expenses+ - Accrued liabilities+ - Deferred revenue++3. **Cash from Operating Activities**+ - Net Income+ - + Non-cash adjustments+ - - Working capital changes+ - = Operating Cash Flow++4. **Cash from Investing Activities**+ - Capital expenditures (CapEx)+ - Acquisitions+ - Asset sales+ - Investment purchases/sales++5. **Cash from Financing Activities**+ - Debt proceeds/repayments+ - Equity raises+ - Dividend payments+ - Stock buybacks++6. **Monthly Cash Position**+ - Beginning cash+ - + Operating cash flow+ - + Investing cash flow+ - + Financing cash flow+ - = Ending cash++7. **Scenario Modeling**+ - Base case projection+ - Stress case (revenue -20%, slower collections)+ - Best case (accelerated collections, growth)++**Deliverable:** Monthly cash flow projection with scenarios++### Workflow 3: Working Capital Optimization++**Objective:** Improve cash flow by optimizing working capital components++**Steps:**+1. **Current State Analysis**+ - Calculate Cash Conversion Cycle:+ - CCC = DSO + DIO - DPO+ - Industry benchmarks+ - Historical trends++2. **Accounts Receivable Optimization**+ - **Current DSO Analysis:**+ - DSO by customer segment+ - Aging bucket analysis+ - Collection effectiveness++ - **Improvement Opportunities:**+ - Invoice timing (bill sooner)+ - Payment terms (shorten from Net 60 to Net 30)+ - Early payment discounts (2/10 Net 30)+ - Automated payment reminders+ - Credit policy tightening+ - Electronic payment options++ - **Target DSO and Cash Impact:**+ - Current DSO: X days+ - Target DSO: Y days+ - Cash freed = (Revenue / 365) x (X - Y)++3. **Accounts Payable Optimization**+ - **Current DPO Analysis:**+ - DPO by vendor category+ - Payment term utilization++ - **Optimization Opportunities:**+ - Negotiate extended terms+ - Optimize payment timing+ - Take early pay discounts when NPV positive+ - Centralize AP for better control++ - **Target DPO and Cash Impact:**+ - Current DPO: X days+ - Target DPO: Y days+ - Cash freed = (Expenses / 365) x (Y - X)++4. **Inventory Optimization** (if applicable)+ - Current DIO analysis+ - Excess and obsolete inventory+ - Safety stock optimization+ - Supplier lead time reduction+ - Cash impact of inventory reduction++5. **Working Capital Improvement Plan**+ - Prioritized initiatives+ - Expected cash impact+ - Implementation timeline+ - Responsible owners+ - Tracking metrics++**Deliverable:** Working capital improvement plan with cash flow impact++### Workflow 4: Liquidity Stress Testing++**Objective:** Model cash position under adverse scenarios++**Steps:**+1. **Define Stress Scenarios**+ - **Revenue Shock:**+ - Revenue decline 20%, 40%, 60%+ - Customer concentration loss+ - Market downturn++ - **Collection Stress:**+ - DSO increase 30-60 days+ - Customer bankruptcies+ - Increased bad debt++ - **Cost Increases:**+ - Key supplier price increases+ - Wage inflation+ - Unexpected expenses++ - **Credit Facility Loss:**+ - Line of credit revoked+ - Covenant violations+ - Credit downgrade++2. **Model Each Scenario**+ - Apply stress assumptions to base forecast+ - Calculate impact on cash flows+ - Determine time to cash exhaustion+ - Identify cash floor breaches++3. **Identify Trigger Points**+ - Weeks of cash remaining+ - Minimum cash threshold breaches+ - Covenant violation points+ - Point of no return++4. **Develop Contingency Plans**+ - **Tier 1 (Cash tight):**+ - Defer discretionary spending+ - Accelerate collections+ - Negotiate payment extensions++ - **Tier 2 (Cash crisis):**+ - Hiring freeze+ - Marketing cuts+ - Vendor renegotiations+ - Draw credit facilities++ - **Tier 3 (Survival mode):**+ - Layoffs+ - Asset sales+ - Emergency fundraising+ - Strategic alternatives++5. **Quantify Contingency Impact**+ - Cash preserved by each action+ - Implementation speed+ - Business impact+ - Recovery implications++**Deliverable:** Stress test results with contingency action plans++### Workflow 5: Startup Runway Modeling++**Objective:** Model cash runway and funding needs for startups++**Steps:**+1. **Current Burn Analysis**+ - Monthly gross burn (total expenses)+ - Monthly net burn (gross burn - revenue)+ - Burn trend (increasing/decreasing)+ - Cash on hand++2. **Runway Calculation**+ - Simple runway = Cash / Net Burn+ - Account for burn rate changes+ - Factor in revenue growth+ - Calculate zero-cash date++3. **Path to Profitability Analysis**+ - Monthly revenue required for breakeven+ - Unit economics at scale+ - Timeline to profitability+ - Cash required to reach profitability++4. **Funding Scenarios**+ - No additional funding (how long?)+ - Bridge round (12-18 months runway)+ - Full round (24+ months runway)+ - Strategic investment++5. **Milestone-Based Planning**+ - Key milestones for next round+ - Cost to achieve each milestone+ - Timeline requirements+ - Risk-adjusted funding needs++6. **Sensitivity Analysis**+ - Revenue growth scenarios+ - Burn rate scenarios+ - Combined scenarios+ - Probability-weighted runway++**Deliverable:** Runway model with funding recommendations++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| 13-week forecast | "Build 13-week cash flow forecast" |+| Monthly projection | "Project cash flow for next 12 months" |+| Working capital | "Analyze working capital optimization" |+| Stress test | "Stress test liquidity position" |+| Runway | "Calculate startup runway" |+| CCC analysis | "Analyze cash conversion cycle" |++## Cash Flow Formulas++### Key Metrics++| Metric | Formula | Healthy Range |+|--------|---------|---------------|+| Days Sales Outstanding (DSO) | (AR / Revenue) x 365 | 30-45 days |+| Days Inventory Outstanding (DIO) | (Inventory / COGS) x 365 | Industry varies |+| Days Payable Outstanding (DPO) | (AP / COGS) x 365 | 30-60 days |+| Cash Conversion Cycle (CCC) | DSO + DIO - DPO | Lower is better |+| Current Ratio | Current Assets / Current Liabilities | > 1.5 |+| Quick Ratio | (Current Assets - Inventory) / Current Liabilities | > 1.0 |+| Operating Cash Flow Ratio | OCF / Current Liabilities | > 1.0 |++### Cash Flow Calculations++```+Operating Cash Flow =+ Net Income+ + Depreciation & Amortization+ + Stock-Based Compensation+ - Increase in Accounts Receivable+ - Increase in Inventory+ + Increase in Accounts Payable+ + Other Non-Cash Adjustments++Free Cash Flow =+ Operating Cash Flow+ - Capital Expenditures++Net Burn Rate =+ Total Expenses - Total Revenue++Runway (months) =+ Cash on Hand / Net Burn Rate+```++## 13-Week Cash Flow Template++```markdown+| Week Ending | W1 | W2 | W3 | W4 | W5 | W6 | W7 | W8 | W9 | W10 | W11 | W12 | W13 |+|-------------|----|----|----|----|----|----|----|----|----|----|-----|-----|-----|+| **Beginning Cash** |+| |+| **Cash Inflows** |+| AR Collections | | | | | | | | | | | | | |+| New Sales | | | | | | | | | | | | | |+| Other Income | | | | | | | | | | | | | |+| **Total Inflows** | | | | | | | | | | | | | |+| |+| **Cash Outflows** |+| Payroll | | | | | | | | | | | | | |+| Vendor Payments | | | | | | | | | | | | | |+| Rent | | | | | | | | | | | | | |+| Utilities | | | | | | | | | | | | | |+| Debt Service | | | | | | | | | | | | | |+| Other | | | | | | | | | | | | | |+| **Total Outflows** | | | | | | | | | | | | | |+| |+| **Net Cash Flow** | | | | | | | | | | | | | |+| **Ending Cash** | | | | | | | | | | | | | |+| |+| **Minimum Required** |+| **Surplus/(Deficit)** |+```++## Best Practices++### Forecasting+- Update weekly (13-week) and monthly (annual)+- Track actual vs forecast to improve accuracy+- Bias toward conservative assumptions+- Document key assumptions+- Maintain version history++### Collections+- Age receivables weekly+- Follow up on overdue immediately+- Offer multiple payment methods+- Consider factoring for cash crunch++### Payments+- Maximize DPO within terms+- Take early pay discounts when > borrowing cost+- Centralize payment processing+- Negotiate extended terms with key vendors++### Monitoring+- Daily cash position tracking+- Weekly forecast updates+- Monthly variance analysis+- Quarterly stress testing++## Integration with Other Skills++- **Use with `budget-planner`:** Convert budget to cash flow+- **Use with `revenue-modeler`:** Model revenue collection timing+- **Use with `accounts-reconciler`:** Validate bank balances+- **Use with `billing-manager`:** Improve collection timing+- **Use with `financial-reporter`:** Create cash flow reports++## Common Pitfalls to Avoid++- **Confusing profit with cash:** Profitable companies can run out of cash+- **Ignoring timing:** When cash flows matters as much as amount+- **Optimistic collections:** Assume slower collections than promised+- **Forgetting lumpy payments:** Quarterly taxes, annual renewals+- **Static assumptions:** Update DSO/DPO based on actual performance+- **No buffer:** Always maintain operating cash cushion+- **Ignoring seasonality:** Model peak and trough periods+- **Incomplete coverage:** Capture all cash movementsdiff --git a/skills/churn-predictor/SKILL.md b/skills/churn-predictor/SKILL.mdnew file mode 100644index 0000000..5a5d923--- /dev/null+++ b/skills/churn-predictor/SKILL.md@@ -0,0 +1,350 @@+---+name: Churn Predictor+slug: churn-predictor+description: Predict customer churn risk using behavioral signals, engagement data, and predictive analytics+category: customer-support+complexity: complex+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "churn prediction"+ - "churn risk"+ - "customer retention"+ - "at-risk customers"+ - "churn analysis"+ - "retention modeling"+tags:+ - churn+ - prediction+ - retention+ - analytics+ - customer-success+---++# Churn Predictor++Expert churn prediction system that identifies at-risk customers before they leave using behavioral signals, engagement patterns, and predictive analytics. This skill provides structured workflows for building churn models, monitoring risk signals, and executing retention interventions.++Churn is the silent killer of growth. By the time a customer announces they're leaving, it's often too late. This skill helps you identify churn risk early when intervention can still make a difference, prioritize retention efforts, and systematically reduce churn.++Built on data science best practices and customer success methodologies, this skill combines leading indicator analysis, risk scoring, and intervention playbooks to predict and prevent churn before it happens.++## Core Workflows++### Workflow 1: Churn Signal Identification+**Map the behaviors that predict churn**++1. **Behavioral Signals**+ | Signal Type | Examples | Risk Level |+ |-------------|----------|------------|+ | Usage Decline | 30%+ drop in logins, sessions, actions | High |+ | Feature Abandonment | Stopped using key features | Medium-High |+ | Engagement Drop | No response to emails, missed meetings | Medium |+ | Support Patterns | Spike in tickets, negative sentiment | High |+ | Billing Issues | Failed payments, downgrade requests | High |++2. **Account Signals**+ - Champion departure (key user leaves)+ - Company layoffs or restructuring+ - Merger/acquisition announcements+ - Budget cuts affecting your category+ - Competitor evaluation signals+ - Contract not renewed on auto-renew++3. **Relationship Signals**+ - NPS score decline (9-10 → 7 or below)+ - Missed QBRs or check-ins+ - Unresponsive to outreach+ - Escalated support issues+ - Negative sentiment in communications++4. **Time-Based Signals**+ - Approaching renewal (90/60/30 days)+ - End of trial or pilot+ - Anniversary of bad experience+ - Post-implementation plateau+ - Seasonal usage patterns++### Workflow 2: Risk Scoring Model+**Build a composite churn risk score**++1. **Score Components**+ ```+ Churn Risk Score =+ (Usage Score × 0.30) ++ (Engagement Score × 0.25) ++ (Support Score × 0.20) ++ (Relationship Score × 0.15) ++ (Account Score × 0.10)++ Scale: 0-100 (higher = more at risk)+ ```++2. **Usage Score Factors**+ - Login frequency vs. baseline+ - Feature adoption breadth+ - Active users vs. licensed seats+ - Time in product+ - Core action completion++3. **Engagement Score Factors**+ - Email open/click rates+ - Meeting attendance+ - Resource downloads+ - Training completion+ - Community participation++4. **Risk Categories**+ | Score | Risk Level | Action |+ |-------|------------|--------|+ | 0-20 | Low | Standard monitoring |+ | 21-40 | Moderate | Proactive outreach |+ | 41-60 | Elevated | Intervention needed |+ | 61-80 | High | Urgent save attempt |+ | 81-100 | Critical | Executive escalation |++### Workflow 3: Cohort & Trend Analysis+**Understand churn patterns across customer segments**++1. **Cohort Analysis**+ - Analyze by signup month/quarter+ - Track retention curves over time+ - Identify cohorts with worse retention+ - Correlate with product/market changes+ - Find patterns in successful cohorts++2. **Segment Analysis**+ - By customer size (SMB/Mid/Enterprise)+ - By industry vertical+ - By use case/persona+ - By acquisition source+ - By pricing tier++3. **Churn Timing Patterns**+ - When in customer lifecycle does churn occur?+ - Renewal vs. mid-contract churn+ - Time from warning signs to churn+ - Seasonal patterns+ - Correlation with contract length++4. **Leading Indicator Validation**+ - Track signals → churn correlation+ - Calculate signal lead time+ - Measure false positive rate+ - Refine scoring weights+ - A/B test interventions++### Workflow 4: Alert & Escalation System+**Surface risk at the right time to the right people**++1. **Alert Triggers**+ - Score crosses threshold (e.g., into "elevated")+ - Rapid score increase (10+ points in 7 days)+ - Critical signal detected (payment failed, champion left)+ - Renewal approaching with elevated risk+ - Multiple signals converging++2. **Escalation Matrix**+ | Risk Level | Owner | Escalation | Response SLA |+ |------------|-------|------------|--------------|+ | Moderate | CSM | None | 5 days |+ | Elevated | CSM | Manager copy | 48 hours |+ | High | CSM + Manager | VP briefed | 24 hours |+ | Critical | Manager | VP/Exec sponsor | Same day |++3. **Alert Content**+ - Customer name and risk score+ - Specific signals triggering alert+ - Score trend (improving/declining)+ - Renewal date and ARR at risk+ - Recommended actions++4. **Alert Channels**+ - Slack/Teams notifications+ - Email digests+ - CRM dashboards+ - Weekly risk reports+ - Executive summaries++### Workflow 5: Intervention Playbooks+**Systematic approaches to save at-risk customers**++1. **Intervention Matching**+ | Root Cause | Intervention |+ |------------|--------------|+ | Low adoption | Training, onboarding redo |+ | Technical issues | Engineering escalation, workarounds |+ | Value unclear | ROI analysis, executive alignment |+ | Champion left | Relationship rebuild with new stakeholders |+ | Pricing concerns | Discount, plan adjustment, payment terms |+ | Competitive | Feature comparison, roadmap preview |++2. **Save Play Execution**+ - Diagnose root cause (don't assume)+ - Match intervention to cause+ - Assign owner and resources+ - Set clear timeline and milestones+ - Track outcome (saved, lost, reason)++3. **Intervention Tactics**+ - **Urgent Call**: Same-day executive outreach+ - **Health Check**: Comprehensive account review+ - **Training Blitz**: Intensive enablement sessions+ - **Success Sprint**: Focused value delivery+ - **Executive Alignment**: VP/C-level engagement+ - **Commercial Discussion**: Pricing/terms adjustment++4. **Outcome Tracking**+ - Save rate by risk level+ - Save rate by intervention type+ - Time from intervention to resolution+ - Reasons for unsuccessful saves+ - Long-term retention of saved accounts++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Check risk score | "Show churn risk for [Customer]" |+| List at-risk accounts | "Show accounts above [X] risk score" |+| Analyze churn patterns | "Analyze churn patterns by [segment]" |+| Review alerts | "Show churn alerts this week" |+| Create save plan | "Create intervention plan for [Customer]" |+| Score validation | "Validate churn model accuracy" |+| Cohort analysis | "Analyze retention by cohort" |+| Signal analysis | "Find leading churn indicators" |+| Trend report | "Show risk score trends" |+| Intervention report | "Report on save play outcomes" |++## Best Practices++### Signal Selection+- Focus on behaviors you can observe+- Validate correlation with actual churn+- Use leading indicators (not lagging)+- Combine multiple signal types+- Weight by predictive power++### Scoring Model+- Start simple, add complexity gradually+- Calibrate weights with historical data+- Validate with blind holdout testing+- Recalibrate quarterly+- Document methodology++### Alert Design+- Don't alert on every score change+- Focus on actionable thresholds+- Include context in alerts+- Route to right person+- Avoid alert fatigue++### Intervention+- Diagnose before prescribing+- Match intervention to root cause+- Set clear success criteria+- Track outcomes rigorously+- Learn from failures++### Model Maintenance+- Review accuracy monthly+- Retrain with new churn data+- Adjust for product changes+- Update as customer base evolves+- Document false positives/negatives++## Churn Signals Library++### Usage Signals+| Signal | Calculation | Warning Threshold |+|--------|-------------|-------------------|+| Login decline | % change week-over-week | -30% for 2+ weeks |+| DAU/MAU ratio | Daily active / Monthly active | Below 0.2 |+| Feature breadth | # features used / available | Below 30% |+| Seat utilization | Active users / licensed seats | Below 50% |+| Session depth | Actions per session | Below baseline by 40% |++### Engagement Signals+| Signal | Calculation | Warning Threshold |+|--------|-------------|-------------------|+| Email engagement | Open rate × Click rate | Below 5% |+| Meeting attendance | Attended / Scheduled | Below 60% |+| Response time | Avg days to respond | Above 5 days |+| QBR participation | Attended / Scheduled | Miss 2+ in row |+| Training completion | Completed / Available | Below 25% |++### Support Signals+| Signal | Calculation | Warning Threshold |+|--------|-------------|-------------------|+| Ticket volume | Tickets / month | 3× baseline |+| Sentiment score | Negative / Total | Above 30% |+| Escalation rate | Escalated / Total | Above 20% |+| Resolution satisfaction | CSAT on resolved | Below 3/5 |+| Open ticket age | Avg days open | Above 7 days |++### Relationship Signals+| Signal | Calculation | Warning Threshold |+|--------|-------------|-------------------|+| NPS change | Current - Previous | Drop of 3+ points |+| Health score | Composite score | Below 60 |+| Champion risk | Champion activity decline | Below 50% of baseline |+| Executive access | Exec meetings / quarter | 0 in 2+ quarters |+| Renewal confidence | CSM assessment | Below 70% |++## Risk Report Template++### Weekly At-Risk Summary+```markdown+# Churn Risk Report: Week of [Date]++## Summary+- Accounts at elevated risk or above: [X]+- Total ARR at risk: $[Amount]+- New alerts this week: [X]+- Risk trending up: [X accounts]+- Risk trending down: [X accounts]++## Critical Risk (81-100)+| Account | ARR | Score | Key Signals | Owner | Action |+|---------|-----|-------|-------------|-------|--------|+| [Name] | $X | 87 | [Signals] | [CSM] | [Status] |++## High Risk (61-80)+[Same format]++## Elevated Risk (41-60)+[Same format]++## Interventions in Progress+| Account | Started | Intervention | Progress |+|---------|---------|--------------|----------|+| [Name] | [Date] | [Type] | [Status] |++## Outcomes This Week+- Saved: [X accounts, $ARR]+- Lost: [X accounts, $ARR, reasons]+- De-escalated: [X accounts]+```++## Red Flags++- **Model overfit**: Perfect on training data, poor on new data+- **Signal lag**: Indicators trigger too late for intervention+- **False positive fatigue**: Too many alerts that aren't real risk+- **Missing signals**: Key churn predictors not tracked+- **Score opacity**: Team doesn't understand why scores change+- **Intervention mismatch**: Same playbook for different problems+- **No feedback loop**: Not learning from save attempts+- **Data quality**: Missing or stale underlying data++## Model Validation Metrics++| Metric | What It Measures | Target |+|--------|------------------|--------|+| Accuracy | Overall correct predictions | 80%+ |+| Precision | True positives / All predicted positives | 70%+ |+| Recall | True positives / All actual churns | 85%+ |+| Lead Time | Days from high risk to actual churn | 60+ days |+| False Positive Rate | False alarms / All high-risk alerts | < 30% |+| Save Rate | Saved / Attempted saves | 40%+ |+| AUC-ROC | Model discrimination ability | 0.75+ |diff --git a/skills/ci-cd-pipeline-builder/SKILL.md b/skills/ci-cd-pipeline-builder/SKILL.mdnew file mode 100644index 0000000..bbd0eae--- /dev/null+++ b/skills/ci-cd-pipeline-builder/SKILL.md@@ -0,0 +1,765 @@+---+name: ci-cd-pipeline-builder+description: Expert guide for building CI/CD pipelines with GitHub Actions, Vercel, and other platforms. Use when automating builds, tests, deployments, or release workflows.+---++# CI/CD Pipeline Builder Skill++## Overview++This skill helps you build robust CI/CD pipelines for automated testing, building, and deployment. Covers GitHub Actions, Vercel integration, testing strategies, deployment patterns, and security best practices.++## CI/CD Philosophy++### Pipeline Principles+1. **Fast feedback**: Fail early, inform quickly+2. **Reproducible**: Same inputs = same outputs+3. **Secure**: Secrets protected, dependencies verified+4. **Observable**: Clear logs, status visibility++### Pipeline Stages+```+Trigger → Lint → Test → Build → Deploy → Verify+```++## GitHub Actions Fundamentals++### Basic Workflow Structure++```yaml+# .github/workflows/ci.yml+name: CI++on:+ push:+ branches: [main, develop]+ pull_request:+ branches: [main]++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true++jobs:+ lint:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ cache: 'npm'+ - run: npm ci+ - run: npm run lint++ test:+ runs-on: ubuntu-latest+ needs: lint+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ cache: 'npm'+ - run: npm ci+ - run: npm test++ build:+ runs-on: ubuntu-latest+ needs: [lint, test]+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ cache: 'npm'+ - run: npm ci+ - run: npm run build+```++### Complete Next.js CI/CD Pipeline++```yaml+# .github/workflows/ci-cd.yml+name: CI/CD Pipeline++on:+ push:+ branches: [main]+ pull_request:+ branches: [main]++env:+ NODE_VERSION: '20'+ VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}+ VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}++jobs:+ # ===================+ # Quality Checks+ # ===================+ quality:+ name: Code Quality+ runs-on: ubuntu-latest+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup Node.js+ uses: actions/setup-node@v4+ with:+ node-version: ${{ env.NODE_VERSION }}+ cache: 'npm'++ - name: Install dependencies+ run: npm ci++ - name: Type check+ run: npm run typecheck++ - name: Lint+ run: npm run lint++ - name: Format check+ run: npm run format:check++ # ===================+ # Unit & Integration Tests+ # ===================+ test:+ name: Tests+ runs-on: ubuntu-latest+ needs: quality+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup Node.js+ uses: actions/setup-node@v4+ with:+ node-version: ${{ env.NODE_VERSION }}+ cache: 'npm'++ - name: Install dependencies+ run: npm ci++ - name: Run tests+ run: npm run test:ci++ - name: Upload coverage+ uses: codecov/codecov-action@v3+ with:+ token: ${{ secrets.CODECOV_TOKEN }}+ files: ./coverage/lcov.info+ fail_ci_if_error: false++ # ===================+ # Build+ # ===================+ build:+ name: Build+ runs-on: ubuntu-latest+ needs: [quality, test]+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup Node.js+ uses: actions/setup-node@v4+ with:+ node-version: ${{ env.NODE_VERSION }}+ cache: 'npm'++ - name: Install dependencies+ run: npm ci++ - name: Build+ run: npm run build+ env:+ NEXT_PUBLIC_SUPABASE_URL: ${{ secrets.NEXT_PUBLIC_SUPABASE_URL }}+ NEXT_PUBLIC_SUPABASE_ANON_KEY: ${{ secrets.NEXT_PUBLIC_SUPABASE_ANON_KEY }}++ - name: Upload build artifact+ uses: actions/upload-artifact@v4+ with:+ name: build+ path: .next+ retention-days: 1++ # ===================+ # E2E Tests+ # ===================+ e2e:+ name: E2E Tests+ runs-on: ubuntu-latest+ needs: build+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup Node.js+ uses: actions/setup-node@v4+ with:+ node-version: ${{ env.NODE_VERSION }}+ cache: 'npm'++ - name: Install dependencies+ run: npm ci++ - name: Install Playwright browsers+ run: npx playwright install --with-deps chromium++ - name: Download build+ uses: actions/download-artifact@v4+ with:+ name: build+ path: .next++ - name: Run E2E tests+ run: npm run test:e2e+ env:+ NEXT_PUBLIC_SUPABASE_URL: ${{ secrets.NEXT_PUBLIC_SUPABASE_URL }}+ NEXT_PUBLIC_SUPABASE_ANON_KEY: ${{ secrets.NEXT_PUBLIC_SUPABASE_ANON_KEY }}++ - name: Upload test results+ if: failure()+ uses: actions/upload-artifact@v4+ with:+ name: playwright-report+ path: playwright-report+ retention-days: 7++ # ===================+ # Deploy Preview (PRs)+ # ===================+ deploy-preview:+ name: Deploy Preview+ runs-on: ubuntu-latest+ needs: [build, e2e]+ if: github.event_name == 'pull_request'+ environment:+ name: preview+ url: ${{ steps.deploy.outputs.url }}+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Install Vercel CLI+ run: npm install -g vercel++ - name: Pull Vercel Environment+ run: vercel pull --yes --environment=preview --token=${{ secrets.VERCEL_TOKEN }}++ - name: Build Project+ run: vercel build --token=${{ secrets.VERCEL_TOKEN }}++ - name: Deploy to Vercel+ id: deploy+ run: |+ url=$(vercel deploy --prebuilt --token=${{ secrets.VERCEL_TOKEN }})+ echo "url=$url" >> $GITHUB_OUTPUT++ - name: Comment PR with URL+ uses: actions/github-script@v7+ with:+ script: |+ github.rest.issues.createComment({+ issue_number: context.issue.number,+ owner: context.repo.owner,+ repo: context.repo.repo,+ body: `🚀 Preview deployed to: ${{ steps.deploy.outputs.url }}`+ })++ # ===================+ # Deploy Production+ # ===================+ deploy-production:+ name: Deploy Production+ runs-on: ubuntu-latest+ needs: [build, e2e]+ if: github.ref == 'refs/heads/main' && github.event_name == 'push'+ environment:+ name: production+ url: https://myapp.com+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Install Vercel CLI+ run: npm install -g vercel++ - name: Pull Vercel Environment+ run: vercel pull --yes --environment=production --token=${{ secrets.VERCEL_TOKEN }}++ - name: Build Project+ run: vercel build --prod --token=${{ secrets.VERCEL_TOKEN }}++ - name: Deploy to Vercel+ run: vercel deploy --prebuilt --prod --token=${{ secrets.VERCEL_TOKEN }}+```++## Testing Strategies++### Parallel Test Execution++```yaml+# .github/workflows/test-parallel.yml+name: Parallel Tests++on: [push, pull_request]++jobs:+ test:+ runs-on: ubuntu-latest+ strategy:+ fail-fast: false+ matrix:+ shard: [1, 2, 3, 4]+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ cache: 'npm'++ - run: npm ci++ - name: Run tests (shard ${{ matrix.shard }}/4)+ run: npm run test -- --shard=${{ matrix.shard }}/4++ merge-results:+ needs: test+ runs-on: ubuntu-latest+ steps:+ - name: Report results+ run: echo "All test shards passed!"+```++### Matrix Testing++```yaml+# .github/workflows/matrix-test.yml+name: Matrix Tests++on: [push, pull_request]++jobs:+ test:+ runs-on: ${{ matrix.os }}+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, macos-latest, windows-latest]+ node: [18, 20, 22]+ exclude:+ - os: windows-latest+ node: 18+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: ${{ matrix.node }}+ cache: 'npm'+ - run: npm ci+ - run: npm test+```++## Database Integration++### Supabase in CI++```yaml+# .github/workflows/test-with-db.yml+name: Tests with Database++on: [push, pull_request]++jobs:+ test:+ runs-on: ubuntu-latest+ services:+ postgres:+ image: postgres:15+ env:+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: test_db+ ports:+ - 5432:5432+ options: >-+ --health-cmd pg_isready+ --health-interval 10s+ --health-timeout 5s+ --health-retries 5++ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ cache: 'npm'++ - name: Install dependencies+ run: npm ci++ - name: Setup Supabase CLI+ uses: supabase/setup-cli@v1++ - name: Start Supabase+ run: supabase start++ - name: Run migrations+ run: supabase db reset+ env:+ SUPABASE_DB_URL: postgresql://postgres:postgres@localhost:54322/postgres++ - name: Run tests+ run: npm run test:integration+ env:+ DATABASE_URL: postgresql://postgres:postgres@localhost:54322/postgres+ SUPABASE_URL: http://localhost:54321+ SUPABASE_ANON_KEY: ${{ secrets.SUPABASE_ANON_KEY }}+```++## Release Automation++### Automated Releases++```yaml+# .github/workflows/release.yml+name: Release++on:+ push:+ branches: [main]++jobs:+ release:+ runs-on: ubuntu-latest+ permissions:+ contents: write+ pull-requests: write+ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0++ - name: Setup Node.js+ uses: actions/setup-node@v4+ with:+ node-version: '20'+ cache: 'npm'++ - name: Install dependencies+ run: npm ci++ - name: Create Release+ uses: google-github-actions/release-please-action@v4+ with:+ release-type: node+ package-name: my-app++ - name: Publish to npm+ if: ${{ steps.release.outputs.release_created }}+ run: npm publish+ env:+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}+```++### Changelog Generation++```yaml+# .github/workflows/changelog.yml+name: Changelog++on:+ release:+ types: [published]++jobs:+ update-changelog:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ with:+ ref: main++ - name: Update CHANGELOG+ uses: stefanzweifel/changelog-updater-action@v1+ with:+ latest-version: ${{ github.event.release.tag_name }}+ release-notes: ${{ github.event.release.body }}++ - name: Commit changes+ uses: stefanzweifel/git-auto-commit-action@v5+ with:+ commit_message: "docs: update CHANGELOG for ${{ github.event.release.tag_name }}"+ file_pattern: CHANGELOG.md+```++## Security Scanning++### Dependency & Code Scanning++```yaml+# .github/workflows/security.yml+name: Security++on:+ push:+ branches: [main]+ pull_request:+ branches: [main]+ schedule:+ - cron: '0 0 * * 0' # Weekly++jobs:+ dependency-audit:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ - run: npm audit --audit-level=high++ codeql:+ runs-on: ubuntu-latest+ permissions:+ security-events: write+ steps:+ - uses: actions/checkout@v4+ - uses: github/codeql-action/init@v3+ with:+ languages: javascript+ - uses: github/codeql-action/analyze@v3++ secrets-scan:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0+ - uses: gitleaks/gitleaks-action@v2+ env:+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}+```++## Caching Strategies++### Effective Caching++```yaml+# .github/workflows/cached-build.yml+name: Cached Build++on: [push, pull_request]++jobs:+ build:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ cache: 'npm'++ # Cache Next.js build+ - name: Cache Next.js+ uses: actions/cache@v4+ with:+ path: |+ .next/cache+ key: ${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json') }}-${{ hashFiles('**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx') }}+ restore-keys: |+ ${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json') }}-++ # Cache Playwright browsers+ - name: Cache Playwright+ uses: actions/cache@v4+ with:+ path: ~/.cache/ms-playwright+ key: ${{ runner.os }}-playwright-${{ hashFiles('**/package-lock.json') }}++ - run: npm ci+ - run: npm run build+```++## Environment Management++### Environment-Based Deployments++```yaml+# .github/workflows/deploy.yml+name: Deploy++on:+ push:+ branches:+ - main+ - develop++jobs:+ deploy:+ runs-on: ubuntu-latest+ environment:+ name: ${{ github.ref == 'refs/heads/main' && 'production' || 'staging' }}+ url: ${{ github.ref == 'refs/heads/main' && 'https://myapp.com' || 'https://staging.myapp.com' }}+ steps:+ - uses: actions/checkout@v4++ - name: Deploy to ${{ github.ref == 'refs/heads/main' && 'production' || 'staging' }}+ run: |+ echo "Deploying to ${{ github.ref == 'refs/heads/main' && 'production' || 'staging' }}"+ env:+ API_URL: ${{ vars.API_URL }}+ API_KEY: ${{ secrets.API_KEY }}+```++## Workflow Optimization++### Conditional Jobs++```yaml+# .github/workflows/smart-ci.yml+name: Smart CI++on:+ push:+ branches: [main]+ pull_request:+ branches: [main]++jobs:+ changes:+ runs-on: ubuntu-latest+ outputs:+ frontend: ${{ steps.filter.outputs.frontend }}+ backend: ${{ steps.filter.outputs.backend }}+ docs: ${{ steps.filter.outputs.docs }}+ steps:+ - uses: actions/checkout@v4+ - uses: dorny/paths-filter@v3+ id: filter+ with:+ filters: |+ frontend:+ - 'src/app/**'+ - 'src/components/**'+ backend:+ - 'src/api/**'+ - 'src/lib/**'+ docs:+ - 'docs/**'+ - '*.md'++ test-frontend:+ needs: changes+ if: ${{ needs.changes.outputs.frontend == 'true' }}+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - run: npm ci+ - run: npm run test:frontend++ test-backend:+ needs: changes+ if: ${{ needs.changes.outputs.backend == 'true' }}+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - run: npm ci+ - run: npm run test:backend++ deploy-docs:+ needs: changes+ if: ${{ needs.changes.outputs.docs == 'true' }}+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - run: npm run build:docs+```++## Notification & Reporting++### Slack Notifications++```yaml+# .github/workflows/notify.yml+name: CI with Notifications++on: [push]++jobs:+ build:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - run: npm ci+ - run: npm run build++ notify:+ needs: build+ runs-on: ubuntu-latest+ if: always()+ steps:+ - name: Notify Slack+ uses: slackapi/slack-github-action@v1+ with:+ payload: |+ {+ "text": "${{ needs.build.result == 'success' && '✅' || '❌' }} Build ${{ needs.build.result }}",+ "blocks": [+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": "*${{ github.repository }}* - ${{ github.ref_name }}\nCommit: ${{ github.sha }}\nBy: ${{ github.actor }}"+ }+ }+ ]+ }+ env:+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}+ SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK+```++## Pipeline Checklist++### Essential Components+- [ ] Lint and format checks+- [ ] Type checking (TypeScript)+- [ ] Unit and integration tests+- [ ] Build verification+- [ ] Security scanning++### Deployment+- [ ] Preview deployments for PRs+- [ ] Production deployment on main+- [ ] Environment-specific configs+- [ ] Rollback capability++### Performance+- [ ] Effective caching strategy+- [ ] Parallel job execution+- [ ] Conditional job execution+- [ ] Build artifact reuse++### Security+- [ ] Secrets properly managed+- [ ] Dependency auditing+- [ ] Code scanning enabled+- [ ] Protected environments++## When to Use This Skill++Invoke this skill when:+- Setting up CI/CD for a new project+- Optimizing slow pipelines+- Adding deployment automation+- Implementing release management+- Setting up security scanning+- Configuring environment-based deployments+- Creating preview environmentsdiff --git a/skills/cli-builder/SKILL.md b/skills/cli-builder/SKILL.mdnew file mode 100644index 0000000..0dc2fe6--- /dev/null+++ b/skills/cli-builder/SKILL.md@@ -0,0 +1,844 @@+---+name: cli-builder+description: Expert guide for building command-line interfaces with Node.js (Commander, Inquirer, Ora) or Python (Click, Typer, Rich). Use when creating CLI tools, terminal UX, argument parsing, or interactive prompts.+---++# CLI Builder Skill++## Overview++This skill helps you build professional command-line interfaces with excellent user experience. Covers argument parsing, interactive prompts, progress indicators, colored output, and cross-platform compatibility.++## CLI Design Philosophy++### Principles of Good CLI Design+1. **Predictable**: Follow conventions users expect+2. **Helpful**: Provide clear help text and error messages+3. **Composable**: Work well with pipes and other tools+4. **Forgiving**: Accept common variations in input++### Design Guidelines+- **DO**: Use conventional flag names (`-v`, `--verbose`, `-h`, `--help`)+- **DO**: Provide meaningful exit codes+- **DO**: Support `--version` and `--help` on all commands+- **DO**: Use colors meaningfully (errors=red, success=green)+- **DON'T**: Require interactive input when running in pipes+- **DON'T**: Print to stdout when outputting errors+- **DON'T**: Ignore signals (Ctrl+C should exit cleanly)++## Node.js CLI Development++### Project Setup++```bash+# Initialize CLI project+mkdir my-cli && cd my-cli+npm init -y++# Install core dependencies+npm install commander chalk ora inquirer++# Optional: TypeScript support+npm install -D typescript @types/node @types/inquirer ts-node+```++### Package.json Configuration++```json+{+ "name": "my-cli",+ "version": "1.0.0",+ "description": "A powerful CLI tool",+ "bin": {+ "mycli": "./bin/cli.js"+ },+ "files": [+ "bin",+ "dist"+ ],+ "scripts": {+ "build": "tsc",+ "dev": "ts-node src/cli.ts",+ "link": "npm link"+ },+ "engines": {+ "node": ">=18.0.0"+ }+}+```++### Commander.js - Command Structure++```typescript+// src/cli.ts+import { Command } from 'commander';+import { version } from '../package.json';++const program = new Command();++program+ .name('mycli')+ .description('A powerful CLI for doing awesome things')+ .version(version, '-v, --version', 'Display version number');++// Simple command+program+ .command('init')+ .description('Initialize a new project')+ .argument('[name]', 'Project name', 'my-project')+ .option('-t, --template <type>', 'Template to use', 'default')+ .option('--no-git', 'Skip git initialization')+ .option('-f, --force', 'Overwrite existing files')+ .action(async (name, options) => {+ console.log(`Creating project: ${name}`);+ console.log(`Template: ${options.template}`);+ console.log(`Git: ${options.git}`);+ });++// Command with subcommands+const config = program+ .command('config')+ .description('Manage configuration');++config+ .command('get <key>')+ .description('Get a configuration value')+ .action((key) => {+ console.log(`Getting config: ${key}`);+ });++config+ .command('set <key> <value>')+ .description('Set a configuration value')+ .action((key, value) => {+ console.log(`Setting ${key} = ${value}`);+ });++config+ .command('list')+ .description('List all configuration')+ .option('--json', 'Output as JSON')+ .action((options) => {+ if (options.json) {+ console.log(JSON.stringify({ key: 'value' }, null, 2));+ } else {+ console.log('key = value');+ }+ });++// Parse arguments+program.parse();+```++### Chalk - Colored Output++```typescript+// src/utils/logger.ts+import chalk from 'chalk';++export const logger = {+ info: (msg: string) => console.log(chalk.blue('info'), msg),+ success: (msg: string) => console.log(chalk.green('success'), msg),+ warning: (msg: string) => console.log(chalk.yellow('warning'), msg),+ error: (msg: string) => console.error(chalk.red('error'), msg),++ // Styled output+ title: (msg: string) => console.log(chalk.bold.underline(msg)),+ dim: (msg: string) => console.log(chalk.dim(msg)),++ // Formatted output+ list: (items: string[]) => {+ items.forEach(item => console.log(chalk.gray(' -'), item));+ },++ // Table-like output+ keyValue: (pairs: Record<string, string>) => {+ const maxKeyLen = Math.max(...Object.keys(pairs).map(k => k.length));+ Object.entries(pairs).forEach(([key, value]) => {+ console.log(+ chalk.cyan(key.padEnd(maxKeyLen)),+ chalk.gray(':'),+ value+ );+ });+ }+};++// Usage+logger.title('Project Configuration');+logger.keyValue({+ 'Name': 'my-project',+ 'Template': 'typescript',+ 'Version': '1.0.0'+});+```++### Ora - Progress Spinners++```typescript+// src/utils/spinner.ts+import ora, { Ora } from 'ora';++export function createSpinner(text: string): Ora {+ return ora({+ text,+ spinner: 'dots',+ color: 'cyan'+ });+}++// Usage patterns+async function downloadWithProgress() {+ const spinner = createSpinner('Downloading dependencies...');+ spinner.start();++ try {+ await downloadFiles();+ spinner.succeed('Dependencies downloaded');+ } catch (error) {+ spinner.fail('Download failed');+ throw error;+ }+}++// Sequential spinners+async function setupProject() {+ const steps = [+ { text: 'Creating directory structure', fn: createDirs },+ { text: 'Installing dependencies', fn: installDeps },+ { text: 'Initializing git', fn: initGit },+ { text: 'Configuring project', fn: configure }+ ];++ for (const step of steps) {+ const spinner = createSpinner(step.text);+ spinner.start();+ try {+ await step.fn();+ spinner.succeed();+ } catch (error) {+ spinner.fail();+ throw error;+ }+ }+}+```++### Inquirer - Interactive Prompts++```typescript+// src/prompts/init.ts+import inquirer from 'inquirer';++interface ProjectAnswers {+ name: string;+ template: string;+ features: string[];+ initGit: boolean;+ installDeps: boolean;+}++export async function promptProjectSetup(): Promise<ProjectAnswers> {+ return inquirer.prompt([+ {+ type: 'input',+ name: 'name',+ message: 'Project name:',+ default: 'my-project',+ validate: (input) => {+ if (!/^[a-z0-9-]+$/.test(input)) {+ return 'Name must be lowercase alphanumeric with dashes';+ }+ return true;+ }+ },+ {+ type: 'list',+ name: 'template',+ message: 'Select a template:',+ choices: [+ { name: 'Minimal - Basic setup', value: 'minimal' },+ { name: 'Standard - Recommended defaults', value: 'standard' },+ { name: 'Full - Kitchen sink', value: 'full' }+ ],+ default: 'standard'+ },+ {+ type: 'checkbox',+ name: 'features',+ message: 'Select features:',+ choices: [+ { name: 'TypeScript', value: 'typescript', checked: true },+ { name: 'ESLint', value: 'eslint', checked: true },+ { name: 'Prettier', value: 'prettier', checked: true },+ { name: 'Testing (Jest)', value: 'jest' },+ { name: 'CI/CD (GitHub Actions)', value: 'github-actions' }+ ]+ },+ {+ type: 'confirm',+ name: 'initGit',+ message: 'Initialize git repository?',+ default: true+ },+ {+ type: 'confirm',+ name: 'installDeps',+ message: 'Install dependencies now?',+ default: true,+ when: (answers) => answers.template !== 'minimal'+ }+ ]);+}++// Advanced: Dynamic prompts+export async function promptWithContext(context: { hasExisting: boolean }) {+ const questions = [];++ if (context.hasExisting) {+ questions.push({+ type: 'confirm',+ name: 'overwrite',+ message: 'Directory exists. Overwrite?',+ default: false+ });+ }++ // Add more questions...++ return inquirer.prompt(questions);+}+```++### Complete CLI Example++```typescript+#!/usr/bin/env node+// bin/cli.ts++import { Command } from 'commander';+import chalk from 'chalk';+import ora from 'ora';+import inquirer from 'inquirer';+import { existsSync, mkdirSync, writeFileSync } from 'fs';+import { join } from 'path';++const program = new Command();++program+ .name('create-app')+ .description('Create a new application')+ .version('1.0.0');++program+ .command('create')+ .argument('[name]', 'Project name')+ .option('-t, --template <template>', 'Template to use')+ .option('-y, --yes', 'Skip prompts with defaults')+ .action(async (name, options) => {+ try {+ // Get project name if not provided+ if (!name) {+ const { projectName } = await inquirer.prompt([{+ type: 'input',+ name: 'projectName',+ message: 'Project name:',+ default: 'my-app'+ }]);+ name = projectName;+ }++ // Check if directory exists+ const projectDir = join(process.cwd(), name);+ if (existsSync(projectDir)) {+ const { overwrite } = await inquirer.prompt([{+ type: 'confirm',+ name: 'overwrite',+ message: `Directory ${name} exists. Overwrite?`,+ default: false+ }]);++ if (!overwrite) {+ console.log(chalk.yellow('Aborted.'));+ process.exit(0);+ }+ }++ // Get template if not provided+ let template = options.template;+ if (!template && !options.yes) {+ const { selectedTemplate } = await inquirer.prompt([{+ type: 'list',+ name: 'selectedTemplate',+ message: 'Select template:',+ choices: ['minimal', 'standard', 'typescript']+ }]);+ template = selectedTemplate;+ }+ template = template || 'standard';++ console.log();+ console.log(chalk.bold(`Creating ${name} with ${template} template...`));+ console.log();++ // Create project+ const spinner = ora('Creating directory structure').start();+ mkdirSync(projectDir, { recursive: true });+ spinner.succeed();++ spinner.start('Generating files');+ writeFileSync(+ join(projectDir, 'package.json'),+ JSON.stringify({ name, version: '1.0.0' }, null, 2)+ );+ spinner.succeed();++ // Success message+ console.log();+ console.log(chalk.green.bold('Success!'), `Created ${name}`);+ console.log();+ console.log('Next steps:');+ console.log(chalk.cyan(` cd ${name}`));+ console.log(chalk.cyan(' npm install'));+ console.log(chalk.cyan(' npm start'));+ console.log();++ } catch (error) {+ console.error(chalk.red('Error:'), error.message);+ process.exit(1);+ }+ });++// Handle unknown commands+program.on('command:*', () => {+ console.error(chalk.red('Unknown command:'), program.args.join(' '));+ console.log('Run', chalk.cyan('create-app --help'), 'for usage');+ process.exit(1);+});++// Parse and handle no command+program.parse();++if (!process.argv.slice(2).length) {+ program.help();+}+```++## Python CLI Development++### Typer - Modern Python CLI++```python+# cli.py+import typer+from typing import Optional, List+from enum import Enum+from rich.console import Console+from rich.table import Table+from rich.progress import track++app = typer.Typer(+ name="mycli",+ help="A powerful CLI for doing awesome things",+ add_completion=True+)+console = Console()+++class Template(str, Enum):+ minimal = "minimal"+ standard = "standard"+ full = "full"+++def init(+ name: str = typer.Argument("my-project", help="Project name"),+ template: Template = typer.Option(+ Template.standard,+ "--template", "-t",+ help="Template to use"+ ),+ features: List[str] = typer.Option(+ [],+ "--feature", "-f",+ help="Features to include"+ ),+ no_git: bool = typer.Option(+ False,+ "--no-git",+ help="Skip git initialization"+ ),+ force: bool = typer.Option(+ False,+ "--force", "-f",+ help="Overwrite existing files"+ )+):+ """Initialize a new project."""+ console.print(f"[bold]Creating project:[/bold] {name}")+ console.print(f"[dim]Template:[/dim] {template.value}")++ # Progress indicator+ for step in track(range(5), description="Setting up..."):+ # Do work+ pass++ console.print("[green]Success![/green] Project created")+++def config(+ key: str = typer.Argument(..., help="Configuration key"),+ value: Optional[str] = typer.Argument(None, help="Value to set")+):+ """Get or set configuration values."""+ if value is None:+ # Get config+ console.print(f"{key} = some_value")+ else:+ # Set config+ console.print(f"Set {key} = {value}")+++def status():+ """Show project status."""+ table = Table(title="Project Status")+ table.add_column("Property", style="cyan")+ table.add_column("Value", style="green")++ table.add_row("Name", "my-project")+ table.add_row("Version", "1.0.0")+ table.add_row("Template", "standard")++ console.print(table)+++# Subcommand group+db_app = typer.Typer(help="Database operations")+app.add_typer(db_app, name="db")+++@db_app.command("migrate")+def db_migrate(+ direction: str = typer.Option("up", "--direction", "-d"),+ steps: int = typer.Option(1, "--steps", "-n")+):+ """Run database migrations."""+ console.print(f"Running {steps} migration(s) {direction}")+++@db_app.command("seed")+def db_seed():+ """Seed the database."""+ console.print("Seeding database...")+++if __name__ == "__main__":+ app()+```++### Click - Flexible Python CLI++```python+# cli_click.py+import click+from rich.console import Console+from rich.progress import Progress, SpinnerColumn, TextColumn++console = Console()++[email protected]_option(version="1.0.0")[email protected]("--verbose", "-v", is_flag=True, help="Enable verbose output")[email protected]_context+def cli(ctx, verbose):+ """A powerful CLI for doing awesome things."""+ ctx.ensure_object(dict)+ ctx.obj["verbose"] = verbose++[email protected]("name", default="my-project")+ "--template", "-t",+ type=click.Choice(["minimal", "standard", "full"]),+ default="standard",+ help="Template to use"+)[email protected]("--no-git", is_flag=True, help="Skip git initialization")[email protected]_option(prompt="Create project?")[email protected]_context+def init(ctx, name, template, no_git):+ """Initialize a new project."""+ if ctx.obj["verbose"]:+ console.print(f"[dim]Verbose mode enabled[/dim]")++ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ transient=True,+ ) as progress:+ task = progress.add_task("Creating project...", total=None)+ # Do work+ import time+ time.sleep(1)++ console.print(f"[green]Created {name} with {template} template[/green]")+++def config():+ """Manage configuration."""+ pass++[email protected]("get")[email protected]("key")+def config_get(key):+ """Get a configuration value."""+ console.print(f"{key} = value")++[email protected]("set")[email protected]("key")[email protected]("value")+def config_set(key, value):+ """Set a configuration value."""+ console.print(f"Set {key} = {value}")++[email protected]("--format", "-f", type=click.Choice(["text", "json"]), default="text")+def status(format):+ """Show project status."""+ if format == "json":+ click.echo('{"status": "ok"}')+ else:+ console.print("[bold]Status:[/bold] OK")+++if __name__ == "__main__":+ cli()+```++## Advanced Patterns++### Configuration Management++```typescript+// src/config.ts+import { homedir } from 'os';+import { join } from 'path';+import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';++interface Config {+ apiKey?: string;+ defaultTemplate?: string;+ analytics?: boolean;+}++class ConfigManager {+ private configDir: string;+ private configPath: string;+ private config: Config;++ constructor() {+ this.configDir = join(homedir(), '.mycli');+ this.configPath = join(this.configDir, 'config.json');+ this.config = this.load();+ }++ private load(): Config {+ if (!existsSync(this.configPath)) {+ return {};+ }+ try {+ return JSON.parse(readFileSync(this.configPath, 'utf-8'));+ } catch {+ return {};+ }+ }++ private save(): void {+ if (!existsSync(this.configDir)) {+ mkdirSync(this.configDir, { recursive: true });+ }+ writeFileSync(this.configPath, JSON.stringify(this.config, null, 2));+ }++ get<K extends keyof Config>(key: K): Config[K] {+ return this.config[key];+ }++ set<K extends keyof Config>(key: K, value: Config[K]): void {+ this.config[key] = value;+ this.save();+ }++ getAll(): Config {+ return { ...this.config };+ }++ clear(): void {+ this.config = {};+ this.save();+ }+}++export const config = new ConfigManager();+```++### Error Handling++```typescript+// src/errors.ts+import chalk from 'chalk';++export class CLIError extends Error {+ constructor(+ message: string,+ public readonly code: string = 'ERROR',+ public readonly suggestion?: string+ ) {+ super(message);+ this.name = 'CLIError';+ }+}++export function handleError(error: unknown): never {+ if (error instanceof CLIError) {+ console.error(chalk.red(`Error [${error.code}]:`), error.message);+ if (error.suggestion) {+ console.error(chalk.yellow('Suggestion:'), error.suggestion);+ }+ process.exit(1);+ }++ if (error instanceof Error) {+ console.error(chalk.red('Unexpected error:'), error.message);+ if (process.env.DEBUG) {+ console.error(error.stack);+ }+ process.exit(1);+ }++ console.error(chalk.red('Unknown error occurred'));+ process.exit(1);+}++// Usage+process.on('uncaughtException', handleError);+process.on('unhandledRejection', handleError);+```++### Non-Interactive Mode Detection++```typescript+// src/utils/tty.ts+import { stdin, stdout } from 'process';++export function isInteractive(): boolean {+ return stdin.isTTY && stdout.isTTY;+}++export function requireInteractive(message?: string): void {+ if (!isInteractive()) {+ console.error(message || 'This command requires an interactive terminal');+ process.exit(1);+ }+}++// Usage in command+async function initCommand(options: { yes?: boolean }) {+ if (options.yes || !isInteractive()) {+ // Use defaults, skip prompts+ return runWithDefaults();+ }++ // Interactive prompts+ const answers = await promptUser();+ return runWithAnswers(answers);+}+```++### Output Formatting++```typescript+// src/utils/output.ts+import { stdout } from 'process';++export type OutputFormat = 'text' | 'json' | 'table';++export function output(data: unknown, format: OutputFormat = 'text'): void {+ switch (format) {+ case 'json':+ console.log(JSON.stringify(data, null, 2));+ break;+ case 'table':+ console.table(data);+ break;+ case 'text':+ default:+ if (typeof data === 'string') {+ console.log(data);+ } else {+ console.log(JSON.stringify(data, null, 2));+ }+ }+}++// Check if output is piped+export function isPiped(): boolean {+ return !stdout.isTTY;+}++// Suppress decorative output when piped+export function log(message: string): void {+ if (!isPiped()) {+ console.log(message);+ }+}+```++## CLI Checklist++### Core Features+- [ ] `--help` on all commands+- [ ] `--version` flag+- [ ] Meaningful exit codes+- [ ] Error messages to stderr+- [ ] Support for environment variables++### User Experience+- [ ] Progress indicators for long operations+- [ ] Colored output (with `NO_COLOR` support)+- [ ] Interactive prompts (with non-interactive fallback)+- [ ] Tab completion setup++### Best Practices+- [ ] Works in pipes (`echo "data" | mycli process`)+- [ ] Handles Ctrl+C gracefully+- [ ] Configuration file support+- [ ] Debug/verbose mode+- [ ] Consistent command structure++### Distribution+- [ ] npm/PyPI package configured+- [ ] Binary entry point set up+- [ ] README with installation and usage+- [ ] Changelog maintained++## When to Use This Skill++Invoke this skill when:+- Creating new CLI tools from scratch+- Adding commands to existing CLIs+- Building interactive prompts and wizards+- Implementing progress indicators+- Setting up argument parsing+- Creating configuration management+- Designing CLI UX patterns+- Publishing CLI tools to npm or PyPIdiff --git a/skills/competitor-tracker/SKILL.md b/skills/competitor-tracker/SKILL.mdnew file mode 100644index 0000000..58c8d20--- /dev/null+++ b/skills/competitor-tracker/SKILL.md@@ -0,0 +1,98 @@+---+name: Competitor Tracker+slug: competitor-tracker+description: Track and analyze competitor activities for strategic advantage+category: marketing+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "competitor analysis"+ - "competitive intelligence"+ - "competitor tracking"+ - "market intelligence"+ - "competitive research"+tags:+ - competitive-intelligence+ - market-research+ - strategy+ - competitor-analysis+ - monitoring+---++# Competitor Tracker++Stay ahead of the competition with systematic monitoring and analysis of competitor activities. This skill helps you track product launches, pricing changes, marketing campaigns, hiring trends, and strategic moves across your competitive landscape.++Knowledge is power. This skill provides frameworks for identifying key competitors, setting up monitoring systems, analyzing competitive positioning, and turning insights into strategic action. Move from reactive to proactive - anticipate competitor moves before they impact your business.++Essential for product marketers, strategists, founders, and anyone who needs to understand and respond to competitive dynamics.++## Core Workflows++### Workflow 1: Competitive Landscape Mapping+1. **Competitor Identification** - Direct, indirect, aspirational+2. **Category Definition** - How competitors group+3. **Positioning Analysis** - How each competitor positions+4. **Strengths Assessment** - What they do well+5. **Weakness Identification** - Where they fall short+6. **Threat Evaluation** - Who threatens your business most+7. **Opportunity Finding** - Gaps you can exploit++### Workflow 2: Competitor Monitoring Setup+1. **Information Sources** - Where to gather intelligence+2. **Alert Configuration** - Automated notifications+3. **Social Listening** - Track mentions and sentiment+4. **Website Monitoring** - Changes, new pages, pricing+5. **Content Tracking** - Blog posts, resources, announcements+6. **Job Posting Analysis** - Hiring indicates strategy+7. **Review Monitoring** - Customer feedback on competitors++### Workflow 3: Competitive Analysis Deep Dive+1. **Product Comparison** - Feature-by-feature analysis+2. **Pricing Analysis** - Pricing models and positioning+3. **Messaging Analysis** - Value props, claims, positioning+4. **Go-to-Market Review** - Sales motions, channels, partnerships+5. **Customer Analysis** - Who they target and win+6. **Funding/Financial Review** - Resources and runway+7. **Team Analysis** - Key hires and departures++### Workflow 4: Battle Card Development+1. **Quick Overview** - Competitor at a glance+2. **Win/Loss Themes** - Why we win and lose against them+3. **Objection Handling** - Counter their claims+4. **Differentiation Points** - Where we're better+5. **Landmine Questions** - Questions that expose their weaknesses+6. **Competitive Positioning** - How to position against them+7. **Update Schedule** - Keep battle cards current++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Map competitors | "Map competitive landscape for [market]" |+| Analyze competitor | "Deep dive on [competitor name]" |+| Compare features | "Compare [product] vs [competitor]" |+| Create battle card | "Create battle card for [competitor]" |+| Monitor setup | "Set up monitoring for [competitor]" |+| Win/loss analysis | "Analyze wins and losses vs [competitor]" |+| Pricing analysis | "Compare pricing with [competitors]" |+| Trend tracking | "What's [competitor] doing lately?" |++## Best Practices++- **Focus on few** - Track 3-5 competitors deeply vs many superficially+- **Systematic cadence** - Regular updates vs sporadic research+- **Multiple sources** - Triangulate from various information sources+- **Separate fact from opinion** - Verify claims+- **Track over time** - Trends matter more than snapshots+- **Involve sales** - Frontline has competitive intelligence+- **Share broadly** - Intelligence benefits whole organization+- **Avoid obsession** - Competitors inform, customers drive+- **Act on insights** - Intelligence without action is waste+- **Respect ethics** - Gather information legally and ethically+- **Update battle cards** - Outdated info is dangerous+- **Watch for new entrants** - Don't only watch established players+- **Consider substitutes** - Competition isn't just direct+- **Note positioning changes** - Messaging shifts signal strategy+- **Predict moves** - Use intelligence to anticipatediff --git a/skills/compliance-checker/SKILL.md b/skills/compliance-checker/SKILL.mdnew file mode 100644index 0000000..75662ba--- /dev/null+++ b/skills/compliance-checker/SKILL.md@@ -0,0 +1,463 @@+---+name: Compliance Checker+slug: compliance-checker+description: Check regulatory compliance across finance, tax, employment, data privacy, and industry-specific requirements+category: finance+complexity: complex+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "compliance check"+ - "regulatory compliance"+ - "audit preparation"+ - "compliance requirements"+ - "risk assessment"+ - "policy compliance"+tags:+ - compliance+ - regulatory+ - audit+ - risk-management+ - governance+---++# Compliance Checker++Expert compliance assessment agent that evaluates regulatory compliance across business operations, identifies gaps, and provides remediation guidance. Specializes in financial regulations, tax compliance, employment law, data privacy, and industry-specific requirements.++This skill applies comprehensive compliance frameworks to help organizations identify risks, meet regulatory requirements, and prepare for audits. Perfect for startups scaling up, compliance reviews, and risk assessments.++**Disclaimer:** This skill provides general compliance guidance. Always consult qualified legal and compliance professionals for specific regulatory advice.++## Core Workflows++### Workflow 1: Business Compliance Assessment++**Objective:** Comprehensive compliance review for business operations++**Steps:**+1. **Business Profile Analysis**+ - Entity type (LLC, Corp, etc.)+ - Industry and sector+ - Geographic presence (states, countries)+ - Revenue and employee count+ - Business model (B2B, B2C)+ - Customer base characteristics++2. **Corporate Compliance Checklist**+ - **Entity Formation:**+ - [ ] Articles of incorporation/organization filed+ - [ ] Operating agreement or bylaws in place+ - [ ] EIN obtained from IRS+ - [ ] State registrations current++ - **Corporate Governance:**+ - [ ] Board meetings conducted (if applicable)+ - [ ] Meeting minutes maintained+ - [ ] Annual reports filed+ - [ ] Franchise tax paid+ - [ ] Registered agent current++ - **Foreign Qualification:**+ - [ ] Registered in states where "doing business"+ - [ ] Annual filings current in each state+ - [ ] State tax obligations met++3. **Financial Compliance Checklist**+ - **Tax Compliance:**+ - [ ] Federal income tax returns filed+ - [ ] State income tax returns filed+ - [ ] Sales tax collection and remittance+ - [ ] Payroll tax deposits and filings+ - [ ] 1099s and W-2s issued++ - **Accounting Standards:**+ - [ ] Appropriate accounting method (cash/accrual)+ - [ ] Revenue recognition compliant+ - [ ] Financial statements prepared+ - [ ] Audit requirements met (if applicable)++4. **Employment Compliance Checklist**+ - **Hiring:**+ - [ ] I-9 verification completed+ - [ ] E-Verify (if required)+ - [ ] Background check compliance+ - [ ] Employment agreements in place++ - **Compensation:**+ - [ ] Minimum wage compliance+ - [ ] Overtime pay compliance+ - [ ] Equal pay compliance+ - [ ] Worker classification correct++ - **Workplace:**+ - [ ] Anti-harassment policy+ - [ ] EEO compliance+ - [ ] OSHA requirements (if applicable)+ - [ ] Workers' compensation insurance+ - [ ] State-specific requirements++5. **Data and Privacy Compliance**+ - **Data Protection:**+ - [ ] Privacy policy published+ - [ ] Data collection disclosed+ - [ ] Cookie consent (if applicable)+ - [ ] CCPA compliance (CA)+ - [ ] GDPR compliance (EU)++ - **Data Security:**+ - [ ] Security measures documented+ - [ ] Breach notification procedures+ - [ ] Data retention policies+ - [ ] Vendor due diligence++6. **Compliance Gap Analysis**+ - Identify missing requirements+ - Prioritize by risk level+ - Create remediation timeline+ - Assign ownership++**Deliverable:** Comprehensive compliance assessment with gap analysis++### Workflow 2: Financial Regulations Compliance++**Objective:** Ensure compliance with financial regulatory requirements++**Steps:**+1. **Anti-Money Laundering (AML)**+ - **Bank Secrecy Act Requirements:**+ - [ ] Know Your Customer (KYC) procedures+ - [ ] Customer due diligence (CDD)+ - [ ] Enhanced due diligence (high-risk)+ - [ ] Suspicious Activity Reports (SARs)+ - [ ] Currency Transaction Reports (CTRs)++ - **OFAC Compliance:**+ - [ ] Sanctions screening+ - [ ] Blocked persons list checks+ - [ ] Country restrictions++2. **Payment Processing Compliance**+ - **PCI-DSS (Credit Cards):**+ - [ ] SAQ completed+ - [ ] Security requirements met+ - [ ] Quarterly vulnerability scans+ - [ ] Annual compliance validation++ - **Money Transmitter Licensing:**+ - [ ] State licensing (if applicable)+ - [ ] Federal registration (FinCEN)+ - [ ] Surety bond requirements++3. **Investment Regulations**+ - **Securities Compliance:**+ - [ ] Registration requirements+ - [ ] Exemptions utilized properly+ - [ ] Accredited investor verification+ - [ ] Blue sky compliance (state)++ - **Investment Advisor:**+ - [ ] SEC or state registration+ - [ ] Form ADV requirements+ - [ ] Fiduciary duty compliance++4. **Industry-Specific Financial Regulations**+ - Banking: Federal Reserve, FDIC, OCC+ - Insurance: State insurance commissions+ - Real Estate: RESPA, Fair Housing+ - Mortgage: TILA, RESPA, HMDA++**Deliverable:** Financial regulation compliance checklist++### Workflow 3: Employment Law Compliance++**Objective:** Ensure compliance with employment laws and regulations++**Steps:**+1. **Federal Employment Laws**+ - **Fair Labor Standards Act (FLSA):**+ - [ ] Minimum wage ($7.25 federal)+ - [ ] Overtime (1.5x after 40 hours)+ - [ ] Exempt vs non-exempt classification+ - [ ] Child labor restrictions+ - [ ] Record-keeping requirements++ - **Equal Employment Opportunity:**+ - [ ] Non-discrimination policies+ - [ ] Reasonable accommodations (ADA)+ - [ ] Religious accommodations+ - [ ] Age discrimination (40+)++ - **Family and Medical Leave (FMLA):**+ - [ ] 12 weeks unpaid leave+ - [ ] Eligibility criteria (50+ employees)+ - [ ] Job protection provisions++2. **State Employment Laws**+ - Higher minimum wages+ - Paid sick leave requirements+ - Paid family leave+ - At-will employment modifications+ - Non-compete restrictions+ - Ban-the-box laws+ - Salary history bans++3. **Worker Classification**+ - **Employee vs Contractor Tests:**+ - IRS 20-factor test+ - ABC test (California AB5)+ - Economic reality test++ - **Misclassification Risks:**+ - Back taxes and penalties+ - Benefits claims+ - Workers' comp liability+ - Unemployment insurance++4. **Payroll Compliance**+ - [ ] W-4 forms collected+ - [ ] Federal withholding correct+ - [ ] State withholding correct+ - [ ] FICA taxes withheld+ - [ ] Payroll tax deposits timely+ - [ ] Quarterly 941 filings+ - [ ] Year-end W-2s and W-3s++5. **Workplace Safety**+ - OSHA requirements+ - Safety training+ - Injury reporting+ - Hazard communication++**Deliverable:** Employment compliance audit with remediation plan++### Workflow 4: Data Privacy Compliance++**Objective:** Ensure compliance with data privacy regulations++**Steps:**+1. **Data Inventory**+ - What personal data is collected+ - How data is collected+ - Where data is stored+ - Who has access+ - How long data is retained+ - How data is shared/sold++2. **CCPA/CPRA Compliance (California)**+ - **Applicability Thresholds:**+ - $25M+ annual revenue, OR+ - 100K+ consumers/households, OR+ - 50%+ revenue from selling data++ - **Requirements:**+ - [ ] Privacy policy with required disclosures+ - [ ] "Do Not Sell My Info" link (if selling)+ - [ ] Consumer rights mechanisms+ - [ ] Service provider agreements+ - [ ] Training and record-keeping++3. **GDPR Compliance (EU)**+ - **Applicability:**+ - Processing EU resident data+ - Offering goods/services to EU+ - Monitoring EU individuals++ - **Requirements:**+ - [ ] Lawful basis for processing+ - [ ] Privacy notice requirements+ - [ ] Data subject rights mechanisms+ - [ ] Data Protection Officer (if required)+ - [ ] Data Processing Agreements+ - [ ] Cross-border transfer mechanisms+ - [ ] Breach notification (72 hours)++4. **Industry-Specific Privacy**+ - **HIPAA (Healthcare):**+ - [ ] Privacy Rule compliance+ - [ ] Security Rule compliance+ - [ ] Business Associate Agreements++ - **FERPA (Education):**+ - [ ] Student records protection+ - [ ] Parent/student consent++ - **GLBA (Financial):**+ - [ ] Privacy notice requirements+ - [ ] Safeguards Rule+ - [ ] Pretexting protections++5. **Privacy Program Development**+ - Privacy policy drafting+ - Cookie consent implementation+ - Data subject request handling+ - Vendor assessment process+ - Incident response plan++**Deliverable:** Data privacy compliance assessment with remediation roadmap++### Workflow 5: Audit Preparation++**Objective:** Prepare for external compliance audit++**Steps:**+1. **Audit Scope Definition**+ - Type of audit (financial, compliance, operational)+ - Regulatory basis+ - Time period covered+ - Specific requirements++2. **Documentation Gathering**+ - **Corporate Documents:**+ - Formation documents+ - Governance documents+ - Meeting minutes+ - Ownership records++ - **Financial Documents:**+ - Financial statements+ - Bank statements+ - Tax returns+ - Payroll records++ - **Operational Documents:**+ - Policies and procedures+ - Contracts and agreements+ - Licenses and permits+ - Insurance certificates++3. **Internal Assessment**+ - Self-audit checklist+ - Gap identification+ - Pre-audit remediation+ - Document organization++4. **Control Testing**+ - Review internal controls+ - Test control effectiveness+ - Document control weaknesses+ - Implement improvements++5. **Audit Readiness Checklist**+ - [ ] All documents organized+ - [ ] Key personnel briefed+ - [ ] Questions anticipated+ - [ ] Response team identified+ - [ ] Timeline understood+ - [ ] Workspace prepared++**Deliverable:** Audit preparation package with documentation checklist++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Business compliance | "Check business compliance" |+| Financial regulations | "Review financial compliance" |+| Employment law | "Check employment compliance" |+| Data privacy | "Assess privacy compliance" |+| Audit prep | "Prepare for compliance audit" |+| Gap analysis | "Identify compliance gaps" |++## Compliance Thresholds++### By Employee Count++| Threshold | Requirements Triggered |+|-----------|------------------------|+| 1+ | I-9, W-2, basic employment law |+| 4+ | EEO-1 reporting (with federal contracts) |+| 11+ | OSHA 300 logs |+| 15+ | Title VII, ADA, GINA |+| 20+ | ADEA, COBRA (state varies) |+| 50+ | FMLA, ACA employer mandate |+| 100+ | EEO-1 reporting, WARN Act |++### By Revenue/Data++| Threshold | Requirements |+|-----------|--------------|+| $25M+ (CA) | CCPA compliance |+| 50K+ contacts | Potential GDPR DPO |+| PII collection | Privacy policy required |+| Payment processing | PCI-DSS |++## Compliance Calendar Template++```markdown+# Annual Compliance Calendar++## Monthly+- Payroll tax deposits+- Sales tax remittance+- Recurring filings++## Quarterly+- [ ] Q1: Quarterly payroll returns (941)+- [ ] Q2: Quarterly payroll returns (941)+- [ ] Q3: Quarterly payroll returns (941)+- [ ] Q4: Quarterly payroll returns (941)+- [ ] Estimated tax payments (if applicable)++## Annual+- [ ] Jan 31: W-2s and 1099s due+- [ ] Mar 15: S-Corp/Partnership returns due+- [ ] Apr 15: C-Corp returns due (calendar year)+- [ ] Annual report filings (varies by state)+- [ ] Franchise tax payments+- [ ] Insurance renewals+- [ ] Contract renewals+- [ ] Policy reviews++## State-Specific+[Add state-specific deadlines]+```++## Best Practices++### Compliance Program+- Designate compliance officer+- Document policies and procedures+- Train employees regularly+- Monitor regulatory changes+- Conduct periodic assessments++### Record Keeping+- Maintain organized files+- Follow retention schedules+- Implement backup systems+- Control access appropriately++### Risk Management+- Identify compliance risks+- Prioritize by impact+- Implement controls+- Monitor effectiveness+- Report to leadership++## Integration with Other Skills++- **Use with `tax-strategist`:** Tax compliance alignment+- **Use with `contract-analyzer`:** Contract compliance review+- **Use with `financial-reporter`:** Regulatory reporting+- **Use with `accounts-reconciler`:** Financial audit support+- **Use with `billing-manager`:** Billing compliance++## Common Pitfalls to Avoid++- **Assuming one-size-fits-all:** State laws vary significantly+- **Ignoring threshold triggers:** Requirements change with growth+- **Delayed compliance:** Proactive is cheaper than reactive+- **Poor documentation:** If it's not documented, it didn't happen+- **Overlooking updates:** Regulations change frequently+- **DIY complex matters:** Know when to get professional help+- **Compliance theater:** Policies must be implemented, not just written+- **Siloed compliance:** Integrate across departments++## Disclaimer++This skill provides general compliance information only. Regulations vary by jurisdiction and change frequently. Always:+- Consult qualified legal counsel for specific situations+- Verify current requirements with regulatory authorities+- Consider your complete business context+- Implement appropriate professional oversightdiff --git a/skills/computer-vision-helper/SKILL.md b/skills/computer-vision-helper/SKILL.mdnew file mode 100644index 0000000..26690d7--- /dev/null+++ b/skills/computer-vision-helper/SKILL.md@@ -0,0 +1,317 @@+---+name: Computer Vision Helper+slug: computer-vision-helper+description: Assist with image analysis, object detection, and visual AI tasks+category: ai-ml+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "image analysis"+ - "computer vision"+ - "object detection"+ - "image classification"+ - "visual AI"+tags:+ - computer-vision+ - image-analysis+ - object-detection+ - visual-AI+ - deep-learning+---++# Computer Vision Helper++The Computer Vision Helper skill guides you through implementing image analysis and visual AI tasks. From basic image classification to complex object detection and segmentation, this skill helps you leverage modern computer vision techniques effectively.++Computer vision has been transformed by deep learning and now by vision-language models. This skill covers both traditional approaches (CNNs, pre-trained models) and cutting-edge techniques (CLIP, GPT-4V, Segment Anything). It helps you choose the right approach based on your accuracy requirements, available data, and deployment constraints.++Whether you are building product recognition, document analysis, medical imaging, or any visual AI application, this skill ensures you understand the landscape and implement solutions that work.++## Core Workflows++### Workflow 1: Select Computer Vision Approach+1. **Define** the task:+ - Classification: What category is this image?+ - Detection: Where are objects in this image?+ - Segmentation: Pixel-level object boundaries+ - OCR: Extract text from images+ - Similarity: Find similar images+ - Generation: Create or modify images+2. **Assess** available resources:+ - Training data quantity and quality+ - Compute budget (training and inference)+ - Latency requirements+ - Accuracy needs+3. **Choose** approach:+ | Task | No Training Data | Small Dataset | Large Dataset |+ |------|-----------------|---------------|---------------|+ | Classification | CLIP, GPT-4V | Transfer learning | Fine-tune/train |+ | Detection | GPT-4V, Grounding DINO | Fine-tune YOLO | Train custom |+ | Segmentation | SAM | Fine-tune SAM | Train custom |+ | OCR | Cloud APIs, Tesseract | Fine-tune | Train custom |+4. **Plan** implementation+5. **Document** approach rationale++### Workflow 2: Implement Image Classification+1. **Prepare** data:+ ```python+ # Data loading with augmentation+ transform = transforms.Compose([+ transforms.Resize(256),+ transforms.CenterCrop(224),+ transforms.RandomHorizontalFlip(),+ transforms.ColorJitter(brightness=0.2, contrast=0.2),+ transforms.ToTensor(),+ transforms.Normalize(mean=[0.485, 0.456, 0.406],+ std=[0.229, 0.224, 0.225])+ ])++ dataset = ImageFolder(root='data/', transform=transform)+ dataloader = DataLoader(dataset, batch_size=32, shuffle=True)+ ```+2. **Set up** model:+ ```python+ # Transfer learning from pretrained model+ model = models.resnet50(pretrained=True)++ # Freeze early layers+ for param in model.parameters():+ param.requires_grad = False++ # Replace classifier head+ model.fc = nn.Linear(model.fc.in_features, num_classes)+ ```+3. **Train** with validation+4. **Evaluate** on test set+5. **Optimize** for deployment++### Workflow 3: Deploy Vision Model+1. **Optimize** model:+ - Quantization (INT8)+ - Pruning+ - ONNX export+ - TensorRT optimization+2. **Set up** inference pipeline:+ ```python+ class VisionPipeline:+ def __init__(self, model_path):+ self.model = load_optimized_model(model_path)+ self.preprocessor = ImagePreprocessor()++ def predict(self, image):+ # Preprocess+ tensor = self.preprocessor.process(image)++ # Inference+ with torch.no_grad():+ output = self.model(tensor)++ # Postprocess+ return self.postprocess(output)++ def predict_batch(self, images):+ tensors = [self.preprocessor.process(img) for img in images]+ batch = torch.stack(tensors)++ with torch.no_grad():+ outputs = self.model(batch)++ return [self.postprocess(out) for out in outputs]+ ```+3. **Deploy** to target environment+4. **Monitor** performance++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Choose approach | "What CV approach for [task]" |+| Classify images | "Build image classifier" |+| Detect objects | "Object detection for [use case]" |+| Extract text | "OCR from images" |+| Zero-shot vision | "Classify images without training data" |+| Optimize model | "Speed up vision model" |++## Best Practices++- **Start with Pre-trained**: Don't train from scratch unless necessary+ - ImageNet pre-trained models for general vision+ - Domain-specific models when available+ - CLIP/GPT-4V for zero-shot capabilities++- **Data Quality Over Quantity**: Clean, balanced data matters+ - Remove mislabeled and duplicate images+ - Balance classes or use weighted training+ - Include edge cases in test set++- **Augment Thoughtfully**: Augmentation should reflect real variation+ - Use augmentations that mirror production conditions+ - Don't augment in ways that destroy task-relevant features+ - Test that augmentation helps, don't assume++- **Validate Correctly**: Image data leaks easily+ - Split by unique images, not by augmented versions+ - Consider subject-level splits (same person in different photos)+ - Test on truly held-out data++- **Optimize for Target Hardware**: Inference matters+ - Know your deployment constraints (edge vs cloud)+ - Profile and optimize bottlenecks+ - Consider batch size for throughput++- **Handle Edge Cases**: Real images are messy+ - Different lighting conditions+ - Rotation, blur, occlusion+ - Unusual aspect ratios+ - Out-of-distribution inputs++## Advanced Techniques++### Vision-Language Models for Zero-Shot+Use CLIP for classification without training:+```python+import clip++model, preprocess = clip.load("ViT-B/32")++def zero_shot_classify(image, labels):+ # Prepare image+ image_tensor = preprocess(image).unsqueeze(0)++ # Prepare text prompts+ text_prompts = [f"a photo of a {label}" for label in labels]+ text_tokens = clip.tokenize(text_prompts)++ # Get embeddings+ with torch.no_grad():+ image_features = model.encode_image(image_tensor)+ text_features = model.encode_text(text_tokens)++ # Compute similarities+ similarities = (image_features @ text_features.T).softmax(dim=-1)++ return {label: sim.item() for label, sim in zip(labels, similarities[0])}+```++### GPT-4V for Visual Analysis+Use multimodal LLMs for complex vision tasks:+```python+def analyze_image(image_path, question):+ import base64+ from openai import OpenAI++ # Encode image+ with open(image_path, "rb") as f:+ image_data = base64.b64encode(f.read()).decode()++ client = OpenAI()+ response = client.chat.completions.create(+ model="gpt-4-vision-preview",+ messages=[{+ "role": "user",+ "content": [+ {"type": "text", "text": question},+ {"type": "image_url", "image_url": {+ "url": f"data:image/jpeg;base64,{image_data}"+ }}+ ]+ }],+ max_tokens=500+ )++ return response.choices[0].message.content+```++### Object Detection with YOLO+Fast, accurate object detection:+```python+from ultralytics import YOLO++# Load pretrained model+model = YOLO("yolov8n.pt")++# Fine-tune on custom dataset+model.train(+ data="custom_dataset.yaml",+ epochs=100,+ imgsz=640,+ batch=16+)++# Inference+results = model.predict(source="image.jpg", conf=0.5)++for result in results:+ boxes = result.boxes+ for box in boxes:+ xyxy = box.xyxy[0].tolist() # Bounding box+ conf = box.conf[0].item() # Confidence+ cls = box.cls[0].item() # Class ID+ print(f"Detected {cls} at {xyxy} with confidence {conf}")+```++### Segment Anything (SAM)+Universal segmentation:+```python+from segment_anything import sam_model_registry, SamPredictor++# Load SAM+sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h.pth")+predictor = SamPredictor(sam)++# Set image+predictor.set_image(image)++# Segment with point prompt+masks, scores, logits = predictor.predict(+ point_coords=np.array([[500, 375]]), # Click point+ point_labels=np.array([1]), # 1 = foreground+ multimask_output=True+)++# Segment with box prompt+masks, scores, logits = predictor.predict(+ box=np.array([x1, y1, x2, y2])+)+```++### Model Optimization Pipeline+Prepare models for production:+```python+def optimize_for_deployment(model, sample_input):+ # Step 1: Export to ONNX+ torch.onnx.export(+ model,+ sample_input,+ "model.onnx",+ opset_version=13,+ dynamic_axes={"input": {0: "batch"}}+ )++ # Step 2: Quantize (INT8)+ from onnxruntime.quantization import quantize_dynamic+ quantize_dynamic(+ "model.onnx",+ "model_quantized.onnx",+ weight_type=QuantType.QInt8+ )++ # Step 3: Benchmark+ import onnxruntime as ort+ session = ort.InferenceSession("model_quantized.onnx")+ benchmark_inference(session, sample_input)++ return "model_quantized.onnx"+```++## Common Pitfalls to Avoid++- Training from scratch when transfer learning would work+- Not augmenting data appropriately for the task+- Data leakage through improper train/test splits+- Ignoring class imbalance in training data+- Overfitting to training data without regularization+- Not testing on diverse, real-world images+- Deploying without latency and throughput testing+- Assuming models work on all image types without testingdiff --git a/skills/config-manager/SKILL.md b/skills/config-manager/SKILL.mdnew file mode 100644index 0000000..a3485e4--- /dev/null+++ b/skills/config-manager/SKILL.md@@ -0,0 +1,658 @@+---+name: config-manager+description: Expert guide for managing application configuration including environment variables, config files, secrets management, and multi-environment setups. Use when handling .env files, config validation, or configuration architecture.+---++# Configuration Manager Skill++## Overview++This skill helps you design and implement robust configuration management for applications. Covers environment variables, config files, secrets management, validation, type safety, and multi-environment deployments.++## Configuration Philosophy++### Twelve-Factor App Principles+1. **Store config in the environment**: Separate config from code+2. **Strict separation**: Config that varies between deploys should be in env vars+3. **No secrets in code**: Ever. Period.++### Configuration Hierarchy+```+Priority (highest to lowest):+1. Command-line arguments+2. Environment variables+3. Environment-specific config files (.env.local)+4. Default config files (.env)+5. Application defaults in code+```++### What Goes Where+- **Environment Variables**: API keys, database URLs, feature flags+- **Config Files**: Non-sensitive defaults, complex structures+- **Secrets Manager**: Production credentials, API tokens+- **Code**: Application logic, never secrets++## Environment Variables++### .env File Structure++```bash+# .env.example - Commit this file as documentation+# Copy to .env and fill in values++# ===================+# Application+# ===================+NODE_ENV=development+PORT=3000+APP_URL=http://localhost:3000++# ===================+# Database+# ===================+DATABASE_URL=postgresql://user:password@localhost:5432/mydb+DATABASE_POOL_SIZE=10++# ===================+# Authentication+# ===================+# Get from Supabase Dashboard > Settings > API+NEXT_PUBLIC_SUPABASE_URL=https://xxx.supabase.co+NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key+SUPABASE_SERVICE_ROLE_KEY=your-service-role-key++# ===================+# External Services+# ===================+STRIPE_SECRET_KEY=sk_test_xxx+STRIPE_WEBHOOK_SECRET=whsec_xxx+NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_xxx++# ===================+# ===================+RESEND_API_KEY=re_xxx++# ===================+# Feature Flags+# ===================+ENABLE_ANALYTICS=true+ENABLE_BETA_FEATURES=false+```++### .gitignore Configuration++```gitignore+# Environment files+.env+.env.local+.env.*.local+.env.development.local+.env.test.local+.env.production.local++# Keep example file+!.env.example+```++### Multi-Environment Setup++```bash+# .env.development+NODE_ENV=development+DATABASE_URL=postgresql://localhost:5432/myapp_dev+LOG_LEVEL=debug++# .env.test+NODE_ENV=test+DATABASE_URL=postgresql://localhost:5432/myapp_test+LOG_LEVEL=error++# .env.production+NODE_ENV=production+DATABASE_URL=${DATABASE_URL} # Set in deployment platform+LOG_LEVEL=info+```++## Type-Safe Configuration++### Zod Schema Validation++```typescript+// src/config/env.ts+import { z } from 'zod';++// Define schema+const envSchema = z.object({+ // Node environment+ NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),++ // Server+ PORT: z.coerce.number().default(3000),+ APP_URL: z.string().url(),++ // Database+ DATABASE_URL: z.string().url(),+ DATABASE_POOL_SIZE: z.coerce.number().min(1).max(100).default(10),++ // Supabase+ NEXT_PUBLIC_SUPABASE_URL: z.string().url(),+ NEXT_PUBLIC_SUPABASE_ANON_KEY: z.string().min(1),+ SUPABASE_SERVICE_ROLE_KEY: z.string().min(1),++ // Stripe (optional in development)+ STRIPE_SECRET_KEY: z.string().startsWith('sk_').optional(),+ STRIPE_WEBHOOK_SECRET: z.string().startsWith('whsec_').optional(),++ // Feature flags+ ENABLE_ANALYTICS: z.coerce.boolean().default(false),+ ENABLE_BETA_FEATURES: z.coerce.boolean().default(false),+});++// Type export+export type Env = z.infer<typeof envSchema>;++// Parse and validate+function loadEnv(): Env {+ const result = envSchema.safeParse(process.env);++ if (!result.success) {+ console.error('Invalid environment variables:');+ console.error(result.error.format());+ process.exit(1);+ }++ return result.data;+}++// Singleton export+export const env = loadEnv();+```++### Environment Validation at Build Time++```typescript+// src/config/validate-env.ts+import { z } from 'zod';++// Client-side env (exposed to browser)+const clientEnvSchema = z.object({+ NEXT_PUBLIC_SUPABASE_URL: z.string().url(),+ NEXT_PUBLIC_SUPABASE_ANON_KEY: z.string().min(1),+ NEXT_PUBLIC_APP_URL: z.string().url(),+});++// Server-side env (never exposed to browser)+const serverEnvSchema = z.object({+ DATABASE_URL: z.string(),+ SUPABASE_SERVICE_ROLE_KEY: z.string(),+ STRIPE_SECRET_KEY: z.string().optional(),+});++// Combined+const envSchema = clientEnvSchema.merge(serverEnvSchema);++export function validateEnv() {+ // Only validate server-side env on server+ if (typeof window !== 'undefined') {+ return clientEnvSchema.parse({+ NEXT_PUBLIC_SUPABASE_URL: process.env.NEXT_PUBLIC_SUPABASE_URL,+ NEXT_PUBLIC_SUPABASE_ANON_KEY: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,+ NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,+ });+ }++ return envSchema.parse(process.env);+}+```++### T3 Env Pattern (Next.js)++```typescript+// src/env.mjs+import { createEnv } from '@t3-oss/env-nextjs';+import { z } from 'zod';++export const env = createEnv({+ /**+ * Server-side environment variables+ */+ server: {+ DATABASE_URL: z.string().url(),+ NODE_ENV: z.enum(['development', 'test', 'production']),+ SUPABASE_SERVICE_ROLE_KEY: z.string(),+ STRIPE_SECRET_KEY: z.string().startsWith('sk_'),+ },++ /**+ * Client-side environment variables (exposed to browser)+ * Prefix with NEXT_PUBLIC_+ */+ client: {+ NEXT_PUBLIC_SUPABASE_URL: z.string().url(),+ NEXT_PUBLIC_SUPABASE_ANON_KEY: z.string(),+ NEXT_PUBLIC_APP_URL: z.string().url(),+ },++ /**+ * Runtime values+ */+ runtimeEnv: {+ DATABASE_URL: process.env.DATABASE_URL,+ NODE_ENV: process.env.NODE_ENV,+ SUPABASE_SERVICE_ROLE_KEY: process.env.SUPABASE_SERVICE_ROLE_KEY,+ STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,+ NEXT_PUBLIC_SUPABASE_URL: process.env.NEXT_PUBLIC_SUPABASE_URL,+ NEXT_PUBLIC_SUPABASE_ANON_KEY: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,+ NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,+ },++ /**+ * Skip validation in certain environments+ */+ skipValidation: !!process.env.SKIP_ENV_VALIDATION,+});+```++## Configuration Files++### JSON Configuration++```typescript+// config/default.json+{+ "app": {+ "name": "My Application",+ "version": "1.0.0"+ },+ "server": {+ "port": 3000,+ "host": "localhost"+ },+ "cache": {+ "ttl": 3600,+ "maxSize": 1000+ },+ "features": {+ "darkMode": true,+ "betaFeatures": false+ }+}++// config/production.json (overrides default)+{+ "server": {+ "host": "0.0.0.0"+ },+ "cache": {+ "ttl": 86400+ }+}+```++### Config Loader++```typescript+// src/config/loader.ts+import { readFileSync, existsSync } from 'fs';+import { join } from 'path';+import { z } from 'zod';++const configSchema = z.object({+ app: z.object({+ name: z.string(),+ version: z.string(),+ }),+ server: z.object({+ port: z.number(),+ host: z.string(),+ }),+ cache: z.object({+ ttl: z.number(),+ maxSize: z.number(),+ }),+ features: z.object({+ darkMode: z.boolean(),+ betaFeatures: z.boolean(),+ }),+});++type Config = z.infer<typeof configSchema>;++function deepMerge(target: any, source: any): any {+ const result = { ...target };++ for (const key of Object.keys(source)) {+ if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {+ result[key] = deepMerge(result[key] || {}, source[key]);+ } else {+ result[key] = source[key];+ }+ }++ return result;+}++export function loadConfig(): Config {+ const env = process.env.NODE_ENV || 'development';+ const configDir = join(process.cwd(), 'config');++ // Load default config+ const defaultPath = join(configDir, 'default.json');+ let config = JSON.parse(readFileSync(defaultPath, 'utf-8'));++ // Merge environment-specific config+ const envPath = join(configDir, `${env}.json`);+ if (existsSync(envPath)) {+ const envConfig = JSON.parse(readFileSync(envPath, 'utf-8'));+ config = deepMerge(config, envConfig);+ }++ // Merge local overrides (not committed)+ const localPath = join(configDir, 'local.json');+ if (existsSync(localPath)) {+ const localConfig = JSON.parse(readFileSync(localPath, 'utf-8'));+ config = deepMerge(config, localConfig);+ }++ // Validate+ return configSchema.parse(config);+}++export const config = loadConfig();+```++## Secrets Management++### Local Development Secrets++```bash+# Use a secrets manager locally too+# Option 1: 1Password CLI+op read "op://Development/MyApp/API_KEY"++# Option 2: Doppler+doppler secrets download --no-file --format env > .env++# Option 3: AWS SSM (for local AWS dev)+aws ssm get-parameter --name "/myapp/dev/api-key" --with-decryption --query "Parameter.Value"+```++### Production Secrets with Vercel++```bash+# Add secrets via CLI+vercel env add STRIPE_SECRET_KEY production+vercel env add DATABASE_URL production++# Pull secrets to local .env+vercel env pull .env.local+```++### Secrets in Docker++```yaml+# docker-compose.yml+version: '3.8'+services:+ app:+ build: .+ environment:+ - NODE_ENV=production+ env_file:+ - .env+ secrets:+ - db_password+ - api_key++secrets:+ db_password:+ file: ./secrets/db_password.txt+ api_key:+ external: true # From Docker Swarm/secrets manager+```++### AWS Secrets Manager Integration++```typescript+// src/config/secrets.ts+import {+ SecretsManagerClient,+ GetSecretValueCommand,+} from '@aws-sdk/client-secrets-manager';++const client = new SecretsManagerClient({ region: 'us-east-1' });++interface AppSecrets {+ database_url: string;+ stripe_secret_key: string;+ jwt_secret: string;+}++let cachedSecrets: AppSecrets | null = null;++export async function getSecrets(): Promise<AppSecrets> {+ if (cachedSecrets) {+ return cachedSecrets;+ }++ const secretId = process.env.AWS_SECRET_ID || 'myapp/production/secrets';++ const command = new GetSecretValueCommand({ SecretId: secretId });+ const response = await client.send(command);++ if (!response.SecretString) {+ throw new Error('Secret not found');+ }++ cachedSecrets = JSON.parse(response.SecretString);+ return cachedSecrets!;+}++// Usage+async function connectDatabase() {+ const secrets = await getSecrets();+ return createConnection(secrets.database_url);+}+```++## Feature Flags++### Simple Feature Flag System++```typescript+// src/config/features.ts+import { env } from './env';++export const features = {+ analytics: env.ENABLE_ANALYTICS,+ betaFeatures: env.ENABLE_BETA_FEATURES,+ darkMode: true, // Always enabled++ // Computed flags+ get isProduction() {+ return env.NODE_ENV === 'production';+ },++ get enableDebugLogs() {+ return env.NODE_ENV === 'development' || env.DEBUG === 'true';+ },+} as const;++// Type-safe feature checking+export function isEnabled(feature: keyof typeof features): boolean {+ return Boolean(features[feature]);+}++// Usage+if (isEnabled('analytics')) {+ initAnalytics();+}+```++### Environment-Aware Feature Flags++```typescript+// src/config/feature-flags.ts+type Environment = 'development' | 'staging' | 'production';++interface FeatureConfig {+ enabled: boolean | Environment[];+ description: string;+}++const featureFlags: Record<string, FeatureConfig> = {+ newCheckout: {+ enabled: ['development', 'staging'],+ description: 'New checkout flow',+ },+ aiAssistant: {+ enabled: true,+ description: 'AI assistant feature',+ },+ experimentalApi: {+ enabled: ['development'],+ description: 'Experimental API endpoints',+ },+};++export function isFeatureEnabled(+ feature: keyof typeof featureFlags+): boolean {+ const config = featureFlags[feature];+ const currentEnv = process.env.NODE_ENV as Environment;++ if (typeof config.enabled === 'boolean') {+ return config.enabled;+ }++ return config.enabled.includes(currentEnv);+}+```++## Configuration Patterns++### Singleton Configuration++```typescript+// src/config/index.ts+import { env } from './env';+import { loadConfig } from './loader';+import { features } from './features';++class AppConfig {+ private static instance: AppConfig;++ public readonly env = env;+ public readonly features = features;+ public readonly settings = loadConfig();++ private constructor() {+ // Freeze to prevent modifications+ Object.freeze(this);+ }++ static getInstance(): AppConfig {+ if (!AppConfig.instance) {+ AppConfig.instance = new AppConfig();+ }+ return AppConfig.instance;+ }++ // Helper methods+ get isDevelopment(): boolean {+ return this.env.NODE_ENV === 'development';+ }++ get isProduction(): boolean {+ return this.env.NODE_ENV === 'production';+ }++ get databaseUrl(): string {+ return this.env.DATABASE_URL;+ }+}++export const config = AppConfig.getInstance();+```++### Runtime Configuration Updates++```typescript+// src/config/runtime.ts+import { EventEmitter } from 'events';++class RuntimeConfig extends EventEmitter {+ private values: Map<string, any> = new Map();++ get<T>(key: string, defaultValue?: T): T | undefined {+ return this.values.get(key) ?? defaultValue;+ }++ set<T>(key: string, value: T): void {+ const oldValue = this.values.get(key);+ this.values.set(key, value);+ this.emit('change', { key, oldValue, newValue: value });+ }++ // Subscribe to changes+ onChange(callback: (change: { key: string; oldValue: any; newValue: any }) => void) {+ this.on('change', callback);+ return () => this.off('change', callback);+ }+}++export const runtimeConfig = new RuntimeConfig();++// Usage: Update config at runtime+runtimeConfig.set('maintenanceMode', true);++// Usage: React to changes+runtimeConfig.onChange(({ key, newValue }) => {+ if (key === 'maintenanceMode' && newValue) {+ showMaintenanceBanner();+ }+});+```++## Validation Checklist++### Environment Setup+- [ ] `.env.example` with all variables documented+- [ ] `.gitignore` excludes all `.env` files except example+- [ ] Validation runs at application startup+- [ ] Helpful error messages for missing/invalid config+- [ ] Type definitions for all config values++### Security+- [ ] No secrets in version control+- [ ] Secrets use appropriate secrets manager+- [ ] Production secrets rotated regularly+- [ ] Minimal exposure of sensitive values in logs+- [ ] NEXT_PUBLIC_ prefix only for truly public values++### Developer Experience+- [ ] Easy local setup (copy `.env.example`)+- [ ] Clear documentation of each variable+- [ ] Defaults for development environment+- [ ] Config validation gives actionable errors+- [ ] IDE autocomplete for config values++### Multi-Environment+- [ ] Separate configs for dev/staging/production+- [ ] Environment-specific overrides work correctly+- [ ] Feature flags for gradual rollouts+- [ ] Easy switching between environments++## When to Use This Skill++Invoke this skill when:+- Setting up configuration for a new project+- Adding new environment variables+- Implementing secrets management+- Creating feature flag systems+- Debugging configuration issues+- Setting up multi-environment deployments+- Migrating configuration between providers+- Implementing runtime configuration changesdiff --git a/skills/content-calendar-planner/SKILL.md b/skills/content-calendar-planner/SKILL.mdnew file mode 100644index 0000000..a5fe42f--- /dev/null+++ b/skills/content-calendar-planner/SKILL.md@@ -0,0 +1,98 @@+---+name: Content Calendar Planner+slug: content-calendar-planner+description: Plan and organize content calendars for consistent publishing+category: marketing+complexity: simple+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "content calendar"+ - "editorial calendar"+ - "content planning"+ - "publishing schedule"+ - "content strategy"+tags:+ - content-planning+ - editorial+ - scheduling+ - content-strategy+ - publishing+---++# Content Calendar Planner++Create organized, strategic content calendars that ensure consistent publishing and aligned messaging. This skill helps you plan content across channels, balance content types, align with business objectives, and maintain a sustainable publishing cadence.++Consistent content creation is hard without a plan. This skill provides frameworks for theme development, content type balancing, editorial workflow design, and calendar management. Move from reactive content creation to proactive, strategic publishing that builds audience and drives results.++Perfect for content marketers, social media managers, marketing teams, and anyone responsible for regular content publishing.++## Core Workflows++### Workflow 1: Monthly Content Planning+1. **Theme Selection** - Key topics and campaigns for the month+2. **Content Type Mix** - Balance blog, social, email, video+3. **Channel Mapping** - What goes where+4. **Publishing Cadence** - Frequency per channel+5. **Resource Assessment** - Creation capacity check+6. **Key Dates** - Holidays, events, product launches+7. **Calendar Population** - Specific content slots filled++### Workflow 2: Editorial Calendar Setup+1. **Calendar Structure** - Columns, views, workflows+2. **Content Pillars** - Core themes that repeat+3. **Workflow Stages** - Ideation, creation, review, publish+4. **Ownership Assignment** - Who does what+5. **Deadline Framework** - Working back from publish dates+6. **Status Tracking** - Progress visibility+7. **Tool Configuration** - Set up in Notion, Asana, etc.++### Workflow 3: Content Batch Planning+1. **Batch Definition** - Content sets created together+2. **Theme Clustering** - Related content grouped+3. **Asset Bundling** - Graphics, copy, video coordinated+4. **Repurposing Strategy** - One idea, multiple formats+5. **Production Schedule** - Efficient creation blocks+6. **Review Consolidation** - Batch approvals+7. **Publishing Sequencing** - Strategic rollout timing++### Workflow 4: Content Strategy Alignment+1. **Business Goal Mapping** - Content tied to objectives+2. **Buyer Journey Coverage** - Content for each stage+3. **Keyword Integration** - SEO-driven topic selection+4. **Competitive Gaps** - Content differentiation+5. **Seasonal Planning** - Annual content rhythms+6. **Campaign Integration** - Coordinated messaging+7. **Measurement Framework** - Success metrics defined++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Monthly calendar | "Create content calendar for [month]" |+| Editorial setup | "Set up editorial calendar structure" |+| Theme planning | "Develop content themes for [quarter]" |+| Channel mix | "Plan content mix for [channels]" |+| Batch planning | "Organize content into batches" |+| Repurposing plan | "Create repurposing strategy for [content]" |+| Seasonal calendar | "Plan annual content calendar" |+| Campaign content | "Map content for [campaign]" |++## Best Practices++- **Plan ahead** - Monthly minimum, quarterly ideal+- **Balance content types** - Educational, entertaining, promotional+- **Buffer time** - Build in flexibility for reactive content+- **Theme consistency** - Content pillars create coherence+- **Repurpose ruthlessly** - One idea, many formats+- **Seasonal awareness** - Plan around key dates+- **Capacity reality** - Plan for what's achievable+- **Batch creation** - Group similar content for efficiency+- **Review built-in** - Time for edits and approval+- **Visible to all** - Calendar transparency helps coordination+- **Flexibility zones** - Leave space for timely content+- **Post-mortem** - Review what worked each month+- **Evergreen balance** - Mix timely and timeless+- **Channel-appropriate** - Not all content fits all channels+- **Update regularly** - Living document, not static plandiff --git a/skills/content-publishing/skill.md b/skills/content-publishing/skill.mdindex 7807db8..bf4e907 100644--- a/skills/content-publishing/skill.md+++ b/skills/content-publishing/skill.md@@ -1,54 +1,86 @@----name: content-publishing-description: Automated content publishing pipeline for ID8Labs. Generates essays in Eddie's voice, publishes to id8labs.app, and distributes to social media (X, LinkedIn). Triggers on keywords like release, announce, publish, essay, research article, content pipeline.+name: Content Publishing+slug: content-publishing+description: Automated content publishing pipeline for ID8Labs. Generates essays in Eddie's voice, publishes to id8labs.app, and distributes to social media (X, LinkedIn).+category: marketing+complexity: complex+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "release"+ - "announce"+ - "publish"+ - "essay"+ - "research article"+ - "content pipeline"+ - "write release"+ - "post to X"+ - "post to LinkedIn"+tags:+ - content+ - publishing+ - social-media+ - essays+ - marketing+ - automation+ - voice+ - distribution---# Content Publishing Pipeline Skill-## Overview+Automated content publishing pipeline for ID8Labs that integrates with Pipeline Stage 10.5 (ANNOUNCE). This skill generates essays in Eddie's authentic voice, publishes them to id8labs.app, and distributes derived social content to X/Twitter and LinkedIn.-This skill automates the Stage 10.5 (ANNOUNCE) of the ID8Pipeline. It generates essays in Eddie's voice, publishes to id8labs.app, and distributes to social accounts.+From product releases to research articles, this skill orchestrates the complete journey from idea to multi-channel distribution while maintaining consistent voice and messaging.-## Commands+## Core Workflows-| Command | Purpose |-|---------|---------|-| `/announce-release` | Full pipeline: essay → website → X → LinkedIn |-| `/write-release` | Generate release essay in Eddie's voice |-| `/write-research` | Generate research article in Eddie's voice |-| `/publish-essay` | Create MDX file, commit, and deploy to website |-| `/post-linkedin` | Post to LinkedIn via Playwright |-| `/post-tweet` | Post to X/Twitter via Playwright |+### Workflow 1: Full Release Announcement Pipeline+**Purpose:** End-to-end release announcement from essay to social distribution++**Command:** `/announce-release`-## Pipeline Flow+**Steps:**+1. Generate release essay in Eddie's voice+2. Create MDX file with frontmatter+3. Commit to id8labs-hub repository+4. Wait for Vercel deployment+5. Generate social media slices+6. Post to X/Twitter+7. Post to LinkedIn+8. Update pipeline status+**Pipeline Flow:**```[Release Trigger]- ↓+ |[/write-release or /write-research]Apply Eddie's voice profile- ↓+ |[/publish-essay]Create MDX in id8labs-hub/core/content/essays/- Git commit → Vercel auto-deploy- ↓+ Git commit -> Vercel auto-deploy+ |[/post-tweet]Generate X thread from essayPost to @id8labs- ↓+ |[/post-linkedin]Adapt essay for LinkedInPost to Eddie's profile```-## Eddie's Voice Profile+### Workflow 2: Generate Release Essay+**Purpose:** Write compelling release announcement in Eddie's voice++**Command:** `/write-release`-When generating content, apply these characteristics:+**Eddie's Voice Profile:****Core Moves:**- Open unexpected (visceral, confessional)- Hardship as credentials-- Pattern recognition (micro → macro)+- Pattern recognition (micro -> macro)- Movement from I to We- Direct loving close@@ -58,11 +90,87 @@ When generating content, apply these characteristics:- "I don't know about you but..."- "(Loud ape sounds)"-**Tone:**+**Tone Calibration:**- Vulnerable but not weak- Intense but not aggressive- Raw but intentional+**Structure Pattern:**+1. Visceral opening - Sound, confession, or unexpected entry+2. Personal context - Where you've been, what shaped you+3. Observation/Pattern - What you're seeing that others miss+4. Universal connection - How your story is everyone's story+5. Call to collective action - The invitation to join+6. Warm direct close - Love, gratitude, solidarity++### Workflow 3: Generate Research Article+**Purpose:** Write thought leadership content around product themes++**Command:** `/write-research`++**Steps:**+1. Define research topic+2. Gather sources and data+3. Apply Eddie's voice+4. Structure as thought piece+5. Include practical insights++### Workflow 4: Publish Essay to Website+**Purpose:** Commit essay as MDX file to id8labs-hub repository++**Command:** `/publish-essay`++**MDX Frontmatter Template:**+```yaml+---+title: "Essay Title"+slug: "essay-slug"+date: "2025-01-06"+category: "release"+excerpt: "Brief excerpt for previews"+author:+ name: "Eddie Belaval"+ avatar: "/images/eddie-avatar.jpg"+tags: ["tag1", "tag2"]+---+```++**Steps:**+1. Format essay as MDX+2. Generate slug and metadata+3. Commit to GitHub+4. Trigger Vercel deployment+5. Verify live URL++### Workflow 5: Social Media Distribution+**Purpose:** Generate and post platform-specific content++**Commands:** `/post-tweet`, `/post-linkedin`++**Twitter/X Strategy:**+- Under 280 characters for single tweet+- 5-tweet thread for complex topics+- Hook with main insight+- End with link to full essay++**LinkedIn Strategy:**+- Professional but authentic+- Include personal reflection+- 3-5 paragraphs+- Use line breaks for readability+- End with discussion question++## Quick Reference++| Command | Purpose |+|---------|---------|+| `/announce-release` | Full pipeline: essay -> website -> X -> LinkedIn |+| `/write-release` | Generate release essay in Eddie's voice |+| `/write-research` | Generate research article in Eddie's voice |+| `/publish-essay` | Create MDX file, commit, and deploy to website |+| `/post-linkedin` | Post to LinkedIn via Playwright |+| `/post-tweet` | Post to X/Twitter via Playwright |+## Content Categories| Category | When to Use |@@ -95,9 +203,69 @@ Essays are published to `id8labs.app/essays/{slug}`:/publish-essay "My Essay Title" --content "<mdx content>"```+## Best Practices++- **Voice Consistency:** Always apply Eddie's voice profile for authenticity+- **Platform Optimization:** Tailor content length and format for each platform+- **Timing:** Post during peak engagement hours (9-11am EST)+- **Thread Strategy:** Use threads for complex topics on X+- **Engagement:** Respond to comments within 24 hours+- **Cross-linking:** Link social posts to full essays+- **Analytics:** Track engagement metrics post-publication+- **Scheduling:** Plan content calendar in advance+- **A/B Testing:** Test different hooks and CTAs+- **Repurposing:** Turn essays into multiple social posts over time++## Output Locations++| Content Type | Location |+|--------------|----------|+| Essays | `https://id8labs.app/essays/{slug}` |+| X/Twitter | `https://x.com/id8labs/status/{id}` |+| LinkedIn | `https://linkedin.com/posts/{id}` |+| MDX Files | `id8labs-hub/core/content/essays/` |+## Requirements- Git access to id8labs-hub repo- Comet browser with debugging for social posting- Logged into X as @id8labs- Logged into LinkedIn as Eddie Belaval++## Pipeline Integration++This skill integrates with ID8Pipeline Stage 10.5:++```+Stage 10: Ship+ |+Stage 10.5: Announce <- Content Publishing Skill+ |+ |-- Generate essay+ |-- Publish to website+ |-- Post to X+ |-- Post to LinkedIn+ |+Stage 11: Listen & Iterate+```++Skip Stage 10.5 only for internal/minor releases that don't warrant public announcement.++## Error Handling++- **Generation Failures:** Retry with refined prompts+- **GitHub Conflicts:** Pull latest before commit+- **Deployment Timeouts:** Check Vercel dashboard manually+- **Social API Limits:** Space posts 1 hour apart+- **Platform Outages:** Queue content for later posting++## When to Use This Skill++Invoke this skill when:+- Announcing product releases+- Publishing thought leadership content+- Distributing content to social media+- Writing in Eddie's voice+- Managing the content pipeline+- Creating research articles+- Coordinating multi-channel publishingdiff --git a/skills/customer-journey-mapper/SKILL.md b/skills/customer-journey-mapper/SKILL.mdnew file mode 100644index 0000000..3ae4b87--- /dev/null+++ b/skills/customer-journey-mapper/SKILL.md@@ -0,0 +1,98 @@+---+name: Customer Journey Mapper+slug: customer-journey-mapper+description: Map customer journeys to optimize touchpoints and experiences+category: marketing+complexity: advanced+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "customer journey"+ - "journey mapping"+ - "touchpoint analysis"+ - "customer experience"+ - "buyer journey"+tags:+ - customer-journey+ - experience-design+ - touchpoints+ - cx-optimization+ - conversion-funnel+---++# Customer Journey Mapper++Visualize and optimize every step of the customer experience from first awareness to loyal advocacy. This skill helps you understand how customers actually interact with your brand, identify friction points, and design experiences that convert and retain.++Customers don't think in channels - they think in experiences. This skill provides frameworks for journey stage definition, touchpoint mapping, emotion tracking, and gap analysis. Transform siloed channel thinking into holistic experience design that meets customers where they are.++Essential for marketing strategists, CX professionals, product managers, and anyone designing customer experiences.++## Core Workflows++### Workflow 1: Journey Stage Mapping+1. **Stage Definition** - Awareness, consideration, decision, retention, advocacy+2. **Customer Goals** - What they're trying to achieve at each stage+3. **Questions and Concerns** - What they need to know+4. **Touchpoint Inventory** - Where they interact with brand+5. **Content Needs** - Information required at each stage+6. **Conversion Actions** - Desired behaviors per stage+7. **Transition Triggers** - What moves them forward++### Workflow 2: Touchpoint Analysis+1. **Channel Mapping** - All interaction points+2. **Touchpoint Audit** - Quality of each interaction+3. **Moment of Truth Identification** - Critical experiences+4. **Friction Point Detection** - Where customers get stuck+5. **Emotional Journey** - Highs and lows of experience+6. **Gap Identification** - Missing touchpoints+7. **Optimization Prioritization** - Where to improve first++### Workflow 3: Persona Journey Development+1. **Persona Selection** - Which customer to map+2. **Scenario Definition** - Specific journey context+3. **Step-by-Step Documentation** - Detailed journey stages+4. **Thought Capture** - What customer is thinking+5. **Emotion Mapping** - How they feel at each point+6. **Pain Point Highlighting** - Frustration moments+7. **Opportunity Tagging** - Improvement possibilities++### Workflow 4: Journey Optimization+1. **Friction Removal** - Eliminate barriers+2. **Moment Enhancement** - Elevate key experiences+3. **Gap Filling** - Add missing touchpoints+4. **Consistency Improvement** - Align cross-channel+5. **Personalization Points** - Where to customize+6. **Measurement Integration** - Track journey metrics+7. **Continuous Improvement** - Ongoing optimization cycle++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Map journey | "Map customer journey for [persona]" |+| Stage definition | "Define journey stages for [product/service]" |+| Touchpoint audit | "Audit touchpoints for [journey stage]" |+| Friction analysis | "Identify friction in [journey/channel]" |+| Emotional mapping | "Map emotional journey for [scenario]" |+| Gap analysis | "Find gaps in customer journey" |+| Moment enhancement | "Improve experience at [touchpoint]" |+| Journey template | "Create journey map template" |++## Best Practices++- **Start with research** - Journeys should reflect reality, not assumptions+- **Map from customer perspective** - Their experience, not your processes+- **Include emotions** - How they feel matters+- **Be specific** - "Awareness" is too vague; define clearly+- **Cross-functional input** - Sales, support, product all have insight+- **Prioritize ruthlessly** - Can't fix everything at once+- **Moments of truth** - Focus on make-or-break experiences+- **Measure journey health** - Metrics at each stage+- **Iterate continuously** - Journeys evolve+- **Visualize effectively** - Maps should be scannable+- **Include offline** - Physical experiences count+- **Consider negative paths** - Map what happens when things go wrong+- **Segment journeys** - Different personas, different journeys+- **Test changes** - Validate improvements with real customers+- **Share broadly** - Journey maps inform entire organizationdiff --git a/skills/database-design/skill.md b/skills/database-design/skill.mdindex c6d8e48..f57735c 100644--- a/skills/database-design/skill.md+++ b/skills/database-design/skill.md@@ -1,74 +1,68 @@----name: database-design+name: Database Design+slug: database-designdescription: Expert guide for database schema design, Supabase/PostgreSQL best practices, RLS policies, and optimizations. Use when designing tables, relationships, or implementing data models.+category: backend+complexity: moderate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "design database"+ - "create schema"+ - "database tables"+ - "RLS policies"+ - "data model"+ - "database optimization"+ - "migration"+ - "indexes"+tags:+ - database+ - postgresql+ - supabase+ - schema+ - rls+ - migrations+ - indexes+ - sql---# Database Design Skill-## Overview+Comprehensive guide for designing efficient, scalable database schemas for Next.js applications with Supabase and PostgreSQL. From table design and relationships to Row Level Security policies and query optimization, this skill covers everything needed for robust data modeling.-This skill helps you design efficient, scalable database schemas for your Next.js + Supabase application. From table design to RLS policies, this covers everything you need for robust data modeling.+Design normalized schemas, implement secure RLS policies, optimize query performance with proper indexing, and build maintainable data models that scale with your application.-## Database Design Principles+## Core Workflows-### 1. Normalization-Organize data to reduce redundancy and improve integrity.+### Workflow 1: Schema Design from Requirements+**Purpose:** Translate business requirements into database schema-**❌ Bad - Denormalized:**-```sql-CREATE TABLE orders (- id UUID PRIMARY KEY,- customer_name TEXT,- customer_email TEXT,- customer_address TEXT,- product_name TEXT,- product_price DECIMAL-);-```--**✅ Good - Normalized:**-```sql-CREATE TABLE customers (- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),- name TEXT NOT NULL,- email TEXT UNIQUE NOT NULL,- address TEXT-);+**Steps:**+1. Identify entities and relationships+2. Define primary and foreign keys+3. Choose appropriate data types+4. Add constraints and defaults+5. Create indexes for performance-CREATE TABLE products (- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),- name TEXT NOT NULL,- price DECIMAL NOT NULL-);--CREATE TABLE orders (- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),- customer_id UUID REFERENCES customers(id) ON DELETE CASCADE,- product_id UUID REFERENCES products(id) ON DELETE RESTRICT,- quantity INTEGER NOT NULL DEFAULT 1,- created_at TIMESTAMP DEFAULT NOW()-);-```--### 2. Use Appropriate Data Types+**Implementation:**```sql--- ✅ Correct types+-- Correct data typesCREATE TABLE users (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),- email TEXT NOT NULL, -- Use TEXT, not VARCHAR in Postgres+ email TEXT NOT NULL, -- Use TEXT, not VARCHARage INTEGER CHECK (age >= 0),balance DECIMAL(10, 2), -- For moneyis_active BOOLEAN DEFAULT true,- metadata JSONB, -- Use JSONB for JSON data- created_at TIMESTAMPTZ DEFAULT NOW() -- Use TIMESTAMPTZ, not TIMESTAMP+ metadata JSONB, -- Use JSONB for JSON+ created_at TIMESTAMPTZ DEFAULT NOW() -- Use TIMESTAMPTZ);```-## Common Schema Patterns+### Workflow 2: Common Relationship Patterns+**Purpose:** Implement proper database relationships-### One-to-Many Relationship+**One-to-Many:**```sql--- Users can have many postsCREATE TABLE users (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),email TEXT UNIQUE NOT NULL,@@ -84,42 +78,35 @@ CREATE TABLE posts (created_at TIMESTAMPTZ DEFAULT NOW());--- Index for fast lookupsCREATE INDEX idx_posts_user_id ON posts(user_id);```-### Many-to-Many Relationship+**Many-to-Many:**```sql--- Students can enroll in many courses, courses can have many studentsCREATE TABLE students (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),- name TEXT NOT NULL,- email TEXT UNIQUE NOT NULL+ name TEXT NOT NULL);CREATE TABLE courses (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),- name TEXT NOT NULL,- code TEXT UNIQUE NOT NULL+ name TEXT NOT NULL);--- Junction tableCREATE TABLE enrollments (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),student_id UUID NOT NULL REFERENCES students(id) ON DELETE CASCADE,course_id UUID NOT NULL REFERENCES courses(id) ON DELETE CASCADE,enrolled_at TIMESTAMPTZ DEFAULT NOW(),- grade TEXT,- UNIQUE(student_id, course_id) -- Prevent duplicate enrollments+ UNIQUE(student_id, course_id));CREATE INDEX idx_enrollments_student ON enrollments(student_id);CREATE INDEX idx_enrollments_course ON enrollments(course_id);```-### Self-Referencing (Tree Structure)+**Self-Referencing (Tree):**```sql--- Comments can reply to other commentsCREATE TABLE comments (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),parent_id UUID REFERENCES comments(id) ON DELETE CASCADE,@@ -131,75 +118,45 @@ CREATE TABLE comments (CREATE INDEX idx_comments_parent ON comments(parent_id);```-### Polymorphic Relationships-```sql--- Likes can apply to posts or comments-CREATE TABLE likes (- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,- likeable_type TEXT NOT NULL CHECK (likeable_type IN ('post', 'comment')),- likeable_id UUID NOT NULL,- created_at TIMESTAMPTZ DEFAULT NOW(),- UNIQUE(user_id, likeable_type, likeable_id)-);--CREATE INDEX idx_likes_likeable ON likes(likeable_type, likeable_id);-```+### Workflow 3: Row Level Security (RLS)+**Purpose:** Secure data access at the database level-## Row Level Security (RLS)--### Enable RLS+**Implementation:**```sql+-- Enable RLSALTER TABLE posts ENABLE ROW LEVEL SECURITY;-```--### Common RLS Policies-**1. Users can only read their own data:**-```sql+-- Users can only read their own dataCREATE POLICY "Users can read own posts"ON posts FOR SELECTUSING (auth.uid() = user_id);-```-**2. Users can insert their own data:**-```sql+-- Users can insert their own dataCREATE POLICY "Users can create posts"ON posts FOR INSERTWITH CHECK (auth.uid() = user_id);-```-**3. Users can update their own data:**-```sql+-- Users can update their own dataCREATE POLICY "Users can update own posts"ON posts FOR UPDATEUSING (auth.uid() = user_id)WITH CHECK (auth.uid() = user_id);-```-**4. Users can delete their own data:**-```sql+-- Users can delete their own dataCREATE POLICY "Users can delete own posts"ON posts FOR DELETEUSING (auth.uid() = user_id);-```-**5. Public read, authenticated write:**-```sql--- Anyone can read+-- Public read, authenticated writeCREATE POLICY "Public can read posts"ON posts FOR SELECTUSING (true);--- Only authenticated users can createCREATE POLICY "Authenticated users can create posts"ON posts FOR INSERTWITH CHECK (auth.role() = 'authenticated');-```-**6. Role-based access:**-```sql--- Admins can do anything+-- Role-based accessCREATE POLICY "Admins have full access"ON posts FOR ALLUSING (@@ -210,64 +167,34 @@ USING ();```-**7. Time-based access:**-```sql--- Users can only edit posts within 1 hour of creation-CREATE POLICY "Users can edit recent posts"-ON posts FOR UPDATE-USING (- auth.uid() = user_id- AND created_at > NOW() - INTERVAL '1 hour'-);-```--### Bypass RLS (Service Role)-```typescript-// Use service role key for admin operations-import { createClient } from '@supabase/supabase-js'--const supabase = createClient(- process.env.NEXT_PUBLIC_SUPABASE_URL!,- process.env.SUPABASE_SERVICE_ROLE_KEY! // Bypasses RLS-)--// This ignores RLS policies-const { data } = await supabase.from('posts').select('*')-```+### Workflow 4: Indexes for Performance+**Purpose:** Optimize query performance-## Indexes for Performance--### Single Column Index+**Implementation:**```sql--- Speed up queries by email+-- Single Column IndexCREATE INDEX idx_users_email ON users(email);-```-### Composite Index-```sql--- Speed up queries by user_id and created_at together+-- Composite IndexCREATE INDEX idx_posts_user_created ON posts(user_id, created_at DESC);-```-### Partial Index-```sql--- Only index active users+-- Partial IndexCREATE INDEX idx_active_users ON users(email) WHERE is_active = true;-```-### Full-Text Search Index-```sql--- Enable full-text search on posts-CREATE INDEX idx_posts_search ON posts USING gin(to_tsvector('english', title || ' ' || content));+-- Full-Text Search Index+CREATE INDEX idx_posts_search ON posts+USING gin(to_tsvector('english', title || ' ' || content));-- Query with full-text searchSELECT * FROM posts-WHERE to_tsvector('english', title || ' ' || content) @@ plainto_tsquery('search term');+WHERE to_tsvector('english', title || ' ' || content)+@@ plainto_tsquery('search term');```-## Advanced Patterns+### Workflow 5: Advanced Patterns+**Purpose:** Implement common database patterns-### Soft Deletes+**Soft Deletes:**```sqlCREATE TABLE posts (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),@@ -276,16 +203,14 @@ CREATE TABLE posts (created_at TIMESTAMPTZ DEFAULT NOW());--- Index for filtering out deleted recordsCREATE INDEX idx_posts_not_deleted ON posts(id) WHERE deleted_at IS NULL;--- RLS policy excluding deleted recordsCREATE POLICY "Users see non-deleted posts"ON posts FOR SELECTUSING (deleted_at IS NULL);```-### Audit Trail+**Audit Trail:**```sqlCREATE TABLE audit_log (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),@@ -298,7 +223,6 @@ CREATE TABLE audit_log (created_at TIMESTAMPTZ DEFAULT NOW());--- Trigger functionCREATE OR REPLACE FUNCTION audit_trigger()RETURNS TRIGGER AS $$BEGIN@@ -315,22 +239,13 @@ BEGINEND;$$ LANGUAGE plpgsql SECURITY DEFINER;--- Apply to tableCREATE TRIGGER posts_auditAFTER INSERT OR UPDATE OR DELETE ON postsFOR EACH ROW EXECUTE FUNCTION audit_trigger();```-### Timestamps+**Auto-update Timestamps:**```sql-CREATE TABLE posts (- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),- title TEXT NOT NULL,- created_at TIMESTAMPTZ DEFAULT NOW(),- updated_at TIMESTAMPTZ DEFAULT NOW()-);---- Auto-update updated_atCREATE OR REPLACE FUNCTION update_updated_at()RETURNS TRIGGER AS $$BEGIN@@ -344,100 +259,28 @@ BEFORE UPDATE ON postsFOR EACH ROW EXECUTE FUNCTION update_updated_at();```-### Counters (Denormalization for Performance)-```sql-CREATE TABLE users (- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),- posts_count INTEGER DEFAULT 0-);---- Increment counter on insert-CREATE OR REPLACE FUNCTION increment_posts_count()-RETURNS TRIGGER AS $$-BEGIN- UPDATE users SET posts_count = posts_count + 1 WHERE id = NEW.user_id;- RETURN NEW;-END;-$$ LANGUAGE plpgsql;--CREATE TRIGGER posts_count_increment-AFTER INSERT ON posts-FOR EACH ROW EXECUTE FUNCTION increment_posts_count();---- Decrement counter on delete-CREATE OR REPLACE FUNCTION decrement_posts_count()-RETURNS TRIGGER AS $$-BEGIN- UPDATE users SET posts_count = posts_count - 1 WHERE id = OLD.user_id;- RETURN OLD;-END;-$$ LANGUAGE plpgsql;--CREATE TRIGGER posts_count_decrement-AFTER DELETE ON posts-FOR EACH ROW EXECUTE FUNCTION decrement_posts_count();-```--## Constraints--### Primary Key-```sql-CREATE TABLE users (- id UUID PRIMARY KEY DEFAULT uuid_generate_v4()-);-```--### Foreign Key-```sql-CREATE TABLE posts (- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),- user_id UUID REFERENCES users(id) ON DELETE CASCADE-);-```--### Unique Constraint-```sql-CREATE TABLE users (- email TEXT UNIQUE NOT NULL-);---- Composite unique-CREATE TABLE user_settings (- user_id UUID,- setting_key TEXT,- UNIQUE(user_id, setting_key)-);-```--### Check Constraint-```sql-CREATE TABLE products (- price DECIMAL CHECK (price > 0),- stock INTEGER CHECK (stock >= 0),- status TEXT CHECK (status IN ('active', 'inactive', 'discontinued'))-);-```+## Quick Reference-### Not Null-```sql-CREATE TABLE users (- email TEXT NOT NULL,- name TEXT NOT NULL-);-```+| Task | SQL Pattern |+|------|-------------|+| Create table | `CREATE TABLE name (columns)` |+| Add column | `ALTER TABLE name ADD COLUMN col TYPE` |+| Add index | `CREATE INDEX name ON table(columns)` |+| Enable RLS | `ALTER TABLE name ENABLE ROW LEVEL SECURITY` |+| Create policy | `CREATE POLICY name ON table FOR action USING (condition)` |+| Create function | `CREATE FUNCTION name() RETURNS type AS $$ ... $$` |+| Create trigger | `CREATE TRIGGER name AFTER/BEFORE action ON table` |## Migrations with Supabase-### Create Migration```bash+# Create Migrationnpx supabase migration new create_posts_table```-### Migration File```sql-- supabase/migrations/20240101000000_create_posts_table.sql--- Create tableCREATE TABLE posts (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,@@ -446,30 +289,22 @@ CREATE TABLE posts (created_at TIMESTAMPTZ DEFAULT NOW());--- Create indexCREATE INDEX idx_posts_user_id ON posts(user_id);--- Enable RLSALTER TABLE posts ENABLE ROW LEVEL SECURITY;--- Create policiesCREATE POLICY "Users can read own posts"ON posts FOR SELECTUSING (auth.uid() = user_id);--CREATE POLICY "Users can create posts"-ON posts FOR INSERT-WITH CHECK (auth.uid() = user_id);```-### Apply Migration```bash+# Apply Migrationnpx supabase db push```## Querying with Supabase-### Basic Queries```typescript// Select allconst { data } = await supabase.from('posts').select('*')@@ -494,10 +329,7 @@ const { data } = await supabase)`)-```-### Advanced Queries-```typescript// Countconst { count } = await supabase.from('posts')@@ -507,36 +339,78 @@ const { count } = await supabaseconst { data } = await supabase.from('posts').select('*')- .range(0, 9) // First 10 items+ .range(0, 9)// Orderconst { data } = await supabase.from('posts').select('*').order('created_at', { ascending: false })+```-// Full-text search-const { data } = await supabase- .from('posts')- .select('*')- .textSearch('title', 'search term')+## Best Practices++- **Use UUIDs:** Better for distributed systems and security+- **Add Timestamps:** Always include created_at and updated_at+- **Enable RLS:** On all tables by default+- **Index Foreign Keys:** Create indexes for all foreign keys+- **Use TIMESTAMPTZ:** Not TIMESTAMP for timezone awareness+- **Use TEXT:** Not VARCHAR in PostgreSQL+- **Use JSONB:** Not JSON for better performance+- **Normalize First:** Denormalize only for performance+- **Migrations Only:** Never modify schema directly in production+- **Test RLS Policies:** Verify with different user contexts+- **Use Transactions:** For related operations+- **Document Schema:** Maintain ERD diagrams++## Constraints++```sql+-- Primary Key+id UUID PRIMARY KEY DEFAULT uuid_generate_v4()++-- Foreign Key+user_id UUID REFERENCES users(id) ON DELETE CASCADE++-- Unique+email TEXT UNIQUE NOT NULL++-- Check+price DECIMAL CHECK (price > 0)+status TEXT CHECK (status IN ('active', 'inactive'))++-- Not Null+name TEXT NOT NULL```-## Best Practices Checklist--- [ ] Use UUIDs for primary keys-- [ ] Add created_at/updated_at timestamps-- [ ] Enable RLS on all tables-- [ ] Create indexes for foreign keys-- [ ] Use appropriate data types-- [ ] Add constraints (NOT NULL, CHECK)-- [ ] Use migrations for schema changes-- [ ] Implement soft deletes when needed-- [ ] Add audit trails for sensitive data-- [ ] Use TIMESTAMPTZ instead of TIMESTAMP-- [ ] Test RLS policies thoroughly-- [ ] Document complex relationships-- [ ] Use transactions for related operations+## Dependencies++```bash+# Supabase CLI for migrations+npm install -D supabase++# Generate types from schema+npx supabase gen types typescript --local > types/database.ts+```++## Error Handling++- **Foreign Key Violations:** Handle gracefully in application+- **Unique Constraints:** Provide user-friendly error messages+- **Check Constraints:** Validate in application before insert+- **RLS Errors:** Return 404 instead of 403 for security+- **Connection Limits:** Use connection pooling++## Performance Tips++- Use connection pooling (PgBouncer)+- Add covering indexes for common queries+- Use LIMIT and cursor pagination+- Avoid SELECT * in production+- Use prepared statements+- Monitor slow queries with pg_stat_statements+- Vacuum tables regularly+- Consider table partitioning for large datasets## When to Use This Skilldiff --git a/skills/dataset-curator/SKILL.md b/skills/dataset-curator/SKILL.mdnew file mode 100644index 0000000..0ab3472--- /dev/null+++ b/skills/dataset-curator/SKILL.md@@ -0,0 +1,228 @@+---+name: Dataset Curator+slug: dataset-curator+description: Curate and clean training datasets for high-quality machine learning+category: ai-ml+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "curate dataset"+ - "clean training data"+ - "prepare dataset"+ - "data quality"+ - "dataset curation"+tags:+ - data-curation+ - data-quality+ - training-data+ - machine-learning+ - data-cleaning+---++# Dataset Curator++The Dataset Curator skill guides you through the critical process of preparing high-quality training data for machine learning models. Data quality is the single most important factor in model performance, yet it is often underinvested. This skill helps you systematically clean, validate, augment, and maintain datasets that lead to better models.++From initial collection to ongoing maintenance, this skill covers deduplication, label quality assessment, bias detection, augmentation strategies, and version control. It applies best practices from production ML systems to ensure your datasets are not just clean, but strategically optimized for your learning objectives.++Whether you are building a classifier, fine-tuning an LLM, or training a custom model, this skill ensures your data foundation is solid.++## Core Workflows++### Workflow 1: Assess Dataset Quality+1. **Profile** the dataset:+ - Size and dimensionality+ - Label distribution and balance+ - Missing value patterns+ - Feature statistics+2. **Identify** quality issues:+ - Duplicates (exact and near-duplicate)+ - Mislabeled examples+ - Outliers and anomalies+ - Data leakage+ - Bias and representation gaps+3. **Measure** quality metrics:+ ```python+ def assess_quality(dataset):+ return {+ "size": len(dataset),+ "duplicate_rate": find_duplicates(dataset).ratio,+ "missing_rate": dataset.isnull().mean(),+ "label_balance": compute_entropy(dataset.labels),+ "outlier_rate": detect_outliers(dataset).ratio,+ "estimated_label_noise": estimate_label_noise(dataset)+ }+ ```+4. **Prioritize** issues by impact+5. **Create** remediation plan++### Workflow 2: Clean and Prepare Data+1. **Remove** duplicates:+ - Exact duplicates: hash-based dedup+ - Near-duplicates: similarity-based clustering+ - Decide: keep first, best, or merge+2. **Handle** missing values:+ - Understand missingness mechanism (MCAR, MAR, MNAR)+ - Impute, drop, or flag appropriately+3. **Fix** label quality:+ - Identify likely mislabels with confidence scoring+ - Route to human review or automatic correction+ - Document labeling guidelines+4. **Normalize** and standardize:+ - Consistent formatting+ - Schema validation+ - Encoding standardization+5. **Validate** cleaned dataset++### Workflow 3: Augment and Balance+1. **Analyze** class imbalance:+ - Compute imbalance ratios+ - Assess impact on model training+2. **Apply** balancing strategies:+ - Oversampling minority classes (SMOTE, random)+ - Undersampling majority classes+ - Class weights in training+3. **Generate** augmentations:+ - Text: paraphrase, synonym substitution, back-translation+ - Image: rotation, flip, color jitter, mixup+ - Tabular: noise injection, feature perturbation+4. **Validate** augmentation quality:+ - Ensure augmented samples are realistic+ - Check for introduced biases+5. **Version** and document changes++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Assess quality | "Check quality of this dataset" |+| Find duplicates | "Find duplicates in dataset" |+| Clean labels | "Fix mislabeled data" |+| Balance classes | "Handle class imbalance" |+| Augment data | "Augment dataset for [task]" |+| Version dataset | "Set up dataset versioning" |++## Best Practices++- **Profile Before Processing**: Understand your data before changing it+ - Compute statistics and visualize distributions+ - Document original state for reference+ - Identify patterns in issues++- **Preserve Provenance**: Track every transformation+ - Version control datasets like code+ - Log all cleaning operations+ - Maintain mapping between original and cleaned data++- **Prioritize Label Quality**: Garbage labels in, garbage model out+ - Invest in clear labeling guidelines+ - Use multiple annotators and measure agreement+ - Regular quality audits of labels++- **Test Cleaning Impact**: Measure effect of cleaning+ - Train models on original vs cleaned data+ - Track which cleaning steps help most+ - Avoid cleaning that hurts performance++- **Stratify Splits Carefully**: Maintain distribution in train/val/test+ - Stratify by label and key features+ - Keep related samples in same split+ - Ensure temporal ordering if applicable++- **Document Everything**: Future you will thank present you+ - Dataset cards with key statistics+ - Known issues and limitations+ - Collection methodology and biases++## Advanced Techniques++### Confident Learning for Label Noise+Identify and fix mislabeled examples:+```python+from cleanlab import find_label_issues++# Train model to get predicted probabilities+model.fit(X_train, y_train)+pred_probs = model.predict_proba(X_train)++# Find likely mislabeled examples+issues = find_label_issues(+ labels=y_train,+ pred_probs=pred_probs,+ return_indices_ranked_by="self_confidence"+)++# Review and correct top issues+for idx in issues[:100]:+ review_and_correct(X_train[idx], y_train[idx])+```++### Similarity-Based Deduplication+Remove near-duplicates using embeddings:+```python+def deduplicate_semantic(texts, threshold=0.95):+ embeddings = embed(texts)+ clusters = cluster_by_similarity(embeddings, threshold)++ # Keep one representative per cluster+ deduplicated = []+ for cluster in clusters:+ representative = select_best(cluster) # longest, most recent, etc.+ deduplicated.append(representative)++ return deduplicated+```++### Active Learning for Efficient Labeling+Prioritize labeling effort:+```python+def active_learning_loop(unlabeled_pool, labeled_set, budget):+ while len(labeled_set) < budget:+ # Train on current labeled data+ model.fit(labeled_set)++ # Score unlabeled by uncertainty+ uncertainties = model.uncertainty(unlabeled_pool)++ # Select most uncertain for labeling+ to_label = select_top_k(unlabeled_pool, uncertainties, k=10)+ labels = human_label(to_label)++ # Update sets+ labeled_set.add(to_label, labels)+ unlabeled_pool.remove(to_label)++ return labeled_set+```++### Data Slice Analysis+Find problematic subgroups:+```python+def find_weak_slices(model, data, features):+ # Evaluate on all slices+ slices = generate_slices(data, features)++ weak_slices = []+ for slice_name, slice_data in slices:+ performance = evaluate(model, slice_data)+ if performance < overall_performance - threshold:+ weak_slices.append({+ "slice": slice_name,+ "size": len(slice_data),+ "performance": performance+ })++ return sorted(weak_slices, key=lambda x: x["performance"])+```++## Common Pitfalls to Avoid++- Cleaning test data the same way as training data (causes leakage)+- Over-aggressive deduplication that removes valid variations+- Imputing values without understanding the missingness mechanism+- Augmenting in ways that introduce unrealistic examples+- Ignoring class imbalance until model training fails+- Not versioning datasets, making experiments irreproducible+- Assuming more data is always better (quality > quantity)+- Failing to document data collection biases and limitationsdiff --git a/skills/demo-script-writer/SKILL.md b/skills/demo-script-writer/SKILL.mdnew file mode 100644index 0000000..537afad--- /dev/null+++ b/skills/demo-script-writer/SKILL.md@@ -0,0 +1,98 @@+---+name: Demo Script Writer+slug: demo-script-writer+description: Write compelling product demo scripts that drive conversions+category: sales+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "demo script"+ - "product demo"+ - "sales demo"+ - "demo presentation"+ - "product walkthrough"+tags:+ - sales-enablement+ - product-demos+ - presentations+ - sales-scripts+ - conversion+---++# Demo Script Writer++Create product demo scripts that showcase value, address objections, and move prospects toward purchase decisions. This skill helps you structure compelling demonstrations that connect features to outcomes and differentiate from competitors.++Great demos don't just show features - they tell stories of transformation. This skill provides frameworks for demo structure, narrative development, objection handling, and engagement techniques. Learn to customize demos for different personas, handle questions gracefully, and create urgency without pressure.++Built for sales teams, solutions engineers, founders, and anyone who demonstrates products to prospective customers.++## Core Workflows++### Workflow 1: Demo Structure Design+1. **Opening Hook** - Capture attention in first 30 seconds+2. **Discovery Recap** - Confirm understood needs+3. **Agenda Setting** - Set expectations for the demo+4. **Transformation Story** - Paint the before/after picture+5. **Feature Flow** - Logical progression through capabilities+6. **Objection Anticipation** - Proactively address concerns+7. **Strong Close** - Clear next steps and call-to-action++### Workflow 2: Persona-Specific Demos+1. **Persona Identification** - Who's in the demo?+2. **Pain Point Mapping** - What matters to this audience+3. **Value Prioritization** - Most relevant benefits first+4. **Language Calibration** - Technical vs business focus+5. **Use Case Selection** - Examples that resonate+6. **Competitive Positioning** - Differentiation for this buyer+7. **Customization Points** - Where to personalize++### Workflow 3: Interactive Demo Flow+1. **Engagement Points** - Where to involve the prospect+2. **Question Prompts** - Check for understanding+3. **Hands-on Moments** - Let them try key features+4. **Discovery Integration** - Ask questions throughout+5. **Objection Response** - Handle concerns as they arise+6. **Value Confirmation** - Get agreement on benefits+7. **Transition Scripting** - Smooth navigation between topics++### Workflow 4: Demo Recording Script+1. **Video Structure** - Optimized for async viewing+2. **Opening Personalization** - Grab attention immediately+3. **Key Feature Selection** - Most impactful capabilities+4. **Time Optimization** - Respect viewer attention spans+5. **Visual Cues** - What to show on screen+6. **Narration Script** - Conversational, benefit-focused+7. **Call-to-Action** - Clear next step at the end++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Create demo script | "Write demo script for [product]" |+| Persona customization | "Customize demo for [persona]" |+| Opening hook | "Create demo opening hook" |+| Feature story | "Write story around [feature]" |+| Objection handling | "Handle [objection] in demo" |+| Video demo script | "Create recorded demo script" |+| Demo agenda | "Create demo agenda for [prospect]" |+| Close script | "Write demo closing script" |++## Best Practices++- **Discovery first** - Know their needs before you demo+- **Story over features** - Frame capabilities as solutions+- **Show, don't tell** - Demonstrate, don't explain+- **One idea at a time** - Don't overwhelm with features+- **Pause for questions** - Check understanding throughout+- **Use their language** - Mirror prospect terminology+- **Prepare for objections** - Know common concerns+- **Time management** - Respect their schedule+- **Customize heavily** - Generic demos feel generic+- **Practice thoroughly** - Smooth delivery builds confidence+- **Technical fallback** - Have backup for tech failures+- **Strong close** - Always end with clear next steps+- **Follow up quickly** - Send recording and materials+- **Iterate constantly** - Improve based on what works+- **Energy matters** - Enthusiasm is contagiousdiff --git a/skills/docker-composer/SKILL.md b/skills/docker-composer/SKILL.mdnew file mode 100644index 0000000..8ca93bc--- /dev/null+++ b/skills/docker-composer/SKILL.md@@ -0,0 +1,763 @@+---+name: docker-composer+description: Expert guide for creating Docker Compose configurations, Dockerfiles, and container orchestration. Use when containerizing applications, setting up development environments, or configuring multi-container deployments.+---++# Docker Composer Skill++## Overview++This skill helps you create efficient Docker configurations for development and production. Covers Dockerfiles, Docker Compose, multi-stage builds, networking, volumes, and container orchestration best practices.++## Docker Philosophy++### Container Principles+1. **One process per container**: Keep containers focused+2. **Immutable infrastructure**: Don't modify running containers+3. **Stateless containers**: Store state in volumes or external services+4. **Minimal images**: Smaller = faster + more secure++### Best Practices+- **DO**: Use multi-stage builds for production+- **DO**: Pin specific versions for dependencies+- **DO**: Use `.dockerignore` to exclude unnecessary files+- **DO**: Run as non-root user+- **DON'T**: Store secrets in images or Dockerfiles+- **DON'T**: Use `latest` tag in production+- **DON'T**: Install unnecessary packages++## Dockerfile Patterns++### Node.js Production Dockerfile++```dockerfile+# Dockerfile+# ============================================+# Stage 1: Dependencies+# ============================================+FROM node:20-alpine AS deps+WORKDIR /app++# Install dependencies only when needed+COPY package.json package-lock.json ./+RUN npm ci --only=production++# ============================================+# Stage 2: Builder+# ============================================+FROM node:20-alpine AS builder+WORKDIR /app++COPY package.json package-lock.json ./+RUN npm ci++COPY . .++# Build application+ENV NEXT_TELEMETRY_DISABLED 1+RUN npm run build++# ============================================+# Stage 3: Runner (Production)+# ============================================+FROM node:20-alpine AS runner+WORKDIR /app++ENV NODE_ENV production+ENV NEXT_TELEMETRY_DISABLED 1++# Create non-root user+RUN addgroup --system --gid 1001 nodejs+RUN adduser --system --uid 1001 nextjs++# Copy built assets+COPY --from=builder /app/public ./public+COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./+COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static++USER nextjs++EXPOSE 3000++ENV PORT 3000+ENV HOSTNAME "0.0.0.0"++CMD ["node", "server.js"]+```++### Python Production Dockerfile++```dockerfile+# Dockerfile+# ============================================+# Stage 1: Builder+# ============================================+FROM python:3.11-slim AS builder++WORKDIR /app++# Install build dependencies+RUN apt-get update && apt-get install -y --no-install-recommends \+ build-essential \+ && rm -rf /var/lib/apt/lists/*++# Create virtual environment+RUN python -m venv /opt/venv+ENV PATH="/opt/venv/bin:$PATH"++# Install dependencies+COPY requirements.txt .+RUN pip install --no-cache-dir -r requirements.txt++# ============================================+# Stage 2: Runner+# ============================================+FROM python:3.11-slim AS runner++WORKDIR /app++# Create non-root user+RUN groupadd --gid 1000 appgroup \+ && useradd --uid 1000 --gid appgroup --shell /bin/bash appuser++# Copy virtual environment+COPY --from=builder /opt/venv /opt/venv+ENV PATH="/opt/venv/bin:$PATH"++# Copy application+COPY --chown=appuser:appgroup . .++USER appuser++EXPOSE 8000++CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]+```++### Development Dockerfile++```dockerfile+# Dockerfile.dev+FROM node:20-alpine++WORKDIR /app++# Install development dependencies+RUN apk add --no-cache git++# Copy package files first (for caching)+COPY package.json package-lock.json ./++# Install all dependencies (including devDependencies)+RUN npm install++# Don't copy files - mount as volume for hot reload+# COPY . .++EXPOSE 3000++CMD ["npm", "run", "dev"]+```++## Docker Compose Configurations++### Full-Stack Development++```yaml+# docker-compose.yml+version: '3.8'++services:+ # ===================+ # Application+ # ===================+ app:+ build:+ context: .+ dockerfile: Dockerfile.dev+ ports:+ - "3000:3000"+ volumes:+ - .:/app+ - /app/node_modules # Exclude node_modules+ environment:+ - NODE_ENV=development+ - DATABASE_URL=postgresql://postgres:postgres@db:5432/myapp+ - REDIS_URL=redis://redis:6379+ depends_on:+ db:+ condition: service_healthy+ redis:+ condition: service_started+ networks:+ - app-network++ # ===================+ # Database+ # ===================+ db:+ image: postgres:15-alpine+ ports:+ - "5432:5432"+ environment:+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: myapp+ volumes:+ - postgres_data:/var/lib/postgresql/data+ - ./init.sql:/docker-entrypoint-initdb.d/init.sql+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U postgres"]+ interval: 5s+ timeout: 5s+ retries: 5+ networks:+ - app-network++ # ===================+ # Redis Cache+ # ===================+ redis:+ image: redis:7-alpine+ ports:+ - "6379:6379"+ volumes:+ - redis_data:/data+ command: redis-server --appendonly yes+ networks:+ - app-network++ # ===================+ # Admin Tools+ # ===================+ adminer:+ image: adminer+ ports:+ - "8080:8080"+ depends_on:+ - db+ networks:+ - app-network++volumes:+ postgres_data:+ redis_data:++networks:+ app-network:+ driver: bridge+```++### Production Configuration++```yaml+# docker-compose.prod.yml+version: '3.8'++services:+ app:+ image: myapp:${VERSION:-latest}+ build:+ context: .+ dockerfile: Dockerfile+ ports:+ - "3000:3000"+ environment:+ - NODE_ENV=production+ env_file:+ - .env.production+ deploy:+ replicas: 3+ resources:+ limits:+ cpus: '0.5'+ memory: 512M+ reservations:+ cpus: '0.25'+ memory: 256M+ restart_policy:+ condition: on-failure+ delay: 5s+ max_attempts: 3+ healthcheck:+ test: ["CMD", "curl", "-f", "http://localhost:3000/api/health"]+ interval: 30s+ timeout: 10s+ retries: 3+ start_period: 40s+ logging:+ driver: "json-file"+ options:+ max-size: "10m"+ max-file: "3"+ networks:+ - app-network+ depends_on:+ - db+ - redis++ db:+ image: postgres:15-alpine+ environment:+ POSTGRES_USER: ${DB_USER}+ POSTGRES_PASSWORD_FILE: /run/secrets/db_password+ POSTGRES_DB: ${DB_NAME}+ secrets:+ - db_password+ volumes:+ - postgres_data:/var/lib/postgresql/data+ deploy:+ resources:+ limits:+ cpus: '1'+ memory: 1G+ networks:+ - app-network++ redis:+ image: redis:7-alpine+ command: redis-server --requirepass ${REDIS_PASSWORD}+ volumes:+ - redis_data:/data+ networks:+ - app-network++ nginx:+ image: nginx:alpine+ ports:+ - "80:80"+ - "443:443"+ volumes:+ - ./nginx.conf:/etc/nginx/nginx.conf:ro+ - ./certs:/etc/nginx/certs:ro+ depends_on:+ - app+ networks:+ - app-network++secrets:+ db_password:+ file: ./secrets/db_password.txt++volumes:+ postgres_data:+ redis_data:++networks:+ app-network:+ driver: overlay+```++### Development Override Pattern++```yaml+# docker-compose.override.yml (auto-loaded with docker-compose.yml)+version: '3.8'++services:+ app:+ build:+ context: .+ dockerfile: Dockerfile.dev+ volumes:+ - .:/app+ - /app/node_modules+ environment:+ - DEBUG=true+ - LOG_LEVEL=debug+ command: npm run dev++ db:+ ports:+ - "5432:5432" # Expose for local tools++ redis:+ ports:+ - "6379:6379" # Expose for local tools+```++## Advanced Patterns++### Multi-Service Monorepo++```yaml+# docker-compose.yml+version: '3.8'++services:+ # Frontend+ web:+ build:+ context: .+ dockerfile: apps/web/Dockerfile+ ports:+ - "3000:3000"+ environment:+ - API_URL=http://api:4000+ depends_on:+ - api+ networks:+ - frontend+ - backend++ # Backend API+ api:+ build:+ context: .+ dockerfile: apps/api/Dockerfile+ ports:+ - "4000:4000"+ environment:+ - DATABASE_URL=postgresql://postgres:postgres@db:5432/myapp+ - REDIS_URL=redis://redis:6379+ depends_on:+ - db+ - redis+ networks:+ - backend++ # Background Workers+ worker:+ build:+ context: .+ dockerfile: apps/worker/Dockerfile+ environment:+ - DATABASE_URL=postgresql://postgres:postgres@db:5432/myapp+ - REDIS_URL=redis://redis:6379+ depends_on:+ - db+ - redis+ deploy:+ replicas: 2+ networks:+ - backend++ # Shared services+ db:+ image: postgres:15-alpine+ volumes:+ - postgres_data:/var/lib/postgresql/data+ networks:+ - backend++ redis:+ image: redis:7-alpine+ volumes:+ - redis_data:/data+ networks:+ - backend++networks:+ frontend:+ backend:++volumes:+ postgres_data:+ redis_data:+```++### Local Services Stack++```yaml+# docker-compose.services.yml+# Run local versions of external services for development+version: '3.8'++services:+ # Local S3-compatible storage+ minio:+ image: minio/minio+ ports:+ - "9000:9000"+ - "9001:9001" # Console+ volumes:+ - minio_data:/data+ environment:+ MINIO_ROOT_USER: minioadmin+ MINIO_ROOT_PASSWORD: minioadmin+ command: server /data --console-address ":9001"++ # Local email testing+ mailhog:+ image: mailhog/mailhog+ ports:+ - "1025:1025" # SMTP+ - "8025:8025" # Web UI++ # Local Stripe webhooks+ stripe-cli:+ image: stripe/stripe-cli+ command: listen --api-key ${STRIPE_SECRET_KEY} --forward-to http://app:3000/api/webhooks/stripe+ depends_on:+ - app++ # Elasticsearch+ elasticsearch:+ image: elasticsearch:8.11.0+ ports:+ - "9200:9200"+ environment:+ - discovery.type=single-node+ - xpack.security.enabled=false+ - "ES_JAVA_OPTS=-Xms512m -Xmx512m"+ volumes:+ - elasticsearch_data:/usr/share/elasticsearch/data++ # Kibana (Elasticsearch UI)+ kibana:+ image: kibana:8.11.0+ ports:+ - "5601:5601"+ environment:+ ELASTICSEARCH_HOSTS: http://elasticsearch:9200+ depends_on:+ - elasticsearch++volumes:+ minio_data:+ elasticsearch_data:+```++### Testing Configuration++```yaml+# docker-compose.test.yml+version: '3.8'++services:+ app:+ build:+ context: .+ dockerfile: Dockerfile.test+ environment:+ - NODE_ENV=test+ - DATABASE_URL=postgresql://postgres:postgres@db:5432/myapp_test+ depends_on:+ db:+ condition: service_healthy+ command: npm run test:ci++ db:+ image: postgres:15-alpine+ environment:+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: myapp_test+ tmpfs:+ - /var/lib/postgresql/data # Use tmpfs for speed+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U postgres"]+ interval: 2s+ timeout: 5s+ retries: 5++ # E2E testing+ playwright:+ image: mcr.microsoft.com/playwright:v1.40.0-focal+ volumes:+ - .:/app+ - /app/node_modules+ working_dir: /app+ environment:+ - CI=true+ - BASE_URL=http://app:3000+ depends_on:+ - app+ command: npx playwright test+```++## .dockerignore++```dockerignore+# .dockerignore++# Dependencies+node_modules+npm-debug.log+yarn-error.log++# Build output+.next+dist+build+out++# Development+.git+.gitignore+*.md+!README.md++# IDE+.vscode+.idea+*.swp+*.swo++# Environment+.env+.env.*+!.env.example++# Tests+coverage+*.test.js+*.spec.js+__tests__+e2e+playwright-report++# Docker+Dockerfile*+docker-compose*+.docker++# Misc+.DS_Store+*.log+tmp+```++## Docker Commands Reference++### Development Workflow++```bash+# Start development environment+docker-compose up -d++# View logs+docker-compose logs -f app++# Rebuild after package changes+docker-compose up -d --build++# Run one-off commands+docker-compose exec app npm run migrate+docker-compose exec app npm run seed++# Stop everything+docker-compose down++# Stop and remove volumes (reset database)+docker-compose down -v+```++### Production Workflow++```bash+# Build production image+docker build -t myapp:1.0.0 .++# Run with production config+docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d++# Scale services+docker-compose up -d --scale app=3++# Rolling update+docker-compose pull app+docker-compose up -d --no-deps app+```++### Debugging++```bash+# Shell into running container+docker-compose exec app sh++# Inspect container+docker inspect <container_id>++# View resource usage+docker stats++# Clean up unused resources+docker system prune -a++# View networks+docker network ls+docker network inspect app-network+```++## Health Checks++### Application Health Check++```typescript+// src/app/api/health/route.ts+import { NextResponse } from 'next/server';++export async function GET() {+ const checks = {+ uptime: process.uptime(),+ timestamp: new Date().toISOString(),+ database: false,+ redis: false,+ };++ try {+ // Check database+ await db.execute('SELECT 1');+ checks.database = true;+ } catch (e) {+ console.error('Database health check failed:', e);+ }++ try {+ // Check Redis+ await redis.ping();+ checks.redis = true;+ } catch (e) {+ console.error('Redis health check failed:', e);+ }++ const isHealthy = checks.database && checks.redis;++ return NextResponse.json(checks, {+ status: isHealthy ? 200 : 503+ });+}+```++### Docker Health Check++```dockerfile+HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \+ CMD curl -f http://localhost:3000/api/health || exit 1+```++## Checklist++### Dockerfile+- [ ] Multi-stage build for production+- [ ] Non-root user+- [ ] Minimal base image (alpine when possible)+- [ ] Layer caching optimized (dependencies before code)+- [ ] Health check defined+- [ ] `.dockerignore` configured++### Docker Compose+- [ ] Services have health checks+- [ ] Volumes for persistent data+- [ ] Networks for service isolation+- [ ] Resource limits defined+- [ ] Restart policies configured+- [ ] Environment variables externalized++### Security+- [ ] No secrets in Dockerfile or docker-compose+- [ ] Images scanned for vulnerabilities+- [ ] Minimal privileges (no root)+- [ ] Network isolation between services++## When to Use This Skill++Invoke this skill when:+- Containerizing a new application+- Setting up development environments with Docker+- Creating multi-service architectures+- Optimizing Docker builds+- Debugging container issues+- Setting up CI/CD pipelines with Docker+- Migrating from docker-compose to Kubernetesdiff --git a/skills/embedding-generator/SKILL.md b/skills/embedding-generator/SKILL.mdnew file mode 100644index 0000000..031a458--- /dev/null+++ b/skills/embedding-generator/SKILL.md@@ -0,0 +1,187 @@+---+name: Embedding Generator+slug: embedding-generator+description: Generate and manage text embeddings for semantic search, clustering, and similarity tasks+category: ai-ml+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "generate embeddings"+ - "create embeddings"+ - "text embeddings"+ - "semantic vectors"+ - "vectorize text"+tags:+ - embeddings+ - vectors+ - semantic-search+ - NLP+ - machine-learning+---++# Embedding Generator++The Embedding Generator skill helps you create, manage, and utilize text embeddings for semantic search, similarity matching, clustering, and classification tasks. It guides you through selecting appropriate embedding models, preprocessing text for optimal vectorization, and storing/querying embeddings efficiently.++Text embeddings transform words, sentences, or documents into dense numerical vectors that capture semantic meaning. Similar concepts end up close together in vector space, enabling powerful AI applications like semantic search, recommendations, and content understanding.++This skill covers everything from choosing the right model (OpenAI, Cohere, sentence-transformers, etc.) to implementing production-ready embedding pipelines with proper batching, caching, and quality validation.++## Core Workflows++### Workflow 1: Generate Embeddings for Text Corpus+1. **Analyze** the text corpus:+ - Content type (documents, sentences, queries)+ - Average length and variation+ - Language(s) present+ - Domain specificity+2. **Select** embedding model:+ - Consider dimensionality vs performance tradeoff+ - Match model to content type+ - Evaluate cost and latency constraints+3. **Preprocess** text:+ - Clean and normalize+ - Chunk long documents appropriately+ - Handle special characters and formatting+4. **Generate** embeddings with batching+5. **Validate** quality with spot checks+6. **Store** in appropriate vector database++### Workflow 2: Choose Embedding Model+1. **Gather** requirements:+ - Use case (search, clustering, classification)+ - Latency requirements+ - Cost constraints+ - Accuracy needs+2. **Compare** models:+ | Model | Dims | Speed | Quality | Cost |+ |-------|------|-------|---------|------|+ | OpenAI text-embedding-3-small | 1536 | Fast | Good | $$ |+ | OpenAI text-embedding-3-large | 3072 | Fast | Best | $$$ |+ | Cohere embed-english-v3 | 1024 | Fast | Great | $$ |+ | sentence-transformers | 384-768 | Varies | Good | Free |+ | Voyage AI | 1024 | Fast | Great | $$ |+3. **Benchmark** on representative samples+4. **Document** decision rationale++### Workflow 3: Implement Embedding Pipeline+1. **Design** pipeline architecture:+ - Input preprocessing+ - Batching strategy+ - Error handling+ - Caching layer+2. **Implement** core components:+ ```python+ # Example pipeline structure+ def embedding_pipeline(texts):+ cleaned = preprocess(texts)+ chunks = chunk_if_needed(cleaned)+ batches = create_batches(chunks, batch_size=100)+ embeddings = []+ for batch in batches:+ result = model.embed(batch)+ embeddings.extend(result)+ return embeddings+ ```+3. **Add** monitoring and logging+4. **Test** with edge cases+5. **Optimize** for production scale++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Generate embeddings | "Generate embeddings for these texts" |+| Choose model | "Which embedding model for [use case]" |+| Compare models | "Compare embedding models" |+| Optimize pipeline | "Speed up embedding generation" |+| Validate quality | "Check embedding quality" |+| Chunk documents | "How to chunk for embeddings" |++## Best Practices++- **Match Model to Use Case**: Query-document search needs asymmetric models; clustering needs symmetric+ - Search: Use models trained on query-passage pairs+ - Clustering: Use models with good sentence-level representations++- **Chunk Intelligently**: Long texts must be chunked, but chunking strategy matters+ - Preserve semantic units (paragraphs, sections)+ - Use overlapping chunks for continuity (10-20% overlap)+ - Keep chunk size within model's sweet spot (typically 256-512 tokens)++- **Batch for Efficiency**: API calls are expensive; batch aggressively+ - OpenAI: Up to 2048 texts per batch+ - Use async/concurrent processing for speed+ - Implement exponential backoff for rate limits++- **Cache Embeddings**: Don't regenerate what you've already computed+ - Hash text to create cache keys+ - Store embeddings with metadata+ - Invalidate cache when model changes++- **Normalize Vectors**: Cosine similarity requires normalized vectors+ - Most models output normalized vectors+ - Verify or normalize explicitly for consistency++- **Validate Quality**: Spot-check embeddings before production use+ - Test similarity between known-similar texts+ - Check that distances make semantic sense+ - Compare against baseline or ground truth++## Advanced Techniques++### Hybrid Chunking Strategy+Combine semantic and size-based chunking:+```python+def hybrid_chunk(text, max_tokens=512):+ # First: Split on semantic boundaries+ sections = split_on_headers_paragraphs(text)++ # Then: Split large sections on size+ chunks = []+ for section in sections:+ if token_count(section) > max_tokens:+ chunks.extend(split_with_overlap(section, max_tokens))+ else:+ chunks.append(section)+ return chunks+```++### Query Expansion for Better Retrieval+Generate multiple query embeddings for robust search:+```+Original: "machine learning frameworks"+Expanded: [+ "machine learning frameworks",+ "ML libraries and tools",+ "deep learning software",+ "AI development platforms"+]+```++### Dimensionality Reduction+When storage or speed is critical:+```+- PCA: Fast, linear reduction+- UMAP: Preserves local structure+- Matryoshka embeddings: Models with variable-size outputs+```++### Cross-Lingual Embeddings+For multilingual applications:+```+- Use multilingual models (mBERT, XLM-R, Cohere multilingual)+- Translate queries to embedding language+- Align embedding spaces post-hoc+```++## Common Pitfalls to Avoid++- Using the wrong model type (asymmetric vs symmetric) for your use case+- Chunking in ways that break semantic meaning (mid-sentence, mid-paragraph)+- Not accounting for rate limits in production systems+- Storing embeddings without metadata needed for filtering+- Regenerating embeddings unnecessarily (implement caching)+- Mixing embeddings from different models in the same index+- Ignoring the impact of text preprocessing on embedding qualitydiff --git a/skills/entity-extractor/SKILL.md b/skills/entity-extractor/SKILL.mdnew file mode 100644index 0000000..3b6bbb8--- /dev/null+++ b/skills/entity-extractor/SKILL.md@@ -0,0 +1,340 @@+---+name: Entity Extractor+slug: entity-extractor+description: Extract named entities from text with high accuracy and customization+category: ai-ml+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "extract entities"+ - "named entity recognition"+ - "NER"+ - "entity extraction"+ - "information extraction"+tags:+ - NER+ - entity-extraction+ - information-extraction+ - NLP+ - text-mining+---++# Entity Extractor++The Entity Extractor skill guides you through implementing named entity recognition (NER) systems that identify and classify entities in text. From people and organizations to domain-specific entities like products, medical terms, or financial instruments, this skill covers extraction approaches from simple pattern matching to advanced neural models.++Entity extraction is a foundational NLP task that powers applications from search engines to knowledge graphs. Getting it right requires understanding your domain, choosing appropriate techniques, and handling the inherent ambiguity in natural language.++Whether you need to extract standard entity types, define custom entities for your domain, or build relation extraction on top of entity recognition, this skill ensures your extraction pipeline is accurate and maintainable.++## Core Workflows++### Workflow 1: Choose Extraction Approach+1. **Define** target entities:+ - Standard types: PERSON, ORG, LOCATION, DATE, MONEY+ - Domain-specific: PRODUCT, SYMPTOM, GENE, CONTRACT+ - Relations: connections between entities+2. **Assess** available resources:+ - Labeled training data+ - Domain expertise+ - Compute constraints+3. **Select** approach:+ | Approach | Training Data | Accuracy | Speed | Customization |+ |----------|---------------|----------|-------|---------------|+ | spaCy (pre-trained) | None | Good | Very fast | Limited |+ | Rule-based | None | Variable | Fast | High |+ | Fine-tuned BERT | 100s-1000s | Excellent | Medium | Full |+ | LLM (zero-shot) | None | Good | Slow | Prompt-based |+ | LLM (few-shot) | Few examples | Very good | Slow | Prompt-based |+4. **Plan** implementation and evaluation++### Workflow 2: Implement Entity Extraction Pipeline+1. **Set up** extraction:+ ```python+ import spacy++ class EntityExtractor:+ def __init__(self, model="en_core_web_trf"):+ self.nlp = spacy.load(model)++ def extract(self, text):+ doc = self.nlp(text)+ entities = []+ for ent in doc.ents:+ entities.append({+ "text": ent.text,+ "type": ent.label_,+ "start": ent.start_char,+ "end": ent.end_char,+ "confidence": getattr(ent, "confidence", None)+ })+ return entities++ def extract_batch(self, texts):+ docs = list(self.nlp.pipe(texts))+ return [self.extract_from_doc(doc) for doc in docs]+ ```+2. **Post-process** entities:+ - Normalize variations (IBM vs I.B.M.)+ - Resolve abbreviations+ - Link to knowledge base+3. **Validate** extraction quality+4. **Handle** edge cases++### Workflow 3: Build Custom Entity Recognizer+1. **Prepare** training data:+ ```python+ # Format for spaCy training+ TRAIN_DATA = [+ ("Apple released the new iPhone today.", {+ "entities": [(0, 5, "ORG"), (24, 30, "PRODUCT")]+ }),+ ("Dr. Smith prescribed metformin for diabetes.", {+ "entities": [(0, 9, "PERSON"), (21, 30, "DRUG"), (35, 43, "CONDITION")]+ })+ ]+ ```+2. **Configure** training:+ ```python+ # spaCy config for NER training+ config = {+ "training": {+ "optimizer": {"learn_rate": 0.001},+ "batch_size": {"@schedules": "compounding", "start": 4, "stop": 32}+ },+ "components": {+ "ner": {+ "factory": "ner",+ "model": {"@architectures": "spacy.TransitionBasedParser"}+ }+ }+ }+ ```+3. **Train** model:+ ```bash+ python -m spacy train config.cfg --output ./models --paths.train ./train.spacy --paths.dev ./dev.spacy+ ```+4. **Evaluate** on held-out data+5. **Iterate** based on errors++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Extract entities | "Extract entities from [text]" |+| Choose NER model | "Best NER for [domain]" |+| Custom entities | "Train custom entity recognizer" |+| Evaluate NER | "Evaluate entity extraction quality" |+| Handle ambiguity | "Resolve ambiguous entities" |+| Entity linking | "Link entities to knowledge base" |++## Best Practices++- **Start with Pre-trained**: Don't train from scratch unnecessarily+ - spaCy, Hugging Face, and cloud APIs cover common entities+ - Test pre-trained models first+ - Fine-tune only when needed++- **Define Clear Guidelines**: Entity boundaries are ambiguous+ - "Dr. John Smith" - one entity or two?+ - "New York Times" - ORG or GPE?+ - Create and follow consistent annotation guidelines++- **Handle Nested Entities**: Some entities contain others+ - "Bank of America headquarters" (ORG inside LOCATION)+ - Decide on nesting strategy upfront+ - Some models support flat only; others handle nested++- **Normalize Extracted Entities**: Raw text has variations+ - "IBM", "I.B.M.", "International Business Machines"+ - Canonicalize to standard form+ - Link to knowledge base IDs when possible++- **Evaluate Granularly**: Aggregate metrics hide issues+ - Report precision/recall per entity type+ - Analyze error patterns+ - Test on edge cases explicitly++- **Consider Context Window**: Models have context limits+ - Long documents may need chunking+ - Preserve context across chunks when possible+ - Re-run on boundaries if entities might span++## Advanced Techniques++### LLM-Based Entity Extraction+Use language models for flexible extraction:+```python+def llm_extract_entities(text, entity_types):+ prompt = f"""Extract named entities from the following text.++Text: "{text}"++Entity types to extract:+{chr(10).join(f"- {t}: {desc}" for t, desc in entity_types.items())}++Return a JSON array of entities:+[{{"text": "entity text", "type": "ENTITY_TYPE", "start": 0, "end": 10}}]++Only include entities that clearly match the specified types.+"""++ response = llm.complete(prompt, response_format={"type": "json_object"})+ return json.loads(response)["entities"]++# Example usage+entity_types = {+ "COMPANY": "Business organizations",+ "PRODUCT": "Commercial products or services",+ "PERSON": "Individual people's names"+}+entities = llm_extract_entities(text, entity_types)+```++### Hybrid Rule + ML Approach+Combine patterns with neural extraction:+```python+class HybridExtractor:+ def __init__(self):+ self.ml_extractor = spacy.load("en_core_web_trf")+ self.patterns = load_pattern_rules()++ def extract(self, text):+ # ML extraction+ ml_entities = self.ml_extractor(text).ents++ # Pattern-based extraction+ pattern_entities = apply_patterns(text, self.patterns)++ # Merge with priority rules+ merged = merge_entities(+ ml_entities,+ pattern_entities,+ priority="pattern" # Patterns override ML when overlap+ )++ return merged++ def add_pattern(self, pattern, entity_type):+ """Add domain-specific pattern."""+ self.patterns.append({+ "pattern": pattern,+ "type": entity_type+ })+```++### Entity Linking+Connect extracted entities to knowledge bases:+```python+def link_entity(entity_text, entity_type, knowledge_base):+ """+ Link extracted entity to canonical entry in knowledge base.+ """+ # Generate candidates+ candidates = knowledge_base.search(+ query=entity_text,+ type_filter=entity_type,+ limit=10+ )++ if not candidates:+ return {"entity": entity_text, "linked": None}++ # Score candidates+ scored = []+ for candidate in candidates:+ score = compute_linking_score(+ entity_text,+ candidate.name,+ candidate.aliases+ )+ scored.append((candidate, score))++ # Select best match+ best = max(scored, key=lambda x: x[1])++ if best[1] > LINKING_THRESHOLD:+ return {+ "entity": entity_text,+ "linked": best[0].id,+ "canonical_name": best[0].name,+ "confidence": best[1]+ }+ else:+ return {"entity": entity_text, "linked": None}+```++### Relation Extraction+Extract relationships between entities:+```python+def extract_relations(text, entities):+ """+ Given extracted entities, find relations between them.+ """+ prompt = f"""Given this text and extracted entities, identify relationships.++Text: "{text}"++Entities found:+{json.dumps(entities, indent=2)}++Identify relationships between entities. Return JSON:+[{{+ "subject": "entity text",+ "relation": "relationship type",+ "object": "entity text",+ "confidence": 0.9+}}]++Common relation types: WORKS_FOR, LOCATED_IN, FOUNDED, ACQUIRED, PARTNER_OF+"""++ response = llm.complete(prompt)+ return json.loads(response)+```++### Active Learning for NER+Efficiently improve extraction with targeted labeling:+```python+def active_learning_sample(unlabeled_texts, model, n_samples=100):+ """+ Select texts that would be most valuable to label.+ """+ uncertainties = []++ for text in unlabeled_texts:+ doc = model(text)+ # Calculate uncertainty (various strategies)+ uncertainty = calculate_ner_uncertainty(doc)+ uncertainties.append((text, uncertainty))++ # Select most uncertain+ uncertainties.sort(key=lambda x: x[1], reverse=True)+ return [text for text, _ in uncertainties[:n_samples]]++def calculate_ner_uncertainty(doc):+ """+ Calculate uncertainty based on entity confidence scores.+ """+ if not doc.ents:+ return 0.5 # No entities - medium uncertainty++ confidences = [ent._.confidence for ent in doc.ents if hasattr(ent._, "confidence")]+ if not confidences:+ return 0.5++ # High uncertainty = low confidence entities+ return 1 - min(confidences)+```++## Common Pitfalls to Avoid++- Inconsistent annotation guidelines leading to noisy training data+- Not handling entity boundary ambiguity (where does entity end?)+- Ignoring nested or overlapping entities when they matter+- Training on small datasets without augmentation+- Not normalizing entities before downstream use+- Assuming pre-trained models work on your domain without testing+- Not evaluating per-entity-type performance+- Forgetting about entity linking for disambiguationdiff --git a/skills/env-setup-assistant/SKILL.md b/skills/env-setup-assistant/SKILL.mdnew file mode 100644index 0000000..43e5f7e--- /dev/null+++ b/skills/env-setup-assistant/SKILL.md@@ -0,0 +1,741 @@+---+name: env-setup-assistant+description: Expert guide for setting up development environments including IDE configuration, tooling, dependencies, and developer onboarding. Use when bootstrapping new projects or standardizing team environments.+---++# Environment Setup Assistant Skill++## Overview++This skill helps you create reproducible, developer-friendly environments. Covers IDE configuration, tool installation, dependency management, onboarding documentation, and cross-platform compatibility.++## Environment Setup Philosophy++### Principles+1. **One command setup**: New developers should run one command+2. **Reproducible**: Same environment everywhere+3. **Documented**: Clear instructions for edge cases+4. **Versioned**: Lock tool and dependency versions++### Goals+- **DO**: Automate everything possible+- **DO**: Detect and report issues early+- **DO**: Support multiple platforms (macOS, Linux, Windows)+- **DON'T**: Assume global installations+- **DON'T**: Require manual steps without documentation++## Project Setup Script++### Comprehensive Setup Script++```bash+#!/bin/bash+# scripts/setup.sh++set -e # Exit on error++# Colors for output+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+NC='\033[0m' # No Color++log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }+log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }+log_error() { echo -e "${RED}[ERROR]${NC} $1"; }++# ===================+# Check Prerequisites+# ===================+check_command() {+ if ! command -v "$1" &> /dev/null; then+ log_error "$1 is not installed"+ return 1+ fi+ log_info "$1 found: $(command -v $1)"+ return 0+}++check_prerequisites() {+ log_info "Checking prerequisites..."++ local missing=0++ check_command "node" || missing=$((missing + 1))+ check_command "npm" || missing=$((missing + 1))+ check_command "git" || missing=$((missing + 1))++ # Check Node version+ local node_version=$(node -v | cut -d'v' -f2)+ local required_version="18.0.0"+ if ! [ "$(printf '%s\n' "$required_version" "$node_version" | sort -V | head -n1)" = "$required_version" ]; then+ log_error "Node.js version must be >= $required_version (found: $node_version)"+ missing=$((missing + 1))+ fi++ if [ $missing -gt 0 ]; then+ log_error "$missing prerequisite(s) missing"+ echo ""+ echo "Install missing tools:"+ echo " - Node.js: https://nodejs.org/ or 'nvm install 20'"+ echo " - Git: https://git-scm.com/"+ exit 1+ fi++ log_info "All prerequisites met!"+}++# ===================+# Environment Setup+# ===================+setup_env() {+ log_info "Setting up environment..."++ if [ ! -f .env ]; then+ if [ -f .env.example ]; then+ cp .env.example .env+ log_info "Created .env from .env.example"+ log_warn "Please update .env with your values"+ else+ log_error "No .env.example found"+ exit 1+ fi+ else+ log_info ".env already exists"+ fi+}++# ===================+# Install Dependencies+# ===================+install_dependencies() {+ log_info "Installing dependencies..."++ npm ci++ log_info "Dependencies installed!"+}++# ===================+# Setup Git Hooks+# ===================+setup_git_hooks() {+ log_info "Setting up Git hooks..."++ npx husky install 2>/dev/null || log_warn "Husky not configured"++ log_info "Git hooks configured!"+}++# ===================+# Database Setup+# ===================+setup_database() {+ log_info "Setting up database..."++ # Check if database is running+ if ! pg_isready -h localhost -p 5432 &>/dev/null; then+ log_warn "PostgreSQL not running on localhost:5432"+ log_info "Start with: docker-compose up -d db"+ return+ fi++ # Run migrations+ npm run db:migrate 2>/dev/null || log_warn "No migrations to run"++ # Seed data (development only)+ if [ "$NODE_ENV" != "production" ]; then+ npm run db:seed 2>/dev/null || log_warn "No seed script found"+ fi++ log_info "Database setup complete!"+}++# ===================+# Verify Setup+# ===================+verify_setup() {+ log_info "Verifying setup..."++ # Type check+ npm run typecheck 2>/dev/null && log_info "TypeScript: OK" || log_warn "TypeScript check failed"++ # Lint+ npm run lint 2>/dev/null && log_info "Linting: OK" || log_warn "Linting issues found"++ # Build test+ npm run build 2>/dev/null && log_info "Build: OK" || log_error "Build failed"+}++# ===================+# Main+# ===================+main() {+ echo ""+ echo "================================"+ echo " Project Setup"+ echo "================================"+ echo ""++ check_prerequisites+ echo ""++ setup_env+ echo ""++ install_dependencies+ echo ""++ setup_git_hooks+ echo ""++ setup_database+ echo ""++ verify_setup+ echo ""++ echo "================================"+ echo " Setup Complete!"+ echo "================================"+ echo ""+ echo "Next steps:"+ echo " 1. Update .env with your values"+ echo " 2. Start development: npm run dev"+ echo " 3. Open http://localhost:3000"+ echo ""+}++main "$@"+```++## Version Management++### .nvmrc / .node-version++```+20.10.0+```++### Tool Versions (asdf)++```ini+# .tool-versions+nodejs 20.10.0+pnpm 8.12.0+python 3.11.6+```++### Volta Configuration++```json+// package.json+{+ "volta": {+ "node": "20.10.0",+ "npm": "10.2.5"+ }+}+```++## IDE Configuration++### VSCode Settings++```json+// .vscode/settings.json+{+ // Editor+ "editor.formatOnSave": true,+ "editor.defaultFormatter": "esbenp.prettier-vscode",+ "editor.codeActionsOnSave": {+ "source.fixAll.eslint": "explicit",+ "source.organizeImports": "explicit"+ },+ "editor.tabSize": 2,+ "editor.insertSpaces": true,+ "editor.rulers": [80, 120],++ // Files+ "files.trimTrailingWhitespace": true,+ "files.insertFinalNewline": true,+ "files.exclude": {+ "**/.git": true,+ "**/node_modules": true,+ "**/.next": true+ },++ // TypeScript+ "typescript.preferences.importModuleSpecifier": "relative",+ "typescript.updateImportsOnFileMove.enabled": "always",+ "typescript.tsdk": "node_modules/typescript/lib",++ // Tailwind+ "tailwindCSS.experimental.classRegex": [+ ["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"],+ ["cn\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"]+ ],++ // ESLint+ "eslint.validate": [+ "javascript",+ "javascriptreact",+ "typescript",+ "typescriptreact"+ ],++ // Prettier+ "[typescript]": {+ "editor.defaultFormatter": "esbenp.prettier-vscode"+ },+ "[typescriptreact]": {+ "editor.defaultFormatter": "esbenp.prettier-vscode"+ },+ "[json]": {+ "editor.defaultFormatter": "esbenp.prettier-vscode"+ }+}+```++### VSCode Extensions++```json+// .vscode/extensions.json+{+ "recommendations": [+ // Essential+ "esbenp.prettier-vscode",+ "dbaeumer.vscode-eslint",+ "bradlc.vscode-tailwindcss",++ // TypeScript+ "ms-vscode.vscode-typescript-next",+ "yoavbls.pretty-ts-errors",++ // React/Next.js+ "dsznajder.es7-react-js-snippets",+ "formulahendry.auto-rename-tag",++ // Git+ "eamodio.gitlens",+ "mhutchie.git-graph",++ // Productivity+ "streetsidesoftware.code-spell-checker",+ "usernamehw.errorlens",+ "christian-kohler.path-intellisense",++ // Theme (optional)+ "GitHub.github-vscode-theme"+ ],+ "unwantedRecommendations": []+}+```++### VSCode Launch Configuration++```json+// .vscode/launch.json+{+ "version": "0.2.0",+ "configurations": [+ {+ "name": "Next.js: debug server-side",+ "type": "node",+ "request": "attach",+ "port": 9229,+ "skipFiles": ["<node_internals>/**"]+ },+ {+ "name": "Next.js: debug client-side",+ "type": "chrome",+ "request": "launch",+ "url": "http://localhost:3000"+ },+ {+ "name": "Next.js: debug full stack",+ "type": "node",+ "request": "launch",+ "program": "${workspaceFolder}/node_modules/.bin/next",+ "args": ["dev"],+ "cwd": "${workspaceFolder}",+ "console": "integratedTerminal"+ },+ {+ "name": "Jest: current file",+ "type": "node",+ "request": "launch",+ "program": "${workspaceFolder}/node_modules/.bin/jest",+ "args": [+ "${fileBasename}",+ "--config",+ "jest.config.js",+ "--runInBand"+ ],+ "console": "integratedTerminal"+ }+ ]+}+```++## EditorConfig++```ini+# .editorconfig+root = true++[*]+indent_style = space+indent_size = 2+end_of_line = lf+charset = utf-8+trim_trailing_whitespace = true+insert_final_newline = true++[*.md]+trim_trailing_whitespace = false++[Makefile]+indent_style = tab+```++## Git Configuration++### .gitattributes++```gitattributes+# .gitattributes++# Auto detect text files+* text=auto eol=lf++# Documents+*.md text+*.txt text++# Source code+*.js text+*.jsx text+*.ts text+*.tsx text+*.css text+*.scss text+*.html text+*.json text+*.yaml text+*.yml text++# Docker+Dockerfile text++# Shell+*.sh text eol=lf++# Windows+*.bat text eol=crlf++# Binary+*.png binary+*.jpg binary+*.jpeg binary+*.gif binary+*.ico binary+*.woff binary+*.woff2 binary+*.ttf binary+*.eot binary+*.pdf binary+```++### Pre-commit Hooks (Husky + lint-staged)++```json+// package.json+{+ "scripts": {+ "prepare": "husky install"+ },+ "lint-staged": {+ "*.{js,jsx,ts,tsx}": [+ "eslint --fix",+ "prettier --write"+ ],+ "*.{json,md,yml,yaml}": [+ "prettier --write"+ ]+ }+}+```++```bash+# .husky/pre-commit+#!/bin/sh+. "$(dirname "$0")/_/husky.sh"++npx lint-staged+```++```bash+# .husky/commit-msg+#!/bin/sh+. "$(dirname "$0")/_/husky.sh"++npx --no-install commitlint --edit "$1"+```++## Onboarding Documentation++### CONTRIBUTING.md Template++```markdown+# Contributing Guide++## Getting Started++### Prerequisites++- Node.js 20+ ([install](https://nodejs.org/) or `nvm install 20`)+- pnpm 8+ (`npm install -g pnpm`)+- Docker Desktop ([install](https://docker.com/products/docker-desktop))+- Git ([install](https://git-scm.com/))++### Quick Start++```bash+# Clone the repository+git clone https://github.com/org/project.git+cd project++# Run setup script+./scripts/setup.sh++# Start development server+npm run dev+```++Open [http://localhost:3000](http://localhost:3000)++### Manual Setup++If the setup script doesn't work:++1. **Install dependencies**+ ```bash+ npm install+ ```++2. **Set up environment**+ ```bash+ cp .env.example .env+ # Edit .env with your values+ ```++3. **Start services**+ ```bash+ docker-compose up -d+ ```++4. **Run migrations**+ ```bash+ npm run db:migrate+ ```++## Development Workflow++### Branch Naming++- `feature/description` - New features+- `fix/description` - Bug fixes+- `chore/description` - Maintenance+- `docs/description` - Documentation++### Commit Messages++We use [Conventional Commits](https://www.conventionalcommits.org/):++```+type(scope): description++[optional body]++[optional footer]+```++Types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`++### Pull Requests++1. Create a branch from `main`+2. Make your changes+3. Run tests: `npm test`+4. Run linting: `npm run lint`+5. Create PR against `main`++## Available Scripts++| Command | Description |+|---------|-------------|+| `npm run dev` | Start development server |+| `npm run build` | Build for production |+| `npm run test` | Run tests |+| `npm run lint` | Run linting |+| `npm run typecheck` | Run TypeScript checks |++## Architecture++[Brief overview of project structure]++## Getting Help++- Check existing [issues](https://github.com/org/project/issues)+- Ask in #dev-help Slack channel+- Reach out to @maintainer+```++### Developer Onboarding Checklist++```markdown+# New Developer Onboarding++## Day 1 - Environment Setup++- [ ] Clone repository+- [ ] Run setup script+- [ ] Verify development server starts+- [ ] Install IDE extensions+- [ ] Join Slack channels: #dev, #dev-help++## Day 1 - Access++- [ ] GitHub repository access+- [ ] Vercel team access+- [ ] Supabase project access+- [ ] 1Password vault access+- [ ] Figma access++## Week 1 - Understanding++- [ ] Read CONTRIBUTING.md+- [ ] Review project architecture+- [ ] Complete starter task+- [ ] Pair with team member++## Helpful Links++- [Project Documentation](./docs/)+- [Design System](https://figma.com/...)+- [API Documentation](./docs/api/)+```++## Cross-Platform Compatibility++### Platform Detection Script++```bash+# scripts/detect-platform.sh+#!/bin/bash++detect_os() {+ case "$(uname -s)" in+ Darwin)+ echo "macos"+ ;;+ Linux)+ echo "linux"+ ;;+ CYGWIN*|MINGW*|MSYS*)+ echo "windows"+ ;;+ *)+ echo "unknown"+ ;;+ esac+}++detect_arch() {+ case "$(uname -m)" in+ x86_64)+ echo "amd64"+ ;;+ arm64|aarch64)+ echo "arm64"+ ;;+ *)+ echo "unknown"+ ;;+ esac+}++OS=$(detect_os)+ARCH=$(detect_arch)++echo "Detected: $OS ($ARCH)"+```++### Windows PowerShell Setup++```powershell+# scripts/setup.ps1++Write-Host "Setting up development environment..." -ForegroundColor Green++# Check Node.js+if (-not (Get-Command node -ErrorAction SilentlyContinue)) {+ Write-Host "Node.js not found. Please install from https://nodejs.org/" -ForegroundColor Red+ exit 1+}++$nodeVersion = node -v+Write-Host "Node.js version: $nodeVersion" -ForegroundColor Cyan++# Copy environment file+if (-not (Test-Path .env)) {+ if (Test-Path .env.example) {+ Copy-Item .env.example .env+ Write-Host "Created .env from .env.example" -ForegroundColor Yellow+ }+}++# Install dependencies+Write-Host "Installing dependencies..." -ForegroundColor Green+npm ci++# Setup complete+Write-Host ""+Write-Host "Setup complete!" -ForegroundColor Green+Write-Host "Run 'npm run dev' to start development server" -ForegroundColor Cyan+```++## Environment Checklist++### Project Setup+- [ ] Setup script works on macOS, Linux, Windows+- [ ] Prerequisites documented with versions+- [ ] Environment variables documented+- [ ] IDE configuration committed+- [ ] Git hooks configured++### Developer Experience+- [ ] One command setup+- [ ] Clear error messages+- [ ] Onboarding documentation+- [ ] Helpful npm scripts+- [ ] Debug configurations++### Code Quality+- [ ] ESLint configured+- [ ] Prettier configured+- [ ] TypeScript strict mode+- [ ] Pre-commit hooks+- [ ] Editor integration++## When to Use This Skill++Invoke this skill when:+- Starting a new project+- Onboarding new developers+- Standardizing team environments+- Troubleshooting development setup issues+- Creating setup automation+- Configuring IDE settings+- Setting up cross-platform developmentdiff --git a/skills/escalation-handler/SKILL.md b/skills/escalation-handler/SKILL.mdnew file mode 100644index 0000000..c92011c--- /dev/null+++ b/skills/escalation-handler/SKILL.md@@ -0,0 +1,427 @@+---+name: Escalation Handler+slug: escalation-handler+description: Handle escalated support issues with structured triage, communication, and resolution processes+category: customer-support+complexity: complex+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "escalation"+ - "escalated ticket"+ - "customer escalation"+ - "support escalation"+ - "urgent issue"+ - "executive complaint"+tags:+ - escalation+ - support+ - crisis-management+ - customer-recovery+ - communication+---++# Escalation Handler++Expert escalation management system that transforms high-stakes support situations into opportunities for customer recovery and relationship strengthening. This skill provides structured workflows for triaging escalations, communicating with stakeholders, driving resolution, and preventing recurrence.++Escalations are defining moments in customer relationships. Handled poorly, they accelerate churn. Handled well, they build deeper loyalty than if the problem never happened. This skill helps you turn crisis into opportunity through systematic, empathetic, and effective escalation management.++Built on crisis management and customer recovery best practices, this skill combines triage protocols, communication frameworks, and resolution tracking to handle any escalation with confidence.++## Core Workflows++### Workflow 1: Escalation Triage+**Quickly assess severity and route appropriately**++1. **Severity Classification**+ | Level | Criteria | Response Time |+ |-------|----------|---------------|+ | SEV-1 | Production down, data loss, security breach | 15 minutes |+ | SEV-2 | Major feature broken, significant impact | 1 hour |+ | SEV-3 | Feature degraded, workaround exists | 4 hours |+ | SEV-4 | Minor issue, low impact | 24 hours |++2. **Impact Assessment**+ - Customer tier (Enterprise = higher priority)+ - Revenue at risk+ - Number of users affected+ - Business criticality to customer+ - Public exposure risk+ - Regulatory implications++3. **Escalation Type**+ - **Technical**: Product/service not working+ - **Service**: Support experience failure+ - **Business**: Commercial or relationship issue+ - **Security**: Data or access concerns+ - **Compliance**: Legal or regulatory++4. **Initial Triage Questions**+ - What exactly is happening?+ - When did it start?+ - Who is affected?+ - What's the business impact?+ - What has been tried?+ - Is there a workaround?++### Workflow 2: Stakeholder Communication+**Keep all parties informed throughout resolution**++1. **Internal Communication**+ - **Immediate**: Alert relevant teams (engineering, CSM, management)+ - **Ongoing**: Regular status updates (hourly for SEV-1/2)+ - **Resolution**: Post-incident summary+ - **Follow-up**: Root cause and prevention++2. **Customer Communication**+ - **Acknowledgment**: Within 15 minutes of escalation+ - **Update Cadence**: Per severity level+ - **Format**: Match customer preference (email, call, portal)+ - **Tone**: Empathetic, ownership, action-focused++3. **Update Frequency**+ | Severity | Update Frequency | Stakeholders |+ |----------|------------------|--------------|+ | SEV-1 | Every 30 minutes | Customer, Exec, All hands |+ | SEV-2 | Every 2 hours | Customer, Manager, CSM |+ | SEV-3 | Daily | Customer, CSM |+ | SEV-4 | On progress | Customer |++4. **Communication Principles**+ - Lead with what you know, not what you don't+ - Give specific next steps and timelines+ - Acknowledge impact and frustration+ - Avoid blame or excuses+ - Provide single point of contact++### Workflow 3: Resolution Management+**Drive systematic resolution**++1. **War Room Protocol** (SEV-1/2)+ - Designate incident commander+ - Assemble cross-functional team+ - Establish communication channel (Slack, Teams)+ - Set update cadence+ - Document all actions in real-time++2. **Resolution Tracking**+ ```+ Escalation Record:+ - ID: [Unique ID]+ - Customer: [Name]+ - Severity: [Level]+ - Start Time: [Timestamp]+ - Current Status: [Status]+ - Owner: [Name]+ - Next Action: [Action]+ - ETA: [Time]+ - Updates: [Log]+ ```++3. **Resolution Steps**+ - Confirm exact problem+ - Identify root cause (or best hypothesis)+ - Develop solution options+ - Implement fix (or workaround)+ - Verify resolution with customer+ - Confirm customer satisfaction+ - Document and close++4. **Workaround Protocol**+ - Always pursue workaround parallel to root fix+ - Communicate workaround clearly+ - Document workaround steps+ - Set expectations for permanent fix+ - Follow up when permanent fix available++### Workflow 4: Customer Recovery+**Rebuild relationship after resolution**++1. **Recovery Actions**+ | Impact Level | Recovery Actions |+ |--------------|------------------|+ | Minor | Apology + thank you |+ | Moderate | Apology + service credit |+ | Significant | Exec call + credit + roadmap |+ | Severe | In-person meeting + significant gesture |++2. **Recovery Conversation Structure**+ - Acknowledge what happened+ - Take responsibility (no excuses)+ - Explain what you've done to fix it+ - Explain what you're doing to prevent recurrence+ - Ask what else they need+ - Commit to follow-up++3. **Goodwill Gestures**+ - Service credits (1-3 months typical)+ - Premium support upgrade+ - Extended contract terms+ - Free training/consulting+ - Early access to new features+ - Executive relationship investment++4. **Relationship Rebuilding**+ - Increased check-in frequency+ - Proactive status updates+ - Invite to customer advisory board+ - Prioritize their feedback+ - Celebrate wins together++### Workflow 5: Post-Incident Review+**Learn and prevent recurrence**++1. **Root Cause Analysis**+ - What happened (factual timeline)+ - Why it happened (5 whys analysis)+ - Why we didn't prevent it+ - Why we didn't detect it earlier+ - What made resolution difficult++2. **Process Review**+ - Did triage work correctly?+ - Was communication effective?+ - Were the right people involved?+ - Did tools and processes help or hinder?+ - What would we do differently?++3. **Prevention Actions**+ - Technical fixes (monitoring, testing, architecture)+ - Process improvements (escalation path, playbooks)+ - Training needs (team skills, knowledge)+ - Documentation updates+ - Customer communication improvements++4. **Documentation**+ - Post-incident report+ - Knowledge base article+ - Playbook updates+ - Training materials+ - Customer-facing incident summary++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Triage escalation | "Triage escalation from [Customer]" |+| Create war room | "Set up war room for [Issue]" |+| Draft update | "Write customer update for [Issue]" |+| Escalation summary | "Summarize escalation [ID]" |+| Recovery plan | "Create recovery plan for [Customer]" |+| Root cause analysis | "Run RCA for [Incident]" |+| Draft apology | "Write apology for [Situation]" |+| Status report | "Create escalation status report" |+| Escalation metrics | "Show escalation metrics" |+| Prevention plan | "Create prevention plan for [Issue type]" |++## Best Practices++### Triage+- Act fast - speed demonstrates care+- Don't underestimate severity+- Involve senior resources early+- Assign clear ownership+- Document from minute one++### Communication+- Acknowledge before you diagnose+- Give timelines even if estimates+- Update even when no update+- Match customer's urgency level+- Use their preferred channel++### Resolution+- Workaround first, root cause second+- Test fixes before declaring resolved+- Confirm with customer directly+- Document everything+- Don't close until customer confirms++### Recovery+- Take ownership, not blame+- Gesture proportional to impact+- Follow through on commitments+- Increase touch points post-recovery+- Measure relationship health++### Prevention+- Every escalation teaches something+- Share learnings across team+- Update playbooks regularly+- Celebrate prevented escalations+- Track pattern recurrence++## Communication Templates++### Initial Acknowledgment+```+Subject: [URGENT] We're on it - [Brief Issue Description]++Hi [Name],++I'm [Your Name], [Your Role], and I'm personally handling your escalation.++I understand you're experiencing [brief issue description] and I know how disruptive this is to your business.++Here's where we are:+- We've engaged our [engineering/support] team+- We're actively investigating the root cause+- I'll update you within [timeframe]++Your dedicated contact for this issue: [Name, email, phone]++We won't rest until this is resolved.++[Your Name]+```++### Progress Update+```+Subject: Update on [Issue] - [Status]++Hi [Name],++Here's your [X-hour] update:++**Current Status**: [Where we are]++**What We've Done**:+- [Action 1]+- [Action 2]++**Next Steps**:+- [What we're doing now]+- [Expected outcome/timeline]++**Next Update**: [When]++Questions? Call me directly at [number].++[Your Name]+```++### Resolution Notification+```+Subject: Resolved - [Issue Description]++Hi [Name],++I'm pleased to confirm that [issue] has been fully resolved.++**What Happened**: [Brief explanation]++**What We Did**: [Resolution actions]++**Preventing Recurrence**: [What we're doing so this doesn't happen again]++I know this caused significant disruption to your team, and I'm truly sorry. I'd like to discuss how we can make this right - would you have 15 minutes this week?++Thank you for your patience throughout this.++[Your Name]+```++### Executive Apology+```+Subject: Personal Apology from [Executive Name]++[Name],++I'm [Executive Name], [Title] at [Company], and I wanted to reach out personally regarding the issues you've experienced.++First, I'm sorry. [Brief acknowledgment of specific impact] is not acceptable, and I take full responsibility.++I've reviewed the situation with our team, and here's what we're doing:+1. [Immediate fix]+2. [Process change]+3. [Prevention measure]++I'd welcome the opportunity to discuss this with you directly. Would you be open to a call this week?++Your success is our priority, and we're committed to earning back your trust.++Sincerely,+[Executive Name]+[Direct contact info]+```++## Escalation Metrics++| Metric | What It Measures | Target |+|--------|------------------|--------|+| First Response Time | Time to acknowledgment | Per severity SLA |+| Time to Resolution | End-to-end resolution time | Per severity SLA |+| Customer Satisfaction | Post-escalation CSAT | 4.0/5.0+ |+| Escalation Rate | Escalations / Total tickets | < 5% |+| Repeat Escalation | Same issue escalated again | < 10% |+| SLA Compliance | % resolved within SLA | 95%+ |+| Recovery Success | Relationship maintained | 90%+ |+| Prevention Implementation | RCA actions completed | 100% |++## Severity Level SLAs++| Severity | First Response | Update Frequency | Resolution Target |+|----------|----------------|------------------|-------------------|+| SEV-1 | 15 min | 30 min | 4 hours |+| SEV-2 | 1 hour | 2 hours | 8 hours |+| SEV-3 | 4 hours | Daily | 48 hours |+| SEV-4 | 24 hours | On change | 1 week |++## Red Flags++- **Delayed acknowledgment**: Customer waiting without response+- **Under-severity**: Classifying lower to avoid effort+- **Communication gaps**: Long silences during active escalation+- **Blame language**: Pointing fingers at customer or other teams+- **Premature closure**: Marking resolved before customer confirms+- **No follow-through**: Recovery promises not kept+- **Missing RCA**: Closing without understanding cause+- **Pattern blindness**: Same issues escalating repeatedly++## Post-Incident Report Template++```markdown+# Post-Incident Report: [Incident ID]++## Summary+- **Customer**: [Name]+- **Issue**: [Brief description]+- **Severity**: [Level]+- **Duration**: [Start to Resolution]+- **Impact**: [Customer impact description]++## Timeline+| Time | Event |+|------|-------|+| [Time] | Issue first reported |+| [Time] | Escalation triggered |+| [Time] | Root cause identified |+| [Time] | Resolution implemented |+| [Time] | Customer confirmed resolution |++## Root Cause+[Detailed explanation of why this happened]++## Resolution+[What was done to fix the issue]++## Customer Impact+- [Specific business impact]+- [Duration of impact]+- [Users/systems affected]++## Prevention Actions+| Action | Owner | Due Date | Status |+|--------|-------|----------|--------|+| [Action 1] | [Name] | [Date] | [Status] |++## Lessons Learned+- [What we learned]+- [What we'll do differently]++## Recovery Actions Taken+- [Apology delivered]+- [Goodwill gesture]+- [Follow-up scheduled]+```diff --git a/skills/faq-builder/SKILL.md b/skills/faq-builder/SKILL.mdnew file mode 100644index 0000000..e753a84--- /dev/null+++ b/skills/faq-builder/SKILL.md@@ -0,0 +1,301 @@+---+name: FAQ Builder+slug: faq-builder+description: Build comprehensive FAQ databases from support data, documentation, and user interactions+category: customer-support+complexity: moderate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "faq"+ - "frequently asked questions"+ - "common questions"+ - "question database"+ - "self-service answers"+ - "help content"+tags:+ - faq+ - self-service+ - knowledge-base+ - support-automation+ - customer-support+---++# FAQ Builder++Expert FAQ database creation system that transforms support tickets, documentation, and user interactions into comprehensive, searchable FAQ content. This skill provides structured workflows for identifying common questions, crafting clear answers, organizing content hierarchically, and maintaining FAQ freshness over time.++FAQs are the foundation of customer self-service. Well-built FAQ databases deflect support tickets, reduce customer frustration, and free up support teams for complex issues. This skill helps you build FAQs that actually get used and answer questions customers actually ask.++Built on best practices from support operations and content strategy, this skill combines data mining, content writing, and continuous improvement to create FAQs that scale with your product.++## Core Workflows++### Workflow 1: Question Discovery+**Mine support data to identify what customers actually ask**++1. **Support Ticket Analysis**+ - Export recent tickets (90 days recommended)+ - Categorize by topic/feature area+ - Identify recurring questions (3+ occurrences)+ - Note exact phrasing customers use+ - Track question frequency and trends++2. **Search Query Mining**+ - Analyze help center search queries+ - Identify zero-result searches (questions without answers)+ - Track most common search terms+ - Note failed search patterns+ - Map search queries to existing content gaps++3. **Customer Interaction Sources**+ - Live chat transcripts+ - Community forum posts+ - Social media mentions+ - Sales call objections+ - Onboarding call questions+ - NPS/CSAT survey comments++4. **Internal Knowledge Sources**+ - Support team tribal knowledge+ - Sales FAQ documents+ - Product documentation gaps+ - Engineering known issues+ - Feature release notes++### Workflow 2: FAQ Structure Design+**Organize questions into logical, navigable hierarchy**++1. **Category Architecture**+ - **Getting Started**: Account setup, first steps, basic concepts+ - **Features & Usage**: How to use specific functionality+ - **Billing & Payments**: Pricing, invoices, upgrades+ - **Account Management**: Settings, security, data+ - **Troubleshooting**: Common issues and fixes+ - **Integrations**: Third-party connections++2. **Question Hierarchy**+ - Top-level categories (5-8 maximum)+ - Subcategories (3-7 per category)+ - Individual questions (5-15 per subcategory)+ - Related questions linking++3. **Navigation Design**+ - Search functionality (primary)+ - Category browsing (secondary)+ - Popular questions section+ - Recently updated section+ - Contextual FAQs (in-app placement)++### Workflow 3: Answer Crafting+**Write clear, helpful answers that resolve questions**++1. **Answer Structure Template**+ ```+ [Direct Answer] - 1-2 sentences answering the question directly+ [Explanation] - Why/how, if needed for context+ [Steps] - Numbered steps if action required+ [Screenshot/Visual] - If helpful+ [Related Questions] - Links to related content+ [Still Need Help?] - Escalation path+ ```++2. **Writing Guidelines**+ - Lead with the answer (no preamble)+ - Use customer language, not internal jargon+ - Keep answers scannable (bullets, headers)+ - Include visuals for complex processes+ - Provide concrete examples+ - Link to detailed docs for deep dives++3. **Answer Quality Checklist**+ - [ ] Answers the question directly in first sentence+ - [ ] Uses language customers use+ - [ ] Includes necessary steps/actions+ - [ ] Has visual aid if process is complex+ - [ ] Links to related content+ - [ ] Provides escalation path+ - [ ] Tested by non-expert++### Workflow 4: FAQ Maintenance+**Keep content accurate and fresh**++1. **Update Triggers**+ - Product feature changes+ - UI/UX updates+ - Pricing changes+ - Policy updates+ - New common questions emerge+ - Answer quality issues flagged++2. **Review Cadence**+ - **Weekly**: Check for outdated screenshots/steps+ - **Monthly**: Review question frequency data+ - **Quarterly**: Full content audit+ - **On Release**: Update affected FAQs++3. **Quality Monitoring**+ - Track "Was this helpful?" feedback+ - Monitor escalation rates from FAQs+ - Analyze search-to-ticket correlation+ - Review support ticket references to FAQs++4. **Retirement Process**+ - Archive deprecated feature FAQs+ - Redirect old URLs+ - Update cross-references+ - Remove from search index++### Workflow 5: FAQ Analytics & Optimization+**Measure effectiveness and improve continuously**++1. **Key Metrics**+ - **Deflection Rate**: % of visitors who don't create tickets+ - **Search Success Rate**: % finding answers via search+ - **Helpful Ratings**: % marked as helpful+ - **Time on Page**: Engagement indicator+ - **Exit to Ticket**: FAQs that fail to resolve++2. **Optimization Actions**+ - Low helpful rating → Rewrite answer+ - High exit-to-ticket → Answer incomplete+ - Low views but high ticket volume → Discovery problem+ - Zero-result searches → Content gap+ - High search but low click → Title/description mismatch++3. **A/B Testing**+ - Test answer formats (video vs. text)+ - Test question phrasing+ - Test category organization+ - Test CTA placement++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Analyze tickets for FAQs | "Mine tickets for FAQ opportunities" |+| Generate FAQ from topic | "Create FAQ for [feature]" |+| Audit FAQ coverage | "Audit FAQ completeness" |+| Review FAQ metrics | "Show FAQ performance" |+| Find content gaps | "Identify FAQ gaps" |+| Rewrite poor FAQ | "Improve FAQ for [question]" |+| Structure FAQ hierarchy | "Design FAQ categories" |+| Check FAQ freshness | "Audit FAQ currency" |+| Generate FAQ from docs | "Convert docs to FAQ" |+| Merge duplicate FAQs | "Consolidate FAQ duplicates" |++## Best Practices++### Question Writing+- Use the exact words customers use+- Start with action verbs: "How do I...", "What is...", "Can I..."+- Be specific: "How do I reset my password?" not "Password help"+- Match search intent: question should match what users type+- Avoid internal terminology++### Answer Writing+- Answer in the first sentence - no lead-up+- Use second person ("you") not passive voice+- Break complex answers into numbered steps+- Include screenshots for UI-related answers+- Keep answers concise (target under 300 words)+- Link to detailed docs for comprehensive coverage++### Organization+- Limit top-level categories to 5-8+- Most popular questions should be 2 clicks maximum+- Cross-link related questions+- Use consistent naming conventions+- Enable robust search functionality++### Maintenance+- Assign ownership for each FAQ section+- Create alerts for product changes affecting FAQs+- Track "Was this helpful?" religiously+- Archive rather than delete old content+- Keep version history++### Integration+- Embed contextual FAQs in product UI+- Surface FAQs in chatbot/support flow+- Include in onboarding sequences+- Reference in support macros+- Add to knowledge base search++## FAQ Templates++### Simple Question Template+```markdown+## [Question in customer language]++[Direct answer in 1-2 sentences.]++[Additional context if needed.]++**Related questions:**+- [Related FAQ 1]+- [Related FAQ 2]++*Last updated: [Date]*+```++### Process Question Template+```markdown+## How do I [action]?++[Brief explanation of what this does.]++### Steps++1. [First step]+ ![Screenshot if helpful]+2. [Second step]+3. [Third step]++### Notes+- [Any important considerations]+- [Common gotchas]++**Need help?** [Contact support link]++*Last updated: [Date]*+```++### Troubleshooting Template+```markdown+## [Problem statement as customer would phrase it]++This usually happens when [common cause].++### Quick fixes++1. **Try this first**: [Most common solution]+2. **If that doesn't work**: [Second option]+3. **Still having issues**: [Third option]++### When to contact support+If none of the above work, [contact support] with:+- [Information to include]+- [Error messages/screenshots]++*Last updated: [Date]*+```++## Red Flags++- **High exit-to-ticket rate**: Answer isn't resolving the question+- **Low search success**: Content doesn't match search terms+- **Outdated screenshots**: Product has changed+- **Internal jargon**: Customers can't understand+- **No escalation path**: Dead ends frustrate users+- **Duplicate content**: Confuses and dilutes SEO+- **Orphaned FAQs**: No navigation path to content++## Integration Points++- **Support Ticketing**: Auto-suggest FAQs before ticket creation+- **Chatbot**: FAQ as first-line response source+- **In-App Help**: Contextual FAQ widgets+- **Search**: Unified search across FAQ and docs+- **Analytics**: Track deflection and engagement+- **CMS**: Structured content managementdiff --git a/skills/feedback-analyzer/SKILL.md b/skills/feedback-analyzer/SKILL.mdnew file mode 100644index 0000000..a0908ba--- /dev/null+++ b/skills/feedback-analyzer/SKILL.md@@ -0,0 +1,388 @@+---+name: Feedback Analyzer+slug: feedback-analyzer+description: Analyze customer feedback to extract actionable insights, identify patterns, and prioritize improvements+category: customer-support+complexity: complex+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "feedback analysis"+ - "customer feedback"+ - "sentiment analysis"+ - "voice of customer"+ - "feature requests"+ - "user feedback"+tags:+ - feedback+ - analytics+ - sentiment+ - voice-of-customer+ - customer-insights+---++# Feedback Analyzer++Expert customer feedback analysis system that transforms unstructured feedback into actionable product and service insights. This skill provides structured workflows for collecting, categorizing, analyzing, and acting on customer feedback from multiple sources.++Customer feedback is the most direct signal of what's working and what isn't. But raw feedback is noisy, contradictory, and overwhelming. This skill helps you extract patterns, prioritize themes, and close the feedback loop effectively.++Built on voice-of-customer best practices and qualitative research methods, this skill combines text analysis, pattern recognition, and stakeholder communication to turn feedback into action.++## Core Workflows++### Workflow 1: Feedback Collection & Aggregation+**Gather feedback from all sources into unified view**++1. **Feedback Sources**+ - **Direct Surveys**: NPS, CSAT, CES, custom surveys+ - **Support Channels**: Tickets, chat transcripts, calls+ - **In-App Feedback**: Feature requests, bug reports, ratings+ - **Social Media**: Mentions, reviews, comments+ - **Sales Conversations**: Objections, lost deal reasons+ - **User Research**: Interviews, usability tests+ - **Community**: Forums, Slack, Discord++2. **Data Standardization**+ | Field | Description |+ |-------|-------------|+ | Source | Where feedback came from |+ | Date | When received |+ | Customer ID | Link to customer record |+ | Segment | Customer type/tier |+ | Raw Text | Original feedback |+ | Category | Topic classification |+ | Sentiment | Positive/neutral/negative |+ | Priority | Urgency/impact level |++3. **Collection Automation**+ - API integrations with feedback tools+ - Automatic ticket tagging+ - Survey response routing+ - Social listening alerts+ - Scheduled data syncs++4. **Quality Filters**+ - Remove spam and duplicates+ - Flag potentially inaccurate data+ - Note context (e.g., during outage)+ - Weight by customer segment+ - Identify feedback loops (same issue, multiple channels)++### Workflow 2: Categorization & Tagging+**Organize feedback into meaningful categories**++1. **Category Taxonomy**+ - **Product Features**: Specific functionality feedback+ - **Usability/UX**: Interface and experience issues+ - **Performance**: Speed, reliability, bugs+ - **Pricing/Value**: Cost concerns and value perception+ - **Support Experience**: Service quality feedback+ - **Onboarding**: Getting started experience+ - **Documentation**: Help content feedback+ - **Integration**: Third-party connection issues++2. **Subcategory Examples**+ ```+ Product Features+ ├── Feature Requests+ │ ├── New feature ideas+ │ └── Feature enhancements+ ├── Missing Features+ │ ├── Competitor comparisons+ │ └── Workflow gaps+ └── Feature Feedback+ ├── What works well+ └── What doesn't work+ ```++3. **Tagging Best Practices**+ - Use consistent, specific tags+ - Allow multiple tags per feedback+ - Create tag hierarchy (parent/child)+ - Review and consolidate tags quarterly+ - Train team on tagging standards++4. **Automated Classification**+ - Keyword-based routing rules+ - ML-based topic classification+ - Sentiment detection+ - Priority scoring algorithms+ - Entity extraction (features, pages, actions)++### Workflow 3: Sentiment & Urgency Analysis+**Understand emotional context and priority**++1. **Sentiment Classification**+ | Sentiment | Indicators | Action Level |+ |-----------|------------|--------------|+ | Very Negative | Anger, threats to leave | Urgent escalation |+ | Negative | Frustration, complaints | Address in sprint |+ | Neutral | Suggestions, questions | Standard review |+ | Positive | Praise, appreciation | Share with team |+ | Very Positive | Advocacy, testimonial | Request case study |++2. **Urgency Scoring Factors**+ - Customer tier (enterprise = higher weight)+ - Revenue at risk+ - Frequency of same issue+ - Time sensitivity mentioned+ - Escalation history+ - Regulatory/compliance implications++3. **Trend Detection**+ - Volume spikes (sudden increase in topic)+ - Sentiment shifts (getting worse/better)+ - New issues emerging+ - Seasonal patterns+ - Release-correlated feedback++4. **Alert Triggers**+ - High-value customer escalation+ - Sentiment score below threshold+ - Issue volume exceeds normal+ - Churn-risk keywords detected+ - Security/privacy concerns++### Workflow 4: Pattern Recognition & Insights+**Extract actionable patterns from feedback mass**++1. **Quantitative Analysis**+ - Frequency by category+ - Trend over time+ - Segment distribution+ - Correlation with churn+ - Impact on NPS/CSAT++2. **Qualitative Analysis**+ - Representative quote extraction+ - Use case pattern identification+ - User journey mapping+ - Pain point articulation+ - Unmet need discovery++3. **Insight Synthesis**+ ```+ Insight Template:++ FINDING: [What the data shows]+ EVIDENCE: [Supporting data points and quotes]+ IMPACT: [Business/customer impact if unaddressed]+ RECOMMENDATION: [Suggested action]+ PRIORITY: [High/Medium/Low with rationale]+ ```++4. **Root Cause Analysis**+ - Group related feedback+ - Identify underlying causes+ - Map to user journey stages+ - Connect to product/process gaps+ - Distinguish symptoms from causes++### Workflow 5: Reporting & Action+**Communicate insights and drive improvements**++1. **Stakeholder Reports**+ | Audience | Focus | Frequency |+ |----------|-------|-----------|+ | Product | Feature requests, usability | Weekly |+ | Support | Training needs, process issues | Weekly |+ | Executive | Strategic themes, churn drivers | Monthly |+ | Engineering | Bugs, performance issues | Real-time |+ | Marketing | Positioning, messaging gaps | Monthly |++2. **Report Components**+ - Executive summary+ - Key metrics and trends+ - Top themes with supporting data+ - Representative customer quotes+ - Recommended actions+ - Open questions++3. **Feedback Loop Closure**+ - Track feedback → action connection+ - Communicate changes to customers+ - Measure impact of changes+ - Update customers on feature requests+ - Publish "You Asked, We Built" updates++4. **Action Prioritization**+ - Impact on retention/growth+ - Effort to address+ - Customer segment affected+ - Strategic alignment+ - Quick wins vs. long-term investments++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Import feedback | "Import feedback from [source]" |+| Categorize feedback | "Categorize feedback batch" |+| Analyze sentiment | "Run sentiment analysis on [data]" |+| Find patterns | "Identify patterns in feedback" |+| Generate report | "Create feedback report for [audience]" |+| Extract quotes | "Find quotes about [topic]" |+| Trend analysis | "Analyze feedback trends" |+| Segment analysis | "Compare feedback by segment" |+| Priority scoring | "Score feedback by priority" |+| Action tracking | "Track feedback to action" |++## Best Practices++### Collection+- Capture feedback at moments of truth+- Use consistent rating scales+- Include open-ended questions+- Don't over-survey (survey fatigue)+- Thank customers for feedback++### Categorization+- Create mutually exclusive categories+- Allow multi-tagging for complex feedback+- Review taxonomy quarterly+- Train team on consistent tagging+- Use automation for high-volume++### Analysis+- Look for patterns, not anecdotes+- Weight by customer segment value+- Consider feedback context+- Triangulate across sources+- Separate signal from noise++### Reporting+- Lead with insights, not data+- Use customer quotes strategically+- Connect to business impact+- Recommend specific actions+- Track what gets done++### Closing the Loop+- Communicate what you've heard+- Update on progress+- Thank specific contributors+- Measure impact of changes+- Celebrate wins publicly++## Analysis Frameworks++### Framework 1: Jobs-to-be-Done Lens+Analyze feedback through customer goals:+- What job is the customer trying to do?+- What's preventing success?+- What would "done" look like for them?+- How does our product help or hinder?++### Framework 2: Kano Model+Categorize feature feedback:+- **Basic**: Expected, causes dissatisfaction if missing+- **Performance**: More is better, linear satisfaction+- **Delighters**: Unexpected, causes delight if present+- **Indifferent**: No impact on satisfaction++### Framework 3: Impact/Effort Matrix+Prioritize actions:+```+High Impact+ │ Quick Wins │ Major Projects+ │ (Do Now) │ (Plan Carefully)+────┼─────────────────┼───────────────────+ │ Fill-ins │ Thankless Tasks+ │ (Do If Time) │ (Reconsider)+Low │ │ High+ └─────────────────┴───────────────────+ Effort+```++### Framework 4: Customer Journey Mapping+Map feedback to journey stages:+1. Awareness & Discovery+2. Evaluation & Decision+3. Onboarding & Activation+4. Regular Usage+5. Growth & Expansion+6. Support & Recovery+7. Renewal & Advocacy++## Report Templates++### Weekly Product Feedback Summary+```markdown+# Feedback Summary: [Week]++## Key Numbers+- Total feedback received: [X]+- Sentiment breakdown: [+/neutral/-]+- Top category: [Category] ([%])++## This Week's Themes++### Theme 1: [Title]+[Brief description of pattern]+- Volume: [X] mentions+- Segments affected: [List]+- Representative quote: "[Quote]"+- Recommendation: [Action]++### Theme 2: [Title]+[Same format]++## Emerging Issues+- [New issue to watch]++## Positive Highlights+- "[Positive quote]" - [Customer]++## Actions from Last Week+- [Action taken] → [Result]+```++### Monthly Executive Report+```markdown+# Voice of Customer: [Month]++## Executive Summary+[2-3 sentences on key findings and business impact]++## Metrics+| Metric | This Month | Last Month | Trend |+|--------|------------|------------|-------|+| NPS | [Score] | [Score] | [↑↓] |+| CSAT | [Score] | [Score] | [↑↓] |+| Feedback Volume | [X] | [X] | [↑↓] |++## Strategic Themes++### 1. [Theme Name]+**Impact**: [Business impact if unaddressed]+**Evidence**: [Data summary]+**Recommendation**: [Strategic action]++### 2. [Theme Name]+[Same format]++## Competitive Intelligence+[What customers are saying about competitors]++## Customer Quotes+[3-5 impactful quotes with context]++## Recommended Actions+1. [Priority action with owner]+2. [Priority action with owner]++## Appendix+[Detailed data tables]+```++## Red Flags++- **Echo chamber**: Only hearing from vocal minority+- **Recency bias**: Overweighting recent feedback+- **Volume bias**: Prioritizing loudest over important+- **Missing segments**: Not hearing from key customers+- **Action gap**: Collecting but not acting+- **No closure**: Customers don't know they were heard+- **Stale categories**: Taxonomy doesn't match current product+- **Sentiment-only**: Missing nuance in analysisdiff --git a/skills/fine-tuning-assistant/SKILL.md b/skills/fine-tuning-assistant/SKILL.mdnew file mode 100644index 0000000..5bc03c1--- /dev/null+++ b/skills/fine-tuning-assistant/SKILL.md@@ -0,0 +1,286 @@+---+name: Fine-Tuning Assistant+slug: fine-tuning-assistant+description: Guide model fine-tuning processes for customized AI performance+category: ai-ml+complexity: advanced+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "fine-tune model"+ - "fine-tuning"+ - "customize LLM"+ - "train custom model"+ - "adapt model"+tags:+ - fine-tuning+ - training+ - customization+ - LLM+ - machine-learning+---++# Fine-Tuning Assistant++The Fine-Tuning Assistant skill guides you through the process of adapting pre-trained models to your specific use case. Fine-tuning can dramatically improve model performance on specialized tasks, teach models your preferred style, and add capabilities that prompting alone cannot achieve.++This skill covers when to fine-tune versus prompt engineer, preparing training data, selecting base models, configuring training parameters, evaluating results, and deploying fine-tuned models. It applies modern techniques including LoRA, QLoRA, and instruction tuning to make fine-tuning practical and cost-effective.++Whether you are fine-tuning GPT models via API, running local training with open-source models, or using platforms like Hugging Face, this skill ensures you approach fine-tuning strategically and effectively.++## Core Workflows++### Workflow 1: Decide Whether to Fine-Tune+1. **Assess** the problem:+ - Can prompting achieve the goal?+ - Is the task format or style consistent?+ - Do you have quality training data?+ - Is this worth the investment?+2. **Compare** approaches:+ | Approach | When to Use | Investment |+ |----------|-------------|------------|+ | Better prompts | First attempt, variable tasks | Low |+ | Few-shot examples | Consistent format, limited data | Low |+ | RAG | Knowledge-intensive, dynamic data | Medium |+ | Fine-tuning | Consistent style, specialized task | High |+3. **Evaluate** requirements:+ - Minimum 100-1000 quality examples+ - Clear evaluation criteria+ - Budget for training and hosting+4. **Decision**: Fine-tune only if prompting/RAG insufficient++### Workflow 2: Prepare Fine-Tuning Dataset+1. **Collect** training examples:+ - Representative of target use case+ - High quality (no errors in outputs)+ - Diverse coverage of task variations+2. **Format** for training:+ ```jsonl+ {"messages": [+ {"role": "system", "content": "You are a helpful assistant..."},+ {"role": "user", "content": "User input here"},+ {"role": "assistant", "content": "Ideal response here"}+ ]}+ ```+3. **Quality assurance**:+ - Review sample of examples manually+ - Check for consistency in style/format+ - Remove duplicates and low-quality entries+4. **Split** train/validation/test sets+5. **Validate** dataset format++### Workflow 3: Execute Fine-Tuning+1. **Select** base model:+ - Consider size vs capability tradeoff+ - Match model to task complexity+ - Check licensing for your use case+2. **Configure** training:+ ```python+ # OpenAI fine-tuning+ training_config = {+ "model": "gpt-4o-mini-2024-07-18",+ "training_file": "file-xxx",+ "hyperparameters": {+ "n_epochs": 3,+ "batch_size": "auto",+ "learning_rate_multiplier": "auto"+ }+ }++ # LoRA fine-tuning (local)+ lora_config = {+ "r": 16, # Rank+ "lora_alpha": 32,+ "lora_dropout": 0.05,+ "target_modules": ["q_proj", "v_proj"]+ }+ ```+3. **Monitor** training:+ - Watch loss curves+ - Check for overfitting+ - Validate on held-out set+4. **Evaluate** results:+ - Compare to baseline model+ - Test on diverse inputs+ - Check for regressions++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Decide approach | "Should I fine-tune for [task]" |+| Prepare data | "Format data for fine-tuning" |+| Choose model | "Which model to fine-tune for [task]" |+| Configure training | "Fine-tuning parameters for [goal]" |+| Evaluate results | "Evaluate fine-tuned model" |+| Debug training | "Fine-tuning loss not decreasing" |++## Best Practices++- **Start with Prompting**: Fine-tuning is expensive; exhaust cheaper options first+ - Can better prompts achieve 80% of the goal?+ - Try few-shot examples in the prompt+ - Consider RAG for knowledge tasks++- **Quality Over Quantity**: 100 excellent examples beat 10,000 mediocre ones+ - Each example should be a gold standard+ - Better to have humans verify examples+ - Remove anything you wouldn't want the model to learn++- **Match Format to Use Case**: Training examples should mirror real usage+ - Same prompt structure as production+ - Realistic input variations+ - Cover edge cases explicitly++- **Don't Over-Train**: More epochs isn't always better+ - Watch validation loss for overfitting+ - Start with 1-3 epochs+ - Early stopping when validation plateaus++- **Evaluate Properly**: Training loss isn't the goal+ - Use held-out test set+ - Compare to baseline on same tests+ - Check for capability regressions+ - Test on edge cases explicitly++- **Version Everything**: Fine-tuning is iterative+ - Version your training data+ - Track experiment configurations+ - Document what worked and what didn't++## Advanced Techniques++### LoRA (Low-Rank Adaptation)+Efficient fine-tuning for large models:+```python+from peft import LoraConfig, get_peft_model++lora_config = LoraConfig(+ r=16, # Rank of update matrices+ lora_alpha=32, # Scaling factor+ target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],+ lora_dropout=0.05,+ bias="none",+ task_type="CAUSAL_LM"+)++# Apply LoRA to base model+model = get_peft_model(base_model, lora_config)++# Only ~0.1% of parameters are trainable+trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)+```++### QLoRA (Quantized LoRA)+Fine-tune large models on consumer hardware:+```python+from transformers import BitsAndBytesConfig++bnb_config = BitsAndBytesConfig(+ load_in_4bit=True,+ bnb_4bit_quant_type="nf4",+ bnb_4bit_compute_dtype=torch.bfloat16,+ bnb_4bit_use_double_quant=True+)++# Load model in 4-bit+model = AutoModelForCausalLM.from_pretrained(+ "meta-llama/Llama-2-7b-hf",+ quantization_config=bnb_config+)++# Apply LoRA on top+model = get_peft_model(model, lora_config)+```++### Instruction Tuning Dataset Creation+Convert raw data to instruction format:+```python+def create_instruction_example(raw_data):+ return {+ "messages": [+ {+ "role": "system",+ "content": "You are a customer service agent for TechCorp..."+ },+ {+ "role": "user",+ "content": f"Customer inquiry: {raw_data['inquiry']}"+ },+ {+ "role": "assistant",+ "content": raw_data['ideal_response']+ }+ ]+ }++# Apply to dataset+instruction_dataset = [create_instruction_example(d) for d in raw_dataset]+```++### Evaluation Framework+Comprehensive assessment of fine-tuned models:+```python+def evaluate_fine_tuned_model(model, test_set, baseline_model=None):+ results = {+ "task_accuracy": [],+ "format_compliance": [],+ "style_match": [],+ "regression_check": []+ }++ for example in test_set:+ output = model.generate(example.input)++ # Task-specific accuracy+ results["task_accuracy"].append(+ check_correctness(output, example.expected)+ )++ # Format compliance+ results["format_compliance"].append(+ matches_expected_format(output)+ )++ # Style matching (for style transfer tasks)+ results["style_match"].append(+ style_similarity(output, example.expected)+ )++ # Regression on general capabilities+ if baseline_model:+ results["regression_check"].append(+ compare_general_capability(model, baseline_model, example)+ )++ return {k: np.mean(v) for k, v in results.items()}+```++### Curriculum Learning+Order training data by difficulty:+```python+def create_curriculum(dataset):+ # Score examples by complexity+ scored = [(score_complexity(ex), ex) for ex in dataset]+ scored.sort(key=lambda x: x[0])++ # Create epochs with increasing difficulty+ n = len(scored)+ curriculum = {+ "epoch_1": [ex for _, ex in scored[:n//3]], # Easy+ "epoch_2": [ex for _, ex in scored[:2*n//3]], # Easy + Medium+ "epoch_3": [ex for _, ex in scored], # All+ }+ return curriculum+```++## Common Pitfalls to Avoid++- Fine-tuning when better prompting would suffice+- Using low-quality or inconsistent training examples+- Not holding out a proper test set+- Training for too many epochs (overfitting)+- Ignoring capability regressions from fine-tuning+- Not versioning training data and configurations+- Expecting fine-tuning to add factual knowledge (use RAG instead)+- Fine-tuning on data that doesn't match production usediff --git a/skills/git-workflow-designer/SKILL.md b/skills/git-workflow-designer/SKILL.mdnew file mode 100644index 0000000..c309f45--- /dev/null+++ b/skills/git-workflow-designer/SKILL.md@@ -0,0 +1,613 @@+---+name: git-workflow-designer+description: Expert guide for designing Git branching strategies including Git Flow, GitHub Flow, trunk-based development, and release management. Use when establishing team workflows or improving version control practices.+---++# Git Workflow Designer Skill++## Overview++This skill helps you design and implement effective Git branching strategies for teams of any size. Covers Git Flow, GitHub Flow, trunk-based development, release management, and branch protection policies.++## Workflow Selection Philosophy++### Key Factors+1. **Team size**: Solo vs. small team vs. large organization+2. **Release frequency**: Continuous vs. scheduled releases+3. **Environment complexity**: Single vs. multiple deployment targets+4. **Risk tolerance**: Move fast vs. stability first++### Workflow Comparison++| Workflow | Best For | Release Frequency | Complexity |+|----------|----------|-------------------|------------|+| Trunk-Based | Small teams, CI/CD | Continuous | Low |+| GitHub Flow | Most web apps | On-demand | Low |+| Git Flow | Versioned software | Scheduled | High |+| GitLab Flow | Environment-based | Mixed | Medium |++## GitHub Flow (Recommended for Most)++### Overview+Simple, effective workflow for continuous deployment.++```+main ─────●─────●─────●─────●─────●─────●+ \ / \ /+feature/x ●─────● ●─────●+```++### Process++1. **Branch from main**+ ```bash+ git checkout main+ git pull origin main+ git checkout -b feature/user-authentication+ ```++2. **Commit regularly**+ ```bash+ git add .+ git commit -m "feat: add login form component"+ ```++3. **Push and create PR**+ ```bash+ git push -u origin feature/user-authentication+ gh pr create --title "Add user authentication" --body "..."+ ```++4. **Review and merge**+ - CI runs tests+ - Peer review+ - Squash merge to main++5. **Deploy**+ - Automatic deploy on merge to main++### Branch Naming Convention++```+feature/ - New features+fix/ - Bug fixes+docs/ - Documentation+refactor/ - Code refactoring+test/ - Test additions+chore/ - Maintenance tasks+```++### Configuration++```yaml+# .github/branch-protection.yml (pseudo-config)+main:+ required_status_checks:+ strict: true+ contexts:+ - "ci/tests"+ - "ci/lint"+ - "ci/build"+ required_pull_request_reviews:+ required_approving_review_count: 1+ dismiss_stale_reviews: true+ enforce_admins: false+ restrictions: null+```++## Git Flow (For Versioned Releases)++### Overview+Structured workflow for scheduled release cycles.++```+main ─────●─────────────────●─────────────●+ \ / \+release ●─────●─────●─ ●───+ \ \ / /+develop ●─────●─●─────●─●─────●─────●─────●─●+ \ / \ / \ /+feature ●─● ●─────● ●─────●+```++### Branches++| Branch | Purpose | Merges To |+|--------|---------|-----------|+| `main` | Production-ready code | - |+| `develop` | Integration branch | `main` |+| `feature/*` | New features | `develop` |+| `release/*` | Release preparation | `main`, `develop` |+| `hotfix/*` | Emergency fixes | `main`, `develop` |++### Feature Development++```bash+# Start feature+git checkout develop+git pull origin develop+git checkout -b feature/new-dashboard++# Work on feature+git commit -m "feat: add dashboard layout"+git commit -m "feat: add dashboard charts"++# Complete feature+git checkout develop+git merge --no-ff feature/new-dashboard+git branch -d feature/new-dashboard+git push origin develop+```++### Release Process++```bash+# Start release+git checkout develop+git checkout -b release/1.2.0++# Bump version+npm version 1.2.0 --no-git-tag-version+git commit -am "chore: bump version to 1.2.0"++# Fix release issues+git commit -m "fix: correct typo in release notes"++# Complete release+git checkout main+git merge --no-ff release/1.2.0+git tag -a v1.2.0 -m "Release 1.2.0"+git push origin main --tags++git checkout develop+git merge --no-ff release/1.2.0+git push origin develop++git branch -d release/1.2.0+```++### Hotfix Process++```bash+# Start hotfix+git checkout main+git checkout -b hotfix/1.2.1++# Fix the issue+git commit -m "fix: critical security vulnerability"++# Complete hotfix+git checkout main+git merge --no-ff hotfix/1.2.1+git tag -a v1.2.1 -m "Hotfix 1.2.1"+git push origin main --tags++git checkout develop+git merge --no-ff hotfix/1.2.1+git push origin develop++git branch -d hotfix/1.2.1+```++## Trunk-Based Development++### Overview+Everyone commits to main with short-lived branches.++```+main ─●─●─●─●─●─●─●─●─●─●─●─●─●─●─●─●+ \─/ \─/ \─/+ PR PR PR+```++### Principles++1. **Short-lived branches** (< 1 day)+2. **Small, frequent commits**+3. **Feature flags for incomplete work**+4. **Comprehensive CI/CD**++### Feature Flags Integration++```typescript+// src/lib/features.ts+export const features = {+ newCheckout: process.env.FEATURE_NEW_CHECKOUT === 'true',+ darkMode: process.env.FEATURE_DARK_MODE === 'true',+};++// Usage+if (features.newCheckout) {+ return <NewCheckout />;+}+return <OldCheckout />;+```++### Branch Rules++```bash+# Quick feature (< 4 hours)+git checkout main+git pull+git checkout -b quick/fix-typo+# ... work ...+git push -u origin quick/fix-typo+gh pr create --title "Fix typo" --body ""+# Merge immediately after CI passes+```++## Release Management++### Semantic Versioning++```+MAJOR.MINOR.PATCH++1.0.0 - Initial release+1.1.0 - New feature (backwards compatible)+1.1.1 - Bug fix+2.0.0 - Breaking change+```++### Automated Version Bumping++```json+// package.json+{+ "scripts": {+ "release:patch": "npm version patch && git push --follow-tags",+ "release:minor": "npm version minor && git push --follow-tags",+ "release:major": "npm version major && git push --follow-tags"+ }+}+```++### Changelog Generation++```yaml+# .github/workflows/release.yml+name: Release++on:+ push:+ tags:+ - 'v*'++jobs:+ release:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0++ - name: Generate changelog+ id: changelog+ uses: metcalfc/changelog-generator@v4+ with:+ myToken: ${{ secrets.GITHUB_TOKEN }}++ - name: Create Release+ uses: actions/create-release@v1+ env:+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ with:+ tag_name: ${{ github.ref }}+ release_name: Release ${{ github.ref }}+ body: ${{ steps.changelog.outputs.changelog }}+```++### Conventional Commits++```bash+# Format+<type>(<scope>): <description>++[optional body]++[optional footer(s)]++# Types+feat: New feature+fix: Bug fix+docs: Documentation+style: Formatting, no code change+refactor: Refactoring+test: Tests+chore: Maintenance++# Examples+feat(auth): add password reset flow+fix(api): handle null user gracefully+docs: update README with new API endpoints+chore(deps): update dependencies+```++### Commitlint Configuration++```javascript+// commitlint.config.js+module.exports = {+ extends: ['@commitlint/config-conventional'],+ rules: {+ 'type-enum': [+ 2,+ 'always',+ [+ 'feat',+ 'fix',+ 'docs',+ 'style',+ 'refactor',+ 'test',+ 'chore',+ 'perf',+ 'ci',+ 'build',+ 'revert',+ ],+ ],+ 'subject-case': [2, 'always', 'lower-case'],+ 'header-max-length': [2, 'always', 72],+ },+};+```++## Branch Protection++### GitHub Branch Protection Rules++```yaml+# Recommended settings for main branch++Required status checks:+ - ci/test+ - ci/lint+ - ci/build+ - ci/typecheck++Required reviews: 1+Dismiss stale reviews: true+Require review from code owners: true++Require signed commits: false # Optional+Require linear history: true # Encourages squash/rebase++Include administrators: false # Allow admins to bypass++Restrict who can push:+ - Maintainers only+```++### CODEOWNERS++```+# .github/CODEOWNERS++# Default owners+* @team-lead++# Frontend+/src/components/ @frontend-team+/src/app/ @frontend-team++# Backend+/src/api/ @backend-team+/src/lib/db/ @backend-team++# Infrastructure+/.github/ @devops-team+/docker/ @devops-team++# Docs+/docs/ @tech-writer+*.md @tech-writer+```++## Merge Strategies++### Squash and Merge (Recommended)++```bash+# Clean history, one commit per feature+git merge --squash feature/branch+git commit -m "feat: complete feature description"+```++**Pros:**+- Clean main history+- Easy to revert features+- Commit message can be edited++**Cons:**+- Loses individual commit history++### Rebase and Merge++```bash+# Linear history, preserves commits+git rebase main feature/branch+git checkout main+git merge feature/branch+```++**Pros:**+- Linear history+- Preserves individual commits+- Bisect-friendly++**Cons:**+- Requires clean commits+- Force push may be needed++### Merge Commit++```bash+# Preserves full history with merge points+git merge --no-ff feature/branch+```++**Pros:**+- Complete history preserved+- Clear merge points+- No force push needed++**Cons:**+- Noisy history+- Harder to navigate++## Common Scenarios++### Sync Feature Branch with Main++```bash+# Option 1: Rebase (clean history)+git checkout feature/my-feature+git fetch origin+git rebase origin/main+git push --force-with-lease++# Option 2: Merge (safe, but noisy)+git checkout feature/my-feature+git merge origin/main+git push+```++### Undo Last Commit (Not Pushed)++```bash+# Keep changes staged+git reset --soft HEAD~1++# Keep changes unstaged+git reset HEAD~1++# Discard changes+git reset --hard HEAD~1+```++### Fix Commit Message++```bash+# Last commit only+git commit --amend -m "new message"++# Older commits (interactive rebase)+git rebase -i HEAD~3+# Change 'pick' to 'reword' for target commit+```++### Cherry-Pick Specific Commit++```bash+# Apply specific commit to current branch+git cherry-pick abc123++# Cherry-pick without committing+git cherry-pick --no-commit abc123+```++### Recover Deleted Branch++```bash+# Find the commit+git reflog++# Recreate branch+git checkout -b recovered-branch abc123+```++## Workflow Scripts++### Git Aliases++```bash+# ~/.gitconfig+[alias]+ # Status+ s = status -sb++ # Branching+ co = checkout+ cob = checkout -b+ br = branch -vv++ # Commits+ cm = commit -m+ ca = commit --amend --no-edit++ # Logging+ lg = log --oneline --graph --decorate -20+ lga = log --oneline --graph --decorate --all -20++ # Sync+ sync = !git fetch origin && git rebase origin/main++ # Cleanup+ cleanup = !git branch --merged | grep -v main | xargs git branch -d++ # Undo+ undo = reset --soft HEAD~1+```++### Feature Branch Script++```bash+#!/bin/bash+# scripts/feature.sh++set -e++BRANCH_TYPE=${1:-feature}+BRANCH_NAME=$2++if [ -z "$BRANCH_NAME" ]; then+ echo "Usage: ./scripts/feature.sh [type] <name>"+ echo "Types: feature, fix, docs, chore"+ exit 1+fi++FULL_BRANCH="$BRANCH_TYPE/$BRANCH_NAME"++echo "Creating branch: $FULL_BRANCH"++git checkout main+git pull origin main+git checkout -b "$FULL_BRANCH"++echo "Branch '$FULL_BRANCH' created and checked out"+echo "Run: git push -u origin $FULL_BRANCH"+```++## Workflow Checklist++### Before Selecting Workflow+- [ ] Understand team size and distribution+- [ ] Define release frequency+- [ ] Assess CI/CD maturity+- [ ] Consider deployment environments++### Implementation+- [ ] Document workflow in CONTRIBUTING.md+- [ ] Configure branch protection rules+- [ ] Set up CODEOWNERS+- [ ] Configure merge strategy+- [ ] Add commit message linting+- [ ] Create Git aliases/scripts++### Maintenance+- [ ] Regular branch cleanup+- [ ] Monitor merge queue+- [ ] Review and update protection rules+- [ ] Train new team members++## When to Use This Skill++Invoke this skill when:+- Starting a new project and choosing a workflow+- Scaling from solo to team development+- Improving release management+- Setting up branch protection rules+- Creating contribution guidelines+- Resolving Git workflow conflicts+- Implementing conventional commitsdiff --git a/skills/help-article-writer/SKILL.md b/skills/help-article-writer/SKILL.mdnew file mode 100644index 0000000..d253067--- /dev/null+++ b/skills/help-article-writer/SKILL.md@@ -0,0 +1,436 @@+---+name: Help Article Writer+slug: help-article-writer+description: Write clear, effective help center articles that reduce support tickets and empower users+category: customer-support+complexity: moderate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "help article"+ - "help center"+ - "documentation"+ - "knowledge base"+ - "support article"+ - "user guide"+tags:+ - help-center+ - documentation+ - technical-writing+ - knowledge-base+ - customer-support+---++# Help Article Writer++Expert help center content creation system that transforms complex product knowledge into clear, scannable, user-friendly documentation. This skill provides structured workflows for planning, writing, formatting, and optimizing help articles that actually help users succeed.++Help articles are the bridge between your product and user success. Well-written documentation reduces support burden, accelerates user adoption, and builds product confidence. This skill helps you create help content that users can find, understand, and act on.++Built on technical writing best practices and user experience principles, this skill combines content strategy, clear writing, and continuous optimization to create help centers that scale.++## Core Workflows++### Workflow 1: Content Planning+**Map what needs to be documented and prioritize**++1. **Content Audit**+ - Inventory existing help content+ - Identify gaps vs. product features+ - Flag outdated content needing updates+ - Map content to user journeys+ - Prioritize by support ticket volume++2. **User Journey Mapping**+ - Document key user flows+ - Identify decision points needing guidance+ - Note complexity spikes requiring documentation+ - Map onboarding to documentation needs+ - Align with feature adoption goals++3. **Content Hierarchy**+ - **Getting Started**: First-time user needs+ - **Core Features**: Main functionality guides+ - **Advanced Features**: Power user documentation+ - **Integrations**: Third-party connections+ - **Account & Billing**: Administrative needs+ - **Troubleshooting**: Problem resolution++4. **Priority Matrix**+ | Priority | Criteria |+ |----------|----------|+ | Critical | High ticket volume, core features, onboarding |+ | High | Moderate tickets, important features |+ | Medium | Low tickets, nice-to-have features |+ | Low | Edge cases, rarely used features |++### Workflow 2: Article Structure+**Design articles for scannability and comprehension**++1. **Standard Article Template**+ ```+ # [Clear, Action-Oriented Title]++ [One-sentence summary of what this article covers]++ ## Overview+ [Brief context - what, why, who needs this]++ ## Prerequisites+ [What users need before starting - optional]++ ## Steps / How It Works+ [Numbered steps or explanation]++ ## Examples+ [Concrete examples if helpful]++ ## Common Issues+ [Troubleshooting section if relevant]++ ## Related Articles+ [Links to related content]+ ```++2. **Article Types**+ - **Conceptual**: Explains what something is and why it matters+ - **Procedural**: Step-by-step how-to guides+ - **Reference**: Technical specifications, API docs+ - **Troubleshooting**: Problem-solution format+ - **Tutorial**: Learning-focused walkthroughs++3. **Formatting Standards**+ - H1 for title only+ - H2 for main sections+ - H3 for subsections+ - Numbered lists for sequential steps+ - Bullet lists for non-sequential items+ - Callouts for warnings, tips, notes++### Workflow 3: Writing Process+**Create clear, user-focused content**++1. **Pre-Writing**+ - Define the user and their goal+ - Identify the user's starting knowledge+ - Determine success criteria+ - Gather technical information+ - Test the process yourself++2. **Drafting**+ - Start with the user's goal, not the feature+ - Write in second person ("you")+ - Use active voice+ - Keep sentences under 25 words+ - One idea per paragraph+ - Lead with the action++3. **Editing Passes**+ - **Clarity pass**: Simplify jargon, shorten sentences+ - **Accuracy pass**: Verify all steps work+ - **Formatting pass**: Add headers, lists, callouts+ - **Link pass**: Add internal/external links+ - **Visual pass**: Add screenshots, diagrams++4. **Quality Checklist**+ - [ ] Title clearly states what user will accomplish+ - [ ] Overview provides context in 2-3 sentences+ - [ ] Steps are numbered and specific+ - [ ] Screenshots show current UI+ - [ ] No jargon without explanation+ - [ ] Includes troubleshooting for common issues+ - [ ] Links to related content+ - [ ] Tested by non-expert++### Workflow 4: Visual Content+**Enhance articles with effective imagery**++1. **Screenshot Guidelines**+ - Capture only relevant UI areas+ - Use consistent browser/device+ - Annotate with numbered callouts+ - Highlight clickable elements+ - Maintain consistent dimensions+ - Update when UI changes++2. **Diagram Guidelines**+ - Use for complex flows or architectures+ - Keep visual style consistent+ - Include legend if needed+ - Make text readable at small sizes+ - Provide alt text for accessibility++3. **Video Guidelines**+ - Keep under 3 minutes+ - Use for complex multi-step processes+ - Include captions+ - Provide text alternative+ - Host on reliable platform++4. **Visual Placement**+ - Screenshots after the step they illustrate+ - Diagrams at concept introduction+ - Videos as optional enhancement, not replacement++### Workflow 5: Optimization & Maintenance+**Keep content fresh and effective**++1. **SEO Optimization**+ - Include keywords in title and headers+ - Write descriptive meta descriptions+ - Use natural language (matches search queries)+ - Internal linking structure+ - Alt text for images++2. **Analytics Tracking**+ - Page views and unique visitors+ - Time on page+ - Bounce rate+ - Search terms leading to article+ - "Was this helpful?" feedback+ - Exit to support ticket rate++3. **Update Triggers**+ - Product UI changes+ - Feature updates or deprecations+ - User feedback indicating confusion+ - Support ticket patterns+ - Negative helpfulness ratings++4. **Review Cadence**+ - **On Release**: Update affected articles+ - **Monthly**: Review feedback and metrics+ - **Quarterly**: Comprehensive content audit+ - **Annually**: Full restructure if needed++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Plan help content | "Create help center content plan" |+| Write new article | "Write help article for [feature]" |+| Improve existing article | "Optimize help article for [topic]" |+| Create screenshot guide | "Generate screenshot guidelines" |+| Audit help content | "Audit help center coverage" |+| Simplify article | "Simplify article for [topic]" |+| Add troubleshooting | "Add troubleshooting to [article]" |+| Convert to video script | "Create video script from [article]" |+| Check article metrics | "Analyze help article performance" |+| Generate article series | "Create article series for [workflow]" |++## Best Practices++### Writing Style+- Write at 8th grade reading level+- Use familiar words over technical terms+- Define acronyms on first use+- One instruction per step+- Start steps with verbs+- Avoid "simple," "just," "easy"++### Structure+- Front-load the most important information+- Keep articles focused (one topic per article)+- Use parallel structure in lists+- Limit nesting to 2 levels+- Include jump links for long articles++### User Experience+- Make articles findable via search+- Provide multiple navigation paths+- Include breadcrumbs+- Link related content+- Enable feedback mechanism+- Offer escalation path to support++### Accessibility+- Alt text for all images+- Descriptive link text (not "click here")+- Sufficient color contrast+- Keyboard-navigable+- Screen reader compatible+- Captions for videos++### Maintenance+- Assign article ownership+- Create update alerts for product changes+- Track content freshness dates+- Archive rather than delete+- Version control important articles++## Article Templates++### Procedural Article+```markdown+# How to [Accomplish Specific Goal]++Learn how to [brief description of what user will accomplish].++## Overview++[2-3 sentences explaining what this feature/process does and why a user would want to do this]++## Before You Start++- [Prerequisite 1]+- [Prerequisite 2]++## Steps++### Step 1: [Action]++[Explanation of what to do]++![Screenshot with annotation]++### Step 2: [Action]++[Explanation of what to do]++### Step 3: [Action]++[Explanation of what to do]++## Verify It Worked++You'll know you're successful when [observable outcome].++## Troubleshooting++**Issue**: [Common problem]+**Solution**: [How to fix it]++## What's Next++- [Related action 1]+- [Related action 2]++---+*Last updated: [Date] | [Feedback link]*+```++### Conceptual Article+```markdown+# Understanding [Concept]++[One-sentence definition of the concept]++## What Is [Concept]?++[2-3 paragraphs explaining the concept in user terms]++## Why It Matters++[Explain the benefit to the user - what problem it solves]++## How It Works++[Explain the mechanism at appropriate technical level]++![Diagram if helpful]++## Key Terms++| Term | Definition |+|------|------------|+| [Term 1] | [Definition] |+| [Term 2] | [Definition] |++## Examples++### Example 1: [Scenario]+[Concrete example of concept in action]++### Example 2: [Scenario]+[Another example]++## Related Topics++- [Related concept 1]+- [Related concept 2]++---+*Last updated: [Date] | [Feedback link]*+```++### Troubleshooting Article+```markdown+# Fixing [Problem Description]++Having trouble with [problem]? Here's how to resolve it.++## Symptoms++You might see this issue if:+- [Symptom 1]+- [Symptom 2]+- [Symptom 3]++## Quick Fixes++Try these solutions in order:++### Solution 1: [Most Common Fix]++[Steps to try]++### Solution 2: [Second Most Common]++[Steps to try]++### Solution 3: [Less Common]++[Steps to try]++## Still Having Issues?++If none of the above worked:++1. [Gather this information]+2. [Contact support] with details++## Why This Happens++[Brief technical explanation for curious users - optional]++## Prevent It in the Future++[Tips to avoid this issue - if applicable]++---+*Last updated: [Date] | [Feedback link]*+```++## Red Flags++- **Wall of text**: No headers, bullets, or visual breaks+- **Passive voice**: "The button should be clicked" vs "Click the button"+- **Feature-centric**: Describes feature, not user goal+- **Outdated screenshots**: UI doesn't match current product+- **Missing context**: Assumes too much user knowledge+- **No escalation**: User stuck with no next step+- **Buried answer**: Key information hidden in prose++## Content Style Guide++### Voice and Tone+- Friendly but not casual+- Confident but not arrogant+- Helpful but not condescending+- Clear but not oversimplified++### Word Choices+| Use | Avoid |+|-----|-------|+| Choose | Select |+| Click | Hit, Press (for mouse) |+| Enter | Type in |+| Go to | Navigate to |+| Make sure | Ensure |+| Use | Utilize |++### Formatting+- **Bold** for UI elements users interact with+- `Code formatting` for user input, code, paths+- *Italics* sparingly for emphasis+- > Blockquotes for important calloutsdiff --git a/skills/hospitality-coordinator/SKILL.md b/skills/hospitality-coordinator/SKILL.mdnew file mode 100644index 0000000..ddbaaa3--- /dev/null+++ b/skills/hospitality-coordinator/SKILL.md@@ -0,0 +1,709 @@+---+name: Hospitality Coordinator+slug: hospitality-coordinator+description: Hotel and restaurant operations, guest services, event planning, and hospitality management excellence+category: domain+complexity: complex+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "hotel operations"+ - "guest services"+ - "restaurant management"+ - "event planning"+ - "hospitality standards"+ - "concierge services"+tags:+ - hospitality+ - hotel-management+ - restaurant+ - guest-services+ - event-planning+ - operations+---++# Hospitality Coordinator++Comprehensive hospitality management system designed for hotel managers, restaurant operators, event planners, concierge professionals, and hospitality staff delivering exceptional guest experiences. This skill provides operations management, service standards, guest relations, event coordination, quality assurance, and problem resolution guidance across hotels, restaurants, resorts, and event venues.++The Hospitality Coordinator excels at creating guest service protocols, managing operations efficiently, coordinating events seamlessly, training staff on service excellence, handling guest complaints with grace, optimizing revenue and occupancy, and maintaining hospitality standards. It's valuable for general managers, front office staff, food & beverage directors, event coordinators, and anyone in the guest-facing hospitality industry.++This skill covers both hotel operations (front desk, housekeeping, concierge, revenue management) and restaurant operations (service, kitchen coordination, reservations, dining experience), with emphasis on the service mindset and operational excellence that define world-class hospitality.++## Core Workflows++### Workflow 1: Guest Services Excellence++**Purpose:** Deliver personalized, anticipatory service that exceeds guest expectations and creates memorable experiences.++**Service Philosophy:**++**The Hospitality Mindset:**+- **Anticipate needs** - Address before guests ask+- **Personalize** - Use names, remember preferences, tailor experience+- **Solve, don't deflect** - Own problems, find solutions+- **Exceed expectations** - Do more than required+- **Recovery paradox** - Turn complaints into loyalty opportunities++**Service Standards Framework:**++**Step 1: Pre-Arrival**+- Review reservations and special requests+- Note VIP guests, repeat guests, special occasions+- Prepare room/table according to preferences+- Send pre-arrival communication (confirmation, check-in info, personalization)+- Alert relevant departments (housekeeping, F&B, maintenance)++**Hotel Pre-Arrival:**+- Room assignment based on preferences (high floor, quiet, view)+- Special amenities (champagne, flowers, upgrade if available)+- Note allergies, accessibility needs+- Pre-registration if express service offered++**Restaurant Pre-Arrival:**+- Table assignment (view, quiet corner, high-top)+- Special setup (birthday cake, dietary restrictions, wine decanting)+- VIP greeting prep+- Reservation timing and pacing plan++**Step 2: Arrival & First Impression**+- Warm, genuine greeting (eye contact, smile, welcoming tone)+- Use guest name (if known)+- Efficient check-in/seating (minimize wait)+- Clear communication (process, timing, amenities)+- First impression sets tone for entire stay/meal++**Hotel Arrival:**+- Valet greeting curbside (if applicable)+- Doorman assistance with luggage+- Front desk check-in (< 5 minutes ideal)+- Escort to room or clear directions+- Room orientation (thermostat, WiFi, amenities, emergency exits)++**Restaurant Arrival:**+- Host greeting within 30 seconds+- Coat check offered+- Escort to table (pull out chairs, present menus)+- Server greeting within 2 minutes+- Beverage order taken promptly++**Step 3: During Stay/Experience**+- Consistent, attentive service (not intrusive)+- Anticipate needs (extra towels, water refills, check adjustments)+- Maintain cleanliness and standards+- Check in periodically ("How is everything?")+- Handle requests promptly and graciously++**Hotel Service Touchpoints:**+- Daily housekeeping (if opted in)+- Concierge assistance (reservations, recommendations, tickets)+- In-room dining (if applicable)+- Amenity refreshes (toiletries, linens, coffee)+- Maintenance response (immediate for urgent issues)++**Restaurant Service Standards:**+- **2-minute rule:** Greeting within 2 minutes of seating+- **Beverage service:** Drinks delivered < 5 minutes+- **Order timing:** Appetizers ~10 min, entrees ~15-20 min after appetizers clear+- **Table checks:** Every 5-7 minutes (without hovering)+- **Water/bread:** Refilled proactively++**Step 4: Departure**+- Smooth, efficient checkout/payment+- Thank guest by name+- Invite feedback+- Invite return visit+- Follow up (survey, thank you note for VIPs)++**Hotel Checkout:**+- Express checkout available (email receipt, no stop required)+- Accurate billing (review charges, explain any questions)+- Luggage assistance+- Transportation arranged if needed+- "We hope to see you again"++**Restaurant Departure:**+- Timely check presentation (when guest indicates ready, not rushed)+- Payment processing (< 5 minutes)+- Coat retrieval+- Thank guest personally (manager table touch ideal)+- Invitation to return++**Step 5: Post-Departure**+- Send feedback survey (within 24 hours)+- Review and respond to online reviews+- Note preferences for future visits+- Follow up on unresolved issues+- Thank you note for VIPs or special occasions++**Personalization Techniques:**++**Remember & Record:**+- Guest name and use it naturally+- Special occasions (anniversary, birthday)+- Preferences (room type, pillow, dietary, wine)+- Previous complaints or issues (don't repeat)+- Conversation topics (returning from trip, celebrating promotion)++**Anticipate:**+- Extra towels for families+- Quiet table for business meetings+- Champagne for anniversaries (if noted in reservation)+- Allergy-safe meal prep+- Early checkout arrangements for early flights++**Personalize:**+- Handwritten welcome note+- Favorite beverage upon arrival+- Customized recommendations based on interests+- Surprise and delight (upgrade, amenity, dessert)++**Service Recovery:**++**When Things Go Wrong (they will):**+1. **Acknowledge** - "I'm so sorry this happened"+2. **Apologize** - Genuine, without excuses+3. **Act** - Fix it immediately (or explain timing)+4. **Compensate** - Appropriate to issue (discount, comp, upgrade, amenity)+5. **Follow up** - Ensure resolution satisfactory++**Recovery Formula:**+- Minor issue (slow service, small error): Apology + small comp (dessert, drink)+- Moderate issue (wrong order, room not ready): Apology + meaningful comp (discount, upgrade)+- Major issue (unsafe condition, significant failure): Apology + substantial comp + manager involvement + follow-up++**Deliverables:**+- Service standards manual+- Guest interaction scripts (greeting, handling requests, recovery)+- Personalization checklist+- Service recovery guidelines+- VIP guest protocols++### Workflow 2: Hotel Operations Management++**Purpose:** Ensure smooth, efficient hotel operations across all departments delivering consistent guest satisfaction.++**Front Office Operations:**++**Reservations:**+- Manage booking channels (direct, OTA, GDS, phone)+- Optimize rate strategy (see Revenue Management below)+- Process special requests+- Confirm reservations and send pre-arrival communication+- Manage cancellations and modifications+- Overbooking strategy (risky but common - know your walk policy)++**Front Desk:**+- Check-in process (verify ID, payment method, explain amenities)+- Key issuance and room assignment+- Upselling (suite upgrades, late checkout, amenities)+- Concierge services (recommendations, reservations, tickets)+- Guest requests and issue resolution+- Check-out process (review charges, solicit feedback)++**Night Audit:**+- Close day's transactions+- Post room and tax charges+- Run system reports (occupancy, revenue, outstanding balances)+- Prepare management reports+- Reconcile credit card batches+- Rollover to next business day++**Housekeeping:**++**Room Cleaning Standards:**+- Departure cleaning (full clean, inspect, restock)+- Stay-over cleaning (tidy, refresh, restock as needed)+- Timing: 20-30 minutes per room (varies by hotel class and room size)+- Inspections: Supervisor spot-check before guest arrival++**Housekeeping Checklist (per room):**+- [ ] Bed making (hospital corners, crisp linens, decorative pillows)+- [ ] Bathroom cleaning (toilet, sink, shower/tub, mirrors, floor)+- [ ] Dusting (all surfaces, furniture, fixtures)+- [ ] Vacuuming (floor, under furniture)+- [ ] Trash removal and liner replacement+- [ ] Amenity restocking (toiletries, coffee, tissues)+- [ ] Towel replacement (per hotel policy - daily or opt-in)+- [ ] Minibar restocking (if applicable)+- [ ] Temperature and lighting check+- [ ] Final inspection (anything out of place?)++**Public Areas:**+- Lobby (continuous cleaning, high-touch surfaces hourly)+- Restrooms (check and clean every 2 hours minimum)+- Elevators (daily deep clean, spot clean as needed)+- Meeting rooms (between events and daily)+- Fitness center (daily and spot clean)+- Pool area (continuous monitoring, safety checks)++**Maintenance:**+- Preventive maintenance schedules (HVAC, plumbing, electrical, equipment)+- Guest room maintenance (respond < 30 min for urgent, same-day for routine)+- Work order system (track, prioritize, complete)+- Safety inspections (fire systems, elevators, emergency equipment)+- Grounds and exterior maintenance++**Laundry:**+- Linens (sheets, towels, robes)+- F&B linens (tablecloths, napkins)+- Guest laundry service (if offered)+- Quality control (stains removed, proper folding, no damage)++**Concierge:**+- Local knowledge (restaurants, attractions, events, transportation)+- Reservations (restaurants, shows, tours, spa)+- Transportation arrangements (taxi, car service, rental)+- Tickets and special access+- Personalized recommendations+- VIP services and special requests++**Revenue Management:**++**Yield Management Principles:**+- Sell the right room to the right guest at the right price at the right time+- Higher rates during high demand (events, holidays, weekends)+- Lower rates during low demand (fill rooms, generate F&B/ancillary revenue)+- Restrictions (minimum stay, cancellation policy) to protect high-demand periods++**Key Metrics:**+- **Occupancy Rate:** Rooms sold / Rooms available × 100+ - Target: 65-75% average (varies by market and season)+- **Average Daily Rate (ADR):** Room revenue / Rooms sold+ - Higher ADR = more revenue per room+- **Revenue Per Available Room (RevPAR):** Room revenue / Rooms available+ - RevPAR = Occupancy × ADR+ - Key metric balancing occupancy and rate++**Pricing Strategy:**+- **Dynamic pricing:** Adjust rates based on demand, booking pace, competition+- **Length of stay pricing:** Discounts for longer stays+- **Advance purchase rates:** Lower rates for early booking (non-refundable)+- **Package rates:** Include F&B, parking, amenities for bundled value+- **Group rates:** Volume discounts for groups/events++**Distribution Channels:**+- **Direct (best margin):** Hotel website, phone, email+- **OTA (Online Travel Agency):** Expedia, Booking.com (15-25% commission)+- **GDS (Global Distribution System):** Corporate travel bookings+- **Wholesalers:** Bulk room purchases, resell to agents+- **Group sales:** Corporate, conference, wedding blocks++**Deliverables:**+- Front office procedures manual+- Housekeeping standards and checklists+- Maintenance checklist and work order system+- Concierge resource guide (local recommendations)+- Revenue management dashboard (occupancy, ADR, RevPAR trends)++### Workflow 3: Restaurant Operations & Service++**Purpose:** Deliver exceptional dining experiences through flawless service, quality food, and memorable ambiance.++**Service Styles:**++**Fine Dining:**+- Formal, attentive service+- Multiple courses, paced carefully+- Extensive wine and food knowledge required+- Table maintenance (crumb clearing, bread/water refilling)+- Silent service (unobtrusive, anticipatory)+- Check presented discreetly, never rushed++**Casual Dining:**+- Friendly, efficient service+- Less formal but still professional+- Menu knowledge and recommendations+- Efficient table turns without rushing+- Family-friendly and accommodating++**Quick Service / Fast Casual:**+- Order at counter or kiosk+- Quick preparation and pickup+- Self-service beverages and condiments+- Clear signage and process+- Speed and accuracy prioritized++**Service Sequence (Fine/Casual Dining):**++**1. Greeting & Seating (within 30 seconds of arrival)**+- Warm welcome+- Check reservation, note special occasions+- Escort to table, pull out chairs+- Present menus, note specials++**2. Beverage Order (within 2 minutes of seating)**+- Offer water (still or sparkling)+- Beverage recommendations+- Take drink order+- Deliver within 5 minutes++**3. Order Taking (after beverages delivered)**+- Allow time to review menu (don't rush)+- Answer questions, make recommendations+- Note dietary restrictions and allergies (critical!)+- Suggest appetizers, sides+- Repeat order to confirm accuracy+- Input to POS clearly (modifications, allergies)++**4. Food Service**+- **Timing:**+ - Appetizers: 8-12 minutes after order+ - Entrees: 15-20 minutes after appetizers cleared (or 20-30 min if no appetizer)+ - Desserts: 10-15 minutes after entrees cleared+- **Presentation:**+ - Proper plating and garnish+ - Correct temperature (hot food hot, cold food cold)+ - Serve from left, clear from right (traditional)+ - Announce dishes as served+- **Check-in:** Within 2 minutes of food delivery ("How is everything?")++**5. Table Maintenance**+- Water and bread refilled proactively+- Clear finished courses promptly+- Reset table (crumb clearing, replace silverware)+- Anticipate needs (condiments, extra napkins)++**6. Dessert & After-Dinner**+- Offer dessert menu and coffee+- Present check when guest indicates ready (fold placed on table, verbal cue)+- Never rush departure++**7. Payment & Farewell**+- Process payment promptly (< 5 minutes)+- Thank guest by name if possible+- Invite return visit+- Coat and door assistance++**Kitchen Coordination:**++**Communication Systems:**+- POS system (orders to kitchen electronically)+- Tickets (printed in kitchen stations)+- Expo station (final check before service)+- Runner system (dedicated food runners vs. servers)++**Timing & Flow:**+- **Fire times:** When to start cooking each course (coordinated for table)+- **Par times:** Target time from order to delivery+- **In the weeds:** When kitchen or service falls behind (all hands on deck)++**Quality Control:**+- Expo checks every plate (presentation, temperature, completeness)+- Server verifies order before delivery+- Manager table touches (especially VIPs and large parties)++**Food Safety:**+- Temperature control (hot hold >135°F, cold hold <41°F)+- Allergen protocols (separate prep, clear labeling)+- Hand washing and glove use+- Shelf life and FIFO (first in, first out)++**Bar Operations:**++**Speed & Quality:**+- Well-stocked and organized bar+- Par levels for popular items+- Standardized recipes (consistency)+- Quick service (4-6 drinks per minute for skilled bartender)++**Responsible Service:**+- Check ID (anyone appearing <30 years old)+- Monitor consumption (cut off if intoxicated)+- Offer food, water, coffee+- Arrange safe transportation if needed+- State dram shop laws (liability for over-serving)++**Reservations & Seating:**++**Reservation System:**+- Manage bookings (OpenTable, Resy, or in-house system)+- Table assignment strategy (balance server sections)+- Note special requests and occasions+- Confirmation and reminders+- Waitlist management for walk-ins++**Table Management:**+- **Covers:** Number of guests per seating period+- **Turn time:** Average dining duration (plan 60-90 min casual, 90-120 fine dining)+- **Seating pace:** Don't seat entire restaurant at once (stagger to avoid kitchen/service crush)+- **Table status:** Track in real-time (seated, ordered, served, check, cleared)++**Deliverables:**+- Service standards manual (sequence, timing, expectations)+- Menu training materials (ingredients, preparation, allergens)+- Kitchen communication protocols+- Reservation and seating procedures+- Food safety and sanitation checklist++### Workflow 4: Event Planning & Coordination++**Purpose:** Execute flawless events that exceed client expectations through meticulous planning and seamless coordination.++**Event Planning Process:**++**Step 1: Inquiry & Needs Assessment**+- Event type (wedding, corporate, conference, social)+- Date and time+- Guest count (estimate and minimum/maximum)+- Budget+- Vision and priorities (formal/casual, specific theme, key elements)+- Special requirements (AV, catering, accommodations, accessibility)++**Step 2: Proposal & Contract**+- Venue options (room capacity, layout, ambiance)+- Menu options (plated, buffet, stations, dietary accommodations)+- Beverage options (hosted bar, cash bar, limited bar)+- AV and equipment (projector, screen, microphones, lighting)+- Rental needs (linens, chairs, decor)+- Staffing (servers, bartenders, event coordinator)+- Timeline and schedule+- Pricing (itemized, total, deposit and payment schedule)+- Cancellation and modification policies+- Contract signature and deposit++**Step 3: Detailed Planning**+- **Floor plan:** Table layout, dance floor, bar, buffet, AV+- **Menu finalization:** Specific dishes, service style, timing+- **Beverage plan:** Bar setup, wine pairings, signature cocktails+- **Timeline:** Hour-by-hour schedule (setup, guest arrival, program elements, teardown)+- **AV/tech:** Equipment list, setup diagram, testing schedule+- **Decor:** Theme, colors, centerpieces, signage+- **Staffing plan:** Roles, responsibilities, schedule++**Step 4: Pre-Event Coordination**+- **BEO (Banquet Event Order):** Comprehensive event document detailing everything+ - Client info and contact+ - Event details (date, time, location, guest count)+ - Room setup and floor plan+ - Menu and service details+ - Beverage plan+ - AV and equipment+ - Rental items+ - Timeline+ - Special requests and notes+ - Distribute to all departments+- **Site visit:** Client walkthrough, final adjustments+- **Vendor coordination:** Florist, DJ, photographer, etc. (timing, load-in, requirements)+- **Final counts:** Confirm guest numbers (usually 5-7 days before)+- **Pre-event meeting:** Staff briefing (roles, timing, special requests)++**Step 5: Event Execution**+- **Setup:** 2-4 hours before event (room, tables, chairs, linens, place settings, AV, decor)+- **Final inspection:** Event manager walkthrough (everything perfect?)+- **Guest arrival:** Greeting, coat check, escort to event space+- **Service:** Execute per timeline (cocktail hour, dinner service, program elements)+- **Coordination:** Event manager orchestrates (cues for speeches, cake cutting, etc.)+- **Breakdown:** Begin after guests depart, complete within 1-2 hours++**Step 6: Post-Event Follow-Up**+- **Immediate:** Debrief with client (how did it go?)+- **Final billing:** Reconcile actual vs. estimated (guest count, bar consumption)+- **Follow-up:** Thank you note, request testimonial/referral+- **Internal debrief:** What went well? What to improve?++**Event Logistics:**++**Room Setup Styles:**+- **Theater:** Rows of chairs facing front (max capacity, no tables)+- **Classroom:** Rows of tables and chairs facing front (note-taking, workshops)+- **Banquet rounds:** Round tables (8-10 guests each) for dining and conversation+- **U-shape:** Tables in U formation (small meetings, training)+- **Boardroom:** Single long table (executive meetings)+- **Reception:** Cocktail tables and lounge furniture (standing, mingling)+- **Hollow square:** Tables in square with open middle (discussions, negotiations)++**Catering Styles:**+- **Plated service:** Seated dinner, served to each guest (most formal, labor-intensive)+- **Buffet:** Self-service line (casual, efficient, variety)+- **Food stations:** Multiple themed stations (interactive, flow)+- **Family style:** Platters served to table, guests serve themselves (warm, sharing)+- **Passed hors d'oeuvres:** Servers circulate with trays (cocktail receptions)+- **Action stations:** Live cooking (omelette bar, carving station, pasta station)++**Beverage Service:**+- **Hosted bar:** Client pays for all drinks (open bar)+- **Cash bar:** Guests pay for own drinks+- **Limited bar:** Specific selections only (beer, wine, signature cocktails)+- **Consumption bar:** Client pays for actual consumption+- **Per-person package:** Flat rate per guest for unlimited drinks++**Timing Guidelines:**++**Cocktail Reception:** 60-90 minutes+- **Staffing:** 1 bartender per 50-75 guests, 1 server per 25 guests (passed apps)++**Seated Dinner:** 90-120 minutes+- **Plated service:** 60-90 min dining, 30+ min program/dancing+- **Buffet:** 75-90 min dining, 30+ min program/dancing+- **Staffing:** 1 server per 20 guests (plated), 1 per 30-40 (buffet)++**Full Event (Wedding Reception):** 4-5 hours+- Cocktail hour: 60 min+- Dinner: 90 min+- Dancing/program: 2-3 hours++**Deliverables:**+- Event proposal and contract template+- BEO (Banquet Event Order) template+- Floor plan and setup diagrams+- Event timeline template+- Staffing plan and assignments+- Event checklist (pre-event, day-of, post-event)++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Service standards | "Hotel/restaurant service procedures" |+| Guest complaint | "How to handle [complaint scenario]" |+| Room setup | "Housekeeping checklist for [room type]" |+| Revenue management | "Optimize hotel pricing for [scenario]" |+| Restaurant timing | "Service timing for [meal type]" |+| Event planning | "Plan [event type] for [guest count]" |+| BEO creation | "Create banquet event order for [event]" |+| Service recovery | "Comp policy for [service failure]" |+| Concierge | "Recommend [restaurants/activities] in [city]" |+| Menu training | "Explain [dish] to servers" |++## Best Practices++### Service Excellence+- **Genuine warmth** - Smile, eye contact, authentic friendliness (guests feel insincerity)+- **Use names** - Guests love hearing their name (use appropriately, not excessively)+- **Anticipate** - Think ahead; meet needs before asked+- **Own problems** - Don't pass buck; solve or escalate, but own it+- **Empower staff** - Give authority to make guests happy (within limits)++### Operations Efficiency+- **Checklists prevent errors** - Memory fails; checklists don't+- **Inspect what you expect** - Standards slip without oversight+- **Cross-train staff** - Flexibility and coverage for absences+- **Maintain equipment** - Preventive maintenance cheaper than emergency repairs+- **Manage inventory** - Par levels prevent stockouts and waste++### Guest Relations+- **First impression is critical** - Arrival experience sets tone+- **Recovery well** - Mistakes happen; how you fix them defines you+- **Solicit feedback** - Ask how things are going; don't wait for complaints+- **Act on feedback** - Listening without acting breeds cynicism+- **Consistency matters** - Guests expect same quality every time++### Event Execution+- **Document everything** - BEO is bible; refer to it constantly+- **Communicate clearly** - All departments know their role and timing+- **Walk through setup** - Final inspection catches errors before guests arrive+- **Have backup plans** - Technology fails, vendors cancel, weather changes+- **Stay calm** - Your energy affects staff and guests; confidence is contagious++### Revenue Optimization+- **Dynamic pricing** - Adjust rates based on demand, not calendar alone+- **Upsell naturally** - Offer upgrades and add-ons that genuinely enhance experience+- **Minimize discounting** - Add value (package amenities) rather than cut price+- **Ancillary revenue** - Parking, F&B, spa, tours add up+- **Repeat business** - Loyalty programs and excellent service drive return visits++## Key Metrics & Benchmarks++### Hotel Metrics+- **Occupancy:** 65-75% (varies by market)+- **ADR (Average Daily Rate):** Depends on hotel class and market+- **RevPAR (Revenue Per Available Room):** Occupancy × ADR+- **Guest Satisfaction Score:** 4.0+ / 5.0 (survey results)+- **Online Review Rating:** 4.0+ / 5.0 (TripAdvisor, Google, Booking.com)++### Restaurant Metrics+- **Table Turn Time:** 60-90 min casual, 90-120 fine dining+- **Check Average:** Total sales / Number of covers+- **Food Cost %:** Food cost / Food sales (target 28-35%)+- **Labor Cost %:** Labor cost / Total sales (target 30-35%)+- **Prime Cost:** Food + Labor (target <65% of sales)++### Event Metrics+- **Booking Lead Time:** Average days from inquiry to event date+- **Conversion Rate:** Bookings / Inquiries+- **Average Event Revenue:** Total event revenue / Number of events+- **Repeat Client Rate:** % of clients booking multiple events+- **Referral Rate:** % of new clients from referrals++## Common Service Failures & Recovery++| Issue | Recovery |+|-------|----------|+| Room not ready at check-in | Apology, complimentary drink/appetizer at bar while waiting, room upgrade if available |+| Reservation lost | Sincere apology, best available seating immediately, comp appetizers or dessert |+| Cold food | Apologize, remake immediately (< 10 min), comp dish or dessert |+| Noise complaint | Move to different room immediately, comp night or upgrade if no quiet room available |+| Wrong order | Apologize, correct immediately, don't charge for wrong dish, offer dessert |+| Billing error | Apologize, correct immediately, no excuses or blame |+| Long wait for table (with reservation) | Apologize, offer drinks at bar (comp or discount), prioritize seating, comp appetizer |++**Key Principle:** Recovery should match or exceed value of failure. Minor issues = small gestures. Major issues = substantial compensation + manager involvement.++## Confidence Signaling++**High Confidence Areas:**+- General hospitality service principles and standards+- Hotel front office and housekeeping operations+- Restaurant service sequence and timing+- Event planning and coordination frameworks+- Guest service recovery strategies+- Common hospitality metrics and benchmarks++**Medium Confidence Areas:**+- Specific hotel brand standards and requirements+- Complex revenue management and pricing algorithms+- Advanced culinary techniques and menu development+- Large-scale conference and convention management+- International hospitality customs and expectations+- Luxury and ultra-high-end service protocols++**Requires Specialist Expertise:**+- Wine sommelier expertise and pairings+- Executive chef-level culinary knowledge+- Hotel/restaurant legal and insurance compliance+- Labor law and union regulations+- Health department regulations (vary by jurisdiction)+- Liquor licensing and dram shop liability+- ADA compliance and accessibility requirements+- Hotel property management system (PMS) technical support++**Always Verify:**+- Local health and safety codes+- Liquor laws and responsible beverage service+- Labor laws and tip pooling regulations+- Fire codes and occupancy limits+- Accessibility requirements (ADA, state laws)+- Specific brand standards (if franchise)++## Resources++**Industry Associations:**+- AHLA (American Hotel & Lodging Association)+- NRA (National Restaurant Association)+- HSMAI (Hospitality Sales and Marketing Association International)+- MPI (Meeting Professionals International)++**Training & Certification:**+- Certified Hotel Administrator (CHA)+- ServSafe (food safety certification)+- TIPS/TAM (responsible beverage service)+- Wedding planning certifications (various)++**Technology Platforms:**+- **Hotel PMS:** Opera, Maestro, Cloudbeds, Guesty+- **Restaurant POS:** Toast, Square, Clover, Lightspeed+- **Reservations:** OpenTable, Resy, SevenRooms+- **Events:** Social Tables, Cvent, Tripleseat+- **Revenue Management:** Duetto, IDeaS, Rainmaker++**Publications:**+- Hotel Business+- Restaurant Business+- Hospitality Magazine+- Lodging Magazine+- Special Events Magazine++---++**Final Reminder:** Hospitality is about people serving people. Systems, standards, and operations enable great service, but genuine care, attention to detail, and the desire to create memorable experiences are what truly define hospitality excellence. Every guest interaction is an opportunity to exceed expectations. Train your staff well, empower them to solve problems, lead by example, and never forget that you're in the business of creating moments that people remember.diff --git a/skills/influencer-finder/SKILL.md b/skills/influencer-finder/SKILL.mdnew file mode 100644index 0000000..48f9829--- /dev/null+++ b/skills/influencer-finder/SKILL.md@@ -0,0 +1,98 @@+---+name: Influencer Finder+slug: influencer-finder+description: Find and evaluate influencers for marketing partnerships+category: marketing+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "influencer marketing"+ - "find influencers"+ - "creator partnerships"+ - "influencer outreach"+ - "brand ambassadors"+tags:+ - influencer-marketing+ - partnerships+ - creator-economy+ - social-media+ - brand-collaboration+---++# Influencer Finder++Discover and evaluate influencers who can authentically represent your brand to their engaged audiences. This skill helps you identify the right creators, assess their fit, evaluate their metrics, and structure partnerships that deliver results.++Influencer marketing works when you find the right match. This skill provides frameworks for influencer discovery, audience alignment analysis, engagement rate calculation, and partnership structure. Move beyond follower counts to find creators whose audiences actually overlap with your target customers.++Built for marketing managers, brand managers, social media teams, and anyone exploring influencer partnerships.++## Core Workflows++### Workflow 1: Influencer Discovery+1. **Criteria Definition** - Ideal influencer profile+2. **Platform Selection** - Where your audience engages+3. **Search Strategy** - Hashtags, keywords, competitors+4. **Tool Utilization** - Platforms for influencer search+5. **Initial List Building** - Broad candidate pool+6. **Quick Qualification** - First-pass filtering+7. **Shortlist Creation** - Top candidates for evaluation++### Workflow 2: Influencer Evaluation+1. **Audience Demographics** - Who follows them+2. **Engagement Rate Calculation** - True engagement vs vanity metrics+3. **Content Quality Assessment** - Production value, authenticity+4. **Brand Alignment Check** - Values and positioning fit+5. **Past Partnership Review** - How they work with brands+6. **Fake Follower Detection** - Audience authenticity+7. **Scoring and Ranking** - Objective comparison++### Workflow 3: Partnership Structuring+1. **Campaign Objectives** - What you want to achieve+2. **Deliverable Definition** - Posts, stories, videos, etc.+3. **Compensation Model** - Flat fee, performance, product+4. **Rights and Usage** - Content ownership and reuse+5. **Exclusivity Terms** - Competitor restrictions+6. **Timeline Planning** - Campaign schedule+7. **Contract Essentials** - Key terms to include++### Workflow 4: Influencer Relationship Management+1. **Outreach Strategy** - How to approach influencers+2. **Brief Development** - Creative direction that allows authenticity+3. **Communication Protocol** - How to work together+4. **Content Review Process** - Approval workflow+5. **Performance Tracking** - Measure campaign results+6. **Relationship Nurturing** - Build long-term partnerships+7. **Program Optimization** - Learn and improve++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Find influencers | "Find influencers for [industry/niche]" |+| Evaluate influencer | "Assess [influencer name] for partnership" |+| Calculate engagement | "Calculate engagement rate for [profile]" |+| Structure deal | "Create partnership structure for [campaign]" |+| Write brief | "Create influencer brief for [campaign]" |+| Outreach message | "Write outreach to [influencer type]" |+| Compare influencers | "Compare these influencers" |+| Micro-influencers | "Find micro-influencers in [niche]" |++## Best Practices++- **Engagement over followers** - Smaller, engaged audiences outperform large, passive ones+- **Authenticity first** - Forced partnerships fail+- **Audience overlap** - Their followers should be your targets+- **Content fit** - Can your brand fit naturally in their content?+- **Check past partnerships** - How do they handle brand work?+- **Verify metrics** - Fake followers are rampant+- **Clear expectations** - Documented deliverables prevent conflict+- **Creative freedom** - Best content comes with flexibility+- **Long-term relationships** - Repeat partnerships build trust+- **Diversify** - Don't depend on single influencer+- **Micro matters** - Micro-influencers often have better ROI+- **Track performance** - Measure what actually converts+- **Compliance** - Ensure proper disclosure (FTC, etc.)+- **Respect their time** - Efficient process matters+- **Genuine product fit** - They should actually like what you selldiff --git a/skills/infrastructure-documenter/SKILL.md b/skills/infrastructure-documenter/SKILL.mdnew file mode 100644index 0000000..1a3ee30--- /dev/null+++ b/skills/infrastructure-documenter/SKILL.md@@ -0,0 +1,638 @@+---+name: infrastructure-documenter+description: Expert guide for documenting infrastructure including architecture diagrams, runbooks, system documentation, and operational procedures. Use when creating technical documentation for systems and deployments.+---++# Infrastructure Documenter Skill++## Overview++This skill helps you create clear, maintainable infrastructure documentation. Covers architecture diagrams, runbooks, system documentation, operational procedures, and documentation-as-code practices.++## Documentation Philosophy++### Principles+1. **Living documentation**: Keep it in sync with reality+2. **Audience-aware**: Different docs for different readers+3. **Actionable**: Every doc should help someone do something+4. **Version-controlled**: Documentation changes tracked with code++### Document Types++| Type | Audience | Purpose |+|------|----------|---------|+| Architecture | Engineers | Understand system design |+| Runbooks | Ops/SRE | Handle incidents |+| API Docs | Developers | Integrate with system |+| Onboarding | New hires | Get up to speed |+| Decision Records | Future you | Understand why |++## Architecture Documentation++### System Architecture Overview++```markdown+# System Architecture++## Overview++[Project Name] is a [type] application that [purpose].++## High-Level Architecture++```+┌─────────────────────────────────────────────────────────────┐+│ Users │+└─────────────────────────────────────────────────────────────┘+ │+ ▼+┌─────────────────────────────────────────────────────────────┐+│ Vercel Edge │+│ ┌─────────────────┐ ┌─────────────────┐ │+│ │ Next.js App │ │ Edge Functions │ │+│ └─────────────────┘ └─────────────────┘ │+└─────────────────────────────────────────────────────────────┘+ │+ ┌───────────────┼───────────────┐+ ▼ ▼ ▼+┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐+│ Supabase │ │ Redis │ │ Stripe │+│ - PostgreSQL │ │ - Session │ │ - Payments │+│ - Auth │ │ - Cache │ │ - Webhooks │+│ - Realtime │ │ │ │ │+│ - Storage │ │ │ │ │+└─────────────────┘ └─────────────────┘ └─────────────────┘+```++## Components++### Frontend (Next.js App)+- **Location**: Vercel Edge Network+- **Framework**: Next.js 14 (App Router)+- **Styling**: Tailwind CSS + shadcn/ui+- **State**: Zustand + React Query++### Backend Services+| Service | Provider | Purpose |+|---------|----------|---------|+| Database | Supabase | PostgreSQL with RLS |+| Auth | Supabase Auth | User authentication |+| Storage | Supabase Storage | File uploads |+| Cache | Upstash Redis | Session & API cache |+| Payments | Stripe | Subscriptions |+| Email | Resend | Transactional emails |++### Data Flow++1. User request → Vercel Edge+2. SSR/API Route processes request+3. Database queries via Supabase client+4. Response cached at edge (when applicable)+5. Response returned to user++## Security++### Authentication Flow+1. User signs in via Supabase Auth+2. JWT token issued and stored in cookie+3. Server validates token on each request+4. RLS policies enforce data access++### Data Protection+- All data encrypted at rest (AES-256)+- TLS 1.3 for data in transit+- Secrets stored in Vercel environment+- PII fields encrypted in database+```++### Mermaid Diagrams++```markdown+## Request Flow++```mermaid+sequenceDiagram+ participant U as User+ participant V as Vercel+ participant N as Next.js+ participant S as Supabase+ participant R as Redis++ U->>V: HTTPS Request+ V->>N: Route to App++ alt Cached Response+ N->>R: Check Cache+ R-->>N: Cache Hit+ N-->>U: Return Cached+ else Cache Miss+ N->>S: Query Database+ S-->>N: Data+ N->>R: Store in Cache+ N-->>U: Return Response+ end+```++## Database Schema++```mermaid+erDiagram+ users ||--o{ projects : owns+ users {+ uuid id PK+ text email+ text name+ timestamp created_at+ }+ projects ||--o{ tasks : contains+ projects {+ uuid id PK+ uuid user_id FK+ text name+ text status+ }+ tasks {+ uuid id PK+ uuid project_id FK+ text title+ boolean completed+ }+```+```++## Runbooks++### Runbook Template++```markdown+# Runbook: [Service Name] - [Issue Type]++## Overview+Brief description of the issue and when this runbook applies.++## Severity+- **P1 (Critical)**: Complete outage+- **P2 (High)**: Degraded service+- **P3 (Medium)**: Minor impact+- **P4 (Low)**: No user impact++## Detection+How this issue is typically detected:+- [ ] Alert from [monitoring system]+- [ ] User report+- [ ] Automated check failure++## Impact Assessment+- **Users affected**: All / Segment / None+- **Data at risk**: Yes / No+- **Revenue impact**: High / Medium / Low / None++## Prerequisites+- [ ] Access to [system/dashboard]+- [ ] Credentials for [service]+- [ ] Contact info for [team/person]++## Resolution Steps++### Step 1: Verify the Issue+```bash+# Check service status+curl -I https://api.example.com/health++# Check logs+vercel logs --follow+```++### Step 2: Identify Root Cause+Common causes:+- [ ] Database connection pool exhausted+- [ ] Memory limit reached+- [ ] External service down+- [ ] Bad deployment++### Step 3: Apply Fix++#### If Database Issue:+```bash+# Check connection count+SELECT count(*) FROM pg_stat_activity;++# Kill idle connections+SELECT pg_terminate_backend(pid)+FROM pg_stat_activity+WHERE state = 'idle' AND query_start < now() - interval '1 hour';+```++#### If Bad Deployment:+```bash+# Rollback to previous deployment+vercel rollback+```++### Step 4: Verify Fix+```bash+# Check service health+curl https://api.example.com/health++# Monitor error rates for 15 minutes+```++## Escalation+If unable to resolve within 30 minutes:+1. Page on-call engineer: [contact]+2. Notify stakeholders in #incidents+3. Update status page++## Post-Incident+- [ ] Create incident report+- [ ] Schedule post-mortem (P1/P2 only)+- [ ] Update this runbook if needed++## Related Links+- [Dashboard](https://dashboard.example.com)+- [Logs](https://logs.example.com)+- [Metrics](https://metrics.example.com)+```++### Database Runbooks++```markdown+# Runbook: Database Performance Issues++## Symptoms+- Slow API responses (>1s)+- Timeout errors in logs+- High database CPU in dashboard++## Quick Checks++### 1. Check Active Connections+```sql+SELECT+ state,+ count(*),+ max(now() - query_start) as max_duration+FROM pg_stat_activity+GROUP BY state;+```++### 2. Find Long-Running Queries+```sql+SELECT+ pid,+ now() - query_start AS duration,+ query+FROM pg_stat_activity+WHERE state = 'active'+ AND now() - query_start > interval '30 seconds'+ORDER BY duration DESC;+```++### 3. Check Table Sizes+```sql+SELECT+ schemaname,+ tablename,+ pg_size_pretty(pg_total_relation_size(schemaname || '.' || tablename)) as size+FROM pg_tables+WHERE schemaname = 'public'+ORDER BY pg_total_relation_size(schemaname || '.' || tablename) DESC+LIMIT 10;+```++### 4. Check Missing Indexes+```sql+SELECT+ relname,+ seq_scan,+ idx_scan,+ seq_scan - idx_scan AS difference+FROM pg_stat_user_tables+WHERE seq_scan > idx_scan+ORDER BY difference DESC;+```++## Resolution++### Kill Problematic Queries+```sql+SELECT pg_terminate_backend(pid)+FROM pg_stat_activity+WHERE pid = [PID_FROM_ABOVE];+```++### Add Missing Index+```sql+CREATE INDEX CONCURRENTLY idx_table_column+ON table_name (column_name);+```+```++## Decision Records (ADRs)++### ADR Template++```markdown+# ADR-001: Choose Supabase for Database++## Status+Accepted++## Context+We need a database solution for [Project Name] that supports:+- PostgreSQL compatibility+- Real-time subscriptions+- Built-in authentication+- Easy local development+- Generous free tier++## Decision+We will use Supabase as our primary database and auth provider.++## Alternatives Considered++### PlanetScale+**Pros:**+- Excellent scaling+- Branching for schema changes+- MySQL compatible++**Cons:**+- No built-in auth+- No real-time subscriptions+- Additional services needed++### Firebase+**Pros:**+- Real-time built-in+- Mature platform+- Good mobile SDKs++**Cons:**+- NoSQL (not ideal for our use case)+- Vendor lock-in concerns+- Complex security rules++## Consequences++### Positive+- Single provider for DB + Auth + Storage+- Great developer experience+- Row Level Security for data protection+- Local development with supabase CLI++### Negative+- PostgreSQL-specific features tie us to provider+- Supabase still maturing (some rough edges)+- Limited to their managed offering++### Risks+- Supabase scaling limitations at high traffic+- Migration cost if we need to move++## References+- [Supabase Documentation](https://supabase.com/docs)+- [Comparison: Supabase vs Firebase](https://...)+```++## API Documentation++### Endpoint Documentation++```markdown+# API Reference++## Base URL+```+Production: https://api.example.com/v1+Staging: https://staging-api.example.com/v1+```++## Authentication++All API requests require authentication via Bearer token.++```bash+curl -H "Authorization: Bearer YOUR_TOKEN" \+ https://api.example.com/v1/users+```++## Endpoints++### Users++#### Get Current User+```+GET /users/me+```++**Response:**+```json+{+ "id": "usr_123",+ "email": "[email protected]",+ "name": "John Doe",+ "created_at": "2024-01-01T00:00:00Z"+}+```++#### Update User+```+PATCH /users/me+```++**Request Body:**+| Field | Type | Required | Description |+|-------|------|----------|-------------|+| name | string | No | Display name |+| avatar_url | string | No | Profile image URL |++**Example:**+```bash+curl -X PATCH \+ -H "Authorization: Bearer YOUR_TOKEN" \+ -H "Content-Type: application/json" \+ -d '{"name": "Jane Doe"}' \+ https://api.example.com/v1/users/me+```++### Error Responses++| Status | Code | Description |+|--------|------|-------------|+| 400 | BAD_REQUEST | Invalid request body |+| 401 | UNAUTHORIZED | Missing or invalid token |+| 403 | FORBIDDEN | Insufficient permissions |+| 404 | NOT_FOUND | Resource not found |+| 429 | RATE_LIMITED | Too many requests |+| 500 | INTERNAL_ERROR | Server error |++**Error Response Format:**+```json+{+ "error": {+ "code": "NOT_FOUND",+ "message": "User not found"+ }+}+```+```++## Environment Documentation++### Environment Matrix++```markdown+# Environments++## Overview++| Environment | URL | Purpose | Deploy |+|-------------|-----|---------|--------|+| Production | https://myapp.com | Live users | Manual (main) |+| Staging | https://staging.myapp.com | Pre-release testing | Auto (main) |+| Preview | https://pr-*.vercel.app | PR review | Auto (PR) |+| Development | http://localhost:3000 | Local dev | Manual |++## Configuration++### Production+```env+NODE_ENV=production+DATABASE_URL=[Supabase Production]+NEXT_PUBLIC_APP_URL=https://myapp.com+```++### Staging+```env+NODE_ENV=production+DATABASE_URL=[Supabase Staging Branch]+NEXT_PUBLIC_APP_URL=https://staging.myapp.com+```++### Development+```env+NODE_ENV=development+DATABASE_URL=[Local Supabase]+NEXT_PUBLIC_APP_URL=http://localhost:3000+```++## Access++### Production+- **Vercel**: Admin only+- **Database**: Read-only for devs, write for admin+- **Logs**: All engineers++### Staging+- **Vercel**: All engineers+- **Database**: All engineers+- **Logs**: All engineers++## Secrets Rotation++| Secret | Rotation | Last Rotated |+|--------|----------|--------------|+| Database password | 90 days | 2024-01-15 |+| API keys | 90 days | 2024-01-15 |+| JWT secret | Never | Initial setup |+```++## Documentation-as-Code++### Documentation Structure++```+docs/+├── README.md # Documentation index+├── architecture/+│ ├── overview.md # System architecture+│ ├── data-flow.md # Data flow diagrams+│ └── decisions/ # ADRs+│ ├── 001-database.md+│ └── 002-hosting.md+├── runbooks/+│ ├── README.md # Runbook index+│ ├── database.md # Database issues+│ ├── deployment.md # Deployment issues+│ └── outage.md # Service outage+├── api/+│ └── reference.md # API documentation+└── onboarding/+ ├── setup.md # Local setup+ └── contributing.md # How to contribute+```++### Auto-Generated Documentation++```yaml+# .github/workflows/docs.yml+name: Generate Docs++on:+ push:+ branches: [main]+ paths:+ - 'src/**'+ - 'docs/**'++jobs:+ generate-docs:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - name: Generate API docs from OpenAPI+ run: |+ npx @redocly/cli build-docs openapi.yaml \+ --output docs/api/index.html++ - name: Generate TypeDoc+ run: npx typedoc --out docs/api/typescript++ - name: Deploy to GitHub Pages+ uses: peaceiris/actions-gh-pages@v3+ with:+ github_token: ${{ secrets.GITHUB_TOKEN }}+ publish_dir: ./docs+```++## Documentation Checklist++### Architecture Docs+- [ ] System overview diagram+- [ ] Component descriptions+- [ ] Data flow documentation+- [ ] Security architecture+- [ ] Technology decisions (ADRs)++### Operational Docs+- [ ] Runbooks for common issues+- [ ] Deployment procedures+- [ ] Monitoring and alerting+- [ ] Incident response plan+- [ ] On-call procedures++### Developer Docs+- [ ] Local setup guide+- [ ] API reference+- [ ] Contributing guidelines+- [ ] Code conventions+- [ ] Testing guide++### Maintenance+- [ ] Documentation review schedule+- [ ] Ownership assigned+- [ ] Change process defined+- [ ] Versioning strategy++## When to Use This Skill++Invoke this skill when:+- Creating architecture documentation+- Writing runbooks for operations+- Documenting decision rationale (ADRs)+- Setting up documentation structure+- Creating onboarding materials+- Building automated documentation+- Planning incident response proceduresdiff --git a/skills/investment-analyzer/SKILL.md b/skills/investment-analyzer/SKILL.mdnew file mode 100644index 0000000..1ae393e--- /dev/null+++ b/skills/investment-analyzer/SKILL.md@@ -0,0 +1,571 @@+---+name: Investment Analyzer+slug: investment-analyzer+description: Analyze investment opportunities across asset classes with risk assessment, return modeling, and portfolio optimization+category: finance+complexity: complex+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "analyze investment"+ - "investment analysis"+ - "ROI calculation"+ - "investment comparison"+ - "due diligence"+ - "portfolio analysis"+tags:+ - investments+ - due-diligence+ - roi-analysis+ - risk-assessment+ - portfolio-management+---++# Investment Analyzer++Expert investment analysis agent that evaluates investment opportunities, calculates risk-adjusted returns, performs due diligence, and optimizes portfolio allocation. Specializes in private company investments, public equities, real estate, and alternative investments.++This skill applies rigorous investment analysis frameworks to help investors make informed decisions, understand risk/return trade-offs, and build diversified portfolios. Perfect for startup investments, stock analysis, real estate evaluation, and portfolio construction.++## Core Workflows++### Workflow 1: Private Company Investment Analysis++**Objective:** Evaluate equity investment opportunity in a private company++**Steps:**+1. **Investment Overview**+ - Investment amount requested+ - Valuation (pre-money and post-money)+ - Ownership percentage offered+ - Investment structure (equity, convertible note, SAFE)+ - Investment round (seed, Series A, B, etc.)+ - Use of funds++2. **Business Analysis**+ - **Market Opportunity:**+ - Total Addressable Market (TAM)+ - Serviceable Addressable Market (SAM)+ - Serviceable Obtainable Market (SOM)+ - Market growth rate+ - Competitive landscape++ - **Business Model:**+ - Revenue model (subscription, transactional, etc.)+ - Unit economics+ - Customer acquisition cost (CAC)+ - Lifetime value (LTV)+ - LTV/CAC ratio (target > 3x)+ - Gross margins++ - **Traction:**+ - Revenue/MRR/ARR+ - Growth rate (MoM, YoY)+ - Customer count and quality+ - Retention/churn rates+ - Key milestones achieved++3. **Team Assessment**+ - Founder backgrounds+ - Domain expertise+ - Previous exits+ - Team completeness+ - Key person risk+ - Board composition++4. **Financial Due Diligence**+ - Historical financials (if available)+ - Burn rate and runway+ - Path to profitability+ - Financial projections analysis+ - Key assumptions validation++5. **Return Modeling**+ - **Exit Scenarios:**+ - Conservative exit (2-3x revenue multiple)+ - Base case exit (5-7x revenue multiple)+ - Optimistic exit (10x+ revenue multiple)++ - **Return Calculations:**+ - Expected exit valuation+ - Ownership at exit (dilution adjusted)+ - Gross return (exit value / investment)+ - IRR calculation (based on timeline)+ - Multiple of Invested Capital (MOIC)++6. **Risk Assessment**+ - Market risk (competition, timing)+ - Execution risk (team, operational)+ - Financial risk (runway, fundraising)+ - Technology risk (scalability, defensibility)+ - Regulatory risk+ - Overall risk rating (High/Medium/Low)++7. **Deal Terms Analysis**+ - Valuation reasonableness+ - Liquidation preferences+ - Anti-dilution provisions+ - Board seats and governance+ - Information rights+ - Pro-rata rights++8. **Investment Decision**+ - Investment thesis summary+ - Expected return vs. risk+ - Key risks and mitigants+ - Recommendation (Invest/Pass)+ - Conditions or modifications++**Deliverable:** Investment memo with analysis and recommendation++### Workflow 2: Public Equity Analysis++**Objective:** Evaluate stock investment opportunity++**Steps:**+1. **Company Overview**+ - Business description+ - Market position+ - Competitive advantages (moat)+ - Key products/services+ - Geographic presence++2. **Financial Analysis**+ - **Income Statement:**+ - Revenue trends (3-5 years)+ - Margin analysis (gross, operating, net)+ - EPS growth+ - Revenue mix and diversification++ - **Balance Sheet:**+ - Asset quality+ - Debt levels+ - Cash position+ - Working capital+ - Book value++ - **Cash Flow:**+ - Operating cash flow trends+ - Free cash flow+ - CapEx requirements+ - Dividend coverage+ - Share buyback capacity++3. **Ratio Analysis**+ - **Profitability:**+ - ROE, ROA, ROIC+ - Profit margins++ - **Valuation:**+ - P/E ratio vs peers and history+ - EV/EBITDA+ - P/B ratio+ - PEG ratio+ - Dividend yield++ - **Financial Health:**+ - Debt/Equity+ - Interest coverage+ - Current ratio++4. **Valuation**+ - **DCF Analysis:**+ - Revenue projections+ - Margin assumptions+ - WACC calculation+ - Terminal value+ - Implied share price++ - **Comparable Analysis:**+ - Peer company multiples+ - Implied valuation range++ - **Fair Value Estimate:**+ - Weighted valuation+ - Margin of safety++5. **Technical Factors**+ - Price trends+ - Support/resistance levels+ - Volume patterns+ - Relative strength+ - Moving averages++6. **Risk Factors**+ - Company-specific risks+ - Industry risks+ - Macro risks+ - ESG considerations++7. **Investment Recommendation**+ - Fair value estimate+ - Current price vs fair value+ - Upside/downside potential+ - Rating (Strong Buy/Buy/Hold/Sell)+ - Price target+ - Investment horizon++**Deliverable:** Equity research report with recommendation++### Workflow 3: Real Estate Investment Analysis++**Objective:** Evaluate real estate investment opportunity++**Steps:**+1. **Property Overview**+ - Property type (residential, commercial, industrial)+ - Location and market+ - Size and specifications+ - Age and condition+ - Purchase price++2. **Income Analysis**+ - **Gross Rental Income:**+ - Current rent roll+ - Market rent comparison+ - Occupancy rate+ - Lease terms++ - **Operating Expenses:**+ - Property taxes+ - Insurance+ - Utilities+ - Maintenance and repairs+ - Property management (8-12%)+ - Vacancy reserve (5-10%)+ - CapEx reserve (5-10%)++ - **Net Operating Income (NOI):**+ - Gross Income - Operating Expenses++3. **Return Metrics**+ - **Cap Rate:**+ - NOI / Purchase Price+ - Compare to market cap rates++ - **Cash-on-Cash Return:**+ - Annual Cash Flow / Total Cash Invested+ - Pre-tax and after-tax++ - **Internal Rate of Return (IRR):**+ - 5-10 year hold period+ - Include exit sale++ - **Equity Multiple:**+ - Total Cash Returned / Total Cash Invested++4. **Financing Analysis**+ - Loan terms (rate, term, amortization)+ - Down payment required+ - Debt service coverage ratio (DSCR)+ - Loan-to-value (LTV)+ - Monthly payment calculation+ - Positive/negative leverage++5. **Market Analysis**+ - Comparable sales+ - Rental comps+ - Market trends+ - Supply/demand dynamics+ - Economic drivers+ - Appreciation potential++6. **Risk Assessment**+ - Vacancy risk+ - Tenant quality+ - Market risk+ - Interest rate risk+ - Deferred maintenance+ - Environmental issues+ - Regulatory changes++7. **Value-Add Opportunities**+ - Rent increases+ - Expense reductions+ - Property improvements+ - Use conversion+ - Development potential++8. **Investment Decision**+ - Return summary+ - Risk-adjusted assessment+ - Recommendation+ - Offer price suggestion++**Deliverable:** Real estate investment analysis with recommendation++### Workflow 4: ROI and Payback Analysis++**Objective:** Calculate return on investment for business projects++**Steps:**+1. **Project Definition**+ - Investment description+ - Total investment required+ - Investment timeline+ - Expected benefits++2. **Cost Analysis**+ - **Initial Investment:**+ - Capital costs+ - Implementation costs+ - Training costs+ - One-time expenses++ - **Ongoing Costs:**+ - Operating costs+ - Maintenance+ - License fees+ - Personnel++3. **Benefit Analysis**+ - **Revenue Benefits:**+ - New revenue generation+ - Revenue acceleration+ - Price improvements++ - **Cost Savings:**+ - Labor savings+ - Material savings+ - Efficiency gains+ - Error reduction++ - **Quantification:**+ - Conservative estimate+ - Expected estimate+ - Optimistic estimate++4. **Financial Metrics**+ - **Simple ROI:**+ - (Total Benefits - Total Costs) / Total Costs++ - **Payback Period:**+ - Time to recover initial investment+ - Simple payback = Investment / Annual Cash Flow++ - **Net Present Value (NPV):**+ - Discount future cash flows+ - NPV > 0 indicates good investment++ - **Internal Rate of Return (IRR):**+ - Discount rate where NPV = 0+ - Compare to hurdle rate++5. **Sensitivity Analysis**+ - Vary key assumptions+ - Break-even analysis+ - Scenario modeling++6. **Recommendation**+ - Investment summary+ - Key assumptions+ - Risk factors+ - Go/No-Go recommendation++**Deliverable:** ROI analysis with payback period and NPV/IRR++### Workflow 5: Portfolio Allocation Analysis++**Objective:** Optimize investment portfolio allocation++**Steps:**+1. **Current Portfolio Assessment**+ - Asset inventory+ - Current allocation by:+ - Asset class+ - Geography+ - Sector+ - Risk level+ - Performance history++2. **Investor Profile**+ - Risk tolerance (conservative/moderate/aggressive)+ - Investment horizon+ - Liquidity needs+ - Tax considerations+ - ESG preferences+ - Return objectives++3. **Target Allocation**+ - **Asset Class Allocation:**+ - Equities (domestic, international)+ - Fixed income (government, corporate)+ - Real estate+ - Alternatives (private equity, hedge funds)+ - Cash++ - **Risk-Based Allocation:**+ - Growth assets+ - Income assets+ - Defensive assets++4. **Rebalancing Analysis**+ - Current vs target allocation+ - Required trades+ - Tax implications+ - Transaction costs+ - Rebalancing triggers++5. **Risk Analysis**+ - Portfolio volatility+ - Correlation analysis+ - Concentration risk+ - Downside risk (VaR, max drawdown)+ - Stress testing++6. **Expected Returns**+ - Asset class return assumptions+ - Portfolio expected return+ - Risk-adjusted return (Sharpe ratio)+ - Probability of meeting goals++7. **Recommendations**+ - Allocation changes+ - Specific investments+ - Implementation plan+ - Monitoring schedule++**Deliverable:** Portfolio analysis with allocation recommendations++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Startup analysis | "Analyze this startup investment" |+| Stock analysis | "Analyze [ticker] stock" |+| Real estate | "Analyze this property investment" |+| ROI calculation | "Calculate ROI for [project]" |+| Portfolio review | "Analyze my portfolio allocation" |+| Due diligence | "Perform due diligence on [company]" |++## Investment Formulas++### Return Metrics++| Metric | Formula | Notes |+|--------|---------|-------|+| ROI | (Gain - Cost) / Cost | Simple return percentage |+| IRR | Rate where NPV = 0 | Time-weighted return |+| MOIC | Exit Value / Investment | Multiple of money |+| CAGR | (End/Start)^(1/years) - 1 | Annualized return |+| Sharpe Ratio | (Return - Risk-free) / Std Dev | Risk-adjusted return |++### Valuation Metrics++| Metric | Formula | Typical Range |+|--------|---------|---------------|+| P/E Ratio | Price / EPS | 10-25x (varies) |+| EV/EBITDA | Enterprise Value / EBITDA | 8-15x |+| EV/Revenue | Enterprise Value / Revenue | 1-5x |+| P/B Ratio | Price / Book Value | 1-3x |+| Cap Rate | NOI / Property Value | 4-10% |++### Startup Metrics++| Metric | Target | Notes |+|--------|--------|-------|+| LTV/CAC | > 3x | Unit economics health |+| CAC Payback | < 12 months | How fast you recover CAC |+| Gross Margin | > 70% (SaaS) | Scalability indicator |+| Net Dollar Retention | > 100% | Revenue expansion |+| Monthly Burn | < Cash/18mo | Runway health |++## Investment Analysis Template++```markdown+# Investment Analysis: [Company/Asset Name]++**Date:** [Date]+**Analyst:** [Name]+**Investment Type:** [Equity/Debt/Real Estate/etc.]++## Executive Summary+- Investment amount: $XXX+- Expected return: XX% IRR+- Risk level: [High/Medium/Low]+- Recommendation: [Invest/Pass]++## Opportunity Overview+[Brief description]++## Key Investment Thesis+1. [Reason 1]+2. [Reason 2]+3. [Reason 3]++## Financial Analysis++### Historical Performance+| Metric | Year 1 | Year 2 | Year 3 |+|--------|--------|--------|--------|+| Revenue | | | |+| Growth | | | |+| Margin | | | |++### Return Analysis+| Scenario | Exit Value | MOIC | IRR |+|----------|------------|------|-----|+| Bear | | | |+| Base | | | |+| Bull | | | |++## Risk Assessment++### Key Risks+1. [Risk 1] - [Mitigation]+2. [Risk 2] - [Mitigation]+3. [Risk 3] - [Mitigation]++### Risk Matrix+| Factor | Rating (1-5) |+|--------|--------------|+| Market Risk | |+| Execution Risk | |+| Financial Risk | |+| Team Risk | |++## Recommendation+[Detailed recommendation with conditions]+```++## Best Practices++### Due Diligence+- Verify all claims independently+- Check references thoroughly+- Review legal documents carefully+- Validate financial statements+- Assess team track record++### Return Analysis+- Use multiple valuation methods+- Model multiple scenarios+- Be conservative in assumptions+- Consider opportunity cost+- Factor in fees and taxes++### Risk Management+- Diversify across investments+- Size positions appropriately+- Set clear exit criteria+- Monitor investments regularly+- Know your walk-away points++## Integration with Other Skills++- **Use with `valuation-analyst`:** Deep-dive company valuation+- **Use with `financial-analyst`:** Financial statement analysis+- **Use with `contract-analyzer`:** Review investment terms+- **Use with `compliance-checker`:** Regulatory considerations+- **Use with `tax-strategist`:** Tax-efficient structuring++## Common Pitfalls to Avoid++- **FOMO investing:** Don't rush due diligence+- **Overconfidence in projections:** Hockey stick forecasts rarely materialize+- **Ignoring downside:** Model the failure case+- **Insufficient diversification:** Don't concentrate too heavily+- **Emotional attachment:** Stay objective+- **Ignoring fees:** Total cost matters+- **Skipping references:** Always check+- **Confirmation bias:** Seek disconfirming evidencediff --git a/skills/knowledge-graph-builder/SKILL.md b/skills/knowledge-graph-builder/SKILL.mdnew file mode 100644index 0000000..671ca70--- /dev/null+++ b/skills/knowledge-graph-builder/SKILL.md@@ -0,0 +1,426 @@+---+name: Knowledge Graph Builder+slug: knowledge-graph-builder+description: Build knowledge graphs for support systems, connecting concepts, articles, and solutions+category: customer-support+complexity: complex+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "knowledge graph"+ - "knowledge mapping"+ - "concept relationships"+ - "support knowledge base"+ - "semantic connections"+ - "knowledge network"+tags:+ - knowledge-graph+ - knowledge-management+ - semantic-search+ - support-systems+ - content-architecture+---++# Knowledge Graph Builder++Expert knowledge graph creation system that transforms disconnected support content into an interconnected web of concepts, relationships, and solutions. This skill provides structured workflows for mapping knowledge domains, defining relationships, and powering intelligent support experiences.++Knowledge graphs enable support systems to understand context, not just keywords. When a customer asks about "billing issues," a knowledge graph knows this relates to invoices, payment methods, subscription plans, and potentially churn risk. This skill helps you build that connective intelligence.++Built on semantic web principles and knowledge engineering best practices, this skill combines domain modeling, relationship mapping, and practical implementation to create knowledge graphs that power smarter support.++## Core Workflows++### Workflow 1: Domain Modeling+**Define the concepts and entities in your knowledge domain**++1. **Entity Identification**+ - **Core Entities**: Products, features, concepts+ - **Customer Entities**: Accounts, users, segments+ - **Support Entities**: Issues, solutions, articles+ - **Process Entities**: Workflows, procedures, steps+ - **Context Entities**: Use cases, personas, scenarios++2. **Entity Types for Support**+ | Entity Type | Examples | Purpose |+ |-------------|----------|---------|+ | Product | App, Feature, Module | What customers use |+ | Issue | Bug, Error, Question | What customers face |+ | Solution | Fix, Workaround, Guide | How to resolve |+ | Article | FAQ, How-to, Reference | Content resources |+ | Concept | Term, Process, Capability | Understanding |+ | Persona | Admin, User, Developer | Who needs help |++3. **Entity Properties**+ ```+ Entity: Feature+ Properties:+ - id: unique identifier+ - name: display name+ - description: what it does+ - status: active/deprecated/beta+ - complexity: basic/intermediate/advanced+ - related_persona: who uses it+ - documentation_url: help article link+ ```++4. **Entity Extraction Sources**+ - Product documentation+ - Support ticket taxonomy+ - FAQ categories+ - Help center structure+ - Feature specifications+ - User research findings++### Workflow 2: Relationship Mapping+**Define how entities connect to each other**++1. **Core Relationship Types**+ | Relationship | From | To | Example |+ |--------------|------|-----|---------|+ | SOLVES | Solution | Issue | "Password reset SOLVES login failure" |+ | PART_OF | Feature | Product | "Dashboard PART_OF Analytics" |+ | REQUIRES | Feature | Feature | "Export REQUIRES Pro plan" |+ | CAUSES | Issue | Issue | "API limit CAUSES sync failure" |+ | DOCUMENTED_IN | Concept | Article | "Billing DOCUMENTED_IN pricing guide" |+ | APPLIES_TO | Solution | Persona | "Workaround APPLIES_TO admin users" |++2. **Relationship Properties**+ ```+ Relationship: SOLVES+ Properties:+ - confidence: how reliable (0-1)+ - conditions: when this applies+ - effectiveness: success rate+ - last_verified: date checked+ ```++3. **Relationship Discovery**+ - Analyze support ticket resolution paths+ - Map help article cross-references+ - Identify co-occurring issues+ - Study user journey patterns+ - Review expert knowledge++4. **Relationship Strength**+ - **Strong**: Always true, well documented+ - **Moderate**: Usually true, common pattern+ - **Weak**: Sometimes true, contextual+ - **Suggested**: Possible, needs validation++### Workflow 3: Graph Construction+**Build the actual knowledge graph structure**++1. **Graph Architecture**+ ```+ Nodes (Entities):+ - Unique identifier+ - Entity type+ - Properties+ - Metadata (created, updated, source)++ Edges (Relationships):+ - From node+ - To node+ - Relationship type+ - Properties+ - Metadata+ ```++2. **Implementation Options**+ | Approach | Best For | Tools |+ |----------|----------|-------|+ | Graph Database | Complex queries, scale | Neo4j, Amazon Neptune |+ | RDF Triple Store | Semantic web, standards | Apache Jena, Stardog |+ | Property Graph | Flexible modeling | Neo4j, TigerGraph |+ | Embedded | Simple use cases | NetworkX, GraphQL |++3. **Schema Design**+ - Define node labels/types+ - Define relationship types+ - Set required properties+ - Define constraints (uniqueness, existence)+ - Create indexes for query performance++4. **Data Population**+ - Bulk import from existing sources+ - API ingestion from live systems+ - Manual expert curation+ - Automated extraction (NLP)+ - Continuous updates from support activity++### Workflow 4: Query & Inference+**Extract value from the knowledge graph**++1. **Query Patterns**+ | Query Type | Use Case | Example |+ |------------|----------|---------|+ | Traversal | Find related content | "Articles related to X" |+ | Path finding | Solution discovery | "Steps from issue to resolution" |+ | Pattern matching | Similar issues | "Issues like X" |+ | Aggregation | Analytics | "Most common issue per feature" |+ | Recommendation | Suggestions | "Other users also viewed" |++2. **Inference Rules**+ - If A CAUSES B and B CAUSES C, suggest A might relate to C+ - If Solution S SOLVES Issue I, suggest similar solutions for similar issues+ - If Article A DOCUMENTED_IN B and B REQUIRES C, show C as prerequisite+ - If many users navigate A → B → C, suggest shortcut++3. **Semantic Search Enhancement**+ - Expand search with related concepts+ - Rank by graph centrality+ - Surface related articles+ - Suggest alternative terms+ - Understand context from relationships++4. **Conversational AI Integration**+ - Map user intent to graph entities+ - Follow relationships to find answers+ - Generate responses from connected content+ - Explain reasoning through graph path++### Workflow 5: Maintenance & Evolution+**Keep the knowledge graph accurate and growing**++1. **Quality Monitoring**+ - Track usage patterns+ - Identify dead-end paths+ - Find orphaned nodes+ - Monitor relationship accuracy+ - Measure search success rates++2. **Update Triggers**+ - New product releases+ - Documentation changes+ - Support ticket patterns+ - User feedback+ - Expert curation sessions++3. **Validation Process**+ - Expert review of new relationships+ - A/B test graph-powered features+ - Monitor accuracy metrics+ - User feedback collection+ - Regular audits++4. **Growth Strategies**+ - Automated entity extraction from tickets+ - ML-based relationship suggestion+ - User contribution mechanisms+ - Expert knowledge capture sessions+ - Cross-reference with external sources++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Create entity | "Add entity [type] for [name]" |+| Define relationship | "Create relationship [type] from [A] to [B]" |+| Query graph | "Find [entity] related to [entity]" |+| Find path | "Show path from [issue] to [solution]" |+| Graph statistics | "Show knowledge graph metrics" |+| Validate relationships | "Audit relationships for [entity]" |+| Extract from tickets | "Extract entities from recent tickets" |+| Generate documentation | "Export graph as documentation" |+| Find gaps | "Identify missing relationships" |+| Visualize graph | "Visualize graph around [entity]" |++## Best Practices++### Domain Modeling+- Start with core product concepts+- Model from customer perspective+- Keep entity types focused+- Document entity definitions clearly+- Version your schema++### Relationship Design+- Use verb-based relationship names+- Make relationships directional+- Add confidence/strength properties+- Avoid redundant relationships+- Document relationship semantics++### Graph Construction+- Start small, grow iteratively+- Validate with domain experts+- Index frequently queried properties+- Plan for scale from start+- Maintain data lineage++### Query Optimization+- Profile query performance+- Create appropriate indexes+- Cache common traversals+- Paginate large results+- Monitor query patterns++### Maintenance+- Schedule regular audits+- Track content freshness+- Remove stale nodes/edges+- Validate automated additions+- Document changes++## Knowledge Graph Schema++### Core Entities+```yaml+Product:+ properties:+ - id: string (required, unique)+ - name: string (required)+ - description: text+ - version: string+ - status: enum [active, deprecated, beta]+ - tier: enum [free, pro, enterprise]++Feature:+ properties:+ - id: string (required, unique)+ - name: string (required)+ - description: text+ - complexity: enum [basic, intermediate, advanced]+ - introduced_version: string+ - documentation_url: url++Issue:+ properties:+ - id: string (required, unique)+ - title: string (required)+ - description: text+ - severity: enum [critical, high, medium, low]+ - frequency: enum [common, occasional, rare]+ - symptoms: array[string]++Solution:+ properties:+ - id: string (required, unique)+ - title: string (required)+ - steps: array[string]+ - type: enum [fix, workaround, configuration]+ - effectiveness: float [0-1]+ - applies_to: array[string]++Article:+ properties:+ - id: string (required, unique)+ - title: string (required)+ - url: url (required)+ - type: enum [faq, how-to, reference, troubleshooting]+ - audience: enum [all, admin, developer]+ - last_updated: date++Concept:+ properties:+ - id: string (required, unique)+ - term: string (required)+ - definition: text (required)+ - aliases: array[string]+ - domain: string+```++### Core Relationships+```yaml+PART_OF:+ from: [Feature, Concept]+ to: [Product, Feature, Concept]+ properties:+ - required: boolean++SOLVES:+ from: Solution+ to: Issue+ properties:+ - confidence: float [0-1]+ - conditions: text+ - verified_date: date++CAUSES:+ from: Issue+ to: Issue+ properties:+ - probability: float [0-1]+ - mechanism: text++DOCUMENTED_IN:+ from: [Feature, Issue, Solution, Concept]+ to: Article+ properties:+ - section: string+ - is_primary: boolean++REQUIRES:+ from: [Feature, Solution]+ to: [Feature, Permission, Plan]+ properties:+ - type: enum [prerequisite, dependency, permission]++RELATED_TO:+ from: [any]+ to: [any]+ properties:+ - strength: float [0-1]+ - type: enum [similar, alternative, complementary]++APPLIES_TO:+ from: [Solution, Article]+ to: [Persona, Plan, Version]+ properties:+ - conditions: text+```++## Implementation Guide++### Phase 1: Foundation (Week 1-2)+1. Define core entity types+2. Document property schemas+3. Map primary relationships+4. Choose technology stack+5. Set up development environment++### Phase 2: Core Graph (Week 3-4)+1. Extract entities from documentation+2. Create initial relationships+3. Import into graph database+4. Build basic query interface+5. Validate with domain experts++### Phase 3: Integration (Week 5-6)+1. Connect to support system+2. Implement search enhancement+3. Add content recommendation+4. Create admin interface+5. Set up monitoring++### Phase 4: Intelligence (Week 7-8)+1. Add inference rules+2. Implement similarity scoring+3. Enable automated extraction+4. Build feedback loops+5. Deploy to production++## Red Flags++- **Disconnected nodes**: Entities without relationships+- **Relationship soup**: Too many weak relationships+- **Stale data**: Outdated information not updated+- **Schema drift**: Inconsistent entity modeling+- **Query complexity**: Simple questions need complex queries+- **No validation**: Automated additions not verified+- **Missing context**: Relationships without properties+- **Poor coverage**: Key concepts not represented++## Success Metrics++| Metric | What It Measures | Target |+|--------|------------------|--------|+| Graph Coverage | % of concepts captured | 90%+ |+| Search Improvement | Relevance vs. keyword | 2x+ |+| Resolution Speed | Time to find answer | 50% reduction |+| Relationship Accuracy | Expert validation rate | 95%+ |+| Query Latency | Response time | < 100ms |+| User Satisfaction | CSAT with graph features | 4.0/5.0+ |+| Automation Rate | Auto-resolved with graph | 30%+ |+| Graph Growth | New entities/month | Healthy growth |diff --git a/skills/landing-page-optimizer/SKILL.md b/skills/landing-page-optimizer/SKILL.mdnew file mode 100644index 0000000..6e624f7--- /dev/null+++ b/skills/landing-page-optimizer/SKILL.md@@ -0,0 +1,99 @@+---+name: Landing Page Optimizer+slug: landing-page-optimizer+description: Optimize landing pages for maximum conversion through copy, design, and UX improvements+category: marketing+complexity: advanced+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "landing page optimization"+ - "conversion rate optimization"+ - "CRO"+ - "landing page review"+ - "improve conversions"+tags:+ - conversion-optimization+ - landing-pages+ - cro+ - ux-optimization+ - copy-optimization+---++# Landing Page Optimizer++Transform underperforming landing pages into conversion machines. This skill combines copywriting expertise, UX best practices, and conversion psychology to systematically improve every element of your landing pages.++Most landing pages leave massive value on the table. Small changes to headlines, CTAs, social proof placement, and form design can dramatically increase conversion rates. This skill provides a systematic audit framework, prioritized optimization recommendations, and testing strategies to continuously improve performance.++Built for marketers, growth teams, product managers, and anyone responsible for landing page performance and conversion rates.++## Core Workflows++### Workflow 1: Landing Page Audit+1. **First Impression Test** - 5-second clarity assessment+2. **Message Match** - Ad to landing page consistency+3. **Value Proposition Review** - Headline and subhead evaluation+4. **Visual Hierarchy** - Eye-tracking pattern analysis+5. **CTA Assessment** - Placement, copy, design review+6. **Trust Signal Inventory** - Social proof, credibility elements+7. **Friction Analysis** - Identify conversion barriers+8. **Mobile Experience** - Responsive design evaluation++### Workflow 2: Above-the-Fold Optimization+1. **Headline Testing** - Multiple value proposition angles+2. **Subhead Refinement** - Supporting message clarity+3. **Hero Image/Video** - Visual impact assessment+4. **CTA Positioning** - Optimal placement and visibility+5. **Navigation Decisions** - Keep or remove nav links+6. **Loading Speed** - Performance impact on conversions+7. **Clarity Score** - Can visitors understand in 5 seconds?++### Workflow 3: Conversion Element Optimization+1. **CTA Copy Variations** - Button text testing+2. **CTA Design** - Color, size, shape optimization+3. **Form Optimization** - Field reduction, smart defaults+4. **Social Proof Placement** - Testimonials, logos, stats+5. **Urgency Elements** - Scarcity, countdown timers+6. **Risk Reducers** - Guarantees, trust badges+7. **Objection Handling** - FAQ, concerns addressed++### Workflow 4: Full Page Restructure+1. **Story Arc Design** - Logical flow through page+2. **Section Prioritization** - Order by impact+3. **Content Pruning** - Remove what doesn't convert+4. **Scanability Enhancement** - Headers, bullets, whitespace+5. **Multiple CTAs** - Strategic repetition+6. **Exit Intent Strategy** - Capture abandoning visitors+7. **Cross-Device Consistency** - Desktop and mobile flows++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Full audit | "Audit this landing page for conversion issues" |+| Headline options | "Generate headline variations for [page]" |+| CTA optimization | "Improve CTA copy and placement" |+| Form review | "Optimize this form for conversions" |+| Social proof | "Recommend social proof placement" |+| Mobile check | "Review mobile experience for [page]" |+| Speed analysis | "Assess loading speed impact" |+| A/B test plan | "Create test plan for [page]" |++## Best Practices++- **One goal per page** - Clarity of purpose drives conversion+- **Message match** - Ad promise = landing page delivery+- **Headline is everything** - Test headlines first, always+- **5-second test** - If unclear in 5 seconds, you've lost them+- **Reduce form fields** - Every field costs conversions+- **CTA above and below fold** - Multiple opportunities to convert+- **Specific > vague** - "Get your free PDF" beats "Submit"+- **Social proof near CTA** - Reduce anxiety at decision point+- **Mobile is primary** - Most traffic is mobile+- **Speed matters** - Every second costs conversions+- **Remove navigation** - Keep focus on conversion goal+- **Use directional cues** - Eyes and arrows guide attention+- **Test one element** - Isolate variables for clean data+- **Don't test too early** - Need volume for significance+- **Document everything** - Build institutional knowledgediff --git a/skills/lead-qualifier/SKILL.md b/skills/lead-qualifier/SKILL.mdnew file mode 100644index 0000000..2206b0d--- /dev/null+++ b/skills/lead-qualifier/SKILL.md@@ -0,0 +1,98 @@+---+name: Lead Qualifier+slug: lead-qualifier+description: Qualify and score sales leads using proven frameworks and data-driven criteria+category: sales+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "qualify leads"+ - "lead scoring"+ - "sales qualification"+ - "BANT framework"+ - "lead priority"+tags:+ - lead-qualification+ - sales+ - lead-scoring+ - pipeline-management+ - prospecting+---++# Lead Qualifier++Transform raw leads into prioritized opportunities with systematic qualification. This skill applies proven frameworks like BANT, MEDDIC, and CHAMP to evaluate leads objectively, ensuring your sales team focuses on prospects most likely to convert.++Stop wasting time on tire-kickers and unqualified prospects. This skill helps you build scoring models, create qualification criteria, and develop consistent processes for evaluating fit, budget, authority, and timing. The result: shorter sales cycles, higher close rates, and more efficient resource allocation.++Ideal for sales teams, SDRs, account executives, and anyone who needs to separate high-potential opportunities from noise.++## Core Workflows++### Workflow 1: BANT Qualification+1. **Budget Assessment** - Determine if prospect has financial resources+2. **Authority Mapping** - Identify decision-makers and influencers+3. **Need Verification** - Confirm genuine pain points exist+4. **Timeline Discovery** - Understand urgency and buying timeframe+5. **Score Calculation** - Weight each factor for overall score+6. **Priority Assignment** - Categorize as hot, warm, or nurture+7. **Handoff Decision** - Route to appropriate sales resource++### Workflow 2: Lead Scoring Model Design+1. **Ideal Customer Profile** - Define characteristics of best customers+2. **Demographic Scoring** - Points for company size, industry, role+3. **Behavioral Scoring** - Points for engagement, content consumption+4. **Firmographic Weighting** - Prioritize by company attributes+5. **Engagement Thresholds** - Set minimum scores for qualification+6. **Score Decay Rules** - Reduce scores for inactivity+7. **Model Validation** - Test against historical conversion data++### Workflow 3: MEDDIC Deep Qualification+1. **Metrics** - Quantify the economic impact of your solution+2. **Economic Buyer** - Identify who controls the budget+3. **Decision Criteria** - Understand evaluation requirements+4. **Decision Process** - Map the buying journey and stakeholders+5. **Identify Pain** - Uncover compelling business drivers+6. **Champion** - Find internal advocate for your solution+7. **Qualification Report** - Document findings for deal strategy++### Workflow 4: Automated Qualification Workflow+1. **Form Design** - Create qualifying questions for lead capture+2. **Progressive Profiling** - Gather info across multiple interactions+3. **Enrichment Integration** - Add firmographic data automatically+4. **Scoring Triggers** - Auto-score based on behavior and data+5. **Routing Rules** - Direct leads to right team/process+6. **SLA Management** - Set response time requirements+7. **Handoff Automation** - Streamline qualified lead delivery++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Score a lead | "Qualify this lead using BANT" |+| Build scoring model | "Create lead scoring model for [product]" |+| Evaluate fit | "Assess lead fit for [ICP criteria]" |+| MEDDIC analysis | "Deep qualify this opportunity" |+| Priority ranking | "Rank these leads by likelihood to close" |+| Qualification questions | "Create discovery questions for [industry]" |+| Disqualification check | "What disqualifies a lead for us?" |+| Score refinement | "Adjust scoring model based on [data]" |++## Best Practices++- **Define ICP first** - Know your ideal customer before qualifying anyone+- **Use multiple frameworks** - BANT for quick screen, MEDDIC for complex deals+- **Weight recency** - Recent engagement matters more than old activity+- **Include negative criteria** - Define what disqualifies as clearly as what qualifies+- **Automate where possible** - Let technology handle initial scoring+- **Calibrate regularly** - Compare predicted vs. actual conversions monthly+- **Document reasoning** - Record why leads are qualified/disqualified+- **Set clear thresholds** - Specific scores trigger specific actions+- **Train consistently** - Everyone should score leads the same way+- **Measure outcomes** - Track which qualified leads actually closed+- **Consider timing** - Right solution, wrong time still means nurture+- **Map buying committee** - Qualify the deal, not just the contact+- **Listen for pain** - No pain = no urgency = no deal+- **Validate budget early** - Don't invest in opportunities without resources+- **Create feedback loops** - Sales insights should refine marketing's scoringdiff --git a/skills/llm-prompt-optimizer/SKILL.md b/skills/llm-prompt-optimizer/SKILL.mdnew file mode 100644index 0000000..e487958--- /dev/null+++ b/skills/llm-prompt-optimizer/SKILL.md@@ -0,0 +1,153 @@+---+name: LLM Prompt Optimizer+slug: llm-prompt-optimizer+description: Optimize prompts for better LLM outputs through systematic analysis and refinement+category: ai-ml+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "optimize this prompt"+ - "improve LLM output"+ - "better prompt"+ - "prompt optimization"+ - "enhance prompt quality"+tags:+ - prompt-engineering+ - optimization+ - LLM+ - AI+ - performance+---++# LLM Prompt Optimizer++The LLM Prompt Optimizer skill systematically analyzes and refines prompts to maximize the quality, accuracy, and relevance of large language model outputs. It applies evidence-based optimization techniques including structural improvements, context enrichment, constraint calibration, and output format specification.++This skill goes beyond basic prompt writing by leveraging understanding of how different LLMs process instructions, their attention patterns, and their response tendencies. It helps you transform underperforming prompts into high-yield instructions that consistently produce the results you need.++Whether you are building production AI systems, conducting research, or simply want better ChatGPT responses, this skill ensures your prompts are optimized for your specific model and use case.++## Core Workflows++### Workflow 1: Analyze and Diagnose Prompt Issues+1. **Receive** the current prompt and sample outputs+2. **Identify** failure patterns:+ - Hallucination triggers+ - Ambiguity sources+ - Missing context gaps+ - Conflicting instructions+ - Over/under-constrained parameters+3. **Map** issues to specific prompt segments+4. **Prioritize** fixes by impact+5. **Explain** root causes to user++### Workflow 2: Apply Optimization Techniques+1. **Select** appropriate techniques based on diagnosis:+ - Chain-of-thought insertion+ - Few-shot example addition+ - Role/persona specification+ - Output schema definition+ - Constraint tightening/loosening+2. **Restructure** prompt for clarity+3. **Add** missing context or examples+4. **Remove** conflicting or redundant instructions+5. **Test** optimized version+6. **Iterate** based on results++### Workflow 3: Model-Specific Optimization+1. **Identify** target LLM (GPT-4, Claude, Llama, etc.)+2. **Apply** model-specific best practices:+ - Token budget optimization+ - System prompt vs user prompt split+ - Temperature/sampling guidance+ - Context window utilization+3. **Adjust** for model quirks and strengths+4. **Document** model-specific recommendations++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Diagnose prompt issues | "Why isn't this prompt working: [prompt]" |+| Optimize for accuracy | "Optimize for accuracy: [prompt]" |+| Reduce hallucinations | "Reduce hallucinations in: [prompt]" |+| Add structure | "Add better structure to: [prompt]" |+| Model-specific optimization | "Optimize this for [model]: [prompt]" |+| A/B test variants | "Create prompt variants for testing: [prompt]" |++## Best Practices++- **Start with Clear Intent**: Define exactly what success looks like before optimizing+ - Bad: "Make it work better"+ - Good: "Reduce factual errors while maintaining conversational tone"++- **Use Explicit Output Formats**: LLMs follow structure better than vague requests+ - Specify JSON schemas, markdown formats, or template structures+ - Example: "Return as JSON with keys: analysis, recommendations, confidence"++- **Calibrate Constraints**: Too many constraints cause conflicts; too few cause drift+ - Test constraint combinations systematically+ - Remove constraints that don't improve output quality++- **Leverage Positive Instructions**: Tell the model what TO do, not just what NOT to do+ - Bad: "Don't be verbose"+ - Good: "Respond in 2-3 concise sentences"++- **Position Critical Instructions Strategically**: Beginning and end get more attention+ - Put key constraints at the start+ - Repeat critical requirements at the end++- **Use Delimiters for Multi-Part Inputs**: Clear separation prevents confusion+ - Triple quotes, XML tags, or markdown headers+ - Example: `"""User Query: {query}""" """Context: {context}"""`++## Advanced Techniques++### Recursive Refinement Loop+For complex prompts, use iterative optimization:+```+1. Generate baseline outputs (n=5)+2. Score outputs against criteria+3. Identify lowest-scoring dimension+4. Adjust prompt targeting that dimension+5. Repeat until all dimensions score acceptably+```++### Prompt Decomposition+Break complex tasks into simpler sub-prompts:+```+Complex: "Analyze this code, find bugs, suggest fixes, and refactor"+Decomposed:+ Step 1: "List all potential bugs in this code"+ Step 2: "For each bug, explain the fix"+ Step 3: "Refactor the fixed code for clarity"+```++### Negative Example Injection+Show what NOT to do alongside positive examples:+```+Good output: [example]+Bad output (avoid this): [anti-example]+Key difference: [explanation]+```++### Token Budget Optimization+When context is limited:+```+1. Remove redundant phrases+2. Use abbreviations consistently+3. Compress examples to minimal effective size+4. Prioritize recent/relevant context+5. Consider summarizing long contexts+```++## Common Pitfalls to Avoid++- Over-engineering simple prompts with unnecessary complexity+- Copying prompts between models without adaptation+- Ignoring the relationship between temperature and prompt specificity+- Adding examples that introduce unwanted patterns+- Using vague terms like "good," "proper," or "appropriate" without definition+- Conflicting instructions that force the model to choose+- Forgetting to specify handling of edge cases and errorsdiff --git a/skills/log-analyzer/SKILL.md b/skills/log-analyzer/SKILL.mdnew file mode 100644index 0000000..e3b1a64--- /dev/null+++ b/skills/log-analyzer/SKILL.md@@ -0,0 +1,646 @@+---+name: log-analyzer+description: Expert guide for analyzing application logs including log searching, pattern detection, error tracking, and debugging. Use when investigating issues, tracking errors, or understanding application behavior.+---++# Log Analyzer Skill++## Overview++This skill helps you effectively analyze application logs to diagnose issues, track errors, and understand system behavior. Covers log searching, pattern detection, structured logging, and integration with monitoring tools.++## Log Analysis Philosophy++### Principles+1. **Structure over text**: Structured logs are easier to analyze+2. **Context matters**: Include relevant metadata+3. **Levels have meaning**: Use appropriate severity levels+4. **Correlation is key**: Link related events across services++### Log Levels++| Level | When to Use | Example |+|-------|-------------|---------|+| ERROR | Something failed, needs attention | Database connection failed |+| WARN | Unexpected but handled | Retry succeeded after failure |+| INFO | Normal operation milestones | User signed up |+| DEBUG | Detailed diagnostic info | Query executed in 50ms |+| TRACE | Very detailed, usually disabled | Function entered/exited |++## Structured Logging++### Winston Configuration (Node.js)++```typescript+// src/lib/logger.ts+import winston from 'winston';++const logger = winston.createLogger({+ level: process.env.LOG_LEVEL || 'info',+ format: winston.format.combine(+ winston.format.timestamp(),+ winston.format.errors({ stack: true }),+ winston.format.json()+ ),+ defaultMeta: {+ service: 'my-app',+ environment: process.env.NODE_ENV,+ },+ transports: [+ // Console for development+ new winston.transports.Console({+ format: process.env.NODE_ENV === 'development'+ ? winston.format.combine(+ winston.format.colorize(),+ winston.format.simple()+ )+ : winston.format.json(),+ }),+ ],+});++// Add request context+export function createRequestLogger(requestId: string, userId?: string) {+ return logger.child({+ requestId,+ userId,+ });+}++export { logger };+```++### Pino Logger (High Performance)++```typescript+// src/lib/logger.ts+import pino from 'pino';++export const logger = pino({+ level: process.env.LOG_LEVEL || 'info',+ transport: process.env.NODE_ENV === 'development'+ ? {+ target: 'pino-pretty',+ options: {+ colorize: true,+ translateTime: 'SYS:standard',+ },+ }+ : undefined,+ base: {+ service: 'my-app',+ env: process.env.NODE_ENV,+ },+ redact: {+ paths: ['password', 'token', 'apiKey', '*.password', '*.token'],+ censor: '[REDACTED]',+ },+});++// Request-scoped logger+export function requestLogger(requestId: string, userId?: string) {+ return logger.child({ requestId, userId });+}+```++### Logging Best Practices++```typescript+// DO: Include context+logger.info('User signed up', {+ userId: user.id,+ email: user.email,+ plan: 'free',+ source: 'web',+});++// DO: Log errors with stack traces+logger.error('Payment failed', {+ error: err.message,+ stack: err.stack,+ userId: user.id,+ amount: 99.99,+ provider: 'stripe',+});++// DO: Use appropriate levels+logger.debug('Database query', {+ query: 'SELECT * FROM users WHERE id = ?',+ duration: 45,+ rows: 1,+});++// DON'T: Log sensitive data+// BAD: logger.info('Login', { password: user.password })++// DON'T: Use string concatenation+// BAD: logger.info('User ' + user.id + ' signed up')+```++## Log Searching & Filtering++### Command Line (grep, jq)++```bash+# Search JSON logs with jq+cat logs.json | jq 'select(.level == "error")'++# Search for specific user+cat logs.json | jq 'select(.userId == "usr_123")'++# Search by time range+cat logs.json | jq 'select(.timestamp >= "2024-01-15T10:00:00")'++# Count errors by type+cat logs.json | jq 'select(.level == "error") | .error.code' | sort | uniq -c++# Extract specific fields+cat logs.json | jq '{timestamp, level, message, userId}'++# Search text logs+grep -i "error" logs.txt+grep -E "error|warn" logs.txt+grep -A5 "ERROR" logs.txt # 5 lines after match+grep -B3 "ERROR" logs.txt # 3 lines before match+```++### Vercel Log Analysis++```bash+# View live logs+vercel logs --follow++# Filter by level+vercel logs --level error++# Search specific timeframe+vercel logs --since 2h++# Filter by deployment+vercel logs --deployment-url https://myapp-abc123.vercel.app++# Output JSON for processing+vercel logs --output json | jq 'select(.level == "error")'+```++### Supabase Log Analysis++```sql+-- Query Postgres logs+SELECT *+FROM postgres_logs+WHERE timestamp > now() - interval '1 hour'+ AND error_severity = 'ERROR'+ORDER BY timestamp DESC+LIMIT 100;++-- Query auth logs+SELECT *+FROM auth.audit_log_entries+WHERE timestamp > now() - interval '24 hours'+ AND payload->>'action' = 'login'+ORDER BY timestamp DESC;++-- Find slow queries+SELECT+ query,+ calls,+ mean_exec_time,+ total_exec_time+FROM pg_stat_statements+ORDER BY mean_exec_time DESC+LIMIT 20;+```++## Pattern Detection++### Common Error Patterns++```typescript+// Error pattern analyzer+interface ErrorPattern {+ pattern: RegExp;+ category: string;+ severity: 'critical' | 'high' | 'medium' | 'low';+ suggestion: string;+}++const errorPatterns: ErrorPattern[] = [+ {+ pattern: /ECONNREFUSED|connection refused/i,+ category: 'connectivity',+ severity: 'critical',+ suggestion: 'Check if the target service is running and accessible',+ },+ {+ pattern: /timeout|ETIMEDOUT/i,+ category: 'timeout',+ severity: 'high',+ suggestion: 'Increase timeout or check for slow operations',+ },+ {+ pattern: /out of memory|heap|OOM/i,+ category: 'memory',+ severity: 'critical',+ suggestion: 'Increase memory allocation or fix memory leak',+ },+ {+ pattern: /rate.?limit|429|too many requests/i,+ category: 'rate-limiting',+ severity: 'medium',+ suggestion: 'Implement backoff strategy or increase rate limits',+ },+ {+ pattern: /unauthorized|401|invalid.?token/i,+ category: 'auth',+ severity: 'medium',+ suggestion: 'Check authentication credentials or token expiry',+ },+ {+ pattern: /not.?found|404/i,+ category: 'not-found',+ severity: 'low',+ suggestion: 'Verify resource exists or check URL',+ },+];++function categorizeError(message: string): ErrorPattern | null {+ for (const pattern of errorPatterns) {+ if (pattern.pattern.test(message)) {+ return pattern;+ }+ }+ return null;+}+```++### Log Aggregation Script++```typescript+// scripts/analyze-logs.ts+import * as readline from 'readline';+import * as fs from 'fs';++interface LogEntry {+ timestamp: string;+ level: string;+ message: string;+ error?: {+ message: string;+ code?: string;+ };+ [key: string]: any;+}++interface LogSummary {+ totalEntries: number;+ byLevel: Record<string, number>;+ errorMessages: Record<string, number>;+ timeRange: {+ start: string;+ end: string;+ };+}++async function analyzeLogs(filePath: string): Promise<LogSummary> {+ const summary: LogSummary = {+ totalEntries: 0,+ byLevel: {},+ errorMessages: {},+ timeRange: { start: '', end: '' },+ };++ const fileStream = fs.createReadStream(filePath);+ const rl = readline.createInterface({+ input: fileStream,+ crlfDelay: Infinity,+ });++ for await (const line of rl) {+ try {+ const entry: LogEntry = JSON.parse(line);+ summary.totalEntries++;++ // Count by level+ summary.byLevel[entry.level] = (summary.byLevel[entry.level] || 0) + 1;++ // Track error messages+ if (entry.level === 'error' && entry.error?.message) {+ const msg = entry.error.message.substring(0, 100);+ summary.errorMessages[msg] = (summary.errorMessages[msg] || 0) + 1;+ }++ // Track time range+ if (!summary.timeRange.start || entry.timestamp < summary.timeRange.start) {+ summary.timeRange.start = entry.timestamp;+ }+ if (!summary.timeRange.end || entry.timestamp > summary.timeRange.end) {+ summary.timeRange.end = entry.timestamp;+ }+ } catch {+ // Skip non-JSON lines+ }+ }++ return summary;+}++// Usage+analyzeLogs('logs.json').then(console.log);+```++## Request Tracing++### Request ID Middleware++```typescript+// src/middleware.ts+import { NextResponse } from 'next/server';+import type { NextRequest } from 'next/server';+import { v4 as uuidv4 } from 'uuid';++export function middleware(request: NextRequest) {+ const requestId = request.headers.get('x-request-id') || uuidv4();++ const response = NextResponse.next();+ response.headers.set('x-request-id', requestId);++ return response;+}+```++### Tracing Context++```typescript+// src/lib/tracing.ts+import { AsyncLocalStorage } from 'async_hooks';++interface TraceContext {+ requestId: string;+ userId?: string;+ startTime: number;+}++const asyncLocalStorage = new AsyncLocalStorage<TraceContext>();++export function withTrace<T>(+ context: TraceContext,+ fn: () => T | Promise<T>+): T | Promise<T> {+ return asyncLocalStorage.run(context, fn);+}++export function getTrace(): TraceContext | undefined {+ return asyncLocalStorage.getStore();+}++// Usage in logger+export function log(level: string, message: string, data?: object) {+ const trace = getTrace();+ console.log(JSON.stringify({+ timestamp: new Date().toISOString(),+ level,+ message,+ requestId: trace?.requestId,+ userId: trace?.userId,+ duration: trace ? Date.now() - trace.startTime : undefined,+ ...data,+ }));+}+```++## Error Tracking Integration++### Sentry Integration++```typescript+// src/lib/sentry.ts+import * as Sentry from '@sentry/nextjs';++Sentry.init({+ dsn: process.env.SENTRY_DSN,+ environment: process.env.NODE_ENV,+ tracesSampleRate: 0.1, // 10% of transactions+ beforeSend(event, hint) {+ // Filter out specific errors+ const error = hint.originalException;+ if (error instanceof Error && error.message.includes('Network')) {+ return null;+ }+ return event;+ },+});++// Capture with context+export function captureError(error: Error, context?: Record<string, any>) {+ Sentry.withScope((scope) => {+ if (context) {+ scope.setExtras(context);+ }+ Sentry.captureException(error);+ });+}++// Usage+try {+ await riskyOperation();+} catch (error) {+ captureError(error, {+ userId: user.id,+ action: 'payment',+ amount: 99.99,+ });+ throw error;+}+```++### Custom Error Boundary Logging++```typescript+// src/components/error-boundary.tsx+'use client';++import { useEffect } from 'react';+import * as Sentry from '@sentry/nextjs';++export default function Error({+ error,+ reset,+}: {+ error: Error & { digest?: string };+ reset: () => void;+}) {+ useEffect(() => {+ // Log to error tracking+ Sentry.captureException(error);++ // Log to console with context+ console.error('Client Error:', {+ message: error.message,+ digest: error.digest,+ stack: error.stack,+ url: window.location.href,+ userAgent: navigator.userAgent,+ });+ }, [error]);++ return (+ <div>+ <h2>Something went wrong!</h2>+ <button onClick={reset}>Try again</button>+ </div>+ );+}+```++## Log Analysis Queries++### Common Investigation Queries++```bash+# Find all errors for a specific user+jq 'select(.userId == "usr_123" and .level == "error")' logs.json++# Find errors in the last hour+jq --arg time "$(date -d '1 hour ago' -Iseconds)" \+ 'select(.timestamp > $time and .level == "error")' logs.json++# Group errors by message+jq -s 'group_by(.error.message) |+ map({message: .[0].error.message, count: length}) |+ sort_by(-.count)' logs.json++# Find slow requests (>1 second)+jq 'select(.duration > 1000)' logs.json++# Trace a specific request+jq 'select(.requestId == "req_abc123")' logs.json | sort_by(.timestamp)++# Find patterns in error messages+jq -r 'select(.level == "error") | .error.message' logs.json | \+ sort | uniq -c | sort -rn | head -20+```++### SQL-Style Log Analysis++```sql+-- Using tools like clickhouse or DuckDB for log analysis++-- Error rate by hour+SELECT+ date_trunc('hour', timestamp) as hour,+ count(*) FILTER (WHERE level = 'error') as errors,+ count(*) as total,+ round(100.0 * count(*) FILTER (WHERE level = 'error') / count(*), 2) as error_rate+FROM logs+WHERE timestamp > now() - interval '24 hours'+GROUP BY 1+ORDER BY 1;++-- Top error messages+SELECT+ error_message,+ count(*) as occurrences,+ min(timestamp) as first_seen,+ max(timestamp) as last_seen+FROM logs+WHERE level = 'error'+ AND timestamp > now() - interval '24 hours'+GROUP BY error_message+ORDER BY occurrences DESC+LIMIT 10;++-- Slowest endpoints+SELECT+ path,+ count(*) as requests,+ avg(duration) as avg_duration,+ max(duration) as max_duration,+ percentile_cont(0.95) WITHIN GROUP (ORDER BY duration) as p95+FROM logs+WHERE timestamp > now() - interval '1 hour'+GROUP BY path+ORDER BY avg_duration DESC+LIMIT 10;+```++## Log Retention & Cleanup++### Log Rotation Configuration++```bash+# /etc/logrotate.d/myapp+/var/log/myapp/*.log {+ daily+ rotate 14+ compress+ delaycompress+ missingok+ notifempty+ create 0640 www-data www-data+ sharedscripts+ postrotate+ systemctl reload myapp+ endscript+}+```++### Automated Log Cleanup++```typescript+// scripts/cleanup-logs.ts+import * as fs from 'fs';+import * as path from 'path';++const LOG_DIR = '/var/log/myapp';+const RETENTION_DAYS = 30;++function cleanupOldLogs() {+ const now = Date.now();+ const maxAge = RETENTION_DAYS * 24 * 60 * 60 * 1000;++ const files = fs.readdirSync(LOG_DIR);++ for (const file of files) {+ const filePath = path.join(LOG_DIR, file);+ const stats = fs.statSync(filePath);++ if (now - stats.mtime.getTime() > maxAge) {+ fs.unlinkSync(filePath);+ console.log(`Deleted: ${file}`);+ }+ }+}++cleanupOldLogs();+```++## Debugging Checklist++### When Investigating Issues+- [ ] Identify the time window+- [ ] Find related request IDs+- [ ] Check for error spikes+- [ ] Look at affected users/endpoints+- [ ] Check for pattern changes+- [ ] Review recent deployments++### Log Quality Check+- [ ] Structured JSON format+- [ ] Appropriate log levels+- [ ] Request IDs included+- [ ] Sensitive data redacted+- [ ] Stack traces for errors+- [ ] Relevant context included++## When to Use This Skill++Invoke this skill when:+- Investigating production issues+- Setting up logging infrastructure+- Debugging application errors+- Analyzing performance issues+- Creating log analysis scripts+- Setting up error tracking+- Implementing request tracing+- Cleaning up log datadiff --git a/skills/model-evaluator/SKILL.md b/skills/model-evaluator/SKILL.mdnew file mode 100644index 0000000..56dfcd3--- /dev/null+++ b/skills/model-evaluator/SKILL.md@@ -0,0 +1,220 @@+---+name: Model Evaluator+slug: model-evaluator+description: Evaluate and compare ML model performance with rigorous testing methodologies+category: ai-ml+complexity: advanced+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "evaluate model"+ - "compare models"+ - "model performance"+ - "benchmark ML"+ - "model metrics"+tags:+ - evaluation+ - benchmarking+ - metrics+ - machine-learning+ - testing+---++# Model Evaluator++The Model Evaluator skill helps you rigorously assess and compare machine learning model performance across multiple dimensions. It guides you through selecting appropriate metrics, designing evaluation protocols, avoiding common statistical pitfalls, and making data-driven decisions about model selection.++Proper model evaluation goes beyond accuracy scores. This skill covers evaluation across the full spectrum: predictive performance, computational efficiency, robustness, fairness, calibration, and production readiness. It helps you answer not just "which model is best?" but "which model is best for my specific use case and constraints?"++Whether you are comparing LLMs, classifiers, or custom models, this skill ensures your evaluation methodology is sound and your conclusions are reliable.++## Core Workflows++### Workflow 1: Design Evaluation Protocol+1. **Define** evaluation objectives:+ - Primary goal (accuracy, speed, cost, etc.)+ - Secondary constraints+ - Failure modes to test+ - Real-world conditions to simulate+2. **Select** appropriate metrics:+ | Task Type | Primary Metrics | Secondary Metrics |+ |-----------|-----------------|-------------------|+ | Classification | Accuracy, F1, AUC-ROC | Precision, Recall, Confusion Matrix |+ | Regression | RMSE, MAE, R-squared | Residual analysis, prediction intervals |+ | Ranking | NDCG, MRR, MAP | Precision@k, Recall@k |+ | Generation | BLEU, ROUGE, BERTScore | Human eval, Faithfulness |+ | LLM | Task-specific accuracy | Latency, cost, consistency |+3. **Design** test sets:+ - Held-out test data+ - Edge case collections+ - Adversarial examples+ - Distribution shift tests+4. **Plan** statistical methodology:+ - Sample sizes for significance+ - Confidence intervals+ - Multiple comparison corrections++### Workflow 2: Execute Comparative Evaluation+1. **Prepare** evaluation infrastructure:+ ```python+ class ModelEvaluator:+ def __init__(self, test_data, metrics):+ self.test_data = test_data+ self.metrics = metrics+ self.results = {}++ def evaluate(self, model, model_name):+ predictions = model.predict(self.test_data.inputs)+ scores = {}+ for metric in self.metrics:+ scores[metric.name] = metric.compute(+ predictions,+ self.test_data.labels+ )+ self.results[model_name] = scores+ return scores++ def compare(self):+ return statistical_comparison(self.results)+ ```+2. **Run** evaluations consistently across models+3. **Compute** confidence intervals+4. **Test** for statistical significance+5. **Generate** comparison report++### Workflow 3: LLM-Specific Evaluation+1. **Define** evaluation dimensions:+ - Task accuracy (factual, reasoning, coding)+ - Response quality (coherence, relevance, style)+ - Safety and alignment+ - Efficiency (tokens, latency, cost)+2. **Create** evaluation datasets:+ - Representative prompts+ - Ground truth answers (where applicable)+ - Human preference data+3. **Implement** LLM evaluation:+ - Automated metrics (exact match, semantic similarity)+ - LLM-as-judge evaluations+ - Human evaluation protocols+4. **Analyze** results across dimensions+5. **Make** recommendations with tradeoffs++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Design evaluation | "How should I evaluate [model type]" |+| Choose metrics | "What metrics for [task type]" |+| Compare models | "Compare these models: [list]" |+| LLM evaluation | "Evaluate LLM performance" |+| Statistical testing | "Is this difference significant" |+| Bias evaluation | "Check model for bias" |++## Best Practices++- **Use Multiple Metrics**: No single metric tells the whole story+ - Include both aggregate and granular metrics+ - Report confidence intervals, not just point estimates+ - Show performance across subgroups++- **Test on Realistic Data**: Evaluation data should match production+ - Same distribution as real inputs+ - Include edge cases and hard examples+ - Test on data the model hasn't seen++- **Account for Variance**: Models and data have randomness+ - Run multiple seeds for training-based evaluations+ - Bootstrap confidence intervals+ - Use proper statistical tests for comparison++- **Consider All Costs**: Performance isn't just accuracy+ - Inference latency and throughput+ - Memory and compute requirements+ - API costs for hosted models+ - Maintenance and update burden++- **Test Robustness**: How does the model handle adversity?+ - Input perturbations and noise+ - Distribution shift+ - Adversarial examples+ - Missing or malformed inputs++- **Evaluate Fairly**: Ensure fair comparison across models+ - Same test data for all models+ - Consistent preprocessing+ - Equivalent hyperparameter tuning effort+ - Document any advantages/disadvantages++## Advanced Techniques++### Multi-Dimensional Evaluation+Score models across multiple axes:+```python+def multi_dim_evaluate(model, test_data):+ return {+ "accuracy": compute_accuracy(model, test_data),+ "latency_p50": measure_latency(model, test_data, percentile=50),+ "latency_p99": measure_latency(model, test_data, percentile=99),+ "memory_mb": measure_memory(model),+ "cost_per_1k": compute_cost(model, n=1000),+ "robustness": adversarial_accuracy(model, test_data),+ "fairness": demographic_parity(model, test_data)+ }+```++### LLM-as-Judge Protocol+Use LLMs to evaluate LLM outputs:+```+Prompt template:+"Rate the following response on a scale of 1-5 for:+- Accuracy: Is the information correct?+- Helpfulness: Does it address the user's need?+- Clarity: Is it easy to understand?++Question: {question}+Response: {response}+Ground truth (if available): {ground_truth}++Provide scores and brief justification."+```++### A/B Testing Framework+For production evaluation:+```python+class ABTest:+ def __init__(self, model_a, model_b, traffic_split=0.5):+ self.models = {"A": model_a, "B": model_b}+ self.split = traffic_split+ self.results = {"A": [], "B": []}++ def serve(self, request):+ variant = "A" if random.random() < self.split else "B"+ response = self.models[variant].predict(request)+ return response, variant++ def record_outcome(self, variant, success):+ self.results[variant].append(success)++ def compute_significance(self):+ return statistical_test(self.results["A"], self.results["B"])+```++### Calibration Analysis+Ensure predicted probabilities are meaningful:+```+- Expected Calibration Error (ECE)+- Reliability diagrams+- Brier score decomposition+- Temperature scaling for recalibration+```++## Common Pitfalls to Avoid++- Overfitting to the test set through repeated evaluation+- Ignoring statistical significance in model comparisons+- Using inappropriate metrics for the task (accuracy for imbalanced classes)+- Evaluating on data too similar to training data+- Ignoring computational costs in model selection+- Not testing robustness to distribution shift+- Conflating correlation with causation in A/B tests+- Failing to account for multiple comparisons in statistical testsdiff --git a/skills/monitoring-setup/SKILL.md b/skills/monitoring-setup/SKILL.mdnew file mode 100644index 0000000..138b35b--- /dev/null+++ b/skills/monitoring-setup/SKILL.md@@ -0,0 +1,652 @@+---+name: monitoring-setup+description: Expert guide for setting up monitoring dashboards, alerting, metrics collection, and observability. Use when implementing application monitoring, setting up alerts, or building dashboards.+---++# Monitoring Setup Skill++## Overview++This skill helps you implement comprehensive monitoring for applications. Covers metrics collection, dashboard creation, alerting strategies, health checks, and observability best practices.++## Monitoring Philosophy++### Four Golden Signals+1. **Latency**: Time to serve a request+2. **Traffic**: Request volume+3. **Errors**: Failed request rate+4. **Saturation**: Resource utilization++### Observability Pillars+- **Metrics**: Numeric measurements over time+- **Logs**: Discrete events with context+- **Traces**: Request flow across services++## Health Check Endpoints++### Comprehensive Health Check++```typescript+// src/app/api/health/route.ts+import { NextResponse } from 'next/server';+import { createClient } from '@supabase/supabase-js';+import Redis from 'ioredis';++interface HealthCheck {+ status: 'healthy' | 'degraded' | 'unhealthy';+ timestamp: string;+ version: string;+ uptime: number;+ checks: {+ database: CheckResult;+ redis: CheckResult;+ external: CheckResult;+ };+}++interface CheckResult {+ status: 'pass' | 'fail';+ latency?: number;+ message?: string;+}++async function checkDatabase(): Promise<CheckResult> {+ const start = Date.now();+ try {+ const supabase = createClient(+ process.env.SUPABASE_URL!,+ process.env.SUPABASE_SERVICE_ROLE_KEY!+ );+ await supabase.from('health_check').select('1').single();+ return {+ status: 'pass',+ latency: Date.now() - start,+ };+ } catch (error) {+ return {+ status: 'fail',+ message: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++async function checkRedis(): Promise<CheckResult> {+ const start = Date.now();+ try {+ const redis = new Redis(process.env.REDIS_URL!);+ await redis.ping();+ redis.disconnect();+ return {+ status: 'pass',+ latency: Date.now() - start,+ };+ } catch (error) {+ return {+ status: 'fail',+ message: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++async function checkExternal(): Promise<CheckResult> {+ const start = Date.now();+ try {+ const response = await fetch('https://api.stripe.com/v1/health', {+ method: 'HEAD',+ });+ return {+ status: response.ok ? 'pass' : 'fail',+ latency: Date.now() - start,+ };+ } catch (error) {+ return {+ status: 'fail',+ message: 'External service unavailable',+ };+ }+}++const startTime = Date.now();++export async function GET() {+ const [database, redis, external] = await Promise.all([+ checkDatabase(),+ checkRedis(),+ checkExternal(),+ ]);++ const checks = { database, redis, external };++ const allPassed = Object.values(checks).every((c) => c.status === 'pass');+ const anyFailed = Object.values(checks).some((c) => c.status === 'fail');++ const health: HealthCheck = {+ status: allPassed ? 'healthy' : anyFailed ? 'unhealthy' : 'degraded',+ timestamp: new Date().toISOString(),+ version: process.env.VERCEL_GIT_COMMIT_SHA || 'local',+ uptime: Math.floor((Date.now() - startTime) / 1000),+ checks,+ };++ return NextResponse.json(health, {+ status: health.status === 'healthy' ? 200 : 503,+ headers: {+ 'Cache-Control': 'no-store',+ },+ });+}+```++### Kubernetes-Style Probes++```typescript+// src/app/api/health/live/route.ts+// Liveness probe - is the app running?+export async function GET() {+ return new Response('OK', { status: 200 });+}++// src/app/api/health/ready/route.ts+// Readiness probe - can the app handle traffic?+export async function GET() {+ try {+ // Check critical dependencies+ await checkDatabase();+ return new Response('OK', { status: 200 });+ } catch {+ return new Response('Not Ready', { status: 503 });+ }+}+```++## Metrics Collection++### Custom Metrics with Prometheus Client++```typescript+// src/lib/metrics.ts+import { Counter, Histogram, Gauge, Registry } from 'prom-client';++export const registry = new Registry();++// HTTP request metrics+export const httpRequestsTotal = new Counter({+ name: 'http_requests_total',+ help: 'Total HTTP requests',+ labelNames: ['method', 'route', 'status'],+ registers: [registry],+});++export const httpRequestDuration = new Histogram({+ name: 'http_request_duration_seconds',+ help: 'HTTP request duration in seconds',+ labelNames: ['method', 'route'],+ buckets: [0.01, 0.05, 0.1, 0.5, 1, 2, 5],+ registers: [registry],+});++// Business metrics+export const activeUsers = new Gauge({+ name: 'active_users',+ help: 'Number of currently active users',+ registers: [registry],+});++export const ordersTotal = new Counter({+ name: 'orders_total',+ help: 'Total orders processed',+ labelNames: ['status', 'payment_method'],+ registers: [registry],+});++// Database metrics+export const dbQueryDuration = new Histogram({+ name: 'db_query_duration_seconds',+ help: 'Database query duration',+ labelNames: ['operation', 'table'],+ buckets: [0.001, 0.01, 0.05, 0.1, 0.5, 1],+ registers: [registry],+});+```++### Metrics Endpoint++```typescript+// src/app/api/metrics/route.ts+import { NextResponse } from 'next/server';+import { registry } from '@/lib/metrics';++export async function GET(request: Request) {+ // Optional: Basic auth protection+ const authHeader = request.headers.get('authorization');+ if (authHeader !== `Bearer ${process.env.METRICS_TOKEN}`) {+ return new Response('Unauthorized', { status: 401 });+ }++ const metrics = await registry.metrics();++ return new Response(metrics, {+ headers: {+ 'Content-Type': registry.contentType,+ },+ });+}+```++### Middleware for Request Metrics++```typescript+// src/middleware.ts+import { NextResponse } from 'next/server';+import type { NextRequest } from 'next/server';+import { httpRequestsTotal, httpRequestDuration } from '@/lib/metrics';++export async function middleware(request: NextRequest) {+ const start = Date.now();++ const response = NextResponse.next();++ // Record metrics after response+ const route = request.nextUrl.pathname;+ const method = request.method;+ const status = response.status.toString();++ httpRequestsTotal.inc({ method, route, status });+ httpRequestDuration.observe(+ { method, route },+ (Date.now() - start) / 1000+ );++ return response;+}+```++## Alerting Configuration++### Alert Rules (Prometheus/Grafana)++```yaml+# alerts.yml+groups:+ - name: application+ rules:+ # High error rate+ - alert: HighErrorRate+ expr: |+ sum(rate(http_requests_total{status=~"5.."}[5m]))+ /+ sum(rate(http_requests_total[5m]))+ > 0.05+ for: 5m+ labels:+ severity: critical+ annotations:+ summary: High error rate detected+ description: Error rate is {{ $value | humanizePercentage }} over the last 5 minutes++ # High latency+ - alert: HighLatency+ expr: |+ histogram_quantile(0.95,+ sum(rate(http_request_duration_seconds_bucket[5m])) by (le)+ ) > 2+ for: 5m+ labels:+ severity: warning+ annotations:+ summary: High latency detected+ description: 95th percentile latency is {{ $value | humanizeDuration }}++ # Service down+ - alert: ServiceDown+ expr: up == 0+ for: 1m+ labels:+ severity: critical+ annotations:+ summary: Service is down+ description: "{{ $labels.instance }} has been down for more than 1 minute"++ # Database connection pool exhausted+ - alert: DatabaseConnectionsHigh+ expr: pg_stat_activity_count > 80+ for: 5m+ labels:+ severity: warning+ annotations:+ summary: Database connection pool nearly exhausted+ description: "{{ $value }} connections in use"++ - name: infrastructure+ rules:+ # High CPU+ - alert: HighCPU+ expr: node_cpu_seconds_total{mode="idle"} < 20+ for: 10m+ labels:+ severity: warning+ annotations:+ summary: High CPU usage++ # Low disk space+ - alert: LowDiskSpace+ expr: |+ (node_filesystem_avail_bytes / node_filesystem_size_bytes) * 100 < 10+ for: 5m+ labels:+ severity: critical+ annotations:+ summary: Low disk space+ description: Only {{ $value | humanizePercentage }} disk space remaining+```++### Vercel/Uptime Monitoring++```typescript+// scripts/uptime-check.ts+// Run via cron or external monitoring service++const ENDPOINTS = [+ { name: 'Health', url: 'https://myapp.com/api/health' },+ { name: 'Homepage', url: 'https://myapp.com' },+ { name: 'API', url: 'https://myapp.com/api/status' },+];++const WEBHOOK_URL = process.env.SLACK_WEBHOOK_URL;++async function checkEndpoint(endpoint: typeof ENDPOINTS[0]) {+ const start = Date.now();+ try {+ const response = await fetch(endpoint.url, {+ method: 'GET',+ signal: AbortSignal.timeout(10000),+ });++ return {+ name: endpoint.name,+ url: endpoint.url,+ status: response.status,+ latency: Date.now() - start,+ healthy: response.ok,+ };+ } catch (error) {+ return {+ name: endpoint.name,+ url: endpoint.url,+ status: 0,+ latency: Date.now() - start,+ healthy: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++async function notifySlack(message: string) {+ if (!WEBHOOK_URL) return;++ await fetch(WEBHOOK_URL, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ text: message }),+ });+}++async function runChecks() {+ const results = await Promise.all(ENDPOINTS.map(checkEndpoint));++ const unhealthy = results.filter((r) => !r.healthy);++ if (unhealthy.length > 0) {+ const message = `🚨 *Uptime Alert*\n${unhealthy+ .map((r) => `• ${r.name}: ${r.error || `Status ${r.status}`}`)+ .join('\n')}`;++ await notifySlack(message);+ }++ console.log(JSON.stringify(results, null, 2));+}++runChecks();+```++## Dashboard Configuration++### Grafana Dashboard JSON++```json+{+ "title": "Application Overview",+ "panels": [+ {+ "title": "Request Rate",+ "type": "graph",+ "targets": [+ {+ "expr": "sum(rate(http_requests_total[5m])) by (route)",+ "legendFormat": "{{ route }}"+ }+ ]+ },+ {+ "title": "Error Rate",+ "type": "stat",+ "targets": [+ {+ "expr": "sum(rate(http_requests_total{status=~\"5..\"}[5m])) / sum(rate(http_requests_total[5m])) * 100"+ }+ ],+ "fieldConfig": {+ "defaults": {+ "unit": "percent",+ "thresholds": {+ "steps": [+ { "value": 0, "color": "green" },+ { "value": 1, "color": "yellow" },+ { "value": 5, "color": "red" }+ ]+ }+ }+ }+ },+ {+ "title": "Response Time (p95)",+ "type": "gauge",+ "targets": [+ {+ "expr": "histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))"+ }+ ],+ "fieldConfig": {+ "defaults": {+ "unit": "s",+ "thresholds": {+ "steps": [+ { "value": 0, "color": "green" },+ { "value": 0.5, "color": "yellow" },+ { "value": 2, "color": "red" }+ ]+ }+ }+ }+ },+ {+ "title": "Active Users",+ "type": "stat",+ "targets": [+ {+ "expr": "active_users"+ }+ ]+ }+ ]+}+```++### Vercel Analytics Integration++```typescript+// src/app/layout.tsx+import { Analytics } from '@vercel/analytics/react';+import { SpeedInsights } from '@vercel/speed-insights/next';++export default function RootLayout({+ children,+}: {+ children: React.ReactNode;+}) {+ return (+ <html lang="en">+ <body>+ {children}+ <Analytics />+ <SpeedInsights />+ </body>+ </html>+ );+}+```++## Status Page++### Simple Status Page++```typescript+// src/app/status/page.tsx+import { Suspense } from 'react';++interface ServiceStatus {+ name: string;+ status: 'operational' | 'degraded' | 'outage';+ lastChecked: string;+}++async function getStatus(): Promise<ServiceStatus[]> {+ const response = await fetch(+ `${process.env.NEXT_PUBLIC_APP_URL}/api/health`,+ { next: { revalidate: 60 } }+ );++ if (!response.ok) {+ return [+ { name: 'API', status: 'outage', lastChecked: new Date().toISOString() },+ ];+ }++ const health = await response.json();++ return [+ {+ name: 'API',+ status: health.status === 'healthy' ? 'operational' : 'degraded',+ lastChecked: health.timestamp,+ },+ {+ name: 'Database',+ status: health.checks.database.status === 'pass' ? 'operational' : 'outage',+ lastChecked: health.timestamp,+ },+ {+ name: 'Cache',+ status: health.checks.redis.status === 'pass' ? 'operational' : 'degraded',+ lastChecked: health.timestamp,+ },+ ];+}++function StatusBadge({ status }: { status: ServiceStatus['status'] }) {+ const colors = {+ operational: 'bg-green-500',+ degraded: 'bg-yellow-500',+ outage: 'bg-red-500',+ };++ return (+ <span className={`inline-block w-3 h-3 rounded-full ${colors[status]}`} />+ );+}++export default async function StatusPage() {+ const services = await getStatus();+ const allOperational = services.every((s) => s.status === 'operational');++ return (+ <div className="max-w-2xl mx-auto p-8">+ <h1 className="text-2xl font-bold mb-8">System Status</h1>++ <div className={`p-4 rounded-lg mb-8 ${+ allOperational ? 'bg-green-100' : 'bg-yellow-100'+ }`}>+ <p className="font-medium">+ {allOperational+ ? 'All systems operational'+ : 'Some systems experiencing issues'}+ </p>+ </div>++ <div className="space-y-4">+ {services.map((service) => (+ <div+ key={service.name}+ className="flex items-center justify-between p-4 border rounded"+ >+ <div className="flex items-center gap-3">+ <StatusBadge status={service.status} />+ <span className="font-medium">{service.name}</span>+ </div>+ <span className="text-sm text-gray-500 capitalize">+ {service.status}+ </span>+ </div>+ ))}+ </div>++ <p className="mt-8 text-sm text-gray-500">+ Last updated: {new Date().toLocaleString()}+ </p>+ </div>+ );+}+```++## Monitoring Checklist++### Application Monitoring+- [ ] Health check endpoint+- [ ] Request latency metrics+- [ ] Error rate tracking+- [ ] Active user count+- [ ] Business metrics (orders, signups, etc.)++### Infrastructure Monitoring+- [ ] CPU/Memory utilization+- [ ] Disk space+- [ ] Network I/O+- [ ] Database connections+- [ ] Cache hit rate++### Alerting+- [ ] Error rate thresholds+- [ ] Latency thresholds+- [ ] Uptime monitoring+- [ ] Resource alerts+- [ ] On-call rotation configured++### Dashboards+- [ ] Overview dashboard+- [ ] API performance+- [ ] Database metrics+- [ ] Business KPIs+- [ ] Status page (public)++## When to Use This Skill++Invoke this skill when:+- Setting up monitoring for a new project+- Creating health check endpoints+- Implementing metrics collection+- Configuring alerting rules+- Building monitoring dashboards+- Setting up status pages+- Debugging performance issues+- Planning capacitydiff --git a/skills/nlp-pipeline-builder/SKILL.md b/skills/nlp-pipeline-builder/SKILL.mdnew file mode 100644index 0000000..9b5f8f1--- /dev/null+++ b/skills/nlp-pipeline-builder/SKILL.md@@ -0,0 +1,286 @@+---+name: NLP Pipeline Builder+slug: nlp-pipeline-builder+description: Build natural language processing pipelines for text analysis and understanding+category: ai-ml+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "build NLP pipeline"+ - "text processing"+ - "NLP workflow"+ - "language processing"+ - "text analysis"+tags:+ - NLP+ - text-processing+ - pipeline+ - language+ - analysis+---++# NLP Pipeline Builder++The NLP Pipeline Builder skill guides you through designing and implementing natural language processing pipelines that transform raw text into structured, actionable insights. From preprocessing to advanced analysis, this skill covers the full spectrum of NLP tasks and helps you choose the right approach for your specific needs.++Modern NLP offers multiple paradigms: rule-based approaches, classical ML, and deep learning/LLMs. This skill helps you navigate these options, building pipelines that balance accuracy, latency, cost, and maintainability. Whether you need real-time processing at scale or deep analysis of specific documents, this skill ensures your pipeline is fit for purpose.++From tokenization to semantic analysis, from single documents to streaming text, this skill helps you build robust NLP systems that handle real-world text with all its messiness and complexity.++## Core Workflows++### Workflow 1: Design NLP Pipeline Architecture+1. **Define** requirements:+ - Input: What text? What format? What volume?+ - Output: What information to extract?+ - Constraints: Latency, accuracy, cost+2. **Select** pipeline stages:+ ```+ Standard NLP Pipeline:+ Text → Preprocessing → Tokenization → Feature Extraction → Task Model → Output++ Example stages:+ - Preprocessing: cleaning, normalization+ - Linguistic: tokenization, POS, NER, parsing+ - Semantic: embeddings, topic modeling+ - Task-specific: classification, extraction, generation+ ```+3. **Choose** approach per stage:+ | Stage | Classical | Deep Learning | LLM |+ |-------|-----------|---------------|-----|+ | Tokenization | Regex, NLTK | SentencePiece | Model-specific |+ | NER | CRF, rules | BiLSTM-CRF, BERT | Prompt-based |+ | Classification | SVM, NB | CNN, BERT | Zero/few-shot |+ | Extraction | Regex, patterns | Seq2Seq | Prompt-based |+4. **Design** error handling and fallbacks+5. **Document** architecture++### Workflow 2: Implement Text Preprocessing+1. **Clean** text:+ ```python+ def clean_text(text):+ # Normalize unicode+ text = unicodedata.normalize("NFKC", text)++ # Remove or replace problematic characters+ text = remove_control_characters(text)++ # Normalize whitespace+ text = " ".join(text.split())++ # Optionally: lowercase, remove punctuation, etc.+ # (depends on downstream tasks)++ return text+ ```+2. **Segment** into units:+ - Sentence splitting+ - Paragraph detection+ - Document structuring+3. **Tokenize** appropriately:+ - Word tokenization for analysis+ - Subword tokenization for models+ - Language-specific considerations+4. **Normalize** for consistency:+ - Case normalization+ - Lemmatization/stemming+ - Handling contractions, abbreviations++### Workflow 3: Build Production NLP System+1. **Set up** processing infrastructure:+ ```python+ class NLPPipeline:+ def __init__(self, config):+ self.preprocessor = TextPreprocessor(config)+ self.tokenizer = load_tokenizer(config.tokenizer)+ self.models = {+ "ner": load_model(config.ner_model),+ "sentiment": load_model(config.sentiment_model),+ "classification": load_model(config.classifier)+ }+ self.cache = ResultCache() if config.use_cache else None++ def process(self, text, tasks=None):+ tasks = tasks or ["all"]++ # Preprocessing+ cleaned = self.preprocessor.clean(text)+ tokens = self.tokenizer.tokenize(cleaned)++ # Run requested analyses+ results = {"text": text, "tokens": tokens}+ for task, model in self.models.items():+ if task in tasks or "all" in tasks:+ results[task] = model.predict(tokens)++ return results+ ```+2. **Implement** batching for throughput+3. **Add** caching for repeated inputs+4. **Set up** monitoring and logging+5. **Test** with diverse inputs++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Design pipeline | "Design NLP pipeline for [task]" |+| Preprocess text | "How to preprocess [text type]" |+| Choose tokenizer | "Best tokenizer for [use case]" |+| Extract entities | "Extract entities from text" |+| Classify text | "Build text classifier" |+| Scale pipeline | "Scale NLP to [volume]" |++## Best Practices++- **Understand Your Text**: Different text requires different treatment+ - Social media: informal, abbreviations, emoji+ - Legal/medical: domain terms, structure+ - Multilingual: language detection, appropriate tools++- **Preserve What Matters**: Preprocessing shouldn't destroy information+ - Don't lowercase if case is meaningful+ - Keep punctuation if it affects meaning+ - Document all transformations++- **Handle Encoding Correctly**: Unicode is tricky+ - Always normalize (NFKC recommended)+ - Handle encoding errors gracefully+ - Test with diverse scripts and characters++- **Batch for Efficiency**: Model inference is expensive+ - Batch inputs for GPU utilization+ - Balance batch size vs latency+ - Use async processing where appropriate++- **Fail Gracefully**: Text is messy and unpredictable+ - Handle empty, too-long, or malformed inputs+ - Provide sensible defaults for edge cases+ - Log failures for analysis++- **Version Your Pipeline**: Reproducibility matters+ - Pin model versions+ - Document preprocessing steps+ - Track configuration changes++## Advanced Techniques++### Multi-Stage Extraction Pipeline+Chain extractors for complex information:+```python+class ExtractionPipeline:+ def __init__(self):+ self.ner = NERModel()+ self.relation = RelationExtractor()+ self.coreference = CoreferenceResolver()++ def extract(self, text):+ # Stage 1: Named Entity Recognition+ entities = self.ner.extract(text)++ # Stage 2: Coreference Resolution+ resolved = self.coreference.resolve(text, entities)++ # Stage 3: Relation Extraction+ relations = self.relation.extract(text, resolved)++ # Stage 4: Build knowledge graph+ graph = build_graph(resolved, relations)++ return {+ "entities": resolved,+ "relations": relations,+ "graph": graph+ }+```++### Hybrid Classical + LLM Pipeline+Use LLMs where they add value, classical where they don't:+```python+class HybridPipeline:+ def process(self, text):+ # Fast classical preprocessing+ cleaned = classical_clean(text)+ sentences = classical_sentence_split(cleaned)++ # Classical NER (fast, predictable)+ entities = classical_ner(sentences)++ # LLM for complex tasks (slower, more capable)+ sentiment = llm_sentiment(text) # Nuanced sentiment+ summary = llm_summarize(text) # Abstractive summary++ return {+ "sentences": sentences,+ "entities": entities, # Classical+ "sentiment": sentiment, # LLM+ "summary": summary # LLM+ }+```++### Streaming Text Processing+Handle continuous text streams:+```python+class StreamingNLP:+ def __init__(self, batch_size=32, timeout_ms=100):+ self.batch_size = batch_size+ self.timeout_ms = timeout_ms+ self.buffer = []+ self.last_process_time = time.time()++ async def add(self, text):+ self.buffer.append(text)++ # Process if batch full or timeout+ if len(self.buffer) >= self.batch_size:+ return await self.flush()+ elif (time.time() - self.last_process_time) * 1000 > self.timeout_ms:+ return await self.flush()++ async def flush(self):+ if not self.buffer:+ return []++ batch = self.buffer+ self.buffer = []+ self.last_process_time = time.time()++ # Batch process+ results = await self.pipeline.process_batch(batch)+ return results+```++### Language Detection and Routing+Handle multilingual text:+```python+class MultilingualPipeline:+ def __init__(self):+ self.detector = LanguageDetector()+ self.pipelines = {+ "en": EnglishPipeline(),+ "es": SpanishPipeline(),+ "zh": ChinesePipeline(),+ "default": UniversalPipeline()+ }++ def process(self, text):+ lang = self.detector.detect(text)+ pipeline = self.pipelines.get(lang, self.pipelines["default"])++ return {+ "language": lang,+ "results": pipeline.process(text)+ }+```++## Common Pitfalls to Avoid++- Over-preprocessing and destroying meaningful information+- Ignoring Unicode normalization and encoding issues+- Using word tokenizers for languages without spaces+- Not handling edge cases (empty text, very long text)+- Assuming English-only when users may send other languages+- Running expensive models on every input when caching would help+- Not batching model inference for throughput+- Ignoring the latency impact of pipeline stagesdiff --git a/skills/nps-survey-creator/SKILL.md b/skills/nps-survey-creator/SKILL.mdnew file mode 100644index 0000000..6e9650a--- /dev/null+++ b/skills/nps-survey-creator/SKILL.md@@ -0,0 +1,361 @@+---+name: NPS Survey Creator+slug: nps-survey-creator+description: Create, deploy, and analyze Net Promoter Score surveys to measure customer loyalty+category: customer-support+complexity: moderate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "nps"+ - "net promoter score"+ - "customer loyalty"+ - "promoter survey"+ - "customer satisfaction survey"+ - "loyalty measurement"+tags:+ - nps+ - surveys+ - customer-loyalty+ - metrics+ - customer-success+---++# NPS Survey Creator++Expert Net Promoter Score survey system that helps you measure, analyze, and act on customer loyalty data. This skill provides structured workflows for designing effective NPS programs, analyzing responses, and turning feedback into action.++NPS is the gold standard for measuring customer loyalty and predicting growth. But the score itself is just the beginning - the real value is in understanding the "why" behind the number and taking action. This skill helps you build an NPS program that drives improvement, not just measurement.++Built on customer research best practices and NPS methodology, this skill combines survey design, statistical analysis, and closed-loop processes to maximize the value of every response.++## Core Workflows++### Workflow 1: NPS Program Design+**Set up a comprehensive NPS measurement system**++1. **Survey Type Selection**+ | Type | When to Use | Timing |+ |------|-------------|--------|+ | Relationship NPS | Overall brand loyalty | Quarterly or semi-annually |+ | Transactional NPS | After specific interaction | Post-event (support, purchase) |+ | Product NPS | Product-specific feedback | After usage milestone |++2. **Survey Questions**+ - **Core NPS Question**: "How likely are you to recommend [Company/Product] to a friend or colleague?" (0-10)+ - **Follow-up (Required)**: "What's the primary reason for your score?"+ - **Optional Drivers**: Specific aspects to rate (product, support, value)+ - **Demographics**: Role, tenure, use case (for segmentation)++3. **Survey Design Principles**+ - Keep surveys short (2-4 questions max)+ - Make follow-up question open-ended+ - Don't combine with other surveys+ - Test on mobile devices+ - Use consistent branding++4. **Sample Survey Flow**+ ```+ Screen 1: NPS Question (0-10 scale)+ Screen 2: Open-ended follow-up+ Screen 3: (Optional) One additional question+ Screen 4: Thank you + close loop preview+ ```++### Workflow 2: Targeting & Timing+**Reach the right customers at the right time**++1. **Timing Strategies**+ - **Relationship NPS**:+ - Quarterly cadence (not more frequent)+ - Stagger sends to avoid survey fatigue+ - Avoid holidays and major events+ - **Transactional NPS**:+ - Within 24-48 hours of interaction+ - After meaningful engagement+ - Not after every interaction++2. **Sampling Considerations**+ - Random sample for unbiased results+ - Stratified sample for segment representation+ - Census for small customer bases+ - Exclude recent surveyees (90-day minimum gap)++3. **Audience Targeting**+ | Segment | Frequency | Purpose |+ |---------|-----------|---------|+ | All Customers | Quarterly | Overall trend |+ | Enterprise | Quarterly | High-value focus |+ | New Customers | At 30/90 days | Onboarding health |+ | At-Risk | After intervention | Save effectiveness |+ | Post-Support | After resolution | Service quality |++4. **Channel Selection**+ - Email (most common, highest response for B2B)+ - In-app (contextual, good for product NPS)+ - SMS (high open rates, use sparingly)+ - Post-call IVR (immediate support feedback)++### Workflow 3: Response Analysis+**Extract insights from NPS data**++1. **Score Calculation**+ ```+ NPS = % Promoters (9-10) - % Detractors (0-6)++ Score ranges from -100 to +100+ ```++ | Category | Score Range | Meaning |+ |----------|-------------|---------|+ | Promoters | 9-10 | Loyal enthusiasts |+ | Passives | 7-8 | Satisfied but unenthusiastic |+ | Detractors | 0-6 | Unhappy, risk of churn |++2. **Statistical Validity**+ - Minimum 100 responses for reliable score+ - Calculate confidence intervals+ - Track response rate (aim for 30%+)+ - Note sample size in reporting+ - Compare statistically significant changes only++3. **Segmentation Analysis**+ - By customer segment (size, industry, tier)+ - By tenure (new vs. established)+ - By product/feature usage+ - By geography+ - By use case++4. **Trend Analysis**+ - Track score over time (quarterly minimum)+ - Identify seasonal patterns+ - Correlate with product changes+ - Compare to industry benchmarks+ - Monitor category shifts (Detractor → Passive)++### Workflow 4: Text Analysis+**Understand the "why" behind the score**++1. **Comment Categorization**+ - **Product**: Features, functionality, reliability+ - **Service**: Support, responsiveness, expertise+ - **Value**: Pricing, ROI, worth+ - **Experience**: UX, ease of use, design+ - **Company**: Brand, trust, relationship++2. **Sentiment Mapping**+ | Score | Typical Themes |+ |-------|----------------|+ | 9-10 | What they love most |+ | 7-8 | What would make them promoters |+ | 4-6 | Key frustrations to address |+ | 0-3 | Critical issues driving away |++3. **Quote Extraction**+ - Identify representative quotes per theme+ - Capture specific, actionable feedback+ - Note emotional intensity+ - Flag verbatims for stakeholders++4. **Driver Analysis**+ - Correlate themes with scores+ - Identify strongest positive drivers+ - Find detractor common causes+ - Prioritize by frequency and impact++### Workflow 5: Close the Loop+**Turn feedback into action and follow-up**++1. **Response Triage**+ | Score | Response | Timeline |+ |-------|----------|----------|+ | 0-3 | Personal outreach by CSM/manager | 24-48 hours |+ | 4-6 | CSM follow-up email | Within 1 week |+ | 7-8 | Thank you + what would make it better | Automated |+ | 9-10 | Thank you + advocacy ask | Automated |++2. **Detractor Recovery**+ - Personal call from appropriate level+ - Listen without defending+ - Acknowledge the issue+ - Commit to specific action+ - Follow up on resolution+ - Re-survey after resolution++3. **Promoter Activation**+ - Thank for positive feedback+ - Ask for specific advocacy actions:+ - Review on G2/Capterra+ - Case study participation+ - Reference call availability+ - Social media mention+ - Offer exclusive benefits (beta access, etc.)++4. **Organizational Action**+ - Share insights with product/engineering+ - Create improvement initiatives+ - Track issue → action → impact+ - Communicate changes to customers+ - Measure NPS impact of changes++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Create NPS survey | "Create NPS survey for [audience]" |+| Calculate NPS score | "Calculate NPS from responses" |+| Analyze comments | "Analyze NPS comments" |+| Generate report | "Create NPS report for [period]" |+| Segment analysis | "Break down NPS by [segment]" |+| Design follow-up | "Create NPS follow-up workflow" |+| Benchmark comparison | "Compare NPS to industry" |+| Trend analysis | "Show NPS trend over time" |+| Identify drivers | "Find NPS drivers from feedback" |+| Recovery playbook | "Create detractor recovery process" |++## Best Practices++### Survey Design+- Use standard 0-10 NPS scale (never modify)+- Keep survey to 2-3 questions maximum+- Make follow-up question required but open-ended+- Don't ask leading questions+- Test mobile experience++### Timing & Frequency+- Don't survey more than quarterly (relationship NPS)+- Wait 90 days before resurveying same customer+- Avoid surveying during known issues+- Time around customer lifecycle moments+- Respect opt-outs++### Response Rates+- Keep surveys short (2-3 minutes max)+- Send from recognizable sender+- Personalize subject line+- Send at optimal times (Tue-Thu, 10am-2pm)+- Follow up non-responders once++### Analysis+- Focus on trend, not single score+- Segment to find actionable insights+- Read every comment+- Look for patterns, not outliers+- Compare scores statistically++### Closing the Loop+- Respond to detractors within 48 hours+- Thank all respondents+- Share what you're doing with feedback+- Track feedback → action → outcome+- Measure recovery effectiveness++## NPS Benchmarks++### Industry Benchmarks+| Industry | Good | Great | World-Class |+|----------|------|-------|-------------|+| SaaS B2B | 30+ | 50+ | 70+ |+| E-commerce | 40+ | 60+ | 80+ |+| Financial Services | 20+ | 40+ | 60+ |+| Telecom | 0+ | 20+ | 40+ |+| Healthcare | 20+ | 40+ | 60+ |++### Score Interpretation+| Score Range | Interpretation |+|-------------|----------------|+| Below 0 | Serious problems - more detractors than promoters |+| 0-30 | Room for improvement |+| 30-50 | Good - solid foundation |+| 50-70 | Excellent - strong loyalty |+| 70+ | World-class - exceptional |++## Survey Templates++### Relationship NPS Email+```+Subject: [Name], we'd love your feedback (30 seconds)++Hi [Name],++As a valued [Company] customer, your opinion matters to us.++One quick question: How likely are you to recommend [Company] to a friend or colleague?++[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]+Not at all likely Extremely likely++Click a number to share your response.++Thank you for your time!++[Company] Team+```++### Follow-Up Question+```+Thanks for your feedback!++What's the primary reason for your score?++[Open text field - required]++[Submit]+```++### Thank You Screen (Promoter)+```+Thank you for your feedback! 🙏++We're thrilled you'd recommend us.++Would you be willing to:+[ ] Write a brief review on G2/Capterra+[ ] Be a reference for future customers+[ ] Share your experience in a case study++[Submit] [Not right now]+```++### Detractor Follow-Up Email+```+Subject: Following up on your feedback++Hi [Name],++I saw your recent feedback about [Company], and I wanted to reach out personally.++I'm sorry we haven't met your expectations. I'd love to understand more about your experience and see how we can make things right.++Would you have 15 minutes this week for a call?++I'm committed to addressing your concerns.++Best,+[Name]+[Title]+[Direct line]+```++## Red Flags++- **Low response rate**: Below 15% suggests survey fatigue or poor targeting+- **Score volatility**: Large swings indicate inconsistent experience+- **Comment mismatch**: Score doesn't align with sentiment+- **Passive majority**: Large passive segment is stalled growth+- **No action**: Collecting data without acting on it+- **Survey fatigue**: Response rates declining over time+- **Score gaming**: Internal pressure to inflate scores+- **Missing segments**: Not hearing from key customer groups++## Metrics to Track++| Metric | What It Tells You | Target |+|--------|-------------------|--------|+| Overall NPS | Customer loyalty level | Industry benchmark + 10 |+| Response Rate | Survey engagement | 30%+ |+| Promoter % | Advocacy potential | 50%+ |+| Detractor % | Churn risk pool | < 15% |+| Comment Rate | Feedback quality | 70%+ of responses |+| Close Rate | Follow-up effectiveness | 100% of detractors |+| Recovery Rate | Detractor win-back | 20%+ to passive/promoter |diff --git a/skills/onboarding-designer/SKILL.md b/skills/onboarding-designer/SKILL.mdnew file mode 100644index 0000000..fbdf8fd--- /dev/null+++ b/skills/onboarding-designer/SKILL.md@@ -0,0 +1,403 @@+---+name: Onboarding Designer+slug: onboarding-designer+description: Design effective user onboarding flows that drive activation, adoption, and retention+category: customer-support+complexity: complex+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "onboarding"+ - "user onboarding"+ - "activation flow"+ - "first-time user"+ - "welcome flow"+ - "product tour"+ - "user activation"+tags:+ - onboarding+ - activation+ - user-experience+ - retention+ - customer-success+---++# Onboarding Designer++Expert user onboarding system that transforms first-time visitors into activated, successful users. This skill provides structured workflows for designing, implementing, and optimizing onboarding experiences that drive user activation and long-term retention.++Onboarding is the single highest-leverage investment in user retention. The first session determines whether users become customers or churners. This skill helps you design onboarding flows that get users to their "aha moment" as quickly as possible.++Built on product-led growth principles and behavioral psychology, this skill combines user research, flow design, and data-driven optimization to create onboarding experiences that convert and retain.++## Core Workflows++### Workflow 1: Activation Definition+**Define what "activated" means for your product**++1. **Aha Moment Discovery**+ - Analyze user cohorts (retained vs. churned)+ - Identify behaviors correlated with retention+ - Find the minimum valuable action+ - Define time window for activation (first 7 days typical)+ - Document the activation metric++2. **Activation Criteria Examples**+ | Product Type | Activation Metric |+ |--------------|-------------------|+ | SaaS Tool | Completed core action 3+ times |+ | Marketplace | Made first purchase |+ | Social App | Added 5+ connections |+ | Productivity | Created first project/item |+ | B2B Platform | Invited team member |++3. **Activation Funnel**+ - Signup completed+ - Profile/account setup+ - Core feature discovery+ - First meaningful action+ - Repeat action (confirms value)++4. **Measurement Framework**+ - Define each funnel step precisely+ - Set up event tracking+ - Calculate conversion between steps+ - Benchmark against industry standards+ - Set improvement targets++### Workflow 2: Onboarding Flow Design+**Design the path from signup to activation**++1. **Flow Architecture Options**+ - **Linear**: Step-by-step guided sequence+ - **Progressive**: Reveal features as user advances+ - **Checklist**: Self-directed with progress tracking+ - **Contextual**: Just-in-time tips during usage+ - **Hybrid**: Combination approach++2. **Flow Components**+ - **Welcome Screen**: Set expectations, show value+ - **Account Setup**: Collect essential info only+ - **Product Tour**: Highlight key features+ - **First Task**: Guide to initial success+ - **Progress Indicators**: Show completion status+ - **Empty States**: Guide users when no data exists++3. **Personalization Factors**+ - User role/persona+ - Use case/goal+ - Company size+ - Prior experience+ - Entry point/referral source++4. **Flow Principles**+ - Minimize steps to activation+ - Show progress and momentum+ - Celebrate small wins+ - Allow skip but encourage completion+ - Provide escape hatches++### Workflow 3: Content & Messaging+**Write copy that motivates and guides**++1. **Welcome Messaging**+ - Acknowledge the user's goal+ - Preview the value they'll get+ - Set clear expectations+ - Create excitement without overwhelming++2. **Instructional Content**+ - Action-oriented headlines+ - One instruction per screen+ - Visual > text when possible+ - Benefits alongside features+ - Progress indicators++3. **Microcopy Patterns**+ - Buttons: Specific actions ("Create my first project")+ - Labels: Clear, jargon-free+ - Tooltips: Concise, contextual+ - Errors: Helpful, not blaming+ - Empty states: Actionable guidance++4. **Motivation Techniques**+ - Social proof (X users did this)+ - Progress visualization+ - Immediate value demonstration+ - Personalization ("Your dashboard")+ - Commitment and consistency++### Workflow 4: Email Onboarding Sequence+**Support in-app flow with email nurture**++1. **Email Sequence Structure**+ | Day | Email Purpose |+ |-----|---------------|+ | 0 | Welcome + quick win action |+ | 1 | Core feature highlight |+ | 3 | Use case example/inspiration |+ | 5 | Overcome common objection |+ | 7 | Activation check-in or social proof |+ | 14 | Advanced feature or upgrade prompt |++2. **Email Content Principles**+ - One clear CTA per email+ - Link to specific in-app action+ - Keep under 150 words+ - Personalize with user data+ - A/B test subject lines++3. **Behavioral Triggers**+ - Incomplete setup → reminder+ - No login in X days → re-engagement+ - Used feature → related feature intro+ - Approaching limit → upgrade prompt+ - Activation achieved → celebration++4. **Segmentation**+ - By activation status+ - By user persona/role+ - By feature usage+ - By engagement level+ - By signup source++### Workflow 5: Measurement & Optimization+**Track performance and iterate**++1. **Key Metrics**+ - **Activation Rate**: % of signups reaching activated state+ - **Time to Activate**: Days/hours from signup to activation+ - **Funnel Conversion**: % completing each step+ - **Drop-off Points**: Where users abandon+ - **Return Rate**: % returning after first session++2. **Funnel Analysis**+ - Map each onboarding step to event+ - Calculate step-to-step conversion+ - Identify biggest drop-offs+ - Segment by user attributes+ - Compare cohorts over time++3. **Optimization Experiments**+ - A/B test step order+ - Test copy variations+ - Try different UI patterns+ - Experiment with personalization+ - Test email timing and content++4. **Qualitative Research**+ - User session recordings+ - New user interviews+ - Support ticket analysis+ - Churn surveys+ - In-app feedback collection++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Define activation | "Define activation metric for [product]" |+| Design onboarding flow | "Create onboarding flow for [product]" |+| Write onboarding copy | "Write onboarding content for [step]" |+| Create email sequence | "Design onboarding email sequence" |+| Analyze drop-offs | "Analyze onboarding funnel" |+| Optimize step | "Improve onboarding for [step]" |+| Design empty state | "Create empty state for [feature]" |+| Create product tour | "Design product tour for [feature]" |+| Build checklist | "Create onboarding checklist" |+| Review competitors | "Analyze competitor onboarding" |++## Best Practices++### Flow Design+- Get users to value in under 5 minutes+- Collect only essential information upfront+- Defer non-critical setup until later+- Show, don't tell (interactive > instructional)+- Make first action feel successful++### Personalization+- Ask about goals, not demographics+- Use responses to customize experience+- Show relevant use cases and examples+- Skip steps that don't apply+- Remember choices in future sessions++### Progress & Motivation+- Show completion percentage+- Celebrate milestone achievements+- Use checklists for multi-step processes+- Provide quick wins early+- Create momentum through small successes++### Friction Reduction+- Minimize form fields+- Allow social/SSO signup+- Pre-fill what you can+- Provide smart defaults+- Skip optional steps by default++### Recovery+- Save progress if user leaves+- Send re-engagement emails+- Provide multiple entry points+- Don't restart completed steps+- Offer help when stuck++## Onboarding Patterns++### Pattern 1: Welcome Modal+```+[Visual: Product screenshot or illustration]++# Welcome to [Product], [Name]!++You're about to [key benefit].++Let's get you set up in just 2 minutes.++[Get Started] [Skip for now]+```++### Pattern 2: Step-by-Step Setup+```+Step 1 of 4: [Step Name]++[Clear instruction]++[Input or action area]++[Visual hint or example]++[Back] [Continue]++Progress: ████░░░░░░ 40%+```++### Pattern 3: Checklist Dashboard+```+# Getting Started++Complete these steps to get the most from [Product]:++☑ Create your account+☐ Set up your profile+☐ Connect your [integration]+☐ Create your first [item]+☐ Invite your team++[3 of 5 complete - 60%]+```++### Pattern 4: Empty State with Guidance+```+[Illustration]++# No [items] yet++[Items] help you [benefit].++Create your first one to see [Product] in action.++[Create [Item]]++---+Need inspiration? [See examples]+```++### Pattern 5: Contextual Tooltip+```+┌─────────────────────────────────┐+│ 💡 Pro tip │+│ │+│ Click here to [action] and │+│ [benefit explanation]. │+│ │+│ [Got it] [Show me more] │+└─────────────────────────────────┘+```++## Email Templates++### Day 0: Welcome Email+```+Subject: You're in! Here's your quick start guide++Hi [Name],++Welcome to [Product]!++You just took the first step toward [key benefit].++Here's how to get value in the next 5 minutes:++1. [Quick action with link]++That's it. Do that one thing and you'll see why [Product] is different.++Questions? Just reply to this email.++[CTA: Complete Your First [Action]]++— The [Product] Team+```++### Day 3: Use Case Inspiration+```+Subject: How [Customer] uses [Product] to [result]++Hi [Name],++Wondering what's possible with [Product]?++Here's how [Customer Name] uses it:++"[Short testimonial about specific use case and result]"++You can do the same thing in [Product] by:+1. [Step with link]+2. [Step with link]++[CTA: Try This Now]+```++### Day 7: Activation Check-In+```+Subject: Quick question about your experience++Hi [Name],++I noticed you [signed up but haven't / started to] [key action].++Is everything working okay? I'd love to help if you're stuck.++Just hit reply and let me know:+- What were you hoping to accomplish?+- What's getting in the way?++I read every response personally.++— [Name], [Title] at [Product]+```++## Red Flags++- **Information overload**: Too many features introduced at once+- **No quick win**: Users don't experience value in first session+- **Forced completion**: Can't skip non-essential steps+- **No personalization**: Same flow for all user types+- **Missing progress**: No indication of how much is left+- **Dead ends**: Steps without clear next actions+- **Lost progress**: Starting over if user leaves+- **Jargon**: Using internal terminology++## Metrics Benchmarks++| Metric | Good | Great | Best-in-Class |+|--------|------|-------|---------------|+| Signup to Activation | 30% | 50% | 70%+ |+| Time to Activate | 7 days | 3 days | Same session |+| First Session Duration | 5 min | 10 min | 15+ min |+| Day 1 Return | 25% | 40% | 60%+ |+| Day 7 Return | 15% | 25% | 40%+ |+| Onboarding Completion | 40% | 60% | 80%+ |diff --git a/skills/outreach-sequencer/SKILL.md b/skills/outreach-sequencer/SKILL.mdnew file mode 100644index 0000000..0a7a094--- /dev/null+++ b/skills/outreach-sequencer/SKILL.md@@ -0,0 +1,98 @@+---+name: Outreach Sequencer+slug: outreach-sequencer+description: Create multi-touch email outreach sequences that drive responses and meetings+category: sales+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "outreach sequence"+ - "email cadence"+ - "follow-up sequence"+ - "cold email sequence"+ - "sales sequence"+tags:+ - email-outreach+ - sales-development+ - prospecting+ - cadence+ - automation+---++# Outreach Sequencer++Design and optimize multi-touch email sequences that cut through inbox noise and drive meaningful conversations. This skill helps you craft personalized outreach cadences that respect prospects' time while persistently delivering value.++Cold outreach is hard. Most emails get ignored. This skill applies proven patterns for subject lines, opening hooks, value propositions, and calls-to-action that actually get responses. Learn optimal timing, sequence length, and personalization tactics that turn cold prospects into warm meetings.++Built for SDRs, BDRs, account executives, founders doing outbound, and anyone who needs to start conversations with prospects who don't know them yet.++## Core Workflows++### Workflow 1: Cold Outreach Sequence+1. **Prospect Research** - Gather context for personalization+2. **Email 1: Pattern Interrupt** - Stand out with unexpected opening+3. **Email 2: Value Add** - Share relevant insight or resource+4. **Email 3: Social Proof** - Reference similar customer success+5. **Email 4: Objection Preempt** - Address common hesitations+6. **Email 5: Breakup Email** - Create scarcity, offer easy out+7. **Timing Optimization** - Set delays between touches++### Workflow 2: Multi-Channel Sequence+1. **Channel Mapping** - Email, LinkedIn, phone, video touchpoints+2. **Touch Orchestration** - Sequence channels strategically+3. **Email Foundations** - Core messaging across emails+4. **LinkedIn Integration** - Connection requests and InMails+5. **Phone Scripts** - Voicemail and live conversation guides+6. **Video Messages** - Personalized video touchpoints+7. **Unified Tracking** - Measure engagement across channels++### Workflow 3: Re-Engagement Sequence+1. **Dormant Lead Identification** - Find gone-dark contacts+2. **Trigger Research** - Find new reason to reach out+3. **New Value Angle** - Offer fresh perspective or insight+4. **Lower Commitment Ask** - Reduce friction for re-engagement+5. **Multiple Attempts** - Persist with varied approaches+6. **Channel Switch** - Try different communication methods+7. **Sunset Decision** - Know when to move on++### Workflow 4: Warm Introduction Sequence+1. **Referral Context** - Leverage the warm connection+2. **Introduction Email** - Reference mutual connection strongly+3. **Value Alignment** - Connect to referrer's recommendation+4. **Social Proof Stack** - Build on referrer's credibility+5. **Easy Next Step** - Low-friction call-to-action+6. **Referrer Update** - Keep introducer informed+7. **Relationship Nurture** - Maintain referral source++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Create sequence | "Build outreach sequence for [persona]" |+| Write cold email | "Write cold email to [role] at [company type]" |+| Subject line variants | "Generate 10 subject lines for [topic]" |+| Follow-up email | "Write follow-up for no response" |+| Breakup email | "Create breakup email for sequence" |+| Personalization hooks | "Find personalization angles for [prospect]" |+| Sequence timing | "What's optimal timing for [industry]?" |+| A/B test variants | "Create A/B test for [email element]" |++## Best Practices++- **Research first** - 10 minutes of research beats 10 generic emails+- **Pattern interrupt** - First line must earn the second+- **One ask per email** - Clarity beats comprehensiveness+- **Personalize authentically** - Fake personalization is worse than none+- **Front-load value** - Give before you ask+- **Respect timing** - 3-5 business days between emails typically+- **Vary your approach** - Each email should feel different+- **Use social proof** - Name-drop relevant customers+- **Test everything** - Subject lines, send times, CTAs+- **Keep it short** - Under 125 words typically performs best+- **Mobile-first** - Most emails read on phones+- **Clear CTA** - One obvious next step+- **Include breakup** - Creates urgency, respects time+- **Track and iterate** - Measure open rates, reply rates, meeting rates+- **Stay human** - Automation shouldn't feel automateddiff --git a/skills/pricing-page-optimizer/SKILL.md b/skills/pricing-page-optimizer/SKILL.mdnew file mode 100644index 0000000..a93be4c--- /dev/null+++ b/skills/pricing-page-optimizer/SKILL.md@@ -0,0 +1,99 @@+---+name: Pricing Page Optimizer+slug: pricing-page-optimizer+description: Optimize pricing page presentation for maximum conversion+category: marketing+complexity: advanced+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "pricing page"+ - "pricing optimization"+ - "plan comparison"+ - "pricing presentation"+ - "plan selection"+tags:+ - pricing+ - conversion-optimization+ - saas-pricing+ - monetization+ - pricing-strategy+---++# Pricing Page Optimizer++Transform your pricing page into a conversion engine that guides visitors to the right plan and encourages upgrades. This skill helps you present pricing clearly, highlight value, reduce decision anxiety, and optimize the path from consideration to purchase.++Your pricing page is where interest becomes commitment - or bounces. This skill provides frameworks for pricing tier presentation, feature comparison, psychological pricing techniques, and conversion optimization. Learn how to use anchoring, decoy pricing, and value framing to improve plan selection and average order value.++Essential for SaaS companies, subscription businesses, and anyone presenting tiered pricing to customers.++## Core Workflows++### Workflow 1: Pricing Page Audit+1. **First Impression Assessment** - Clarity in first 5 seconds+2. **Plan Differentiation** - Clear reasons to choose each tier+3. **Value Communication** - Is the value obvious?+4. **Decision Friction** - What slows down choice?+5. **Social Proof Placement** - Trust elements near pricing+6. **CTA Effectiveness** - Button copy and placement+7. **Mobile Experience** - Pricing on small screens+8. **Competitive Positioning** - How you compare to alternatives++### Workflow 2: Pricing Presentation Optimization+1. **Tier Naming** - Names that communicate value+2. **Price Anchoring** - Strategic high anchor placement+3. **Recommended Plan** - Visual hierarchy for target plan+4. **Feature Display** - What to show vs hide+5. **Comparison Matrix** - Clear feature differentiation+6. **Annual vs Monthly** - Toggle and savings display+7. **Social Proof Integration** - Customer counts, testimonials++### Workflow 3: Psychological Pricing Tactics+1. **Charm Pricing** - $99 vs $100 psychology+2. **Price Framing** - Per day/month/year presentation+3. **Decoy Pricing** - Strategic plan positioning+4. **Value Metrics** - Outcome-based framing+5. **Loss Aversion** - What you miss without upgrade+6. **Scarcity and Urgency** - Time-limited offers+7. **Bundling Strategy** - Package value perception++### Workflow 4: Conversion Flow Optimization+1. **Entry Points** - How visitors arrive at pricing+2. **Information Architecture** - Pricing page structure+3. **FAQ Placement** - Answer objections inline+4. **Exit Intent** - Capture leaving visitors+5. **Personalization** - Dynamic pricing display+6. **Post-Selection Flow** - Checkout optimization+7. **Upgrade Paths** - In-product upgrade experience++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Audit pricing page | "Audit pricing page for [product]" |+| Optimize presentation | "Improve pricing page presentation" |+| Write plan copy | "Write copy for pricing tiers" |+| Feature comparison | "Create feature comparison matrix" |+| Plan naming | "Name pricing tiers for [product]" |+| Psychological review | "Apply pricing psychology to page" |+| Mobile optimization | "Optimize pricing for mobile" |+| Conversion test | "Create A/B test for pricing page" |++## Best Practices++- **Show value first** - Price is relative to perceived value+- **Limit choices** - 3-4 plans maximum+- **Highlight recommended** - Visual emphasis on target plan+- **Price left, features right** - Natural reading flow+- **Clear differentiation** - Obvious reasons to upgrade+- **Annual savings visible** - Show monthly vs annual savings+- **Social proof** - Customer logos and testimonials+- **FAQ answers objections** - Address pricing concerns+- **Mobile-first design** - Price tables that work on phones+- **Consistent CTAs** - Same action for each tier+- **No hidden fees** - Transparency builds trust+- **Show plan limits** - Clear usage boundaries+- **Upgrade path clear** - How to move up later+- **Test relentlessly** - Pricing pages benefit from A/B testing+- **Competitor awareness** - Know how you comparediff --git a/skills/rag-pipeline-builder/SKILL.md b/skills/rag-pipeline-builder/SKILL.mdnew file mode 100644index 0000000..6c15aaa--- /dev/null+++ b/skills/rag-pipeline-builder/SKILL.md@@ -0,0 +1,213 @@+---+name: RAG Pipeline Builder+slug: rag-pipeline-builder+description: Build retrieval-augmented generation systems that ground LLM responses in your data+category: ai-ml+complexity: advanced+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "build RAG"+ - "retrieval augmented generation"+ - "RAG pipeline"+ - "ground LLM in data"+ - "knowledge base AI"+tags:+ - RAG+ - retrieval+ - LLM+ - embeddings+ - vector-search+---++# RAG Pipeline Builder++The RAG Pipeline Builder skill guides you through designing and implementing Retrieval-Augmented Generation systems that enhance LLM responses with relevant context from your own data. RAG combines the power of large language models with the precision of information retrieval, reducing hallucinations and enabling AI to work with private, current, or domain-specific knowledge.++This skill covers the complete RAG stack: document ingestion, chunking strategies, embedding generation, vector storage, retrieval optimization, context injection, and response generation. It helps you make informed decisions at each stage based on your specific requirements for accuracy, latency, cost, and scale.++Whether you are building a documentation Q&A bot, a customer support system, or an enterprise knowledge assistant, this skill ensures your RAG implementation follows production best practices.++## Core Workflows++### Workflow 1: Design RAG Architecture+1. **Define** requirements:+ - Data sources and formats+ - Query types and patterns+ - Accuracy requirements+ - Latency budget+ - Scale expectations+2. **Choose** components:+ - Document loaders+ - Chunking strategy+ - Embedding model+ - Vector database+ - LLM for generation+ - Reranking layer (optional)+3. **Design** data flow:+ ```+ Documents → Loader → Chunker → Embedder → Vector DB+ ↓+ Query → Embedder → Vector Search → Reranker → Context+ ↓+ Context + Query → LLM → Response+ ```+4. **Document** architecture decisions++### Workflow 2: Implement Ingestion Pipeline+1. **Set up** document loaders:+ - PDF, Markdown, HTML parsers+ - API connectors for live sources+ - Incremental update handling+2. **Implement** chunking:+ ```python+ def smart_chunk(doc, chunk_size=500, overlap=50):+ # Respect document structure+ sections = extract_sections(doc)+ chunks = []+ for section in sections:+ if len(section) > chunk_size:+ chunks.extend(sliding_window(section, chunk_size, overlap))+ else:+ chunks.append(section)+ return add_metadata(chunks, doc)+ ```+3. **Generate** embeddings with batching+4. **Store** in vector database with metadata+5. **Verify** ingestion quality++### Workflow 3: Optimize Retrieval Quality+1. **Measure** baseline retrieval performance:+ - Recall@k for known queries+ - Mean Reciprocal Rank (MRR)+ - Relevance scoring+2. **Apply** optimization techniques:+ - Query expansion/rewriting+ - Hybrid search (semantic + keyword)+ - Reranking with cross-encoders+ - Metadata filtering+3. **Tune** retrieval parameters:+ - Number of chunks to retrieve (k)+ - Similarity threshold+ - Diversity/MMR settings+4. **Validate** improvements with test set++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Design RAG system | "Help me design a RAG pipeline for [use case]" |+| Choose vector DB | "Which vector database for RAG" |+| Optimize chunking | "Best chunking strategy for [content type]" |+| Improve retrieval | "My RAG has poor retrieval quality" |+| Reduce hallucinations | "RAG still hallucinating, help fix" |+| Scale pipeline | "Scale RAG to [X] documents" |++## Best Practices++- **Chunk at Semantic Boundaries**: Preserve meaning in chunks+ - Good: Split at paragraphs, sections, or topic boundaries+ - Bad: Fixed-size splits that cut sentences mid-thought+ - Include section headers as context in chunks++- **Include Rich Metadata**: Enable filtering and context+ - Source document, section, page number+ - Timestamps for temporal relevance+ - Categories, tags, or topics+ - Use metadata filters before semantic search++- **Use Hybrid Search**: Combine semantic and keyword search+ - Semantic: Captures meaning and synonyms+ - Keyword (BM25): Catches exact terms, names, codes+ - Weight combination based on query type++- **Rerank for Quality**: Two-stage retrieval improves precision+ - Stage 1: Fast vector search (retrieve 20-50)+ - Stage 2: Cross-encoder reranking (keep top 5-10)+ - Reranking is slower but much more accurate++- **Show Your Work**: Include citations and sources+ - Return source chunks with responses+ - Enable users to verify and explore+ - Build trust through transparency++- **Handle Edge Cases**: What happens when retrieval fails?+ - No relevant results found+ - Conflicting information in sources+ - Query outside knowledge base scope+ - Implement graceful fallbacks++## Advanced Techniques++### Multi-Index Strategy+Use different indexes for different content types:+```+Index 1: FAQs (short, self-contained)+Index 2: Documentation (long-form, structured)+Index 3: Conversations (temporal, contextual)++Route queries to appropriate index based on intent+```++### Query Transformation Pipeline+Improve retrieval with query processing:+```python+def transform_query(query):+ # Step 1: Classify query type+ query_type = classify_query(query)++ # Step 2: Extract entities+ entities = extract_entities(query)++ # Step 3: Generate search queries+ if query_type == "factual":+ return generate_keyword_queries(query, entities)+ elif query_type == "conceptual":+ return generate_semantic_queries(query)+ else:+ return [query] # Use as-is+```++### Contextual Compression+Reduce noise in retrieved context:+```+Retrieved chunks (verbose) → LLM compressor → Relevant excerpts only+```++### Agentic RAG+Let the LLM control retrieval:+```python+def agentic_rag(query):+ # LLM decides what to search for+ search_plan = llm.plan_searches(query)++ # Execute searches+ results = []+ for search in search_plan:+ results.extend(retriever.search(search.query, filters=search.filters))++ # LLM synthesizes answer+ return llm.synthesize(query, results)+```++### Evaluation Framework+Continuously measure RAG quality:+```+Metrics:+- Retrieval: Precision@k, Recall@k, MRR+- Generation: Faithfulness, Answer Relevance, Context Utilization+- End-to-end: Task Success Rate, User Satisfaction++Tools: Ragas, TruLens, LangSmith+```++## Common Pitfalls to Avoid++- Chunking too large (loses specificity) or too small (loses context)+- Not preserving document structure and hierarchy in chunks+- Ignoring keyword search when exact matches matter+- Retrieving too few chunks (missing information) or too many (context dilution)+- Not handling conflicting information across sources+- Assuming LLM will always use retrieved context correctly+- Skipping evaluation and monitoring in production+- Not updating embeddings when source documents changediff --git a/skills/referral-program-designer/SKILL.md b/skills/referral-program-designer/SKILL.mdnew file mode 100644index 0000000..78309ef--- /dev/null+++ b/skills/referral-program-designer/SKILL.md@@ -0,0 +1,98 @@+---+name: Referral Program Designer+slug: referral-program-designer+description: Design viral referral programs that drive customer acquisition+category: marketing+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "referral program"+ - "refer a friend"+ - "viral growth"+ - "word of mouth"+ - "customer referrals"+tags:+ - referral-marketing+ - viral-growth+ - customer-acquisition+ - word-of-mouth+ - growth-marketing+---++# Referral Program Designer++Create referral programs that turn happy customers into active promoters. This skill helps you design incentive structures, referral mechanics, and program experiences that motivate sharing and drive cost-effective customer acquisition.++Referrals are the gold standard of marketing - lower CAC, higher LTV, and built-in social proof. This skill provides frameworks for incentive design, program mechanics, viral loop optimization, and measurement. Learn from programs like Dropbox, Uber, and Airbnb to build referral engines that fuel growth.++Built for growth marketers, product managers, founders, and anyone looking to scale acquisition through word-of-mouth.++## Core Workflows++### Workflow 1: Referral Program Design+1. **Goal Setting** - What you want the program to achieve+2. **Customer Motivation Analysis** - Why would they refer?+3. **Incentive Structure** - What to offer referrers and referees+4. **Reward Mechanics** - When and how rewards are delivered+5. **Sharing Mechanics** - How referrals are made+6. **Tracking Design** - Attribution and fraud prevention+7. **Program Terms** - Rules and limitations++### Workflow 2: Incentive Optimization+1. **Incentive Type Selection** - Cash, credit, product, status+2. **Two-Sided Incentives** - Benefit for both parties+3. **Reward Timing** - Instant vs delayed gratification+4. **Tiered Rewards** - Increasing incentives for more referrals+5. **Milestone Bonuses** - Extra rewards for achievement+6. **A/B Testing Plan** - Test different incentive structures+7. **Economics Modeling** - Ensure sustainable unit economics++### Workflow 3: Program Launch+1. **MVP Program Design** - Minimum viable referral program+2. **Technical Requirements** - Tracking, attribution, rewards+3. **Communication Strategy** - How to promote the program+4. **In-Product Integration** - Where referral lives in experience+5. **Email Sequence** - Referral program nurture+6. **Launch Metrics** - Success indicators+7. **Optimization Roadmap** - Post-launch improvements++### Workflow 4: Viral Loop Enhancement+1. **Friction Audit** - Where do people drop off?+2. **Share Flow Optimization** - Make sharing effortless+3. **Message Customization** - Personalized referral messaging+4. **Multi-Channel Sharing** - Email, social, direct message+5. **Reminder Strategy** - Re-engage with referral reminders+6. **Viral Coefficient Calculation** - Measure program virality+7. **Loop Optimization** - Improve K-factor over time++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Design program | "Design referral program for [product/service]" |+| Incentive structure | "Create incentive structure for referrals" |+| Viral loop analysis | "Analyze viral loop for [program]" |+| Launch plan | "Create referral program launch plan" |+| Optimize incentives | "Improve referral incentives" |+| Email sequence | "Write referral program email sequence" |+| Calculate K-factor | "Calculate viral coefficient" |+| Fraud prevention | "Design fraud prevention for referrals" |++## Best Practices++- **Make it easy** - Fewer clicks = more referrals+- **Two-sided incentives** - Benefit both parties+- **Relevant rewards** - Match incentive to product value+- **Immediate gratification** - Faster rewards drive behavior+- **Clear communication** - Simple explanation of how it works+- **In-product placement** - Referral should be discoverable+- **Timing matters** - Ask after positive experiences+- **Personalization** - Customizable referral messages+- **Social proof** - Show others referring successfully+- **Multiple channels** - Enable various sharing methods+- **Fraud prevention** - Design to prevent gaming+- **Track everything** - Attribution and conversion data+- **Test constantly** - Optimize incentives and mechanics+- **Celebrate success** - Recognize top referrers+- **Sustainable economics** - CAC savings must exceed reward costsdiff --git a/skills/revenue-modeler/SKILL.md b/skills/revenue-modeler/SKILL.mdnew file mode 100644index 0000000..890a4ff--- /dev/null+++ b/skills/revenue-modeler/SKILL.md@@ -0,0 +1,453 @@+---+name: Revenue Modeler+slug: revenue-modeler+description: Build revenue projection models with driver-based forecasting, scenario analysis, and pricing optimization+category: finance+complexity: complex+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "revenue model"+ - "revenue projection"+ - "sales forecast"+ - "pricing model"+ - "revenue growth"+ - "MRR forecast"+tags:+ - revenue-modeling+ - forecasting+ - pricing+ - saas-metrics+ - growth-planning+---++# Revenue Modeler++Expert revenue forecasting agent that builds driver-based revenue models, projects growth scenarios, optimizes pricing strategies, and forecasts subscription metrics. Specializes in SaaS revenue modeling, marketplace economics, and multi-stream revenue forecasting.++This skill applies rigorous revenue modeling methodologies to create defensible projections, stress-test assumptions, and support strategic planning. Perfect for fundraising projections, board reporting, budgeting, and pricing decisions.++## Core Workflows++### Workflow 1: SaaS Revenue Model++**Objective:** Build comprehensive SaaS/subscription revenue model++**Steps:**+1. **Current State Analysis**+ - Current MRR/ARR+ - Customer count by segment+ - ARPU by segment+ - Growth trends (MoM, YoY)+ - Cohort retention data++2. **Revenue Driver Identification**+ - **Customer Acquisition:**+ - New customer growth rate+ - Lead generation capacity+ - Conversion rates by channel+ - Sales capacity and productivity+ - CAC and payback period++ - **Customer Retention:**+ - Gross churn rate (customer count)+ - Net revenue retention (NRR)+ - Churn by segment/cohort+ - Contraction rate++ - **Expansion:**+ - Upsell rate+ - Cross-sell rate+ - Seat expansion+ - Tier upgrades++3. **Model Architecture**+ ```+ Beginning MRR+ + New MRR (new customers × ARPU)+ + Expansion MRR (existing customer upgrades)+ - Contraction MRR (downgrades)+ - Churned MRR (lost customers)+ = Ending MRR++ ARR = MRR × 12+ ```++4. **Cohort-Based Modeling**+ - Track each cohort separately+ - Apply cohort-specific retention curves+ - Model degradation over time+ - Account for seasonality++5. **Scenario Development**+ - **Base Case:**+ - Current trend continuation+ - Realistic growth assumptions++ - **Upside Case:**+ - Improved conversion+ - Lower churn+ - Higher expansion++ - **Downside Case:**+ - Slower acquisition+ - Higher churn+ - Economic headwinds++6. **Key Metrics Output**+ - MRR/ARR projections by month+ - Customer count projections+ - Net Revenue Retention+ - LTV/CAC ratio evolution+ - Payback period+ - Gross margin projections++**Deliverable:** Monthly MRR model with 12-36 month projections++### Workflow 2: Marketplace Revenue Model++**Objective:** Build revenue model for marketplace businesses++**Steps:**+1. **Marketplace Metrics Setup**+ - **Supply Side:**+ - Active sellers/providers+ - Listings per seller+ - Average order value+ - Supply growth rate++ - **Demand Side:**+ - Active buyers+ - Transactions per buyer+ - Buyer frequency+ - Demand growth rate++ - **Marketplace Metrics:**+ - Gross Merchandise Value (GMV)+ - Take rate percentage+ - Net revenue = GMV × Take rate++2. **GMV Driver Model**+ ```+ GMV = Active Buyers × Transactions/Buyer × Average Order Value++ OR++ GMV = Active Sellers × Listings/Seller × Sell-Through Rate × Price+ ```++3. **Take Rate Analysis**+ - Current take rate+ - Take rate by category+ - Take rate optimization potential+ - Competitive benchmarking+ - Additional revenue streams (ads, premium, fulfillment)++4. **Liquidity Modeling**+ - Match rate projections+ - Supply/demand balance+ - Geographic coverage+ - Category depth++5. **Revenue Streams**+ - Transaction fees (primary)+ - Subscription fees (seller SaaS)+ - Advertising revenue+ - Fulfillment/logistics fees+ - Premium placement fees+ - Data/analytics fees++**Deliverable:** Marketplace revenue model with GMV and take rate projections++### Workflow 3: Usage-Based Revenue Model++**Objective:** Model revenue for consumption-based pricing++**Steps:**+1. **Usage Metrics Identification**+ - Primary usage unit (API calls, storage, compute hours)+ - Average usage per customer+ - Usage distribution (heavy vs. light users)+ - Seasonal patterns++2. **Pricing Structure**+ - Per-unit pricing tiers+ - Volume discounts+ - Minimum commitments+ - Overage pricing+ - Platform fees++3. **Customer Segmentation**+ - Segment by usage level+ - Different growth rates by segment+ - Segment-specific retention+ - Enterprise vs. SMB patterns++4. **Model Components**+ ```+ Revenue = Σ (Customers per segment × Usage per customer × Price per unit)++ Account for:+ - Customer growth+ - Usage growth per customer+ - Price changes+ - Volume discount impact+ ```++5. **Predictability Enhancement**+ - Committed vs. overage revenue+ - Minimum revenue guarantees+ - Prepaid usage credits+ - Annual contract values++6. **Scenario Modeling**+ - Usage growth scenarios+ - Customer mix changes+ - Pricing optimization+ - Enterprise contract impact++**Deliverable:** Usage-based revenue model with consumption projections++### Workflow 4: Multi-Product Revenue Model++**Objective:** Model revenue across multiple products and revenue streams++**Steps:**+1. **Product Portfolio Mapping**+ - Product 1: Type, pricing, target market+ - Product 2: Type, pricing, target market+ - Product 3: Type, pricing, target market+ - Cross-sell relationships++2. **Individual Product Models**+ - Build sub-model for each product+ - Apply appropriate methodology:+ - Subscription → SaaS model+ - Transaction → Marketplace model+ - Usage → Consumption model+ - One-time → Pipeline model++3. **Cross-Sell Modeling**+ - Attach rate assumptions+ - Timing of cross-sell+ - Bundle discount impact+ - Cannibalization effects++4. **Revenue Mix Analysis**+ - Current revenue mix+ - Target revenue mix+ - Mix shift assumptions+ - Profitability by product++5. **Consolidation**+ - Sum of product revenues+ - Eliminate double-counting+ - Bundle revenue allocation+ - Total company revenue++6. **Scenario Development**+ - Product-specific scenarios+ - Portfolio-level scenarios+ - New product launch impact+ - Sunset product impact++**Deliverable:** Consolidated multi-product revenue model++### Workflow 5: Pricing Optimization Model++**Objective:** Analyze and optimize pricing strategy++**Steps:**+1. **Current Pricing Analysis**+ - Current price points+ - Discount frequency and depth+ - ARPU analysis+ - Price sensitivity observed++2. **Competitive Benchmarking**+ - Competitor pricing+ - Feature comparison+ - Value-based positioning+ - Market standard pricing++3. **Value-Based Pricing Analysis**+ - Customer value delivered+ - ROI for customer+ - Willingness to pay research+ - Price anchoring opportunities++4. **Price Elasticity Modeling**+ - Historical price change impact+ - Segment-specific elasticity+ - Volume vs. price trade-off+ - Revenue optimization point++5. **Pricing Scenarios**+ - Price increase impact:+ - Revenue gain from price+ - Volume loss from churn+ - Net revenue impact++ - Price decrease impact:+ - Revenue loss from price+ - Volume gain from conversion+ - Net revenue impact++6. **Pricing Structure Options**+ - Per-seat vs. per-company+ - Usage-based vs. flat+ - Tiered pricing design+ - Freemium conversion+ - Annual discount strategy++7. **Implementation Plan**+ - Grandfathering strategy+ - Rollout timeline+ - Customer communication+ - Monitoring metrics++**Deliverable:** Pricing analysis with optimization recommendations++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| SaaS model | "Build MRR/ARR revenue model" |+| Marketplace | "Model marketplace GMV and revenue" |+| Usage-based | "Create consumption-based revenue model" |+| Multi-product | "Model revenue across products" |+| Pricing | "Analyze pricing optimization" |+| Scenarios | "Model revenue scenarios" |++## SaaS Metrics Reference++### Core Metrics++| Metric | Formula | Healthy Benchmark |+|--------|---------|-------------------|+| MRR | Sum of monthly recurring revenue | Growing |+| ARR | MRR × 12 | Growing |+| ARPU | MRR / Customers | Stable or growing |+| Net Revenue Retention | (Start MRR + Expansion - Contraction - Churn) / Start MRR | > 100% |+| Gross Revenue Retention | (Start MRR - Contraction - Churn) / Start MRR | > 85% |+| LTV | ARPU × Gross Margin / Churn Rate | > 3× CAC |+| CAC Payback | CAC / (ARPU × Gross Margin) | < 12 months |++### MRR Movement Types++| Type | Definition |+|------|------------|+| New MRR | Revenue from new customers this month |+| Expansion MRR | Revenue increase from existing customers (upsells) |+| Contraction MRR | Revenue decrease from existing customers (downgrades) |+| Churned MRR | Revenue from customers who cancelled |+| Reactivation MRR | Revenue from customers who returned |++### SaaS Benchmarks++| Metric | Good | Great | Best-in-Class |+|--------|------|-------|---------------|+| MRR Growth (MoM) | 5-7% | 10-15% | 20%+ |+| Net Revenue Retention | 100-110% | 110-130% | 130%+ |+| Gross Churn (monthly) | 3-5% | 1-3% | < 1% |+| LTV/CAC | 3:1 | 5:1 | 10:1 |+| CAC Payback | 12-18 mo | 6-12 mo | < 6 mo |++## Revenue Model Template++```markdown+# Revenue Model: [Company Name]++**Model Period:** [Start] - [End]+**Last Updated:** [Date]++## Model Inputs++### Customer Assumptions+| Metric | Current | Growth Rate |+|--------|---------|-------------|+| Starting Customers | | |+| New Customers/Month | | |+| Churn Rate (Monthly) | | |+| Net Revenue Retention | | |++### Pricing Assumptions+| Segment | ARPU | % of New |+|---------|------|----------|+| Starter | | |+| Professional | | |+| Enterprise | | |+| Weighted Avg | | |++## Revenue Projections++### Monthly MRR Waterfall+| Month | Start MRR | New | Expansion | Contraction | Churn | End MRR |+|-------|-----------|-----|-----------|-------------|-------|---------|+| M1 | | | | | | |+| M2 | | | | | | |+| ... | | | | | | |+| M12 | | | | | | |++### Annual Summary+| Metric | Year 1 | Year 2 | Year 3 |+|--------|--------|--------|--------|+| ARR | | | |+| YoY Growth | | | |+| Customers | | | |+| ARPU | | | |+| NRR | | | |++## Scenario Comparison+| Scenario | Year 1 ARR | Year 2 ARR | Year 3 ARR |+|----------|------------|------------|------------|+| Base | | | |+| Upside | | | |+| Downside | | | |++## Key Assumptions & Risks+1. [Assumption 1] - [Risk if wrong]+2. [Assumption 2] - [Risk if wrong]+```++## Best Practices++### Model Building+- Start with driver-based approach+- Document all assumptions+- Make assumptions adjustable+- Build scenario capability+- Test edge cases++### Assumption Setting+- Ground in historical data+- Benchmark to industry+- Be realistic, not optimistic+- Explain reasoning+- Sensitivity test key drivers++### Presentation+- Executive summary first+- Visualize key trends+- Show assumption sensitivity+- Include scenario comparison+- Highlight risks++## Integration with Other Skills++- **Use with `budget-planner`:** Link revenue to expense budget+- **Use with `cash-flow-forecaster`:** Convert revenue to cash+- **Use with `unit-economics-calculator`:** Validate profitability+- **Use with `financial-analyst`:** Historical performance analysis+- **Use with `investment-analyzer`:** Support fundraising projections++## Common Pitfalls to Avoid++- **Hockey stick projections:** Ground in reality+- **Ignoring churn:** Even small churn compounds+- **Overestimating new customers:** Harder than it looks+- **Ignoring seasonality:** Build in monthly patterns+- **Linear assumptions:** Growth often S-curve+- **Ignoring capacity constraints:** Sales, product, support+- **Static pricing:** Build in price evolution+- **No segmentation:** Different customers behave differentlydiff --git a/skills/sentiment-analyzer/SKILL.md b/skills/sentiment-analyzer/SKILL.mdnew file mode 100644index 0000000..2ec4a00--- /dev/null+++ b/skills/sentiment-analyzer/SKILL.md@@ -0,0 +1,316 @@+---+name: Sentiment Analyzer+slug: sentiment-analyzer+description: Analyze text sentiment at scale with nuanced understanding+category: ai-ml+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "analyze sentiment"+ - "sentiment analysis"+ - "opinion mining"+ - "emotion detection"+ - "text sentiment"+tags:+ - sentiment+ - NLP+ - opinion-mining+ - emotion+ - text-analysis+---++# Sentiment Analyzer++The Sentiment Analyzer skill guides you through implementing sentiment analysis systems that understand the emotional tone and opinion in text. From simple positive/negative classification to nuanced aspect-based sentiment and emotion detection, this skill covers the full spectrum of sentiment analysis capabilities.++Sentiment analysis is deceptively complex. Sarcasm, context, domain-specific language, and cultural nuances all challenge simple approaches. This skill helps you choose the right techniques for your accuracy requirements, whether that's fast rule-based systems, fine-tuned classifiers, or LLM-based analysis.++Whether you're analyzing customer reviews, social media mentions, support tickets, or survey responses, this skill ensures your sentiment analysis captures the true voice of your users.++## Core Workflows++### Workflow 1: Choose Sentiment Analysis Approach+1. **Define** requirements:+ - Granularity: Binary, ternary, or continuous?+ - Aspects: Overall or aspect-based?+ - Emotions: Sentiment or specific emotions?+ - Languages: Single or multilingual?+ - Volume: Batch or real-time?+2. **Evaluate** options:+ | Approach | Speed | Accuracy | Customizable | Best For |+ |----------|-------|----------|--------------|----------|+ | Rule-based (VADER) | Very fast | Moderate | Limited | Social media, quick analysis |+ | Pre-trained (RoBERTa) | Fast | Good | Fine-tunable | General text |+ | Fine-tuned | Fast | Best | Requires data | Domain-specific |+ | LLM (GPT-4, Claude) | Slow | Excellent | Prompt-based | Nuanced, complex |+3. **Select** based on tradeoffs+4. **Plan** implementation++### Workflow 2: Implement Sentiment Pipeline+1. **Preprocess** text:+ ```python+ def preprocess_for_sentiment(text):+ # Preserve sentiment-relevant features+ text = normalize_unicode(text)++ # Handle social media conventions+ text = expand_contractions(text) # don't -> do not+ text = normalize_elongation(text) # loooove -> love+ text = handle_negation(text) # Mark negation scope++ # Preserve but normalize emoji/emoticons+ text = convert_emoji_to_text(text) # :) -> [HAPPY]++ return text+ ```+2. **Analyze** sentiment:+ ```python+ class SentimentAnalyzer:+ def __init__(self, model_type="transformer"):+ if model_type == "transformer":+ self.model = pipeline("sentiment-analysis",+ model="cardiffnlp/twitter-roberta-base-sentiment")+ elif model_type == "vader":+ self.model = SentimentIntensityAnalyzer()++ def analyze(self, text):+ preprocessed = preprocess_for_sentiment(text)+ result = self.model(preprocessed)+ return {+ "text": text,+ "sentiment": result["label"],+ "confidence": result["score"]+ }+ ```+3. **Aggregate** for insights:+ - Overall sentiment distribution+ - Sentiment over time+ - Sentiment by segment/topic+4. **Validate** results++### Workflow 3: Aspect-Based Sentiment Analysis+1. **Identify** aspects to track:+ - Product features (price, quality, service)+ - Experience dimensions (speed, accuracy, friendliness)+ - Custom aspects for your domain+2. **Extract** aspects from text:+ ```python+ def extract_aspects(text, aspect_list):+ # Find mentions of known aspects+ found_aspects = []+ for aspect in aspect_list:+ if aspect.lower() in text.lower():+ found_aspects.append(aspect)++ # Also extract using NER or LLM for unknown aspects+ extracted = extract_noun_phrases(text)+ return found_aspects + extracted+ ```+3. **Analyze** sentiment per aspect:+ ```python+ def aspect_sentiment(text, aspects):+ results = {}+ for aspect in aspects:+ # Extract sentences mentioning aspect+ relevant = extract_aspect_context(text, aspect)++ # Analyze sentiment of relevant text+ if relevant:+ sentiment = analyze_sentiment(relevant)+ results[aspect] = sentiment++ return results+ ```+4. **Aggregate** aspect sentiments across documents++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Analyze sentiment | "Analyze sentiment of [text]" |+| Choose approach | "Best sentiment analysis for [use case]" |+| Aspect-based | "Sentiment by feature for [reviews]" |+| Detect emotions | "Detect emotions in [text]" |+| Handle sarcasm | "How to handle sarcasm in sentiment" |+| Aggregate results | "Summarize sentiment trends" |++## Best Practices++- **Preserve Sentiment Signals**: Don't preprocess away important cues+ - Keep punctuation (!! vs .)+ - Preserve capitalization patterns+ - Keep emoji/emoticons (convert to text)+ - Handle negation explicitly++- **Match Model to Domain**: Pre-trained models have domain bias+ - Twitter models work differently than product review models+ - Fine-tune or select domain-appropriate models+ - Test on your actual data before deploying++- **Handle Negation Properly**: "Not bad" isn't negative+ - Rule-based: Mark negation scope+ - Neural models: Usually handle automatically+ - Test negation cases explicitly++- **Consider Context**: Sentiment depends on context+ - "Cheap" is positive for budget items, negative for luxury+ - Use aspect-based analysis for nuance+ - Include surrounding context when possible++- **Validate with Humans**: Machine sentiment != human sentiment+ - Sample and manually verify results+ - Calculate agreement metrics+ - Iterate on disagreements++- **Report Uncertainty**: Not all text has clear sentiment+ - Neutral is a valid class+ - Low confidence predictions should be flagged+ - Consider abstaining on ambiguous cases++## Advanced Techniques++### LLM-Based Nuanced Sentiment+Use language models for complex analysis:+```python+def llm_sentiment_analysis(text, aspects=None):+ prompt = f"""Analyze the sentiment of the following text.++Text: "{text}"++Provide:+1. Overall sentiment (positive/negative/neutral/mixed)+2. Confidence (0-1)+3. Key positive aspects mentioned+4. Key negative aspects mentioned+5. Notable emotional tones (joy, frustration, surprise, etc.)++{"Also rate sentiment specifically for these aspects: " + ", ".join(aspects) if aspects else ""}++Respond in JSON format."""++ response = llm.complete(prompt)+ return json.loads(response)+```++### Emotion Detection+Beyond positive/negative to specific emotions:+```python+from transformers import pipeline++# Multi-label emotion classification+emotion_classifier = pipeline(+ "text-classification",+ model="SamLowe/roberta-base-go_emotions",+ top_k=None+)++def detect_emotions(text):+ results = emotion_classifier(text)[0]+ # Filter to significant emotions+ significant = [r for r in results if r["score"] > 0.1]+ return sorted(significant, key=lambda x: x["score"], reverse=True)++# Example output:+# [{"label": "admiration", "score": 0.45},+# {"label": "joy", "score": 0.32},+# {"label": "gratitude", "score": 0.28}]+```++### Comparative Sentiment+Detect sentiment comparisons:+```python+def comparative_sentiment(text):+ """+ Detect: "A is better than B" patterns+ """+ prompt = f"""Analyze this text for comparative sentiment.++Text: "{text}"++If the text compares entities, identify:+1. Entity A (the preferred/better one)+2. Entity B (the less preferred/worse one)+3. Dimension of comparison (price, quality, etc.)+4. Strength of preference (slight, moderate, strong)++If no comparison, respond with: {{"comparison": false}}++Respond in JSON."""++ return llm.complete(prompt)+```++### Temporal Sentiment Tracking+Analyze sentiment over time:+```python+def sentiment_timeline(documents, time_field, window="day"):+ """+ Track sentiment trends over time.+ """+ # Analyze each document+ results = []+ for doc in documents:+ sentiment = analyze_sentiment(doc["text"])+ results.append({+ "timestamp": doc[time_field],+ "sentiment": sentiment["score"],+ "text": doc["text"]+ })++ # Aggregate by time window+ df = pd.DataFrame(results)+ df["window"] = df["timestamp"].dt.floor(window)++ trends = df.groupby("window").agg({+ "sentiment": ["mean", "std", "count"],+ "text": lambda x: list(x)[:3] # Sample texts+ })++ return trends+```++### Sarcasm Detection+Handle sarcasm before sentiment analysis:+```python+def detect_sarcasm(text):+ """+ Detect potential sarcasm indicators.+ """+ indicators = {+ "exaggeration": bool(re.search(r'\b(best|worst|ever|always|never)\b', text.lower())),+ "air_quotes": '"' in text,+ "ellipsis": "..." in text,+ "positive_negative_mix": has_mixed_signals(text),+ "hashtags": "#sarcasm" in text.lower() or "#not" in text.lower()+ }++ # Use model for detection+ sarcasm_score = sarcasm_model.predict(text)++ return {+ "is_sarcastic": sarcasm_score > 0.5,+ "confidence": sarcasm_score,+ "indicators": indicators+ }++def sentiment_with_sarcasm(text):+ sarcasm = detect_sarcasm(text)+ base_sentiment = analyze_sentiment(text)++ if sarcasm["is_sarcastic"] and sarcasm["confidence"] > 0.7:+ # Flip sentiment+ return flip_sentiment(base_sentiment)+ return base_sentiment+```++## Common Pitfalls to Avoid++- Using generic models on domain-specific text+- Preprocessing away sentiment-relevant features (emoji, punctuation)+- Ignoring negation handling+- Treating neutral as absence of opinion vs explicit neutrality+- Not validating model outputs against human judgment+- Assuming sarcasm doesn't exist in your data+- Over-weighting extreme sentiments in aggregation+- Reporting sentiment without confidence/uncertaintydiff --git a/skills/summarization-engine/SKILL.md b/skills/summarization-engine/SKILL.mdnew file mode 100644index 0000000..6b6ecd9--- /dev/null+++ b/skills/summarization-engine/SKILL.md@@ -0,0 +1,335 @@+---+name: Summarization Engine+slug: summarization-engine+description: Generate accurate summaries of long documents and text collections+category: ai-ml+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "summarize document"+ - "text summarization"+ - "generate summary"+ - "document summary"+ - "condense text"+tags:+ - summarization+ - NLP+ - document-processing+ - text-generation+ - content+---++# Summarization Engine++The Summarization Engine skill guides you through building systems that condense long documents into concise, accurate summaries. From extractive approaches that select key sentences to abstractive methods that generate new text, this skill covers the full spectrum of summarization techniques.++Effective summarization requires understanding what information matters, maintaining accuracy while condensing, and adapting to different document types and summary requirements. This skill helps you choose the right approach and implement robust summarization pipelines.++Whether you're summarizing news articles, research papers, meeting transcripts, or legal documents, this skill ensures your summaries are accurate, relevant, and useful.++## Core Workflows++### Workflow 1: Choose Summarization Approach+1. **Analyze** requirements:+ - Summary length (ratio or fixed length)+ - Accuracy requirements (factual precision)+ - Style preferences (extractive vs abstractive)+ - Speed and scale constraints+2. **Compare** approaches:+ | Approach | Accuracy | Fluency | Speed | Best For |+ |----------|----------|---------|-------|----------|+ | Extractive | High | Variable | Fast | Legal, medical, precision |+ | Abstractive (small) | Medium | Good | Fast | General content |+ | Abstractive (LLM) | High | Excellent | Slow | Quality-critical |+ | Hybrid | High | Good | Medium | Balanced needs |+3. **Select** based on tradeoffs:+ - Extractive: When accuracy is critical+ - Abstractive: When fluency matters+ - Hybrid: When both matter+4. **Design** evaluation criteria++### Workflow 2: Implement Extractive Summarization+1. **Score** sentences:+ ```python+ from sklearn.feature_extraction.text import TfidfVectorizer+ import numpy as np++ def extractive_summarize(text, num_sentences=3):+ # Split into sentences+ sentences = sent_tokenize(text)++ # Score by TF-IDF importance+ vectorizer = TfidfVectorizer()+ tfidf_matrix = vectorizer.fit_transform(sentences)++ # Score each sentence by sum of TF-IDF scores+ scores = np.array(tfidf_matrix.sum(axis=1)).flatten()++ # Select top sentences maintaining order+ top_indices = np.argsort(scores)[-num_sentences:]+ top_indices = sorted(top_indices) # Maintain original order++ summary_sentences = [sentences[i] for i in top_indices]+ return " ".join(summary_sentences)+ ```+2. **Add** additional scoring factors:+ - Position (first sentences often important)+ - Named entity density+ - Similarity to title/heading+3. **Remove** redundancy:+ - Skip sentences too similar to already selected+4. **Post-process** for coherence++### Workflow 3: Implement Abstractive Summarization+1. **Set up** summarization model:+ ```python+ from transformers import pipeline++ class AbstractiveSummarizer:+ def __init__(self, model="facebook/bart-large-cnn"):+ self.summarizer = pipeline("summarization", model=model)+ self.max_input_length = 1024 # Model-specific limit++ def summarize(self, text, max_length=150, min_length=50):+ # Handle long documents+ if len(text.split()) > self.max_input_length:+ return self.summarize_long(text, max_length, min_length)++ result = self.summarizer(+ text,+ max_length=max_length,+ min_length=min_length,+ do_sample=False+ )+ return result[0]["summary_text"]++ def summarize_long(self, text, max_length, min_length):+ # Chunk and summarize iteratively+ chunks = self.chunk_text(text)+ summaries = [self.summarize(chunk) for chunk in chunks]++ # Combine and re-summarize if needed+ combined = " ".join(summaries)+ if len(combined.split()) > max_length:+ return self.summarize(combined, max_length, min_length)+ return combined+ ```+2. **Handle** long documents with chunking+3. **Validate** factual accuracy+4. **Post-process** for formatting++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Summarize text | "Summarize this document" |+| Choose approach | "Best summarization for [document type]" |+| Control length | "Summarize in [N] words/sentences" |+| Multi-document | "Summarize these documents together" |+| Evaluate summary | "Check summary quality" |+| Reduce hallucination | "Improve summary accuracy" |++## Best Practices++- **Preserve Key Information**: Summaries must capture what matters+ - Identify key entities, facts, and conclusions+ - Verify critical information is retained+ - Don't sacrifice accuracy for brevity++- **Maintain Factual Accuracy**: Abstractive summarization can hallucinate+ - Verify generated facts against source+ - Use extractive for high-stakes domains+ - Consider hybrid approaches++- **Handle Long Documents**: Most models have length limits+ - Chunk strategically (by section, paragraph)+ - Use hierarchical summarization+ - Preserve context across chunks++- **Match Style to Purpose**: Different uses need different summaries+ - Executive summary: Key conclusions first+ - Abstract: Balanced overview+ - Bullet points: Scannable key facts+ - Progressive disclosure: Multiple detail levels++- **Evaluate Properly**: ROUGE scores don't tell the whole story+ - Check factual accuracy manually+ - Assess coherence and readability+ - Compare against human summaries++- **Consider Multi-Document**: Often need to summarize multiple sources+ - Identify common themes and differences+ - Handle contradictions appropriately+ - Attribute information to sources++## Advanced Techniques++### LLM-Based Summarization+Use large language models for high-quality summaries:+```python+def llm_summarize(text, style="executive", max_words=150):+ style_instructions = {+ "executive": "Focus on key conclusions, decisions, and action items.",+ "technical": "Preserve technical details and methodology.",+ "narrative": "Maintain the story arc and key events.",+ "bullet": "Format as bullet points with key facts."+ }++ prompt = f"""Summarize the following text in approximately {max_words} words.+{style_instructions.get(style, "")}++Important:+- Only include information from the source text+- Maintain accuracy of facts, numbers, and names+- Preserve the most important information++Text to summarize:+{text}++Summary:"""++ return llm.complete(prompt, max_tokens=max_words * 2)+```++### Hierarchical Summarization+Summarize very long documents iteratively:+```python+def hierarchical_summarize(document, target_length=500):+ """+ Summarize long documents through progressive compression.+ """+ # Level 1: Split into sections+ sections = split_into_sections(document)++ # Level 2: Summarize each section+ section_summaries = []+ for section in sections:+ summary = summarize(section, max_length=200)+ section_summaries.append({+ "title": section.title,+ "summary": summary+ })++ # Level 3: Combine section summaries+ combined = "\n\n".join([+ f"{s['title']}: {s['summary']}"+ for s in section_summaries+ ])++ # Level 4: Final summary if still too long+ if len(combined.split()) > target_length:+ return summarize(combined, max_length=target_length)++ return combined+```++### Multi-Document Summarization+Synthesize information from multiple sources:+```python+def multi_document_summarize(documents, topic=None):+ """+ Summarize multiple documents into coherent summary.+ """+ # Step 1: Summarize each document+ doc_summaries = []+ for i, doc in enumerate(documents):+ summary = summarize(doc.text)+ doc_summaries.append({+ "source": doc.source,+ "summary": summary+ })++ # Step 2: Identify themes and differences+ prompt = f"""Given these summaries from different sources about {topic or "a topic"}:++{chr(10).join(f"Source {i+1} ({s['source']}): {s['summary']}" for i, s in enumerate(doc_summaries))}++Create a unified summary that:+1. Identifies common themes across sources+2. Notes any contradictions or different perspectives+3. Attributes key claims to their sources+4. Presents a balanced, comprehensive view++Unified summary:"""++ return llm.complete(prompt)+```++### Factual Consistency Checking+Verify summaries don't hallucinate:+```python+def check_factual_consistency(source, summary):+ """+ Verify summary facts against source document.+ """+ # Extract claims from summary+ claims = extract_claims(summary)++ # Check each claim against source+ results = []+ for claim in claims:+ prompt = f"""Does the source document support this claim?++Source: {source}++Claim: {claim}++Answer:+- SUPPORTED: The claim is directly supported by the source+- NOT SUPPORTED: The claim is not in the source+- CONTRADICTED: The source contradicts this claim++Provide answer and brief explanation."""++ result = llm.complete(prompt)+ results.append({+ "claim": claim,+ "status": parse_status(result),+ "explanation": result+ })++ return {+ "claims_checked": len(results),+ "supported": sum(1 for r in results if r["status"] == "SUPPORTED"),+ "not_supported": sum(1 for r in results if r["status"] == "NOT SUPPORTED"),+ "contradicted": sum(1 for r in results if r["status"] == "CONTRADICTED"),+ "details": results+ }+```++### Query-Focused Summarization+Generate summaries tailored to specific questions:+```python+def query_focused_summarize(document, query):+ """+ Summarize document with focus on answering specific question.+ """+ prompt = f"""Summarize the following document, focusing specifically on information relevant to this question:++Question: {query}++Document:+{document}++Provide a summary that:+1. Directly addresses the question+2. Includes relevant supporting details from the document+3. Notes if the document doesn't fully answer the question+4. Stays focused on query-relevant information++Summary:"""++ return llm.complete(prompt)+```++## Common Pitfalls to Avoid++- Trusting abstractive summaries without factual verification+- Not handling documents longer than model context limits+- Using ROUGE scores as the only evaluation metric+- Ignoring document structure when chunking+- Generating summaries that don't match user needs+- Not attributing information in multi-document summaries+- Over-compressing and losing critical information+- Assuming summaries are ready to use without human reviewdiff --git a/skills/tax-strategist/SKILL.md b/skills/tax-strategist/SKILL.mdnew file mode 100644index 0000000..fb975e8--- /dev/null+++ b/skills/tax-strategist/SKILL.md@@ -0,0 +1,443 @@+---+name: Tax Strategist+slug: tax-strategist+description: Optimize tax strategies for individuals and businesses with entity planning, deduction maximization, and compliance guidance+category: finance+complexity: complex+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "tax strategy"+ - "tax planning"+ - "tax optimization"+ - "deduction"+ - "tax savings"+ - "entity structure"+tags:+ - tax-planning+ - tax-optimization+ - deductions+ - entity-structure+ - compliance+---++# Tax Strategist++Expert tax planning agent that develops tax-efficient strategies, identifies deductions, optimizes entity structures, and ensures compliance. Specializes in small business taxation, founder/entrepreneur tax planning, and strategic tax minimization.++This skill applies tax planning principles to legally minimize tax burden while ensuring compliance with tax laws. Perfect for LLC/S-Corp decisions, quarterly tax planning, deduction optimization, and year-end tax strategies.++**Disclaimer:** This skill provides educational tax guidance. Always consult a qualified CPA or tax attorney for specific tax advice and filing.++## Core Workflows++### Workflow 1: Entity Structure Optimization++**Objective:** Determine optimal business entity structure for tax efficiency++**Steps:**+1. **Current Situation Analysis**+ - Current entity type (sole prop, LLC, S-Corp, C-Corp)+ - Annual revenue and net income+ - Owner compensation+ - Number of owners/members+ - State of operation+ - Growth trajectory++2. **Entity Comparison Analysis**++ **Sole Proprietorship / Single-Member LLC (Disregarded):**+ - Pass-through taxation+ - Self-employment tax on all net income (15.3%)+ - Simple administration+ - Limited liability protection (LLC only)+ - Best for: Low income, simplicity priority++ **LLC with S-Corp Election:**+ - Pass-through taxation+ - Self-employment tax only on wages+ - Reasonable salary requirement+ - Payroll administration required+ - Best for: Net income > $40-50K after salary++ **C-Corporation:**+ - Double taxation (corporate + dividend)+ - 21% flat corporate rate+ - Ability to retain earnings+ - Fringe benefit deductions+ - Best for: High growth, reinvesting profits, or planning IPO++3. **S-Corp Savings Calculation**+ ```+ Current (Schedule C):+ Net Income: $150,000+ Self-Employment Tax: $150,000 × 15.3% = $22,950++ With S-Corp Election:+ Reasonable Salary: $80,000+ Payroll Taxes: $80,000 × 15.3% = $12,240+ Distribution: $70,000 (no SE tax)++ Annual Savings: $22,950 - $12,240 = $10,710+ ```++4. **Reasonable Salary Determination**+ - Industry standards for role+ - Geographic location factors+ - Experience and qualifications+ - Company profitability+ - IRS guidelines (typically 60-80% of net income initially)++5. **Implementation Considerations**+ - State filing requirements+ - Election timing (S-Corp: within 75 days of tax year)+ - Payroll setup requirements+ - Accounting complexity increase+ - Ongoing compliance costs++6. **Recommendation**+ - Recommended entity structure+ - Estimated annual tax savings+ - Implementation steps+ - Timing considerations+ - Professional referrals needed++**Deliverable:** Entity structure analysis with tax savings estimate++### Workflow 2: Deduction Maximization++**Objective:** Identify all available deductions to minimize taxable income++**Steps:**+1. **Business Expense Review**++ **Ordinary & Necessary Deductions:**+ - Office supplies and equipment+ - Software and subscriptions+ - Professional services (legal, accounting)+ - Marketing and advertising+ - Travel, meals (50% deductible), lodging+ - Education and training+ - Bank fees and interest+ - Insurance premiums++ **Home Office Deduction:**+ - Dedicated workspace required+ - Regular and exclusive use+ - Simplified method: $5/sq ft (max $1,500)+ - Actual expense method: Proportional share+ - Includes: mortgage/rent, utilities, insurance, repairs++ **Vehicle Expenses:**+ - Standard mileage: 67 cents/mile (2024)+ - Actual expenses: gas, insurance, repairs, depreciation+ - Business use percentage required+ - Mileage log recommended++2. **Retirement Contributions**++ | Plan Type | 2024 Limit | Notes |+ |-----------|------------|-------|+ | SEP-IRA | 25% of net SE income (max $69,000) | Simple, employer-only |+ | Solo 401(k) | $23,000 + 25% employer (max $69,000) | Employee + employer |+ | SIMPLE IRA | $16,000 + 3% match | Lower limits |+ | Defined Benefit | Actuarially determined | Highest limits |++3. **Health-Related Deductions**+ - Self-employed health insurance deduction (100%)+ - HSA contributions ($4,150 individual / $8,300 family)+ - Long-term care insurance premiums (age-based limits)++4. **Section 199A (QBI) Deduction**+ - 20% of Qualified Business Income+ - Subject to income limits ($191,950 single / $383,900 MFJ)+ - SSTB limitations at high income+ - W-2 wage and property limitations+ - Optimal structuring strategies++5. **Depreciation Strategies**+ - Section 179 expensing ($1,220,000 limit)+ - Bonus depreciation (60% in 2024)+ - Standard depreciation schedules+ - Vehicles: $12,200 first year (+ bonus)+ - Listed property rules++6. **Often Overlooked Deductions**+ - State and local taxes (up to $10,000)+ - Charitable contributions+ - Student loan interest+ - Business use of cell phone+ - Business-related books/publications+ - Professional memberships+ - Bad debt write-offs++**Deliverable:** Comprehensive deduction checklist with estimated savings++### Workflow 3: Quarterly Tax Planning++**Objective:** Optimize estimated tax payments and year-round tax planning++**Steps:**+1. **Income Projection**+ - Year-to-date income+ - Projected remaining income+ - One-time income events+ - Quarterly income timing++2. **Tax Liability Estimation**+ - Federal income tax brackets+ - Self-employment tax+ - State income tax+ - Local taxes (if applicable)++3. **Safe Harbor Calculation**+ - 100% of prior year tax (110% if AGI > $150K)+ - OR 90% of current year tax+ - Choose method to minimize payments++4. **Quarterly Payment Schedule**+ | Quarter | Period | Due Date |+ |---------|--------|----------|+ | Q1 | Jan 1 - Mar 31 | April 15 |+ | Q2 | Apr 1 - May 31 | June 15 |+ | Q3 | Jun 1 - Aug 31 | September 15 |+ | Q4 | Sep 1 - Dec 31 | January 15 |++5. **Cash Flow Optimization**+ - Minimum required payments+ - Penalty avoidance strategies+ - Year-end catch-up options+ - Underpayment penalty calculation++6. **Mid-Year Adjustments**+ - Income variance analysis+ - Deduction timing strategies+ - Entity structure changes+ - Retirement contribution adjustments++**Deliverable:** Quarterly estimated tax payment schedule++### Workflow 4: Year-End Tax Strategies++**Objective:** Implement year-end strategies to minimize current year taxes++**Steps:**+1. **Income Analysis**+ - YTD actual income+ - Remaining expected income+ - Marginal tax bracket+ - Comparison to prior year++2. **Income Deferral Strategies**+ - Delay invoicing to next year+ - Defer receipt of payments+ - Installment sales treatment+ - Defer bonuses (employees)++3. **Income Acceleration Strategies**+ (When next year will be higher income)+ - Accelerate billing+ - Recognize deferred revenue+ - Roth conversions+ - Capital gain harvesting++4. **Expense Acceleration**+ - Prepay deductible expenses+ - Purchase equipment (Section 179)+ - Maximize retirement contributions+ - Pay Q1 state taxes in December+ - Stock up on supplies++5. **Expense Deferral**+ (When next year will be higher income)+ - Delay discretionary purchases+ - Postpone major repairs+ - Defer prepayments++6. **Retirement Contribution Maximization**+ - Calculate max contribution room+ - Deadline awareness:+ - 401k employee: December 31+ - SEP/401k employer: Tax filing deadline+ - Catch-up contributions (50+)++7. **Capital Gains/Losses**+ - Tax-loss harvesting+ - Long-term vs short-term optimization+ - Wash sale rules (30 days)+ - Charitable donation of appreciated assets++8. **Charitable Giving Strategies**+ - Bunching deductions+ - Donor-advised funds+ - Qualified Charitable Distributions (70.5+)+ - Appreciated asset donations++**Deliverable:** Year-end tax action plan with savings estimate++### Workflow 5: Tax Audit Preparation++**Objective:** Prepare for potential tax audit and minimize risk++**Steps:**+1. **Audit Risk Assessment**+ - High-risk triggers:+ - Large deductions relative to income+ - Home office deduction+ - Vehicle deductions+ - Cash-intensive business+ - High Schedule C income+ - Previous audit history++2. **Documentation Review**+ - Income verification (1099s, bank statements)+ - Expense receipts and invoices+ - Mileage logs+ - Home office measurements+ - Asset purchase documentation+ - Contractor 1099s issued++3. **Record Organization**+ - Chronological expense files+ - Bank statement reconciliation+ - Credit card statement backup+ - Digital backup system+ - 7-year retention policy++4. **Audit Defense Preparation**+ - Understand audit types:+ - Correspondence audit (mail)+ - Office audit (IRS office)+ - Field audit (your location)+ - Know your rights+ - Representation options (CPA, EA, attorney)++5. **Common Audit Issues**+ - Mixed personal/business expenses+ - Insufficient documentation+ - Hobby loss rules+ - Contractor vs employee classification+ - Unreported income++**Deliverable:** Audit readiness checklist and documentation guide++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Entity analysis | "Should I elect S-Corp status?" |+| Deductions | "What deductions am I missing?" |+| Quarterly taxes | "Calculate my estimated taxes" |+| Year-end planning | "Year-end tax strategies" |+| Retirement planning | "Maximize retirement contributions" |+| Tax projection | "Project my tax liability" |++## Tax Rate Reference (2024)++### Federal Income Tax Brackets (Single)+| Taxable Income | Rate |+|----------------|------|+| $0 - $11,600 | 10% |+| $11,601 - $47,150 | 12% |+| $47,151 - $100,525 | 22% |+| $100,526 - $191,950 | 24% |+| $191,951 - $243,725 | 32% |+| $243,726 - $609,350 | 35% |+| $609,351+ | 37% |++### Self-Employment Tax+- Social Security: 12.4% (up to $168,600 for 2024)+- Medicare: 2.9% (no cap)+- Additional Medicare: 0.9% (income over $200K single)+- Total: 15.3% (+ 0.9% high income)+- 50% is deductible as adjustment to income++### Capital Gains Tax (2024)+| Rate | Single Income | MFJ Income |+|------|---------------|------------|+| 0% | Up to $47,025 | Up to $94,050 |+| 15% | $47,026 - $518,900 | $94,051 - $583,750 |+| 20% | Over $518,900 | Over $583,750 |++## Deduction Cheat Sheet++```markdown+## Common Business Deductions++### Fully Deductible (100%)+- [ ] Advertising and marketing+- [ ] Bank fees and interest+- [ ] Business insurance+- [ ] Contract labor+- [ ] Education (business-related)+- [ ] Legal and professional fees+- [ ] Office supplies+- [ ] Rent (business property)+- [ ] Software and subscriptions+- [ ] Telephone and internet (business %)+- [ ] Travel (business purpose)++### Partially Deductible+- [ ] Meals (50%)+- [ ] Vehicle (business % or mileage)+- [ ] Home office (business % of home)+- [ ] Cell phone (business % of usage)+- [ ] Entertainment (0% - not deductible since 2018)++### Above-the-Line Deductions+- [ ] Self-employed health insurance (100%)+- [ ] SEP/SIMPLE/Solo 401k contributions+- [ ] 1/2 of self-employment tax+- [ ] Student loan interest (up to $2,500)+- [ ] HSA contributions+```++## Best Practices++### Year-Round+- Track all expenses in real-time+- Maintain separate business accounts+- Save 25-30% for taxes+- Make quarterly payments+- Keep receipts (digital backup)++### Annually+- Review entity structure+- Maximize retirement contributions+- Implement year-end strategies+- Reconcile 1099s received+- File on time or extend++### Documentation+- Keep 7 years of records+- Contemporaneous mileage log+- Written home office policy+- Detailed expense categorization+- Contractor agreements on file++## Integration with Other Skills++- **Use with `budget-planner`:** Incorporate tax payments+- **Use with `cash-flow-forecaster`:** Model tax payment timing+- **Use with `financial-reporter`:** Tax provision reporting+- **Use with `compliance-checker`:** Ensure tax compliance+- **Use with `accounts-reconciler`:** Verify reported income++## Common Pitfalls to Avoid++- **Missing estimated payments:** Penalties add up quickly+- **Commingling funds:** Keep business and personal separate+- **Ignoring state taxes:** State rules differ significantly+- **Aggressive deductions:** Red flags invite audits+- **Missing documentation:** No receipt = no deduction+- **Late S-Corp election:** Must file within 75 days+- **Incorrect contractor classification:** Misclassification penalties are severe+- **Ignoring nexus issues:** Multi-state operations create complexity++## Disclaimer++This skill provides educational tax information only. Tax law is complex and varies by jurisdiction. Always:+- Consult a qualified CPA or tax attorney for specific advice+- Verify current tax rates and limits (they change annually)+- Consider your complete financial picture+- File accurately and on timediff --git a/skills/translation-assistant/SKILL.md b/skills/translation-assistant/SKILL.mdnew file mode 100644index 0000000..9f6fda0--- /dev/null+++ b/skills/translation-assistant/SKILL.md@@ -0,0 +1,407 @@+---+name: Translation Assistant+slug: translation-assistant+description: Handle multilingual translation tasks with quality and cultural sensitivity+category: ai-ml+complexity: intermediate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "translate text"+ - "translation"+ - "multilingual"+ - "language translation"+ - "localization"+tags:+ - translation+ - multilingual+ - NLP+ - localization+ - language+---++# Translation Assistant++The Translation Assistant skill guides you through implementing multilingual translation systems that bridge language barriers accurately and culturally appropriately. From simple phrase translation to full document localization, this skill covers the spectrum of translation needs.++Modern translation has been transformed by neural machine translation and large language models, but effective translation still requires understanding context, domain, and cultural nuances. This skill helps you choose the right tools, handle translation quality, and build systems that work across languages.++Whether you're translating user interfaces, customer communications, technical documentation, or creative content, this skill ensures your translations are accurate, natural, and culturally appropriate.++## Core Workflows++### Workflow 1: Choose Translation Approach+1. **Assess** requirements:+ - Language pairs needed+ - Domain specificity+ - Quality requirements+ - Volume and speed needs+ - Budget constraints+2. **Compare** options:+ | Approach | Quality | Speed | Cost | Best For |+ |----------|---------|-------|------|----------|+ | Google Translate API | Good | Fast | $ | General, high volume |+ | DeepL | Very good | Fast | $$ | European languages, quality |+ | OpenAI/Anthropic | Excellent | Medium | $$$ | Nuanced, context-heavy |+ | Custom NMT | Domain-specific | Fast | Setup cost | Specialized domains |+ | Human + MT | Best | Slow | $$$$ | Critical content |+3. **Select** based on tradeoffs+4. **Plan** quality assurance process++### Workflow 2: Implement Translation Pipeline+1. **Set up** translation service:+ ```python+ from google.cloud import translate_v2 as translate++ class TranslationPipeline:+ def __init__(self, provider="google"):+ if provider == "google":+ self.client = translate.Client()+ elif provider == "deepl":+ self.client = deepl.Translator(auth_key)+ elif provider == "llm":+ self.client = LLMTranslator()++ def translate(self, text, source_lang, target_lang):+ # Preprocess+ prepared = self.preprocess(text, source_lang)++ # Translate+ if self.provider == "google":+ result = self.client.translate(+ prepared,+ source_language=source_lang,+ target_language=target_lang+ )+ translated = result["translatedText"]+ elif self.provider == "llm":+ translated = self.llm_translate(prepared, source_lang, target_lang)++ # Postprocess+ final = self.postprocess(translated, target_lang)++ return final+ ```+2. **Handle** special content:+ - Preserve placeholders and variables+ - Handle HTML/markup+ - Maintain formatting+3. **Validate** translation quality+4. **Add** caching for repeated content++### Workflow 3: Build Localization System+1. **Extract** translatable content:+ ```python+ def extract_strings(source_files):+ """Extract strings needing translation."""+ strings = []+ for file in source_files:+ # Find translatable strings+ content = read_file(file)+ matches = find_translatable(content)++ for match in matches:+ strings.append({+ "key": generate_key(match),+ "source": match.text,+ "context": match.surrounding_context,+ "file": file,+ "line": match.line+ })++ return strings+ ```+2. **Translate** with context:+ ```python+ def translate_with_context(strings, target_lang):+ results = []+ for s in strings:+ translation = translate(+ text=s["source"],+ context=s["context"],+ target_lang=target_lang+ )+ results.append({+ **s,+ "translation": translation,+ "target_lang": target_lang+ })+ return results+ ```+3. **Store** in translation management:+ - Translation memory for consistency+ - Glossary for terminology+ - Version control for changes+4. **Deploy** localized content++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Translate text | "Translate [text] to [language]" |+| Choose service | "Best translation for [use case]" |+| Handle domain terms | "Translation glossary for [domain]" |+| Quality check | "Check translation quality" |+| Localize app | "Localize UI for [languages]" |+| Batch translate | "Translate [N] documents" |++## Best Practices++- **Provide Context**: Translation quality depends on context+ - Include surrounding text+ - Specify domain/subject matter+ - Note tone and register (formal/informal)++- **Maintain Terminology Consistency**: Key terms should translate consistently+ - Build domain glossaries+ - Use translation memory+ - Review terminology with stakeholders++- **Preserve Formatting and Variables**: Technical content has special needs+ - Protect placeholders ({name}, %s, etc.)+ - Maintain HTML/markdown structure+ - Handle number and date formats++- **Handle Untranslatable Content**: Some things shouldn't be translated+ - Brand names and trademarks+ - Technical identifiers and codes+ - Legal disclaimers (sometimes)++- **Quality Assurance is Essential**: Machine translation makes mistakes+ - Back-translation for verification+ - Native speaker review+ - Automated quality checks++- **Consider Cultural Adaptation**: Translation != localization+ - Date and number formats+ - Currency and units+ - Cultural references and idioms+ - Right-to-left languages++## Advanced Techniques++### LLM-Based Contextual Translation+Use language models for nuanced translation:+```python+def llm_translate(text, source_lang, target_lang, context=None, style=None):+ prompt = f"""Translate the following text from {source_lang} to {target_lang}.++{"Context: " + context if context else ""}+{"Style: " + style if style else ""}++Important guidelines:+- Maintain the meaning and tone of the original+- Use natural, fluent {target_lang}+- Preserve any formatting, placeholders, or special characters+- If there are cultural references, adapt them appropriately++Source text:+{text}++Translation:"""++ return llm.complete(prompt)++# Example with context+result = llm_translate(+ text="The app crashed when I clicked submit.",+ source_lang="English",+ target_lang="Japanese",+ context="This is a bug report from a user",+ style="Formal technical support"+)+```++### Translation Memory System+Reuse previous translations for consistency:+```python+class TranslationMemory:+ def __init__(self):+ self.memory = {} # source -> {lang: translation}+ self.fuzzy_index = FuzzyMatcher()++ def add(self, source, target_lang, translation):+ if source not in self.memory:+ self.memory[source] = {}+ self.memory[source][target_lang] = translation+ self.fuzzy_index.add(source)++ def lookup(self, source, target_lang, fuzzy_threshold=0.8):+ # Exact match+ if source in self.memory and target_lang in self.memory[source]:+ return {+ "match_type": "exact",+ "translation": self.memory[source][target_lang],+ "confidence": 1.0+ }++ # Fuzzy match+ matches = self.fuzzy_index.search(source, threshold=fuzzy_threshold)+ if matches:+ best = matches[0]+ if target_lang in self.memory[best.text]:+ return {+ "match_type": "fuzzy",+ "original_source": best.text,+ "translation": self.memory[best.text][target_lang],+ "confidence": best.score+ }++ return None++ def translate_with_memory(self, text, target_lang):+ # Check memory first+ cached = self.lookup(text, target_lang)+ if cached and cached["confidence"] > 0.95:+ return cached["translation"]++ # Translate fresh+ translation = translate_api(text, target_lang)++ # Store in memory+ self.add(text, target_lang, translation)++ return translation+```++### Domain Glossary Management+Ensure consistent terminology:+```python+class TranslationGlossary:+ def __init__(self, domain):+ self.domain = domain+ self.terms = {} # source_term -> {lang: translated_term}++ def add_term(self, source, translations):+ self.terms[source.lower()] = translations++ def apply_to_translation(self, source_text, target_lang, translation):+ """+ Ensure glossary terms are used correctly in translation.+ """+ corrections = []+ source_lower = source_text.lower()++ for term, translations in self.terms.items():+ if term in source_lower and target_lang in translations:+ expected = translations[target_lang]+ if expected.lower() not in translation.lower():+ corrections.append({+ "source_term": term,+ "expected": expected,+ "found": False+ })++ if corrections:+ # Re-translate with glossary enforcement+ return self.translate_with_glossary(source_text, target_lang)++ return translation++ def translate_with_glossary(self, text, target_lang):+ glossary_context = "\n".join([+ f"'{term}' should be translated as '{trans[target_lang]}'"+ for term, trans in self.terms.items()+ if target_lang in trans+ ])++ prompt = f"""Translate to {target_lang}, using these required terms:+{glossary_context}++Text: {text}"""++ return llm.complete(prompt)+```++### Quality Estimation+Automatically assess translation quality:+```python+def estimate_translation_quality(source, translation, source_lang, target_lang):+ """+ Estimate translation quality without reference translation.+ """+ checks = []++ # Check 1: Back-translation similarity+ back_translated = translate(translation, target_lang, source_lang)+ back_similarity = compute_similarity(source, back_translated)+ checks.append({+ "check": "back_translation",+ "score": back_similarity,+ "details": {"back_translated": back_translated}+ })++ # Check 2: Length ratio (translations should be similar length)+ length_ratio = len(translation) / max(len(source), 1)+ expected_ratio = get_expected_length_ratio(source_lang, target_lang)+ length_score = 1 - abs(length_ratio - expected_ratio) / expected_ratio+ checks.append({+ "check": "length_ratio",+ "score": max(0, length_score),+ "details": {"ratio": length_ratio, "expected": expected_ratio}+ })++ # Check 3: LLM quality assessment+ quality_prompt = f"""Rate this translation from 1-10 for accuracy and fluency.++Source ({source_lang}): {source}+Translation ({target_lang}): {translation}++Provide scores and brief explanation."""++ llm_assessment = llm.complete(quality_prompt)+ checks.append({+ "check": "llm_assessment",+ "score": parse_score(llm_assessment) / 10,+ "details": {"assessment": llm_assessment}+ })++ # Combined score+ overall = sum(c["score"] for c in checks) / len(checks)++ return {+ "overall_score": overall,+ "checks": checks,+ "recommendation": "accept" if overall > 0.8 else "review"+ }+```++### Batch Translation with Consistency+Translate large volumes while maintaining consistency:+```python+async def batch_translate_consistent(texts, target_lang, batch_size=50):+ """+ Translate many texts while maintaining terminology consistency.+ """+ # Step 1: Extract unique terms for glossary+ all_text = " ".join(texts)+ key_terms = extract_key_terms(all_text)++ # Step 2: Translate key terms first for consistency+ term_translations = {}+ for term in key_terms:+ translation = await translate_with_verification(term, target_lang)+ term_translations[term] = translation++ # Step 3: Batch translate with glossary context+ results = []+ for batch in chunk(texts, batch_size):+ batch_results = await asyncio.gather(*[+ translate_with_glossary(text, target_lang, term_translations)+ for text in batch+ ])+ results.extend(batch_results)++ return results+```++## Common Pitfalls to Avoid++- Translating without context, leading to wrong word choices+- Inconsistent terminology across a project+- Not handling placeholders and variables correctly+- Ignoring cultural differences (dates, currencies, idioms)+- Trusting machine translation without quality checks+- Not maintaining translation memory for consistency+- Forgetting about text expansion (translations are often longer)+- Ignoring right-to-left language considerationsdiff --git a/skills/unit-economics-calculator/SKILL.md b/skills/unit-economics-calculator/SKILL.mdnew file mode 100644index 0000000..e32c601--- /dev/null+++ b/skills/unit-economics-calculator/SKILL.md@@ -0,0 +1,497 @@+---+name: Unit Economics Calculator+slug: unit-economics-calculator+description: Calculate and optimize unit economics including CAC, LTV, payback periods, and contribution margins+category: finance+complexity: moderate+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "unit economics"+ - "CAC calculation"+ - "LTV calculation"+ - "payback period"+ - "contribution margin"+ - "customer profitability"+tags:+ - unit-economics+ - cac+ - ltv+ - saas-metrics+ - profitability+---++# Unit Economics Calculator++Expert unit economics analysis agent that calculates customer acquisition costs, lifetime value, payback periods, and contribution margins. Specializes in SaaS unit economics, e-commerce profitability, and margin optimization.++This skill applies rigorous unit economics frameworks to understand business profitability at the individual customer or transaction level. Perfect for evaluating business viability, optimizing marketing spend, and making pricing decisions.++## Core Workflows++### Workflow 1: SaaS Unit Economics Analysis++**Objective:** Calculate complete SaaS unit economics package++**Steps:**+1. **Customer Acquisition Cost (CAC)**+ - **Fully Loaded CAC:**+ ```+ CAC = (Sales & Marketing Spend) / (New Customers Acquired)++ Include:+ - Advertising spend+ - Marketing team salaries+ - Sales team salaries+ - Sales tools and software+ - Events and conferences+ - Content creation costs+ - Agency fees+ ```++ - **Blended vs. Paid CAC:**+ - Blended CAC: All customers / All S&M spend+ - Paid CAC: Paid acquired customers / Paid marketing spend+ - Organic CAC: Organic customers / Organic costs++ - **CAC by Channel:**+ | Channel | Spend | Customers | CAC |+ |---------|-------|-----------|-----|+ | Paid Search | | | |+ | Paid Social | | | |+ | Content/SEO | | | |+ | Sales Outbound | | | |+ | Referrals | | | |++2. **Lifetime Value (LTV)**+ - **Simple LTV:**+ ```+ LTV = ARPU × Gross Margin × Customer Lifetime++ Customer Lifetime = 1 / Churn Rate+ ```++ - **LTV with Expansion:**+ ```+ LTV = ARPU × Gross Margin / (Churn Rate - Expansion Rate)+ ```++ - **Cohort-Based LTV:**+ - Track actual revenue per cohort over time+ - More accurate but requires historical data+ - Account for degradation curves++3. **LTV/CAC Ratio**+ - **Calculation:**+ ```+ LTV/CAC = Lifetime Value / Customer Acquisition Cost+ ```++ - **Benchmarks:**+ | Ratio | Interpretation |+ |-------|----------------|+ | < 1:1 | Losing money on customers |+ | 1:1 - 3:1 | Underinvesting in growth |+ | 3:1 - 5:1 | Healthy, efficient |+ | > 5:1 | Could invest more in growth |++4. **CAC Payback Period**+ - **Calculation:**+ ```+ Payback (months) = CAC / (Monthly Revenue × Gross Margin)+ ```++ - **Benchmarks:**+ | Segment | Target Payback |+ |---------|----------------|+ | SMB | < 12 months |+ | Mid-Market | < 18 months |+ | Enterprise | < 24 months |++5. **Contribution Margin**+ - **Gross Margin per Customer:**+ ```+ Gross Margin = Revenue - COGS+ Gross Margin % = (Revenue - COGS) / Revenue+ ```++ - **Contribution Margin (after CAC):**+ ```+ CM = LTV - CAC+ CM Ratio = (LTV - CAC) / LTV+ ```++**Deliverable:** Complete SaaS unit economics dashboard++### Workflow 2: E-Commerce Unit Economics++**Objective:** Calculate per-order and per-customer economics++**Steps:**+1. **Per-Order Economics**+ - **Average Order Value (AOV):**+ ```+ AOV = Total Revenue / Number of Orders+ ```++ - **Cost of Goods Sold (COGS):**+ - Product cost+ - Packaging+ - Inbound freight+ - Warehousing allocation++ - **Variable Costs:**+ - Payment processing (2-3%)+ - Outbound shipping+ - Returns/refunds+ - Customer service allocation++ - **Contribution Margin per Order:**+ ```+ CM = AOV - COGS - Variable Costs+ CM % = CM / AOV+ ```++2. **Customer Acquisition Cost**+ ```+ CAC = Marketing Spend / New Customers++ Channel-specific:+ - Paid: Direct spend / Attributed customers+ - Organic: Content + SEO costs / Organic customers+ ```++3. **Customer Lifetime Value**+ - **Repeat Purchase Analysis:**+ ```+ Orders per Customer = Total Orders / Unique Customers+ Purchase Frequency = Orders per Year+ Customer Lifetime = 1 / Annual Churn++ LTV = AOV × Orders per Year × Customer Lifetime × CM %+ ```++ - **Cohort-Based LTV:**+ - Track actual spend by acquisition cohort+ - 12, 24, 36 month LTV by cohort++4. **Return and Refund Impact**+ ```+ Return Rate = Returns / Orders+ Net AOV = AOV × (1 - Return Rate)+ Return Cost = Shipping + Restocking + Lost Product Value+ ```++5. **Break-Even Analysis**+ ```+ Break-Even Orders = CAC / CM per Order+ Break-Even Time = Break-Even Orders / Orders per Year+ ```++**Deliverable:** E-commerce unit economics model++### Workflow 3: Marketplace Unit Economics++**Objective:** Calculate take economics for marketplace businesses++**Steps:**+1. **Transaction Economics**+ - **Gross Merchandise Value (GMV):**+ ```+ GMV = Number of Transactions × Average Transaction Value+ ```++ - **Take Rate:**+ ```+ Take Rate = Net Revenue / GMV+ Typical ranges: 10-30% depending on category+ ```++ - **Net Revenue per Transaction:**+ ```+ Net Revenue = GMV × Take Rate+ ```++2. **Cost per Transaction**+ - Payment processing (2-3%)+ - Fraud/chargebacks+ - Customer support allocation+ - Platform costs allocation+ - Trust and safety++3. **Contribution Margin per Transaction**+ ```+ CM = Net Revenue - Variable Costs per Transaction+ CM % = CM / GMV+ ```++4. **Buyer/Seller Economics**+ - **Buyer CAC:**+ - Acquisition cost+ - Transactions per buyer+ - Buyer LTV++ - **Seller CAC:**+ - Onboarding cost+ - GMV per seller+ - Seller LTV++5. **Liquidity Economics**+ ```+ Match Rate = Successful Transactions / Total Demand+ Higher liquidity → Lower CAC → Better unit economics+ ```++**Deliverable:** Marketplace unit economics framework++### Workflow 4: Subscription Box Unit Economics++**Objective:** Calculate unit economics for subscription box businesses++**Steps:**+1. **Box Economics**+ - **Price per Box:**+ - Monthly subscription price+ - Discounts for prepay (quarterly, annual)+ - Effective monthly revenue++ - **Cost per Box:**+ - Product costs (target 30-40% of price)+ - Packaging materials+ - Fulfillment labor+ - Outbound shipping+ - Payment processing+ - Returns/replacements++2. **Variable Costs**+ ```+ Variable Cost per Box = Products + Packaging + Shipping + Processing+ Contribution per Box = Price - Variable Costs+ Contribution Margin % = Contribution / Price+ ```++3. **Customer Metrics**+ - **Subscriber Lifetime:**+ ```+ Lifetime (months) = 1 / Monthly Churn Rate+ Example: 5% churn = 20 month lifetime+ ```++ - **LTV:**+ ```+ LTV = Contribution per Box × Lifetime (months)+ ```++4. **Acquisition Economics**+ - **CAC Components:**+ - Paid media+ - Influencer costs+ - Trial/free box costs+ - Referral incentives++ - **First Box Profitability:**+ ```+ First Box P&L = Revenue - COGS - CAC+ Many subscription boxes lose money on first box+ ```++5. **Break-Even Analysis**+ ```+ Break-Even Month = CAC / Contribution per Box+ Must retain past break-even to be profitable+ ```++**Deliverable:** Subscription box unit economics model++### Workflow 5: Unit Economics Optimization++**Objective:** Identify and implement unit economics improvements++**Steps:**+1. **Current State Assessment**+ - Calculate current LTV, CAC, LTV/CAC+ - Identify weakest metrics+ - Benchmark vs. best-in-class++2. **CAC Reduction Levers**+ - **Channel Optimization:**+ - Cut underperforming channels+ - Double down on efficient channels+ - Improve conversion rates++ - **Efficiency Improvements:**+ - Sales productivity+ - Marketing automation+ - Better targeting+ - Lower CPM/CPC negotiation++ - **Organic Growth:**+ - Referral programs+ - Content marketing+ - SEO investment+ - Product-led growth++3. **LTV Improvement Levers**+ - **Reduce Churn:**+ - Improve onboarding+ - Better customer success+ - Product improvements+ - Save/retention programs++ - **Increase ARPU:**+ - Price increases+ - Upsell motions+ - Cross-sell products+ - Premium tiers++ - **Improve Margins:**+ - COGS reduction+ - Pricing optimization+ - Efficiency gains++4. **Impact Modeling**+ | Lever | Current | Target | Impact on LTV/CAC |+ |-------|---------|--------|-------------------|+ | Reduce CAC 20% | | | |+ | Reduce Churn 20% | | | |+ | Increase ARPU 15% | | | |+ | Improve Margin 5pp | | | |++5. **Prioritized Action Plan**+ - Quick wins (30 days)+ - Medium-term (90 days)+ - Long-term initiatives (12 months)+ - Expected improvement trajectory++**Deliverable:** Unit economics optimization plan with projected improvements++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Calculate CAC | "Calculate customer acquisition cost" |+| Calculate LTV | "Calculate customer lifetime value" |+| LTV/CAC analysis | "Analyze unit economics" |+| Payback period | "Calculate CAC payback period" |+| Contribution margin | "Calculate contribution margin" |+| Optimize | "How do I improve unit economics?" |++## Unit Economics Formulas++### Customer Acquisition++| Metric | Formula |+|--------|---------|+| CAC | Total S&M Spend / New Customers |+| Blended CAC | All S&M / All New Customers |+| Paid CAC | Paid Spend / Paid Customers |+| Channel CAC | Channel Spend / Channel Customers |++### Customer Value++| Metric | Formula |+|--------|---------|+| LTV (simple) | ARPU × Gross Margin / Churn |+| LTV (with expansion) | ARPU × GM / (Churn - Expansion) |+| Customer Lifetime | 1 / Churn Rate |+| ARPU | Revenue / Customers |++### Efficiency Metrics++| Metric | Formula | Benchmark |+|--------|---------|-----------|+| LTV/CAC | LTV / CAC | > 3:1 |+| CAC Payback | CAC / (Monthly Rev × GM) | < 12 mo |+| Magic Number | Net New ARR / Prior Q S&M | > 0.75 |+| Burn Multiple | Net Burn / Net New ARR | < 2 |++### Margin Metrics++| Metric | Formula |+|--------|---------|+| Gross Margin | (Revenue - COGS) / Revenue |+| Contribution Margin | (Revenue - COGS - Variable Costs) / Revenue |+| Net Margin | Net Income / Revenue |++## Unit Economics Dashboard Template++```markdown+# Unit Economics Dashboard: [Company]+**Period:** [Date Range]++## Customer Acquisition+| Metric | Value | Benchmark | Status |+|--------|-------|-----------|--------|+| Blended CAC | $ | $ | |+| Paid CAC | $ | $ | |+| Organic CAC | $ | $ | |+| S&M as % of Revenue | % | % | |++## Customer Value+| Metric | Value | Benchmark | Status |+|--------|-------|-----------|--------|+| ARPU | $ | $ | |+| Gross Margin | % | % | |+| LTV | $ | $ | |+| Customer Lifetime | mo | mo | |++## Efficiency+| Metric | Value | Benchmark | Status |+|--------|-------|-----------|--------|+| LTV/CAC | :1 | 3:1+ | |+| CAC Payback | mo | <12 mo | |+| Magic Number | | >0.75 | |++## Trends+| Metric | Last Q | This Q | Change |+|--------|--------|--------|--------|+| CAC | | | |+| LTV | | | |+| LTV/CAC | | | |+| Payback | | | |++## Action Items+1. [Priority 1]+2. [Priority 2]+3. [Priority 3]+```++## Best Practices++### Calculation+- Use consistent time periods+- Include all relevant costs in CAC+- Account for expansion in LTV+- Segment by customer type+- Track trends over time++### Benchmarking+- Compare to industry standards+- Track improvement over time+- Adjust for business model differences+- Consider stage of company++### Optimization+- Focus on biggest leverage points+- Test changes carefully+- Monitor for unintended effects+- Balance growth and efficiency++## Integration with Other Skills++- **Use with `revenue-modeler`:** Validate revenue assumptions+- **Use with `cash-flow-forecaster`:** Model CAC payback impact+- **Use with `budget-planner`:** Inform marketing budget+- **Use with `investment-analyzer`:** Support investor metrics+- **Use with `financial-analyst`:** Deep-dive profitability++## Common Pitfalls to Avoid++- **Incomplete CAC:** Missing costs understates true CAC+- **Overstated LTV:** Optimistic churn assumptions+- **Ignoring cohort degradation:** LTV changes over time+- **Channel mixing:** Blended CAC hides inefficiencies+- **Ignoring payback:** LTV/CAC without cash timing+- **No segmentation:** Different segments have different economics+- **Static analysis:** Unit economics change over time+- **Ignoring CAC payback timing:** Cash flow mattersdiff --git a/skills/valuation-analyst/SKILL.md b/skills/valuation-analyst/SKILL.mdnew file mode 100644index 0000000..84630af--- /dev/null+++ b/skills/valuation-analyst/SKILL.md@@ -0,0 +1,497 @@+---+name: Valuation Analyst+slug: valuation-analyst+description: Perform company and asset valuations using DCF, comparables, precedent transactions, and other methodologies+category: finance+complexity: complex+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "valuation analysis"+ - "company valuation"+ - "DCF model"+ - "comparable analysis"+ - "enterprise value"+ - "fair value"+tags:+ - valuation+ - dcf+ - comparables+ - m-and-a+ - enterprise-value+---++# Valuation Analyst++Expert valuation agent that determines fair value of companies and assets using multiple methodologies. Specializes in DCF analysis, comparable company analysis, precedent transactions, and asset-based valuation. Provides comprehensive valuation for investment decisions, M&A, and strategic planning.++This skill applies rigorous valuation frameworks used by investment banks, private equity firms, and corporate finance professionals. Perfect for startup valuations, M&A analysis, investment decisions, and fairness opinions.++## Core Workflows++### Workflow 1: Discounted Cash Flow (DCF) Valuation++**Objective:** Value company based on projected future cash flows++**Steps:**+1. **Financial Projections (5-10 years)**+ - **Revenue Projections:**+ - Historical growth analysis+ - Market size and share+ - Segment-level forecasts+ - Growth rate deceleration++ - **Profitability Projections:**+ - Gross margin trends+ - Operating margin expansion+ - SG&A leverage+ - Target margins at maturity++ - **Capital Requirements:**+ - CapEx as % of revenue+ - Working capital changes+ - D&A schedule++2. **Free Cash Flow Calculation**+ ```+ EBIT (Earnings Before Interest & Taxes)+ - Taxes (EBIT × Tax Rate)+ = NOPAT (Net Operating Profit After Tax)+ + Depreciation & Amortization+ - Capital Expenditures+ - Change in Working Capital+ = Unlevered Free Cash Flow (UFCF)+ ```++3. **Discount Rate (WACC)**+ - **Cost of Equity (CAPM):**+ ```+ Ke = Rf + β × (Rm - Rf)++ Where:+ Rf = Risk-free rate (10-year Treasury)+ β = Levered beta+ Rm - Rf = Equity risk premium (5-7%)++ For private companies, add size premium (2-6%)+ ```++ - **Cost of Debt:**+ ```+ Kd = Interest Rate × (1 - Tax Rate)+ ```++ - **WACC Calculation:**+ ```+ WACC = (E/V × Ke) + (D/V × Kd)++ E = Market value of equity+ D = Market value of debt+ V = E + D+ ```++4. **Terminal Value**+ - **Perpetuity Growth Method:**+ ```+ TV = FCF(final year) × (1 + g) / (WACC - g)++ g = Terminal growth rate (typically 2-3%)+ ```++ - **Exit Multiple Method:**+ ```+ TV = EBITDA(final year) × Exit Multiple++ Exit multiple based on comparables+ ```++5. **Enterprise Value Calculation**+ ```+ Enterprise Value = Σ(FCF / (1 + WACC)^t) + TV / (1 + WACC)^n++ t = year number+ n = final projection year+ ```++6. **Equity Value Bridge**+ ```+ Enterprise Value+ - Total Debt+ - Preferred Stock+ - Minority Interest+ + Cash & Equivalents+ + Non-operating Assets+ = Equity Value++ Per Share Value = Equity Value / Diluted Shares+ ```++7. **Sensitivity Analysis**+ - WACC vs Terminal Growth matrix+ - Revenue growth sensitivity+ - Margin sensitivity+ - Multiple sensitivity++**Deliverable:** DCF valuation with sensitivity tables++### Workflow 2: Comparable Company Analysis++**Objective:** Value company using trading multiples of similar public companies++**Steps:**+1. **Select Comparable Companies**+ - Same industry/sector+ - Similar business model+ - Comparable size (revenue, market cap)+ - Similar growth profile+ - Geographic relevance+ - Minimum 5-7 comps preferred++2. **Gather Market Data**+ - Stock price (current)+ - Shares outstanding (diluted)+ - Market capitalization+ - Total debt+ - Cash and equivalents+ - Minority interest++3. **Calculate Enterprise Value**+ ```+ Market Cap = Share Price × Diluted Shares++ Enterprise Value = Market Cap + Debt - Cash + Minority Interest+ ```++4. **Gather Financial Metrics**+ - LTM (Last Twelve Months):+ - Revenue+ - EBITDA+ - EBIT+ - Net Income+ - EPS++ - NTM (Next Twelve Months) estimates:+ - Revenue+ - EBITDA+ - EPS++5. **Calculate Trading Multiples**+ | Multiple | Formula | When to Use |+ |----------|---------|-------------|+ | EV/Revenue | EV / Revenue | High growth, negative EBITDA |+ | EV/EBITDA | EV / EBITDA | Most common, capital intensive |+ | EV/EBIT | EV / EBIT | D&A differs materially |+ | P/E | Price / EPS | Mature, profitable |+ | P/B | Price / Book | Financial institutions |+ | PEG | P/E / Growth | Growth-adjusted comparison |++6. **Analyze and Select Multiples**+ - Calculate mean, median, range+ - Identify outliers+ - Consider premium/discount factors+ - Select appropriate multiple range++7. **Apply to Target Company**+ ```+ Enterprise Value = Target Metric × Selected Multiple++ Example:+ Target EBITDA = $50M+ Median EV/EBITDA = 12.0x+ Implied EV = $600M+ ```++8. **Valuation Range**+ - Low (25th percentile multiple)+ - Mid (median multiple)+ - High (75th percentile multiple)++**Deliverable:** Comparable company analysis with valuation range++### Workflow 3: Precedent Transaction Analysis++**Objective:** Value company using M&A transaction multiples++**Steps:**+1. **Identify Relevant Transactions**+ - Same industry+ - Similar deal size+ - Recent (last 3-5 years)+ - Similar deal structure+ - Minimum 5-7 transactions++2. **Gather Transaction Details**+ - Announcement date+ - Acquirer and target+ - Deal value+ - Deal structure (stock/cash)+ - Strategic vs financial buyer+ - Control premium paid++3. **Calculate Transaction Multiples**+ - EV/Revenue at time of deal+ - EV/EBITDA at time of deal+ - EV/EBIT at time of deal+ - Premium to trading price++4. **Adjust for Context**+ - Market conditions at time of deal+ - Synergy expectations+ - Competitive bidding situation+ - Distressed vs strategic deals++5. **Apply to Target**+ ```+ Transaction EV = Target Metric × Transaction Multiple+ ```++6. **Consider Control Premium**+ - Typical premium: 20-40% over trading+ - Adjust for minority vs control stakes+ - Strategic vs financial buyers++**Deliverable:** Precedent transaction analysis with implied value range++### Workflow 4: Startup/Private Company Valuation++**Objective:** Value early-stage or private company++**Steps:**+1. **Valuation Method Selection**++ | Stage | Primary Methods |+ |-------|-----------------|+ | Pre-revenue | Scorecard, Berkus, Risk Factor |+ | Early revenue | Revenue multiples, DCF (if possible) |+ | Growth stage | Revenue multiples, DCF |+ | Late stage | DCF, comps, precedent transactions |++2. **Revenue Multiple Approach**+ - **Select Comparable Multiples:**+ - Public SaaS: 5-15x revenue+ - Marketplace: 1-5x GMV, 5-15x revenue+ - E-commerce: 0.5-2x revenue++ - **Apply Discount:**+ - Illiquidity discount: 20-35%+ - Size discount: 10-30%+ - Stage discount: varies++ - **Calculation:**+ ```+ Value = Revenue × Multiple × (1 - Discounts)+ ```++3. **Venture Capital Method**+ ```+ Exit Value = Projected Revenue × Exit Multiple+ Pre-money Value = Exit Value / Target Return++ Example:+ Year 5 Revenue = $100M+ Exit Multiple = 6x+ Exit Value = $600M+ Target Return = 10x+ Current Value = $60M+ ```++4. **Scorecard Method (Pre-revenue)**+ - Average pre-money for stage/region+ - Score on factors (±50%):+ - Team strength+ - Market opportunity+ - Product/technology+ - Competitive environment+ - Partnerships+ - Need for financing+ - Multiply base by weighted factors++5. **Cap Table Implications**+ - Pre-money vs post-money+ - Dilution calculation+ - Option pool sizing+ - Liquidation preferences++**Deliverable:** Private company valuation with methodology explanation++### Workflow 5: Sum-of-the-Parts (SOTP) Valuation++**Objective:** Value multi-segment company by valuing each segment separately++**Steps:**+1. **Segment Identification**+ - Business segments from filings+ - Geographic segments+ - Product line segments+ - Operational vs non-operating assets++2. **Segment Financial Separation**+ - Segment revenue+ - Segment EBITDA+ - Segment assets+ - Corporate overhead allocation++3. **Segment Valuation**+ - Value each segment using appropriate method:+ - Growth segment: Revenue multiple or DCF+ - Mature segment: EBITDA multiple+ - Asset-heavy: Asset-based+ - Use segment-specific comparables++4. **Corporate Adjustments**+ - Corporate overhead (capitalize as liability)+ - Shared services+ - Intercompany eliminations+ - Net debt allocation++5. **Sum of Parts**+ ```+ Segment A Value: $X+ + Segment B Value: $Y+ + Segment C Value: $Z+ - Corporate Overhead Value: ($W)+ - Net Debt: ($D)+ = Total Equity Value+ ```++6. **Conglomerate Discount**+ - Typical discount: 10-25%+ - Reasons: complexity, capital allocation+ - Consider break-up value++**Deliverable:** SOTP valuation with segment breakdown++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| DCF valuation | "Perform DCF analysis" |+| Comparables | "Value using comparable companies" |+| Transactions | "Analyze precedent transactions" |+| Startup value | "Value this startup" |+| SOTP | "Sum-of-the-parts valuation" |+| Full analysis | "Complete valuation analysis" |++## Valuation Multiples Reference++### By Industry (EV/EBITDA Ranges)++| Industry | Range | Notes |+|----------|-------|-------|+| Software/SaaS | 15-30x | Revenue multiples also common |+| Healthcare | 10-15x | Varies by sub-sector |+| Consumer Retail | 6-10x | Location matters |+| Manufacturing | 6-10x | Asset intensity varies |+| Financial Services | P/B or P/E | Book value focus |+| Energy | 4-8x | Commodity sensitive |+| Real Estate | Cap rate | NOI based |+| Media | 8-15x | Content value matters |++### SaaS Revenue Multiples++| Growth Rate | ARR Multiple |+|-------------|--------------|+| < 20% | 3-6x |+| 20-40% | 6-10x |+| 40-60% | 10-15x |+| 60-100% | 15-25x |+| > 100% | 25x+ |++### Common Adjustments++| Adjustment | Application |+|------------|-------------|+| Illiquidity discount | Private companies (20-35%) |+| Control premium | Acquisitions (20-40%) |+| Size premium | Small companies (add to WACC) |+| Country risk | Emerging markets (add to WACC) |+| Minority discount | Non-control stakes (15-30%) |++## DCF Template++```markdown+# DCF Valuation: [Company Name]++## Assumptions+| Input | Value | Source |+|-------|-------|--------|+| Risk-free Rate | % | 10-yr Treasury |+| Equity Risk Premium | % | Market |+| Beta (Levered) | | Comparable |+| Cost of Debt | % | Current rate |+| Tax Rate | % | Statutory |+| D/E Ratio | % | Target |+| Terminal Growth | % | GDP proxy |++## WACC Calculation+Cost of Equity: %+Cost of Debt (after-tax): %+WACC: %++## Projections ($M)+| | Y1 | Y2 | Y3 | Y4 | Y5 | Terminal |+|-|----|----|----|----|----| ---------|+| Revenue | | | | | | |+| EBITDA | | | | | | |+| EBIT | | | | | | |+| Taxes | | | | | | |+| NOPAT | | | | | | |+| + D&A | | | | | | |+| - CapEx | | | | | | |+| - Δ WC | | | | | | |+| FCF | | | | | | |+| Discount Factor | | | | | | |+| PV of FCF | | | | | | |++## Valuation Summary+Sum of PV of FCF: $+Terminal Value: $+PV of Terminal Value: $+Enterprise Value: $+- Net Debt: $+Equity Value: $+Shares Outstanding:+Value per Share: $++## Sensitivity Analysis+[WACC vs Terminal Growth matrix]+```++## Best Practices++### Methodology Selection+- Use multiple methods for triangulation+- Weight methods by applicability+- Consider data availability+- Match to purpose (minority, control, etc.)++### Assumption Setting+- Ground assumptions in data+- Be explicit about sources+- Test sensitivity+- Document reasoning++### Presentation+- Show range, not point estimate+- Include key assumptions+- Provide sensitivity analysis+- Compare methods++## Integration with Other Skills++- **Use with `financial-analyst`:** Financial statement analysis+- **Use with `investment-analyzer`:** Investment decision support+- **Use with `revenue-modeler`:** Revenue projection inputs+- **Use with `contract-analyzer`:** Deal term analysis+- **Use with `compliance-checker`:** Regulatory considerations++## Common Pitfalls to Avoid++- **Single methodology:** Use multiple approaches+- **Circular references:** WACC and capital structure+- **Terminal value dominance:** Should be < 75% of value+- **Hockey stick projections:** Reality check growth rates+- **Ignoring working capital:** Significant for many businesses+- **Wrong peer selection:** Comparability matters+- **Stale data:** Use current market data+- **Overcomplication:** Simpler models often more reliablediff --git a/skills/vector-search-designer/SKILL.md b/skills/vector-search-designer/SKILL.mdnew file mode 100644index 0000000..f3fb22f--- /dev/null+++ b/skills/vector-search-designer/SKILL.md@@ -0,0 +1,232 @@+---+name: Vector Search Designer+slug: vector-search-designer+description: Design vector similarity search systems for semantic retrieval at scale+category: ai-ml+complexity: advanced+version: "1.0.0"+author: "ID8Labs"+triggers:+ - "vector search"+ - "similarity search"+ - "vector database"+ - "semantic search design"+ - "nearest neighbor"+tags:+ - vector-search+ - similarity+ - vector-database+ - ANN+ - semantic-search+---++# Vector Search Designer++The Vector Search Designer skill helps you architect and implement vector similarity search systems that power semantic search, recommendation engines, and AI applications. It guides you through selecting the right vector database, designing index structures, optimizing query performance, and scaling to millions or billions of vectors.++Vector search has become foundational to modern AI systems, from RAG pipelines to product recommendations. This skill covers the full stack: understanding approximate nearest neighbor (ANN) algorithms, choosing between database options, tuning recall vs latency tradeoffs, and implementing production-ready search infrastructure.++Whether you are building on Pinecone, Weaviate, Qdrant, pgvector, or implementing your own solution, this skill ensures your vector search system meets your performance and accuracy requirements.++## Core Workflows++### Workflow 1: Select Vector Database+1. **Gather** requirements:+ - Scale: How many vectors?+ - Query patterns: Single vs batch, filters needed?+ - Latency requirements: Real-time vs batch?+ - Update frequency: Static vs dynamic?+ - Infrastructure: Managed vs self-hosted?+2. **Compare** options:+ | Database | Scale | Managed | Features | Best For |+ |----------|-------|---------|----------|----------|+ | Pinecone | Billion+ | Yes | Hybrid, namespaces | Production, zero-ops |+ | Weaviate | 100M+ | Both | GraphQL, modules | Multi-modal, complex queries |+ | Qdrant | 100M+ | Both | Rust perf, filtering | High performance, self-hosted |+ | Milvus | Billion+ | Both | GPU support, clustering | Large scale, ML teams |+ | pgvector | 10M | No | PostgreSQL native | Existing Postgres, small scale |+ | Chroma | 1M | No | Simple API | Prototyping, embedded |+3. **Evaluate** with your data+4. **Document** decision rationale++### Workflow 2: Design Index Architecture+1. **Choose** ANN algorithm:+ - HNSW: Best recall/speed tradeoff, memory intensive+ - IVF: Good for very large datasets, requires training+ - PQ: Compression for scale, some accuracy loss+ - Flat: Exact search, small datasets only+2. **Configure** index parameters:+ ```python+ # HNSW example configuration+ hnsw_config = {+ "M": 16, # Connections per node (higher = better recall, more memory)+ "efConstruction": 200, # Build-time search depth+ "efSearch": 100, # Query-time search depth+ }++ # IVF example configuration+ ivf_config = {+ "nlist": 1024, # Number of clusters+ "nprobe": 32, # Clusters to search at query time+ }+ ```+3. **Plan** sharding strategy for scale+4. **Design** metadata schema for filtering++### Workflow 3: Optimize Search Performance+1. **Benchmark** baseline performance:+ - Queries per second (QPS)+ - Latency (p50, p95, p99)+ - Recall@k accuracy+2. **Identify** bottlenecks:+ - Index loading time+ - Search latency+ - Filter computation+ - Network overhead+3. **Apply** optimizations:+ - Tune index parameters (ef, nprobe)+ - Implement query caching+ - Optimize filter expressions+ - Consider quantization for memory+4. **Validate** recall vs latency tradeoff+5. **Document** optimal configuration++## Quick Reference++| Action | Command/Trigger |+|--------|-----------------|+| Choose database | "Which vector database for [use case]" |+| Design index | "Design vector index for [scale]" |+| Optimize search | "Speed up vector search" |+| Add filtering | "Add metadata filters to vector search" |+| Scale vectors | "Scale to [N] million vectors" |+| Benchmark search | "Benchmark vector search performance" |++## Best Practices++- **Right-Size Your Database**: Don't over-engineer for scale you don't need+ - <1M vectors: pgvector or Chroma often sufficient+ - 1-100M vectors: Qdrant, Weaviate, or Pinecone+ - 100M+ vectors: Milvus or Pinecone with careful design++- **Understand Recall vs Speed Tradeoff**: ANN is approximate by design+ - Higher recall = slower queries+ - Tune based on your accuracy requirements+ - Measure actual recall, don't assume++- **Use Hybrid Search When Needed**: Combine vector and keyword search+ - Vector: semantic similarity+ - Keyword (BM25): exact terms, names, codes+ - Typically improves results for mixed queries++- **Design Metadata for Filtering**: Plan your filter strategy upfront+ - Indexed fields for frequent filters+ - Avoid filtering on high-cardinality fields+ - Pre-filter vs post-filter tradeoffs++- **Batch Operations When Possible**: Reduce network overhead+ - Batch upserts for ingestion+ - Batch queries when latency allows+ - Use async operations++- **Monitor and Alert**: Production search needs observability+ - Query latency percentiles+ - Index size and memory usage+ - Recall degradation over time++## Advanced Techniques++### Multi-Vector Search+Handle documents with multiple representations:+```python+class MultiVectorIndex:+ def __init__(self):+ self.title_index = VectorIndex(dim=768)+ self.content_index = VectorIndex(dim=768)+ self.summary_index = VectorIndex(dim=768)++ def search(self, query_embedding, weights=None):+ weights = weights or {"title": 0.3, "content": 0.5, "summary": 0.2}++ results = {}+ for field, weight in weights.items():+ index = getattr(self, f"{field}_index")+ field_results = index.search(query_embedding, k=20)+ for doc_id, score in field_results:+ results[doc_id] = results.get(doc_id, 0) + score * weight++ return sorted(results.items(), key=lambda x: x[1], reverse=True)[:10]+```++### Filtered Vector Search Strategies+Optimize search with filters:+```python+def filtered_search(query_embedding, filters, k=10):+ # Strategy 1: Pre-filter (for selective filters)+ if estimate_selectivity(filters) < 0.1:+ candidate_ids = apply_filters(filters)+ return vector_search_subset(query_embedding, candidate_ids, k)++ # Strategy 2: Post-filter (for non-selective filters)+ elif estimate_selectivity(filters) > 0.5:+ results = vector_search(query_embedding, k * 3)+ filtered = [r for r in results if matches_filters(r, filters)]+ return filtered[:k]++ # Strategy 3: Hybrid (general case)+ else:+ return vector_search_with_filters(query_embedding, filters, k)+```++### Quantization for Scale+Reduce memory with acceptable accuracy loss:+```python+# Product Quantization configuration+pq_config = {+ "nbits": 8, # Bits per sub-quantizer+ "m": 16, # Number of sub-quantizers+ # 768-dim * 4 bytes = 3KB/vector -> 16 * 1 byte = 16 bytes/vector+}++# Binary quantization (extreme compression)+binary_config = {+ "threshold": 0, # Values > 0 -> 1, else -> 0+ # 768-dim * 4 bytes = 3KB/vector -> 768 bits = 96 bytes/vector+}+```++### Incremental Index Updates+Handle dynamic data efficiently:+```python+class DynamicVectorIndex:+ def __init__(self, rebuild_threshold=10000):+ self.main_index = build_optimized_index()+ self.delta_index = [] # Recent additions+ self.rebuild_threshold = rebuild_threshold++ def add(self, vector, metadata):+ self.delta_index.append((vector, metadata))+ if len(self.delta_index) >= self.rebuild_threshold:+ self.rebuild()++ def search(self, query, k):+ main_results = self.main_index.search(query, k)+ delta_results = brute_force_search(self.delta_index, query, k)+ return merge_results(main_results, delta_results, k)++ def rebuild(self):+ all_data = self.main_index.get_all() + self.delta_index+ self.main_index = build_optimized_index(all_data)+ self.delta_index = []+```++## Common Pitfalls to Avoid++- Using exact (flat) search at scale instead of ANN+- Not measuring actual recall, assuming ANN is "good enough"+- Over-indexing metadata fields, slowing down updates+- Ignoring the memory requirements of HNSW indexes+- Not planning for index rebuilds and maintenance windows+- Assuming vector databases handle all use cases (sometimes Elasticsearch is better)+- Forgetting to normalize vectors for cosine similarity+- Mixing embeddings from different models in the same index