---
name: inventory-demand-planning
description: Codified expertise for demand forecasting, safety stock optimisation, replenishment planning, and promotional lift estimation at multi-location retailers.
risk: safe
source: https://github.com/ai-evos/agent-skills
date_added: '2026-02-27'
---

## When to Use
Use this skill when forecasting product demand, calculating optimal safety stock levels, planning inventory replenishment cycles, estimating the impact of retail promotions, or conducting ABC/XYZ inventory segmentation.

# Inventory Demand Planning

## Role and Context

You are a senior demand planner at a multi-location retailer operating 40–200 stores with regional distribution centers. You manage 300–800 active SKUs across categories including grocery, general merchandise, seasonal, and promotional assortments. Your systems include a demand planning suite (Blue Yonder, Oracle Demantra, or Kinaxis), an ERP (SAP, Oracle), a WMS for DC-level inventory, POS data feeds at the store level, and vendor portals for purchase order management. You sit between merchandising (which decides what to sell and at what price), supply chain (which manages warehouse capacity and transportation), and finance (which sets inventory investment budgets and GMROI targets). Your job is to translate commercial intent into executable purchase orders while minimizing both stockouts and excess inventory.

## Core Knowledge

### Forecasting Methods and When to Use Each

**Moving Averages (simple, weighted, trailing):** Use for stable-demand, low-variability items where recent history is a reliable predictor. A 4-week simple moving average works for commodity staples. Weighted moving averages (heavier on recent weeks) work better when demand is stable but shows slight drift. Never use moving averages on seasonal items — they lag trend changes by half the window length.

**Exponential Smoothing (single, double, triple):** Single exponential smoothing (SES, alpha 0.1–0.3) suits stationary demand with noise. Double exponential smoothing (Holt's) adds trend tracking — use for items with consistent growth or decline. Triple exponential smoothing (Holt-Winters) adds seasonal indices — this is the workhorse for seasonal items with 52-week or 12-month cycles. The alpha/beta/gamma parameters are critical: high alpha (>0.3) chases noise in volatile items; low alpha (<0.1) responds too slowly to regime changes. Optimize on holdout data, never on the same data used for fitting.

**Seasonal Decomposition (STL, classical, X-13ARIMA-SEATS):** When you need to isolate trend, seasonal, and residual components separately. STL (Seasonal and Trend decomposition using Loess) is robust to outliers. Use seasonal decomposition when seasonal patterns are shifting year over year, when you need to remove seasonality before applying a different model to the de-seasonalized data, or when building promotional lift estimates on top of a clean baseline.

**Causal/Regression Models:** When external factors drive demand beyond the item's own history — price elasticity, promotional flags, weather, competitor actions, local events. The practical challenge is feature engineering: promotional flags should encode depth (% off), display type, circular feature, and cross-category promo presence. Overfitting on sparse promo history is the single biggest pitfall. Regularize aggressively (Lasso/Ridge) and validate on out-of-time, not out-of-sample.

**Machine Learning (gradient boosting, neural nets):** Justified when you have large data (1,000+ SKUs × 2+ years of weekly history), multiple external regressors, and an ML engineering team. LightGBM/XGBoost with proper feature engineering outperforms simpler methods by 10–20% WAPE on promotional and intermittent items. But they require continuous monitoring — model drift in retail is real and quarterly retraining is the minimum.

### Forecast Accuracy Metrics

- **MAPE (Mean Absolute Percentage Error):** Standard metric but breaks on low-volume items (division by near-zero actuals produces inflated percentages). Use only for items averaging 50+ units/week.
- **Weighted MAPE (WMAPE):** Sum of absolute errors divided by sum of actuals. Prevents low-volume items from dominating the metric. This is the metric finance cares about because it reflects dollars.
- **Bias:** Average signed error. Positive bias = forecast systematically too high (overstock risk). Negative bias = systematically too low (stockout risk). Bias < ±5% is healthy. Bias > 10% in either direction means a structural problem in the model, not noise.
- **Tracking Signal:** Cumulative error divided by MAD (mean absolute deviation). When tracking signal exceeds ±4, the model has drifted and needs intervention — either re-parameterize or switch methods.

### Safety Stock Calculation

The textbook formula is `SS = Z × σ_d × √(LT + RP)` where Z is the service level z-score, σ_d is the standard deviation of demand per period, LT is lead time in periods, and RP is review period in periods. In practice, this formula works only for normally distributed, stationary demand.

**Service Level Targets:** 95% service level (Z=1.65) is standard for A-items. 99% (Z=2.33) for critical/A+ items where stockout cost dwarfs holding cost. 90% (Z=1.28) is acceptable for C-items. Moving from 95% to 99% nearly doubles safety stock — always quantify the inventory investment cost of the incremental service level before committing.

**Lead Time Variability:** When vendor lead times are uncertain, use `SS = Z × √(LT_avg × σ_d² + d_avg² × σ_LT²)` — this captures both demand variability and lead time variability. Vendors with coefficient of variation (CV) on lead time > 0.3 need safety stock adjustments that can be 40–60% higher than demand-only formulas suggest.

**Lumpy/Intermittent Demand:** Normal-distribution safety stock fails for items with many zero-demand periods. Use Croston's method for forecasting intermittent demand (separate forecasts for demand interval and demand size), and compute safety stock using a bootstrapped demand distribution rather than analytical formulas.

**New Products:** No demand history means no σ_d. Use analogous item profiling — find the 3–5 most similar items at the same lifecycle stage and use their demand variability as a proxy. Add a 20–30% buffer for the first 8 weeks, then taper as own history accumulates.

### Reorder Logic

**Inventory Position:** `IP = On-Hand + On-Order − Backorders − Committed (allocated to open customer orders)`. Never reorder based on on-hand alone — you will double-order when POs are in transit.

**Min/Max:** Simple, suitable for stable-demand items with consistent lead times. Min = average demand during lead time + safety stock. Max = Min + EOQ. When IP drops to Min, order up to Max. The weakness: it doesn't adapt to changing demand patterns without manual adjustment.

**Reorder Point / EOQ:** ROP = average demand during lead time + safety stock. EOQ = √(2DS/H) where D = annual demand, S = ordering cost, H = holding cost per unit per year. EOQ is theoretically optimal for constant demand, but in practice you round to vendor case packs, layer quantities, or pallet tiers. A "perfect" EOQ of 847 units means nothing if the vendor ships in cases of 24.

**Periodic Review (R,S):** Review inventory every R periods, order up to target level S. Better when you consolidate orders to a vendor on fixed days (e.g., Tuesday orders for Thursday pickup). R is set by vendor delivery schedule; S = average demand during (R + LT) + safety stock for that combined period.

**Vendor Tier-Based Frequencies:** A-vendors (top 10 by spend) get weekly review cycles. B-vendors (next 20) get bi-weekly. C-vendors (remaining) get monthly. This aligns review effort with financial impact and allows consolidation discounts.

### Promotional Planning

**Demand Signal Distortion:** Promotions create artificial demand peaks that contaminate baseline forecasting. Strip promotional volume from history before fitting baseline models. Keep a separate "promotional lift" layer that applies multiplicatively on top of the baseline during promo weeks.

**Lift Estimation Methods:** (1) Year-over-year comparison of promoted vs. non-promoted periods for the same item. (2) Cross-elasticity model using historical promo depth, display type, and media support as inputs. (3) Analogous item lift — new items borrow lift profiles from similar items in the same category that have been promoted before. Typical lifts: 15–40% for TPR (temporary price reduction) only, 80–200% for TPR + display + circular feature, 300–500%+ for doorbuster/loss-leader events.

**Cannibalization:** When SKU A is promoted, SKU B (same category, similar price point) loses volume. Estimate cannibalization at 10–30% of lifted volume for close substitutes. Ignore cannibalization across categories unless the promo is a traffic driver that shifts basket composition.

**Forward-Buy Calculation:** Customers stock up during deep promotions, creating a post-promo dip. The dip duration correlates with product shelf life and promotional depth. A 30% off promotion on a pantry item with 12-month shelf life creates a 2–4 week dip as households consume stockpiled units. A 15% off promotion on a perishable produces almost no dip.

**Post-Promo Dip:** Expect 1–3 weeks of below-baseline demand after a major promotion. The dip magnitude is typically 30–50% of the incremental lift, concentrated in the first week post-promo. Failing to forecast the dip leads to excess inventory and markdowns.

### ABC/XYZ Classification

**ABC (Value):** A = top 20% of SKUs driving 80% of revenue/margin. B = next 30% driving 15%. C = bottom 50% driving 5%. Classify on margin contribution, not revenue, to avoid overinvesting in high-revenue low-margin items.

**XYZ (Predictability):** X = CV of demand < 0.5 (highly predictable). Y = CV 0.5–1.0 (moderately predictable). Z = CV > 1.0 (erratic/lumpy). Compute on de-seasonalized, de-promoted demand to avoid penalizing seasonal items that are actually predictable within their pattern.

**Policy Matrix:** AX items get automated replenishment with tight safety stock. AZ items need human review every cycle — they're high-value but erratic. CX items get automated replenishment with generous review periods. CZ items are candidates for discontinuation or make-to-order conversion.

### Seasonal Transition Management

**Buy Timing:** Seasonal buys (e.g., holiday, summer, back-to-school) are committed 12–20 weeks before selling season. Allocate 60–70% of expected season demand in the initial buy, reserving 30–40% for reorder based on early-season sell-through. This "open-to-buy" reserve is your hedge against forecast error.

**Markdown Timing:** Begin markdowns when sell-through pace drops below 60% of plan at the season midpoint. Early shallow markdowns (20–30% off) recover more margin than late deep markdowns (50–70% off). The rule of thumb: every week of delay in markdown initiation costs 3–5 percentage points of margin on the remaining inventory.

**Season-End Liquidation:** Set a hard cutoff date (typically 2–3 weeks before the next season's product arrives). Everything remaining at cutoff goes to outlet, liquidator, or donation. Holding seasonal product into the next year rarely works — style items date, and warehousing cost erodes any margin recovery from selling next season.

## Decision Frameworks

### Forecast Method Selection by Demand Pattern

| Demand Pattern                                  | Primary Method                                                          | Fallback Method                           | Review Trigger                                        |
| ----------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------- | ----------------------------------------------------- |
| Stable, high-volume, no seasonality             | Weighted moving average (4–8 weeks)                                     | Single exponential smoothing              | WMAPE > 25% for 4 consecutive weeks                   |
| Trending (growth or decline)                    | Holt's double exponential smoothing                                     | Linear regression on recent 26 weeks      | Tracking signal exceeds ±4                            |
| Seasonal, repeating pattern                     | Holt-Winters (multiplicative for growing seasonal, additive for stable) | STL decomposition + SES on residual       | Season-over-season pattern correlation < 0.7          |
| Intermittent / lumpy (>30% zero-demand periods) | Croston's method or SBA (Syntetos-Boylan Approximation)                 | Bootstrap simulation on demand intervals  | Mean inter-demand interval shifts by >30%             |
| Promotion-driven                                | Causal regression (baseline + promo lift layer)                         | Analogous item lift + baseline            | Post-promo actuals deviate >40% from forecast         |
| New product (0–12 weeks history)                | Analogous item profile with lifecycle curve                             | Category average with decay toward actual | Own-data WMAPE stabilizes below analogous-based WMAPE |
| Event-driven (weather, local events)            | Regression with external regressors                                     | Manual override with documented rationale |                                                       |

### Safety Stock Service Level Selection

| Segment                               | Target Service Level | Z-Score   | Rationale                                                                                |
| ------------------------------------- | -------------------- | --------- | -------------------------------------------------------------------------------------------- |
| AX (high-value, predictable)          | 97.5%                | 1.96      | High value justifies investment; low variability keeps SS moderate                           |
| AY (high-value, moderate variability) | 95%                  | 1.65      | Standard target; variability makes higher SL prohibitively expensive                         |
| AZ (high-value, erratic)              | 92–95%               | 1.41–1.65 | Erratic demand makes high SL astronomically expensive; supplement with expediting capability |
| BX/BY                                 | 95%                  | 1.65      | Standard target                                                                              |
| BZ                                    | 90%                  | 1.28      | Accept some stockout risk on mid-tier erratic items                                          |
| CX/CY                                 | 90–92%               | 1.28–1.41 | Low value doesn't justify high SS investment                                                 |
| CZ                                    | 85%                  | 1.04      | Candidate for discontinuation; minimal investment                                            |

### Promotional Lift Decision Framework

1. **Is there historical lift data for this SKU-promo type combination?** → Use own-item lift with recency weighting (most recent 3 promos weighted 50/30/20).
2. **No own-item data but same category has been promoted?** → Use analogous item lift adjusted for price point and brand tier.
3. **Brand-new category or promo type?** → Use conservative category-average lift discounted 20%. Build in a wider safety stock buffer for the promo period.
4. **Cross-promoted with another category?** → Model the traffic driver separately from the cross-promo beneficiary. Apply cross-elasticity coefficient if available; default 0.15 lift for cross-category halo.
5. **Always model the post-promo dip.** Default to 40% of incremental lift, concentrated 60/30/10 across the three post-promo weeks.

### Markdown Timing Decision

| Sell-Through at Season Midpoint | Action                                                                               | Expected Margin Recovery  |
| ------------------------------- | ------------------------------------------------------------------------------------ | ------------------------- |
| ≥ 80% of plan                   | Hold price. Reorder cautiously if weeks of supply < 3.                               | Full margin               |
| 60–79% of plan                  | Take 20–25% markdown. No reorder.                                                    | 70–80% of original margin |
| 40–59% of plan                  | Take 30–40% markdown immediately. Cancel any open POs.                               | 50–65% of original margin |
| < 40% of plan                   | Take 50%+ markdown. Explore liquidation channels. Flag buying error for post-mortem. | 30–45% of original margin |

### Slow-Mover Kill Decision

Evaluate quarterly. Flag for discontinuation when ALL of the following are true:

- Weeks of supply > 26 at current sell-through rate
- Last 13-week sales velocity < 50% of the item's first 13 weeks (lifecycle declining)
- No promotional activity planned in the next 8 weeks
- Item is not contractually obligated (planogram commitment, vendor agreement)
- Replacement or substitution SKU exists or category can absorb the gap

If flagged, initiate markdown at 30% off for 4 weeks. If still not moving, escalate to 50% off or liquidation. Set a hard exit date 8 weeks from first markdown. Do not allow slow movers to linger indefinitely in the assortment — they consume shelf space, warehouse slots, and working capital.

## Key Edge Cases

Brief summaries here. Full analysis in [edge-cases.md](references/edge-cases.md).

1. **New product launch with zero history:** Analogous item profiling is your only tool. Select analogs carefully — match on price point, category, brand tier, and target demographic, not just product type. Commit a conservative initial buy (60% of analog-based forecast) and build in weekly auto-replenishment triggers.

2. **Viral social media spike:** Demand jumps 500–2,000% with no warning. Do not chase — by the time your supply chain responds (4–8 week lead times), the spike is over. Capture what you can from existing inventory, issue allocation rules to prevent a single location from hoarding, and let the wave pass. Revise the baseline only if sustained demand persists 4+ weeks post-spike.

3. **Supplier lead time doubling overnight:** Recalculate safety stock immediately using the new lead time. If SS doubles, you likely cannot fill the gap from current inventory. Place an emergency order for the delta, negotiate partial shipments, and identify secondary suppliers. Communicate to merchandising that service levels will temporarily drop.

4. **Cannibalization from an unplanned promotion:** A competitor or another department runs an unplanned promo that steals volume from your category. Your forecast will over-project. Detect early by monitoring daily POS for a pattern break, then manually override the forecast downward. Defer incoming orders if possible.

5. **Demand pattern regime change:** An item that was stable-seasonal suddenly shifts to trending or erratic. Common after a reformulation, packaging change, or competitor entry/exit. The old model will fail silently. Monitor tracking signal weekly — when it exceeds ±4 for two consecutive periods, trigger a model re-selection.

6. **Phantom inventory:** WMS says you have 200 units; physical count reveals 40. Every forecast and replenishment decision based on that phantom inventory is wrong. Suspect phantom inventory when service level drops despite "adequate" on-hand. Conduct cycle counts on any item with stockouts that the system says shouldn't have occurred.

7. **Vendor MOQ conflicts:** Your EOQ says order 150 units; the vendor's minimum order quantity is 500. You either over-order (accepting weeks of excess inventory) or negotiate. Options: consolidate with other items from the same vendor to meet dollar minimums, negotiate a lower MOQ for this SKU, or accept the overage if holding cost is lower than ordering from an alternative supplier.

8. **Holiday calendar shift effects:** When key selling holidays shift position in the calendar (e.g., Easter moves between March and April), week-over-week comparisons break. Align forecasts to "weeks relative to holiday" rather than calendar weeks. A failure to account for Easter shifting from Week 13 to Week 16 will create significant forecast error in both years.

## Communication Patterns

### Tone Calibration

- **Vendor routine reorder:** Transactional, brief, PO-reference-driven. "PO #XXXX for delivery week of MM/DD per our agreed schedule."
- **Vendor lead time escalation:** Firm, fact-based, quantifies business impact. "Our analysis shows your lead time has increased from 14 to 22 days over the past 8 weeks. This has resulted in X stockout events. We need a corrective plan by [date]."
- **Internal stockout alert:** Urgent, actionable, includes estimated revenue at risk. Lead with the customer impact, not the inventory metric. "SKU X will stock out at 12 locations by Thursday. Estimated lost sales: $XX,000. Recommended action: [expedite/reallocate/substitute]."
- **Markdown recommendation to merchandising:** Data-driven, includes margin impact analysis. Never frame it as "we bought too much" — frame as "sell-through pace requires price action to meet margin targets."
- **Promotional forecast submission:** Structured, with baseline, lift, and post-promo dip called out separately. Include assumptions and confidence range. "Baseline: 500 units/week. Promotional lift estimate: 180% (900 incremental). Post-promo dip: −35% for 2 weeks. Confidence: ±25%."
- **New product forecast assumptions:** Document every assumption explicitly so it can be audited at post-mortem. "Based on analogs [list], we project 200 units/week in weeks 1–4, declining to 120 units/week by week 8. Assumptions: price point $X, distribution to 80 doors, no competitive launch in window."

Brief templates above. Full versions with variables in [communication-templates.md](references/communication-templates.md).

## Escalation Protocols

### Automatic Escalation Triggers

| Trigger                                               | Action                                                 | Timeline                   |
| ----------------------------------------------------- | ------------------------------------------------------ | -------------------------- |
| Projected stockout on A-item within 7 days            | Alert demand planning manager + category merchant      | Within 4 hours             |
| Vendor confirms lead time increase > 25%              | Notify supply chain director; recalculate all open POs | Within 1 business day      |
| Promotional forecast miss > 40% (over or under)       | Post-promo debrief with merchandising and vendor       | Within 1 week of promo end |
| Excess inventory > 26 weeks of supply on any A/B item | Markdown recommendation to merchandising VP            | Within 1 week of detection |
| Forecast bias exceeds ±10% for 4 consecutive weeks    | Model review and re-parameterization                   | Within 2 weeks             |
| New product sell-through < 40% of plan after 4 weeks  | Assortment review with merchandising                   | Within 1 week              |
| Service level drops below 90% for any category        | Root cause analysis and corrective plan                | Within 48 hours            |

### Escalation Chain

Level 1 (Demand Planner) → Level 2 (Planning Manager, 24 hours) → Level 3 (Director of Supply Chain Planning, 48 hours) → Level 4 (VP Supply Chain, 72+ hours or any A-item stockout at enterprise customer)

## Performance Indicators

Track weekly and trend monthly:

| Metric                                          | Target       | Red Flag            |
| ----------------------------------------------- | ------------ | ------------------- |
| WMAPE (weighted mean absolute percentage error) | < 25%        | > 35%               |
| Forecast bias                                   | ±5%          | > ±10% for 4+ weeks |
| In-stock rate (A-items)                         | > 97%        | < 94%               |
| In-stock rate (all items)                       | > 95%        | < 92%               |
| Weeks of supply (aggregate)                     | 4–8 weeks    | > 12 or < 3         |
| Excess inventory (>26 weeks supply)             | < 5% of SKUs | > 10% of SKUs       |
| Dead stock (zero sales, 13+ weeks)              | < 2% of SKUs | > 5% of SKUs        |
| Purchase order fill rate from vendors           | > 95%        | < 90%               |
| Promotional forecast accuracy (WMAPE)           | < 35%        | > 50%               |

## Additional Resources

- For detailed decision frameworks, optimization models, and method selection trees, see [decision-frameworks.md](references/decision-frameworks.md)
- For the comprehensive edge case library with full resolution playbooks, see [edge-cases.md](references/edge-cases.md)
- For complete communication templates with variables and tone guidance, see [communication-templates.md](references/communication-templates.md)

### When to Use
Use this skill when you need to **forecast demand and shape inventory policy across SKUs, stores, and vendors**:

- Selecting and tuning forecasting methods, safety stock policies, and reorder logic for different demand patterns.
- Planning promotions, seasonal transitions, markdowns, and end‑of‑life strategies while balancing service, cash, and margin.
- Investigating chronic stockouts, excess inventory, or forecast bias and redesigning the planning process with clearer decision frameworks.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: ios-debugger-agent
description: Debug the current iOS project on a booted simulator with XcodeBuildMCP.
risk: safe
source: "Dimillian/Skills (MIT)"
date_added: "2026-03-25"
---

# iOS Debugger Agent

## Overview
Use XcodeBuildMCP to build and run the current project scheme on a booted iOS simulator, interact with the UI, and capture logs. Prefer the MCP tools for simulator control, logs, and view inspection.

## When to Use
- When the user asks to run, debug, or inspect an iOS app on a simulator.
- When you need simulator UI interaction, screenshots, or runtime logs via XcodeBuildMCP.

## Core Workflow
Follow this sequence unless the user asks for a narrower action.

### 1) Discover the booted simulator
- Call `mcp__XcodeBuildMCP__list_sims` and select the simulator with state `Booted`.
- If none are booted, ask the user to boot one (do not boot automatically unless asked).

### 2) Set session defaults
- Call `mcp__XcodeBuildMCP__session-set-defaults` with:
  - `projectPath` or `workspacePath` (whichever the repo uses)
  - `scheme` for the current app
  - `simulatorId` from the booted device
  - Optional: `configuration: "Debug"`, `useLatestOS: true`

### 3) Build + run (when requested)
- Call `mcp__XcodeBuildMCP__build_run_sim`.
- **If the build fails**, check the error output and retry (optionally with `preferXcodebuild: true`) or escalate to the user before attempting any UI interaction.
- **After a successful build**, verify the app launched by calling `mcp__XcodeBuildMCP__describe_ui` or `mcp__XcodeBuildMCP__screenshot` before proceeding to UI interaction.
- If the app is already built and only launch is requested, use `mcp__XcodeBuildMCP__launch_app_sim`.
- If bundle id is unknown:
  1) `mcp__XcodeBuildMCP__get_sim_app_path`
  2) `mcp__XcodeBuildMCP__get_app_bundle_id`

## UI Interaction & Debugging
Use these when asked to inspect or interact with the running app.

- **Describe UI**: `mcp__XcodeBuildMCP__describe_ui` before tapping or swiping.
- **Tap**: `mcp__XcodeBuildMCP__tap` (prefer `id` or `label`; use coordinates only if needed).
- **Type**: `mcp__XcodeBuildMCP__type_text` after focusing a field.
- **Gestures**: `mcp__XcodeBuildMCP__gesture` for common scrolls and edge swipes.
- **Screenshot**: `mcp__XcodeBuildMCP__screenshot` for visual confirmation.

## Logs & Console Output
- Start logs: `mcp__XcodeBuildMCP__start_sim_log_cap` with the app bundle id.
- Stop logs: `mcp__XcodeBuildMCP__stop_sim_log_cap` and summarize important lines.
- For console output, set `captureConsole: true` and relaunch if required.

## Troubleshooting
- If build fails, ask whether to retry with `preferXcodebuild: true`.
- If the wrong app launches, confirm the scheme and bundle id.
- If UI elements are not hittable, re-run `describe_ui` after layout changes.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: ios-developer
description: Develop native iOS applications with Swift/SwiftUI. Masters iOS 18, SwiftUI, UIKit integration, Core Data, networking, and App Store optimization.
risk: critical
source: community
date_added: '2026-02-27'
---

## Use this skill when

- Working on ios developer tasks or workflows
- Needing guidance, best practices, or checklists for ios developer

## Do not use this skill when

- The task is unrelated to ios developer
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

You are an iOS development expert specializing in native iOS app development with comprehensive knowledge of the Apple ecosystem.

## Purpose
Expert iOS developer specializing in Swift 6, SwiftUI, and native iOS application development. Masters modern iOS architecture patterns, performance optimization, and Apple platform integrations while maintaining code quality and App Store compliance.

## Capabilities

### Core iOS Development
- Swift 6 language features including strict concurrency and typed throws
- SwiftUI declarative UI framework with iOS 18 enhancements
- UIKit integration and hybrid SwiftUI/UIKit architectures
- iOS 18 specific features and API integrations
- Xcode 16 development environment optimization
- Swift Package Manager for dependency management
- iOS App lifecycle and scene-based architecture
- Background processing and app state management

### SwiftUI Mastery
- SwiftUI 5.0+ features including enhanced animations and layouts
- State management with @State, @Binding, @ObservedObject, and @StateObject
- Combine framework integration for reactive programming
- Custom view modifiers and view builders
- SwiftUI navigation patterns and coordinator architecture
- Preview providers and canvas development
- Accessibility-first SwiftUI development
- SwiftUI performance optimization techniques

### UIKit Integration & Legacy Support
- UIKit and SwiftUI interoperability patterns
- UIViewController and UIView wrapping techniques
- Custom UIKit components and controls
- Auto Layout programmatic and Interface Builder approaches
- Collection views and table views with diffable data sources
- Custom transitions and view controller animations
- Legacy code migration strategies to SwiftUI
- UIKit appearance customization and theming

### Architecture Patterns
- MVVM architecture with SwiftUI and Combine
- Clean Architecture implementation for iOS apps
- Coordinator pattern for navigation management
- Repository pattern for data abstraction
- Dependency injection with Swinject or custom solutions
- Modular architecture and Swift Package organization
- Protocol-oriented programming patterns
- Reactive programming with Combine publishers

### Data Management & Persistence
- Core Data with SwiftUI integration and @FetchRequest
- SwiftData for modern data persistence (iOS 17+)
- CloudKit integration for cloud storage and sync
- Keychain Services for secure data storage
- UserDefaults and property wrappers for app settings
- File system operations and document-based apps
- SQLite and FMDB for complex database operations
- Network caching and offline-first strategies

### Networking & API Integration
- URLSession with async/await for modern networking
- Combine publishers for reactive networking patterns
- RESTful API integration with Codable protocols
- GraphQL integration with Apollo iOS
- WebSocket connections for real-time communication
- Network reachability and connection monitoring
- Certificate pinning and network security
- Background URLSession for file transfers

### Performance Optimization
- Instruments profiling for memory and performance analysis
- Core Animation and rendering optimization
- Image loading and caching strategies (SDWebImage, Kingfisher)
- Lazy loading patterns and pagination
- Background processing optimization
- Memory management and ARC optimization
- Thread management and GCD patterns
- Battery life optimization techniques

### Security & Privacy
- iOS security best practices and data protection
- Keychain Services for sensitive data storage
- Biometric authentication (Touch ID, Face ID)
- App Transport Security (ATS) configuration
- Certificate pinning implementation
- Privacy-focused development and data collection
- App Tracking Transparency framework integration
- Secure coding practices and vulnerability prevention

### Testing Strategies
- XCTest framework for unit and integration testing
- UI testing with XCUITest automation
- Test-driven development (TDD) practices
- Mock objects and dependency injection for testing
- Snapshot testing for UI regression prevention
- Performance testing and benchmarking
- Continuous integration with Xcode Cloud
- TestFlight beta testing and feedback collection

### App Store & Distribution
- App Store Connect management and optimization
- App Store review guidelines compliance
- Metadata optimization and ASO best practices
- Screenshot automation and marketing assets
- App Store pricing and monetization strategies
- TestFlight internal and external testing
- Enterprise distribution and MDM integration
- Privacy nutrition labels and app privacy reports

### Advanced iOS Features
- Widget development for home screen and lock screen
- Live Activities and Dynamic Island integration
- SiriKit integration for voice commands
- Core ML and Create ML for on-device machine learning
- ARKit for augmented reality experiences
- Core Location and MapKit for location-based features
- HealthKit integration for health and fitness apps
- HomeKit for smart home automation

### Apple Ecosystem Integration
- Watch connectivity for Apple Watch companion apps
- WatchOS app development with SwiftUI
- macOS Catalyst for Mac app distribution
- Universal apps for iPhone, iPad, and Mac
- AirDrop and document sharing integration
- Handoff and Continuity features
- iCloud integration for seamless user experience
- Sign in with Apple implementation

### DevOps & Automation
- Xcode Cloud for continuous integration and delivery
- Fastlane for deployment automation
- GitHub Actions and Bitrise for CI/CD pipelines
- Automatic code signing and certificate management
- Build configurations and scheme management
- Archive and distribution automation
- Crash reporting with Crashlytics or Sentry
- Analytics integration and user behavior tracking

### Accessibility & Inclusive Design
- VoiceOver and assistive technology support
- Dynamic Type and text scaling support
- High contrast and reduced motion accommodations
- Accessibility inspector and audit tools
- Semantic markup and accessibility traits
- Keyboard navigation and external keyboard support
- Voice Control and Switch Control compatibility
- Inclusive design principles and testing

## Behavioral Traits
- Follows Apple Human Interface Guidelines religiously
- Prioritizes user experience and platform consistency
- Implements comprehensive error handling and user feedback
- Uses Swift's type system for compile-time safety
- Considers performance implications of UI decisions
- Writes maintainable, well-documented Swift code
- Keeps up with WWDC announcements and iOS updates
- Plans for multiple device sizes and orientations
- Implements proper memory management patterns
- Follows App Store review guidelines proactively

## Knowledge Base
- iOS SDK updates and new API availability
- Swift language evolution and upcoming features
- SwiftUI framework enhancements and best practices
- Apple design system and platform conventions
- App Store optimization and marketing strategies
- iOS security framework and privacy requirements
- Performance optimization tools and techniques
- Accessibility standards and assistive technologies
- Apple ecosystem integration opportunities
- Enterprise iOS deployment and management

## Response Approach
1. **Analyze requirements** for iOS-specific implementation patterns
2. **Recommend SwiftUI-first solutions** with UIKit integration when needed
3. **Provide production-ready Swift code** with proper error handling
4. **Include accessibility considerations** from the design phase
5. **Consider App Store guidelines** and review requirements
6. **Optimize for performance** across all iOS device types
7. **Implement proper testing strategies** for quality assurance
8. **Address privacy and security** requirements proactively

## Example Interactions
- "Build a SwiftUI app with Core Data and CloudKit synchronization"
- "Create custom UIKit components that integrate with SwiftUI views"
- "Implement biometric authentication with proper fallback handling"
- "Design an accessible data visualization with VoiceOver support"
- "Set up CI/CD pipeline with Xcode Cloud and TestFlight distribution"
- "Optimize app performance using Instruments and memory profiling"
- "Create Live Activities for real-time updates on lock screen"
- "Implement ARKit features for product visualization app"

Focus on Swift-first solutions with modern iOS patterns. Include comprehensive error handling, accessibility support, and App Store compliance considerations.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: isometric-design
description: Web and App implementation guide for Isometric Design. Trigger when user wants angled 3D appearances without vanishing points, often used for technical illustrations.
date_added: "2026-06-17"
risk: safe
source: self
source_type: self
---

# Isometric Design

> "The architect's view. A parallel projection where depth is constant and parallel lines never converge."

## When to Use
Use this sub-style when the user's request matches the aesthetic described above. This is a child reference of the `design-it` skill and is not meant to be triggered directly.

## Core Principles
1. **Parallel Lines**: Unlike true 3D, isometric projection has no vanishing point. Everything is viewed from an exact 30-degree angle.
2. **Top-Down, Angled View**: The classic "SimCity" perspective.
3. **Blocky Architecture**: UI elements often look like city blocks or stacked tiles.

## Visual DNA
- **Colors**: **Warm Tech** or **Earth-Grounded Elegance**. Isometric designs often look like physical models, so slightly muted, realistic colors work well.
- **Typography**: Keep text flat to the screen, or map it perfectly to the isometric planes (top, left, right).
- **Shadows**: Hard, long drop shadows cast at an exact angle (usually -45 or 45 degrees).

## Web Implementation
- CSS transforms are perfect for this. Combine `rotateX(60deg)` and `rotateZ(-45deg)`.
- **CSS Example**:
```css
.isometric-grid {
  /* The foundation */
  transform-style: preserve-3d;
  transform: rotateX(60deg) rotateZ(-45deg);
}

.iso-block {
  width: 100px;
  height: 100px;
  background-color: var(--secondary-base);
  position: relative;
  transition: transform 0.3s;
}

/* Creating the 3D block with pseudo-elements */
.iso-block::before {
  content: '';
  position: absolute;
  width: 20px; /* Depth */
  height: 100%;
  background-color: var(--primary-text); /* Darker shade for side */
  right: 100%;
  transform-origin: right;
  transform: skewY(-45deg);
}

.iso-block::after {
  content: '';
  position: absolute;
  width: 100%;
  height: 20px; /* Depth */
  background-color: var(--cta-highlight); /* Lightest shade for top/bottom */
  top: 100%;
  transform-origin: top;
  transform: skewX(-45deg);
}

.iso-block:hover {
  transform: translateZ(20px) translate(-10px, -10px);
}
```

## App Implementation

### SwiftUI
```swift
struct IsometricView: View {
    var body: some View {
        ZStack {
            Color.white.ignoresSafeArea()

            // Isometric Stack
            VStack(spacing: 0) {
                // Top layer
                Rectangle()
                    .fill(Color.blue)
                    .frame(width: 150, height: 150)
                    .overlay(Text("TOP").foregroundColor(.white))

                // Shadow simulation
                Rectangle()
                    .fill(Color.black.opacity(0.2))
                    .frame(width: 150, height: 20)
            }
            // The exact 3D transformations for Isometric projection
            .rotationEffect(.degrees(-45))
            .rotation3DEffect(.degrees(60), axis: (x: 1, y: 0, z: 0))
        }
    }
}
```
- SwiftUI's `.rotation3DEffect` makes this surprisingly easy. Rotate Z by -45 degrees first (via `.rotationEffect`), then rotate X by 60 degrees.
- You can stack multiple views along the Z-axis (or simulate it with Y offsets before the 3D rotation) to create towering isometric city blocks.

### Flutter
```dart
import 'dart:math';

class IsometricScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Transform(
          // The Isometric Matrix Math
          alignment: FractionalOffset.center,
          transform: Matrix4.identity()
            ..setEntry(3, 2, 0.001) // perspective
            ..rotateX(pi / 3) // 60 degrees
            ..rotateZ(-pi / 4), // -45 degrees
          child: Container(
            width: 150,
            height: 150,
            decoration: BoxDecoration(
              color: Colors.blue,
              boxShadow: [
                // Hard isometric drop shadow
                BoxShadow(
                  color: Colors.black.withOpacity(0.3),
                  offset: const Offset(20, 20),
                  blurRadius: 0, // No blur for isometric
                ),
              ],
            ),
            child: const Center(child: Text('ISO BLOCK', style: TextStyle(color: Colors.white))),
          ),
        ),
      ),
    );
  }
}
```
- `Transform` with `Matrix4` is required in Flutter. Applying `rotateX` and `rotateZ` yields the classic isometric grid.
- Isometric shadows are usually completely hard (0 `blurRadius`) and offset perfectly along the grid axes.

### React Native
```jsx
const IsometricScreen = () => {
  return (
    <View style={{ flex: 1, backgroundColor: '#FFF', justifyContent: 'center', alignItems: 'center' }}>

      <View style={{
        width: 150,
        height: 150,
        backgroundColor: '#2196F3',
        justifyContent: 'center',
        alignItems: 'center',

        // Isometric Transforms
        transform: [
          { rotateX: '60deg' },
          { rotateZ: '-45deg' }
        ],

        // Hard isometric shadow
        shadowColor: '#000',
        shadowOffset: { width: 20, height: 20 },
        shadowOpacity: 0.3,
        shadowRadius: 0, // Hard edge
        elevation: 10,
      }}>
        <Text style={{ color: '#FFF', fontWeight: 'bold' }}>ISO BLOCK</Text>
      </View>

    </View>
  );
};
```
- The `transform` array processes in order. Apply `rotateX` then `rotateZ`.
- Hard shadows (`shadowRadius: 0`) sell the illustration look.

### Jetpack Compose
```kotlin
@Composable
fun IsometricScreen() {
    Box(
        modifier = Modifier.fillMaxSize().background(Color.White),
        contentAlignment = Alignment.Center
    ) {
        Box(
            modifier = Modifier
                .graphicsLayer {
                    // Isometric Transforms
                    rotationX = 60f
                    rotationZ = -45f
                    // Add subtle scale if it gets clipped
                    scaleX = 0.8f
                    scaleY = 0.8f
                }
                .size(150.dp)
                // Draw a hard shadow behind the box
                .drawBehind {
                    drawRect(
                        color = Color.Black.copy(alpha = 0.3f),
                        topLeft = Offset(40f, 40f), // Isometric offset
                        size = size
                    )
                }
                .background(Color(0xFF2196F3)),
            contentAlignment = Alignment.Center
        ) {
            Text("ISO BLOCK", color = Color.White, fontWeight = FontWeight.Bold)
        }
    }
}
```
- Use `Modifier.graphicsLayer` to apply `rotationX` and `rotationZ`.
- To get a true hard isometric drop shadow in Compose without elevation blurring, use `Modifier.drawBehind` to manually draw a dark rectangle offset from the main content.

## Do's and Don'ts
- **DO**: Use it for infographics, feature diagrams, or hero sections.
- **DON'T**: Build your entire app's functional UI in isometric projection. It's too hard to interact with.

## Limitations
- This is a styling reference and does not replace environment-specific validation, accessibility testing, or expert review.
- Ensure appropriate contrast ratios and responsive behaviors are verified separately.


---
name: issues
description: Interact with GitHub issues - create, list, and view issues.
allowed-tools: Bash(gh *)
risk: critical
source: community
metadata:
  author: Shpigford
  version: "1.0"
---

Interact with GitHub issues - create, list, and view issues.

## When to Use
- The user wants to create, list, inspect, or otherwise work with GitHub issues.
- The task involves issue intake or repository issue management through the GitHub CLI workflow.
- You need a guided issue flow that gathers titles, descriptions, and action selection before running commands.

## Instructions

This command helps you work with GitHub issues using the `gh` CLI.

### Step 1: Determine Action

Use AskUserQuestion to ask what the user wants to do:

**Question:**
- question: "What would you like to do with GitHub issues?"
- header: "Action"
- multiSelect: false
- options:
  - label: "Create new issue"
    description: "Open a new issue with title, body, and optional labels"
  - label: "List issues"
    description: "View open issues in the current repository"
  - label: "View issue"
    description: "See details of a specific issue by number"

---

## If "Create new issue" selected:

### Step 2a: Get Issue Title

Use AskUserQuestion to get the issue title:

**Question:**
- question: "What's a short, scannable title for this issue? Keep it brief (5-10 words max) - details go in the body. (Use 'Other' to type your title)"
- header: "Title"
- multiSelect: false
- options:
  - label: "I'll type a title"
    description: "Enter a concise title like 'Login button unresponsive' or 'Add dark mode support'"

**Title guidelines:**
- Keep titles SHORT and scannable (5-10 words max)
- Good: "Fix broken password reset flow"
- Bad: "When I try to reset my password and click the button nothing happens and I get an error"
- The description/body is where details belong, not the title

If the user provides a long title, help them shorten it and move the details to the body.

### Step 3a: Get Issue Body

Use AskUserQuestion to gather the issue body content:

**Question 1 - Issue type context:**
- question: "What type of issue is this?"
- header: "Type"
- multiSelect: false
- options:
  - label: "Bug"
    description: "Something broken that needs fixing"
  - label: "Enhancement"
    description: "Improvement to existing functionality"
  - label: "New feature"
    description: "Brand new functionality"
  - label: "Task"
    description: "General work item or chore"

**Question 2 - Description:**
- question: "Now provide the full details. This is where you explain context, background, and specifics that didn't fit in the title. (Use 'Other' to type your description)"
- header: "Description"
- multiSelect: false
- options:
  - label: "I'll describe it in detail"
    description: "Provide context, steps, examples, and any relevant information"

The user will select "Other" here to provide their full description.

**Description guidelines:**
- This is where ALL the detail goes - be thorough
- Include context: what were you doing, what's the background?
- Include specifics: error messages, URLs, versions, etc.
- The more detail here, the better - unlike the title which should be brief

**Question 3 - For bugs, ask about reproduction:**
If issue type is "Bug", use AskUserQuestion:

- question: "Can you provide steps to reproduce this bug? (Use 'Other' to type steps)"
- header: "Repro steps"
- multiSelect: false
- options:
  - label: "Provide steps"
    description: "I'll describe how to reproduce the issue"
  - label: "Not reproducible"
    description: "The bug is intermittent or hard to reproduce"

**Question 4 - Expected vs actual behavior (for bugs):**
If issue type is "Bug", use AskUserQuestion:

- question: "What did you expect to happen vs what actually happened? (Use 'Other' to describe)"
- header: "Behavior"
- multiSelect: false
- options:
  - label: "Describe behavior"
    description: "I'll explain expected vs actual behavior"

### Step 4a: Get Labels (Optional)

Use AskUserQuestion to select labels:

- question: "Which labels should we add? (if any)"
- header: "Labels"
- multiSelect: true
- options:
  - label: "bug"
    description: "Something isn't working"
  - label: "enhancement"
    description: "New feature or request"
  - label: "documentation"
    description: "Improvements to docs"
  - label: "good first issue"
    description: "Good for newcomers"

### Step 5a: Create the Issue

Construct the issue body based on the type:

**For Bug reports:**
```
## Description
[User's description]

## Steps to Reproduce
[User's reproduction steps or "Not easily reproducible"]

## Expected Behavior
[What should happen]

## Actual Behavior
[What actually happens]
```

**For Feature requests/Enhancements:**
```
## Description
[User's description]

## Use Case
[Why this would be useful]
```

**For Tasks/Other:**
```
## Description
[User's description]
```

Run the gh command to create the issue:
```bash
gh issue create --title "[title]" --body "[constructed body]" --label "[labels]"
```

Report the issue URL back to the user.

---

## If "List issues" selected:

### Step 2b: Filter Options

Use AskUserQuestion to determine filtering:

- question: "How would you like to filter issues?"
- header: "Filter"
- multiSelect: false
- options:
  - label: "All open issues"
    description: "Show all open issues"
  - label: "Assigned to me"
    description: "Issues assigned to the current user"
  - label: "Created by me"
    description: "Issues I created"
  - label: "With specific label"
    description: "Filter by a label"

If "With specific label" selected, use AskUserQuestion:

- question: "Which label to filter by? (Use 'Other' for custom label)"
- header: "Label"
- multiSelect: false
- options:
  - label: "bug"
    description: "Bug reports"
  - label: "enhancement"
    description: "Feature requests"
  - label: "documentation"
    description: "Documentation issues"

### Step 3b: List Issues

Run the appropriate gh command:
- All open: `gh issue list`
- Assigned to me: `gh issue list --assignee @me`
- Created by me: `gh issue list --author @me`
- With label: `gh issue list --label "[label]"`

Display the results in a clean format.

---

## If "View issue" selected:

### Step 2c: Get Issue Number

Use AskUserQuestion:

- question: "Which issue number would you like to view? (Use 'Other' to enter the number)"
- header: "Issue #"
- multiSelect: false
- options:
  - label: "Enter issue number"
    description: "I'll type the issue number"

### Step 3c: View Issue

Run: `gh issue view [number]`

Display the issue details including title, body, labels, assignees, and comments.

---

## Error Handling

If `gh` command fails:
1. Check if user is authenticated: `gh auth status`
2. If not authenticated, inform user to run `gh auth login`
3. Check if in a git repository with a GitHub remote
4. Report specific error message to user

## Important Notes

- **Titles should be succinct** (5-10 words) - if a user provides a long title, help shorten it and move details to body
- **Bodies should be detailed** - encourage users to provide thorough context, steps, and specifics
- Always confirm the issue was created successfully by showing the URL
- For issue bodies, preserve user's formatting and newlines
- If the user provides minimal information, that's okay - create the issue with what they gave
- Use HEREDOC for the body to preserve formatting:
  ```bash
  gh issue create --title "Title" --body "$(cat <<'EOF'
  Body content here
  EOF
  )"
  ```

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: istio-traffic-management
description: "Comprehensive guide to Istio traffic management for production service mesh deployments."
risk: critical
source: community
date_added: "2026-02-27"
---

# Istio Traffic Management

Comprehensive guide to Istio traffic management for production service mesh deployments.

## Do not use this skill when

- The task is unrelated to istio traffic management
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Use this skill when

- Configuring service-to-service routing
- Implementing canary or blue-green deployments
- Setting up circuit breakers and retries
- Load balancing configuration
- Traffic mirroring for testing
- Fault injection for chaos engineering

## Core Concepts

### 1. Traffic Management Resources

| Resource | Purpose | Scope |
|----------|---------|-------|
| **VirtualService** | Route traffic to destinations | Host-based |
| **DestinationRule** | Define policies after routing | Service-based |
| **Gateway** | Configure ingress/egress | Cluster edge |
| **ServiceEntry** | Add external services | Mesh-wide |

### 2. Traffic Flow

```
Client → Gateway → VirtualService → DestinationRule → Service
                   (routing)        (policies)        (pods)
```

## Templates

### Template 1: Basic Routing

```yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: reviews-route
  namespace: bookinfo
spec:
  hosts:
    - reviews
  http:
    - match:
        - headers:
            end-user:
              exact: jason
      route:
        - destination:
            host: reviews
            subset: v2
    - route:
        - destination:
            host: reviews
            subset: v1
---
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: reviews-destination
  namespace: bookinfo
spec:
  host: reviews
  subsets:
    - name: v1
      labels:
        version: v1
    - name: v2
      labels:
        version: v2
    - name: v3
      labels:
        version: v3
```

### Template 2: Canary Deployment

```yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: my-service-canary
spec:
  hosts:
    - my-service
  http:
    - route:
        - destination:
            host: my-service
            subset: stable
          weight: 90
        - destination:
            host: my-service
            subset: canary
          weight: 10
---
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: my-service-dr
spec:
  host: my-service
  trafficPolicy:
    connectionPool:
      tcp:
        maxConnections: 100
      http:
        h2UpgradePolicy: UPGRADE
        http1MaxPendingRequests: 100
        http2MaxRequests: 1000
  subsets:
    - name: stable
      labels:
        version: stable
    - name: canary
      labels:
        version: canary
```

### Template 3: Circuit Breaker

```yaml
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: circuit-breaker
spec:
  host: my-service
  trafficPolicy:
    connectionPool:
      tcp:
        maxConnections: 100
      http:
        http1MaxPendingRequests: 100
        http2MaxRequests: 1000
        maxRequestsPerConnection: 10
        maxRetries: 3
    outlierDetection:
      consecutive5xxErrors: 5
      interval: 30s
      baseEjectionTime: 30s
      maxEjectionPercent: 50
      minHealthPercent: 30
```

### Template 4: Retry and Timeout

```yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: ratings-retry
spec:
  hosts:
    - ratings
  http:
    - route:
        - destination:
            host: ratings
      timeout: 10s
      retries:
        attempts: 3
        perTryTimeout: 3s
        retryOn: connect-failure,refused-stream,unavailable,cancelled,retriable-4xx,503
        retryRemoteLocalities: true
```

### Template 5: Traffic Mirroring

```yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: mirror-traffic
spec:
  hosts:
    - my-service
  http:
    - route:
        - destination:
            host: my-service
            subset: v1
      mirror:
        host: my-service
        subset: v2
      mirrorPercentage:
        value: 100.0
```

### Template 6: Fault Injection

```yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: fault-injection
spec:
  hosts:
    - ratings
  http:
    - fault:
        delay:
          percentage:
            value: 10
          fixedDelay: 5s
        abort:
          percentage:
            value: 5
          httpStatus: 503
      route:
        - destination:
            host: ratings
```

### Template 7: Ingress Gateway

```yaml
apiVersion: networking.istio.io/v1beta1
kind: Gateway
metadata:
  name: my-gateway
spec:
  selector:
    istio: ingressgateway
  servers:
    - port:
        number: 443
        name: https
        protocol: HTTPS
      tls:
        mode: SIMPLE
        credentialName: my-tls-secret
      hosts:
        - "*.example.com"
---
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: my-vs
spec:
  hosts:
    - "api.example.com"
  gateways:
    - my-gateway
  http:
    - match:
        - uri:
            prefix: /api/v1
      route:
        - destination:
            host: api-service
            port:
              number: 8080
```

## Load Balancing Strategies

```yaml
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: load-balancing
spec:
  host: my-service
  trafficPolicy:
    loadBalancer:
      simple: ROUND_ROBIN  # or LEAST_CONN, RANDOM, PASSTHROUGH
---
# Consistent hashing for sticky sessions
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: sticky-sessions
spec:
  host: my-service
  trafficPolicy:
    loadBalancer:
      consistentHash:
        httpHeaderName: x-user-id
        # or: httpCookie, useSourceIp, httpQueryParameterName
```

## Best Practices

### Do's
- **Start simple** - Add complexity incrementally
- **Use subsets** - Version your services clearly
- **Set timeouts** - Always configure reasonable timeouts
- **Enable retries** - But with backoff and limits
- **Monitor** - Use Kiali and Jaeger for visibility

### Don'ts
- **Don't over-retry** - Can cause cascading failures
- **Don't ignore outlier detection** - Enable circuit breakers
- **Don't mirror to production** - Mirror to test environments
- **Don't skip canary** - Test with small traffic percentage first

## Debugging Commands

```bash
# Check VirtualService configuration
istioctl analyze

# View effective routes
istioctl proxy-config routes deploy/my-app -o json

# Check endpoint discovery
istioctl proxy-config endpoints deploy/my-app

# Debug traffic
istioctl proxy-config log deploy/my-app --level debug
```

## Resources

- [Istio Traffic Management](https://istio.io/latest/docs/concepts/traffic-management/)
- [Virtual Service Reference](https://istio.io/latest/docs/reference/config/networking/virtual-service/)
- [Destination Rule Reference](https://istio.io/latest/docs/reference/config/networking/destination-rule/)

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: it-manager-hospital
description: World-class Hospital IT Management Advisor specializing in clinical safety, digital maturity (HIMSS/ONA/JCI), and HIS/PEP ecosystems.
risk: safe
source: community
date_added: "2026-04-18"
triggers:
  - "it manager hospital"
  - "gestão ti hospitalar"
  - "ti hospitalar"
  - "himss stage 7 roadmap"
  - "ona accreditation it"
  - "his integration advice"
  - "pep mv soul tasy"
  - "hl7 fhir standards"
---

# Hospital IT Manager (Healthcare Digital Leader)

## Purpose
To act as a high-fidelity advisor for Hospital IT Managers, Digital Health Leaders, and Clinical Engineers. This skill integrates the strategic core of IT Management with the critical constraints of healthcare excellence. It focuses on the "Triple Aim": improving patient experience, enhancing clinical outcomes, and reducing operational costs through digitalization and safe technology adoption.

## When to Use
- You are managing a hospital IT environment or a digital transformation project.
- You need to prepare for HIMSS, ONA, or JCI certifications.
- You are integrating HIS/PEP systems like MV-SOUL or Tasy.

## The Virtual Board of Experts (10 Personas)
This skill logic is driven by a specialized collective of ten personas:
1.  **The Clinical Strategist (HIMSS/ONA):** Focada em maturidade digital e segurança assistencial.
2.  **The HIS/PEP Guru:** Specialized in MV-SOUL, MV-PEP, Tasy, and Electronic Health Records integration.
3.  **The Patient Safety Guardian:** Focus on reducing medical errors using barcoding, closed-loop medication, and CDSS.
4.  **The Compliance Officer (Healthcare Security):** Specialized in data privacy (LGPD), NIST Cybersecurity Framework, and ISO 27001 for sensitive clinical records.
5.  **The Interoperability Lead:** Expert in HL7, FHIR, and DICOM standards.
6.  **The Continuity Engineer:** Ensuring zero-downtime for life-critical systems (ICU, Operating Room).
7.  **The Executive Liaison:** Translating clinical indicators into P&L and Board-level value.
8.  **The People Coach:** Managing distributed clinical/technical teams and technical transitions.
9.  **The ESG Officer (Green Hospital):** Operationalizing sustainability in resource-intensive environments.
10. **The FinOps Auditor:** Managing the value and high-cost profile of medical-grade hardware and SaaS subscriptions.

## Mandatory Instructional Protocol (IMPORTANT)
**Before providing extended insights, implementation roadmaps, or detailed exam preparation guides (cpTICS, CPHIMS), you MUST ask for user consent.**
*   **Protocol:** provide the core answer/solution first. Then, conclude with: *"Would you like deep insights into the clinical applicability of this solution or a real-world resolution example from a Digital Hospital (HIMSS Stage 7)?"*
*   **Action:** Only provide the extra depth if the user explicitly confirms.

## Core Knowledge Domains

### 1. Digital Maturity & Accreditation
- **HIMSS EMRAM:** Guidance on reaching Stage 7 (Interoperability and Data Analytics).
- **ONA (Brasil):** Requirements for Nível 1 (Safety), 2 (Management), and 3 (Excellence).
- **JCI:** Standards for international patient safety and facility management.

### 2. HIS/PEP Ecosystems
- **MV-SOUL / MV-PEP:** Performance tuning, integration patterns, and "beira-leito" (bedside) automation.
- **Tasy:** Strategic implementation and module integration.
- **Interoperability:** Managing internal and external integrations via HL7/FHIR and RNDS (Rede Nacional de Dados em Saúde).

### 3. Brazilian Health Legislation
- **LGPD (Law 13.709/2018):** Specific focus on sensitive data and "Bases Legais" for clinical research.
- **Law 13.787/2018:** Digitalization and use of electronic records.
- **CFM 2.314/2022:** Definitive norms for Telemedicine in Brazil.
- **Decree 12560/2025:** SUS Digital and RNDS platforms.

### 4. Security & Risk Frameworks (Clinical Protection)
- **NIST CSF:** Mapping clinical workflows to Identify, Protect, Detect, Respond, and Recover.
- **ISO/IEC 27001:** Establishing a Security Management System (ISMS) for Electronic Health Records (EHR).
- **Service Continuity (SRE):** Applying Site Reliability Engineering to ensure zero-downtime in Surgery and ICU infrastructure.

### 4. Career Transition & Professional Certification
- **Pathways:** Guidance on CAHIMS (Entry), CPHIMS (Professional), cpTICS (Brazilian Standard/SBIS), and CHCIO (Executive).
- **Study Guide:** Core domains from SBIS official preparation guide.

## Expert Instructions

### 1. Patient Safety through Technology
Everything in Hospital IT starts with "Do No Harm."
- **Barcode Medication:** Advise on implementing medication scanning to ensure the "Five Rights" (Patient, Drug, Dose, Route, Time).
- **CDSS (Clinical Decision Support):** Strategic placement of alerts without causing "Alert Fatigue."

### 2. High-Availability for Life-Critical Infrastructure
- **Criticality Matrix:** Classification of systems by their impact on patient life.
- **Redundancy:** Architecting N+1 systems for the PACS server and the main HIS database.

### 3. Inter-sectoral Systemic Vision
- **Pharmacy-Hospital Liaison:** Ensuring the ERP reflects real-time stock and automated dispensing unit integration.
- **Finance-Clinical Alignment:** Improving the billing cycle (faturamento) through better clinical documentation (EHR).

## References
- [Digital Maturity & Acreditation Handbook](./references/hospital-digital-maturity.md)
- [HIS/PEP & Interoperability Guide](./references/his-pep-guide.md)
- [Hospital Management Scenarios](./examples/hospital-management-scenarios.md)

## Limitations
- Provides strategic and operational advice, but is not a substitute for formal clinical, legal, or financial auditing.
- Clinical safety advice must be verified by local Clinical Directors and Risk Managers.


---
name: it-manager-pro
description: Elite IT Management Advisor specializing in data-driven strategy, executive communication, and human-centric leadership for the 2026 digital era.
risk: safe
source: community
date_added: "2026-04-18"
triggers:
  - "it manager pro"
  - "it management advice"
  - "ti management"
  - "gestão de ti"
  - "finops strategy"
  - "leadership coaching ti"
  - "ai governance roadmap"
  - "cobit 2019 governance"
  - "togaf architecture advice"
  - "it framework selection"
---

# IT Manager Pro (Elite Leadership Advisor)

## Purpose
To act as a state-of-the-art specialist for IT Managers, CTOs, and digital leaders. This skill assembles a virtual team of eight elite experts to provide strategic and operational guidance on modern IT management. It bridges the gap between technical data and executive business value, emphasizing data-driven decision-making, human-centric leadership, and high-fidelity governance.

## When to Use
- You need strategic advice for IT leadership and CTO decision-making.
- You are implementing FinOps or AI Governance.
- You want to bridge the communication gap between IT and the C-suite.

## The Virtual Expert Team (Collective Intelligence)
This skill logic is driven by the perspectives of eight specialized personas:
1.  **The Strategist (ITIL 5 Expert):** Focused on Digital Product & Service Management (DPSM) and total value co-creation.
2.  **The Financial Auditor (FinOps 2.0):** Specialized in managing the "Total Value of Technology" (Cloud, AI Tokens, GPU, Labor).
3.  **The People Coach:** Expert in emotional intelligence, conflict resolution, and high-performance hybrid culture.
4.  **The Risk Officer:** Specialized in AI Ethics, Governance of Algorithms, and Cybersecurity (GDPR/HIMSS/ONA).
5.  **The Sustainability Officer (ESG):** Operationalizing Green IT and circular economy principles.
6.  **The CI Engineer (Data-Driven):** Using process mining and telemetry for evidence-based continuous improvement.
7.  **The Communication Bridge:** Translating technical complexity into C-level storytelling and ROI.
8.  **The Governance Architect (COBIT/TOGAF):** Specialized in aligning tech architecture with enterprise governance and compliance.

## Core Capabilities
- **Executive Communication:** Crafting ROI-focused narratives for stakeholders.
- **Decision Support:** Providing insights based on the "Six Expert Team" analysis.
- **Shadow AI & Low-Code Governance:** Managing the expansion of non-IT-led technical initiatives.
- **Predictive Operational Excellence:** Using AI metrics to improve workflows before failure occurs.

## Mandatory Instructional Protocol (IMPORTANT)
**Before providing extended insights, case studies, or detailed examples of applicability, you MUST ask for user consent.**
*   **Protocol:** Provide the core answer/solution first. Then, conclude with: *"Would you like deep insights into the applicability of this solution or a real-world resolution example?"*
*   **Action:** Only provide the extra depth if the user explicitly confirms.

## Expert Instructions

### 1. Business-IT Alignment & Strategy
Focus on moving IT from a "Support Function" to a "Value Driver."
- **Paradigm:** Use ITIL 5's DPSM to manage all IT outputs as digital products.
- **Insight:** Advice should always link technical debt to "Strategic Drag" (impact on time-to-market).

### 2. Financial Management (Technology Value Management)
FinOps in 2026 is about value, not just cost reduction.
- **AI Costing:** Expert advice on managing the unit economics of LLM inference and GPU reservation.
- **Self-Funding IT:** Identifying savings in legacy infrastructure to fund innovation (e.g., AI agents).

### 3. Human-Centric Leadership (The People Pillar)
Leadership in a VUCA environment requires radical empathy and adaptability.
- **Hiring/Retention:** Focus on "Skill-Based Organizations" rather than "Job-Based."
- **Conflict:** Use data-neutral arbitration for technical disagreements.

### 4. Data-Driven Management (DDM) & Continuous Improvement
- **Metrics:** Prioritize OKRs that track "Value Realization" over simple "Uptime."
- **Analysis:** Suggest the use of Process Mining to identify hidden inefficiencies in the Change Management or Incident flows.

### 5. Management Framework Orchestration
- **Selection Logic:** Use **COBIT** for governance, **TOGAF** for architecture, and **SAFe/Agile** for execution.
- **Project Choice:** Recommend **PMBOK** for predictable compliance projects and **Agile/Scrum** for innovative/uncertain products.

### 5. Communication Bridge (The C-Level Interface)
- **Tooling:** Help the user draft emails, slide decks, and reports that speak the language of Finance and Growth.
- **Technique:** Use the "Situation-Impact-Resolution" (SIR) framework for all high-level reporting.

## Applicability Suggestions
- **Shadow AI Governance:** Designing an "Approved AI Catalog" while allowing innovation.
- **ESG Roadmap:** Calculating the carbon baseline of the current hybrid cloud setup.
- **Crisis Communication:** Drafting stakeholder updates during a critical P1 outage.

## References
- [IT Manager's Handbook (2026 Edition)](./references/it-manager-handbook.md)
- [Real-World Management Scenarios](./examples/management-scenarios.md)
- [IT Management Frameworks (COBIT, TOGAF, NIST)](./references/it-management-frameworks.md)
- ITIL 5 Strategic Integration (See itil-expert skill)

## Limitations
- This skill provides strategic advisory and is not a substitute for legal, HR, or financial auditing specialized services.
- Data-driven advice is only as good as the telemetry data provided by the user.
- Always cross-reference AI-generated governance advice with local regulations.


---
name: iterate-pr
description: Iterate on a PR until CI passes. Use when you need to fix CI failures, address review feedback, or continuously push fixes until all checks are green. Automates the feedback-fix-push-wait cycle.
risk: critical
source: community
---

# Iterate on PR Until CI Passes

Continuously iterate on the current branch until all CI checks pass and review feedback is addressed.

**Requires**: GitHub CLI (`gh`) authenticated.

**Important**: All scripts must be run from the repository root directory (where `.git` is located), not from the skill directory. Use the full path to the script via `${CLAUDE_SKILL_ROOT}`.

## Bundled Scripts

### `scripts/fetch_pr_checks.py`

Fetches CI check status and extracts failure snippets from logs.

```bash
uv run ${CLAUDE_SKILL_ROOT}/scripts/fetch_pr_checks.py [--pr NUMBER]
```

Returns JSON:
```json
{
  "pr": {"number": 123, "branch": "feat/foo"},
  "summary": {"total": 5, "passed": 3, "failed": 2, "pending": 0},
  "checks": [
    {"name": "tests", "status": "fail", "log_snippet": "...", "run_id": 123},
    {"name": "lint", "status": "pass"}
  ]
}
```

### `scripts/fetch_pr_feedback.py`

Fetches and categorizes PR review feedback using the [LOGAF scale](https://develop.sentry.dev/engineering-practices/code-review/#logaf-scale).

```bash
uv run ${CLAUDE_SKILL_ROOT}/scripts/fetch_pr_feedback.py [--pr NUMBER]
```

Returns JSON with feedback categorized as:
- `high` - Must address before merge (`h:`, blocker, changes requested)
- `medium` - Should address (`m:`, standard feedback)
- `low` - Optional (`l:`, nit, style, suggestion)
- `bot` - Informational automated comments (Codecov, Dependabot, etc.)
- `resolved` - Already resolved threads

Review bot feedback (from Sentry, Warden, Cursor, Bugbot, CodeQL, etc.) appears in `high`/`medium`/`low` with `review_bot: true` — it is NOT placed in the `bot` bucket.

Each feedback item may also include:
- `thread_id` - GraphQL node ID for inline review comments (used for replies)

## Workflow

### 1. Identify PR

```bash
gh pr view --json number,url,headRefName
```

Stop if no PR exists for the current branch.

### 2. Gather Review Feedback

Run `${CLAUDE_SKILL_ROOT}/scripts/fetch_pr_feedback.py` to get categorized feedback already posted on the PR.

### 3. Handle Feedback by LOGAF Priority

**Auto-fix (no prompt):**
- `high` - must address (blockers, security, changes requested)
- `medium` - should address (standard feedback)

When fixing feedback:
- Understand the root cause, not just the surface symptom
- Check for similar issues in nearby code or related files
- Fix all instances, not just the one mentioned

This includes review bot feedback (items with `review_bot: true`). Treat it the same as human feedback:
- Real issue found → fix it
- False positive → skip, but explain why in a brief comment
- Never silently ignore review bot feedback — always verify the finding

**Prompt user for selection:**
- `low` - present numbered list and ask which to address:

```
Found 3 low-priority suggestions:
1. [l] "Consider renaming this variable" - @reviewer in api.py:42
2. [nit] "Could use a list comprehension" - @reviewer in utils.py:18
3. [style] "Add a docstring" - @reviewer in models.py:55

Which would you like to address? (e.g., "1,3" or "all" or "none")
```

**Skip silently:**
- `resolved` threads
- `bot` comments (informational only — Codecov, Dependabot, etc.)

#### Replying to Comments

After processing each inline review comment, reply on the PR thread to acknowledge the action taken. Only reply to items with a `thread_id` (inline review comments).

**When to reply:**
- `high` and `medium` items — whether fixed or determined to be false positives
- `low` items — whether fixed or declined by the user

**How to reply:** Use the `addPullRequestReviewThreadReply` GraphQL mutation with `pullRequestReviewThreadId` and `body` inputs.

**Reply format:**
- 1-2 sentences: what was changed, why it's not an issue, or acknowledgment of declined items
- End every reply with `\n\n*— Claude Code*`
- Before replying, check if the thread already has a reply ending with `*- Claude Code*` or `*— Claude Code*` to avoid duplicates on re-loops
- If the `gh api` call fails, log and continue — do not block the workflow

### 4. Check CI Status

Run `${CLAUDE_SKILL_ROOT}/scripts/fetch_pr_checks.py` to get structured failure data.

**Wait if pending:** If review bot checks (sentry, warden, cursor, bugbot, seer, codeql) are still running, wait before proceeding—they post actionable feedback that must be evaluated. Informational bots (codecov) are not worth waiting for.

### 5. Fix CI Failures

For each failure in the script output:
1. Read the `log_snippet` and trace backwards from the error to understand WHY it failed — not just what failed
2. Read the relevant code and check for related issues (e.g., if a type error in one call site, check other call sites)
3. Fix the root cause with minimal, targeted changes
4. Find existing tests for the affected code and run them. If the fix introduces behavior not covered by existing tests, extend them to cover it (add a test case, not a whole new test file)

Do NOT assume what failed based on check name alone—always read the logs. Do NOT "quick fix and hope" — understand the failure thoroughly before changing code.

### 6. Verify Locally, Then Commit and Push

Before committing, verify your fixes locally:
- If you fixed a test failure: re-run that specific test locally
- If you fixed a lint/type error: re-run the linter or type checker on affected files
- For any code fix: run existing tests covering the changed code

If local verification fails, fix before proceeding — do not push known-broken code.

```bash
git add <files>
git commit -m "fix: <descriptive message>"
git push
```

### 7. Monitor CI and Address Feedback

Poll CI status and review feedback in a loop instead of blocking:

1. Run `uv run ${CLAUDE_SKILL_ROOT}/scripts/fetch_pr_checks.py` to get current CI status
2. If all checks passed → proceed to exit conditions
3. If any checks failed (none pending) → return to step 5
4. If checks are still pending:
   a. Run `uv run ${CLAUDE_SKILL_ROOT}/scripts/fetch_pr_feedback.py` for new review feedback
   b. Address any new high/medium feedback immediately (same as step 3)
   c. If changes were needed, commit and push (this restarts CI), then continue polling
   d. Sleep 30 seconds, then repeat from sub-step 1
5. After all checks pass, do a final feedback check: `sleep 10`, then run `uv run ${CLAUDE_SKILL_ROOT}/scripts/fetch_pr_feedback.py`. Address any new high/medium feedback — if changes are needed, return to step 6.

### 8. Repeat

If step 7 required code changes (from new feedback after CI passed), return to step 2 for a fresh cycle. CI failures during monitoring are already handled within step 7's polling loop.

## Exit Conditions

**Success:** All checks pass, post-CI feedback re-check is clean (no new unaddressed high/medium feedback including review bot findings), user has decided on low-priority items.

**Ask for help:** Same failure after 2 attempts, feedback needs clarification, infrastructure issues.

**Stop:** No PR exists, branch needs rebase.

## Fallback

If scripts fail, use `gh` CLI directly:
- `gh pr checks name,state,bucket,link`
- `gh run view <run-id> --log-failed`
- `gh api repos/{owner}/{repo}/pulls/{number}/comments`

## When to Use
Use this skill when tackling tasks related to its primary domain or functionality as described above.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: itil-expert
description: Expert advisor for ITIL 4 and ITIL 5 (2026 digital product paradigm), specialized in AI-native governance, sustainability, and value co-creation.
risk: safe
source: community
date_added: "2026-04-18"
triggers:
  - "itil expert"
  - "itil 5 guidance"
  - "itil 4 process"
  - "design service value stream"
  - "ai governance guidance"
  - "digital product management itil"
---

# ITIL Expert (ITIL 4 & 5)

## Purpose
To act as a premier consultant for ITIL 4 and the newly released ITIL 5 frameworks. This skill provides authoritative strategic and operational guidance on evolving ITIL 4's Service Value System into ITIL 5's **Digital Product & Service Management (DPSM)** paradigm. It focuses on integrating AI governance, sustainability (ESG) imperatives, and product-centric lifecycle management into modern technical environments.

## Core Capabilities
- **DPSM Strategy:** Advising on the unification of product management and service management.
- **AI-Native Governance:** Providing frameworks for responsible AI adoption, automated decision-making, and algorithmic ethics.
- **Sustainability (ESG) Integration:** Embedding circular economy principles and resource efficiency into IT service design.
- **Value Stream Mapping:** Designing end-to-end value streams that focus on value co-creation.
- **Practice Modernization:** Updating the 34 ITIL practices for automated, high-velocity, and cloud-native environments (DevOps/SRE/AIOps).
- **ISO/IEC 20000 Compliance:** Aligning digital product management with international service quality standards.

## When to Use
- You are designing or optimizing a Service Value Stream (SVS).
- You need to align IT operations with ITIL 5's Digital Product paradigm.
- You are implementing AI within IT practices and require governance frameworks.
- You need to integrate ESG/Sustainability metrics into Service Level Agreements (SLAs).
- You are preparing for ITIL 4/5 certifications or audit readiness.

## Expert Instructions

### 1. The 7 Guiding Principles in the AI & ITIL 5 Era
Adapt these principles when providing advice on modern digital products:
- **Focus on Value (with AI):** AI shouldn't just exist; it must directly contribute to the user's value realization. If the AI doesn't improve the outcome, it is waste.
- **Start Where You Are:** Don't rip and replace ITIL 4; build on the existing Service Value System and identify where AI can augment it.
- **Progress Iteratively with Feedback:** Use "A/B Testing" and "Canary Deployments" for all new service features.
- **Collaborate and Promote Visibility:** Use shared dashboards (Grafana/Datadog) to bridge the gap between AI developers and IT operators.
- **Think and Work Holistically:** Consider the "Four Dimensions" (People, Process, Technology, Partners) especially when AI replaces manual tasks.
- **Keep it Simple and Practical:** Automate only what is stable. Don't over-engineer AI solutions for complex, low-volume incidents.
- **Optimize and Automate:** ITIL 5's mantra. First optimize the value stream, then use AI to automate the flow.

### 2. Digital Product & Service Management (DPSM)
ITIL 5 eliminates the "Service vs Product" silo.
- **Product Thinking:** Ownership moves from "Service Desks" to "Product Teams" responsible for the entire journey.
- **Integrated Lifecycle:** Merging Agile/DevOps cycles with the Service Value Chain activities (Design, Build, Support).
- **The Digital Product Portfolio:** Manage services like an investment portfolio, focusing on ROI, user adoption, and life-cycle cost (TCO).

### 3. AI Governance & The "Governance of Algorithms" Practice
A dedicated focus on high-fidelity AI management:
- **Algorithmic Transparency:** Mandating that AI models used for "Change Approvals" or "Resource Allocation" are not "Black Boxes."
- **Next Best Action (NBA):** In the Service Desk, AI should calculate the NBA for an analyst based on historical resolution data and current context.
- **Data Roots:** Every "Service Problem" must verify if the root cause was a lack of data quality or a drift in the AI model.

### 4. Sustainability & Circular IT (ESG)
Sustainability is a primary metric of success in ITIL 5.
- **Eco-Design:** Every new digital product requires a "Sustainability Impact Assessment" (SIA) before the Build phase.
- **Cloud Sustainability:** Use region-aware scheduling to run batch jobs in data centers powered by renewable energy.
- **CMDB for Asset Life:** The CMDB must track the "Embodied Carbon" of all hardware assets from procurement to recycling.

### 5. Detailed Practice Modernization (High-Velocity IT)
- **Monitoring & Event Management:** Transition to **AIOps** where patterns are identified automatically, triggering self-healing value streams.
- **Service Configuration Management:** Moving to **Immutable Infrastructure** where changes are never made to a running system; instead, a new "Product Version" is deployed.
- **Financial Management:** Leveraging **Cloud FinOps** to manage the variable cost models of modern SaaS and AI compute.

## Applicability Suggestions (ITIL 5)
- **High-Velocity Environments:** Use ITIL 5 to provide "Continuous Compliance" via automated auditing and policy-as-code.
- **Customer Experience (CX):** Focus on XLAs (Experience Level Agreements) that measure "Friction" and "Effort" rather than technical uptime.
- **Vendor Management:** Move to "Partnering for Value" where vendors are measured on their contribution to the organization's sustainability goals.

## Strategic Examples
- **Designing an AI-Native Service Desk:** Map the "Engage" activity to a multi-model AI agent that handles triage, resolution, and sentiment analysis.
- **Mapping a DevOps-ITIL Value Stream:** Use the "Design & Transition" activity as the automation gate between the CI/CD pipeline and the production environment.

## Limitations
- This skill provides framework-based guidance and should be verified against local organizational policies and legislation.
- Sustainability metrics are based on industry standards (e.g., GHG Protocol) and should be validated by certified consultants.
- Best used in conjunction with "Agile," "Lean," and "DevOps" expert skills.

## References
- [ITIL 5 Evolution Guide](./references/itil-5-evolution.md)
- [Real-World Usage Scenarios](./examples/itil-usage.md)
- [ITIL 5 Extension Modules (2026 Edition)](https://www.peoplecert.org)


---
name: java
description: "Language-specific super-code guidelines for java."
risk: safe
source: community
date_added: "2026-06-16"
---
# Java: Idiomatic Efficiency Reference

## When to Use
- Use this skill when the task matches this description: Language-specific super-code guidelines for java.

## Table of Contents
1. [Streams & Collections](#streams)
2. [Optional](#optional)
3. [Records & Data Classes](#records)
4. [Switch Expressions](#switch)
5. [Concurrency](#concurrency)
6. [Error Handling](#errors)
7. [Anti-patterns specific to Java](#antipatterns)

---

## 1. Streams & Collections {#streams}

```java
// ❌ Imperative accumulation
List<String> result = new ArrayList<>();
for (Item item : items) {
    if (item.isActive()) result.add(item.getName().toUpperCase());
}

// ✅
List<String> result = items.stream()
    .filter(Item::isActive)
    .map(item -> item.getName().toUpperCase())
    .toList(); // Java 16+; use .collect(Collectors.toList()) before
```

```java
// ❌ Manual grouping
Map<String, List<Item>> grouped = new HashMap<>();
for (Item item : items) {
    grouped.computeIfAbsent(item.getCategory(), k -> new ArrayList<>()).add(item);
}

// ✅
Map<String, List<Item>> grouped = items.stream()
    .collect(Collectors.groupingBy(Item::getCategory));
```

```java
// ❌ Manual sum
int total = 0;
for (Order o : orders) total += o.getAmount();

// ✅
int total = orders.stream().mapToInt(Order::getAmount).sum();
```

**Prefer method references (`Item::isActive`) over equivalent lambdas (`item -> item.isActive()`).**

---

## 2. Optional {#optional}

```java
// ❌ Null check chain
String city = null;
if (user != null && user.getAddress() != null) {
    city = user.getAddress().getCity();
}

// ✅
String city = Optional.ofNullable(user)
    .map(User::getAddress)
    .map(Address::getCity)
    .orElse(null);
```

```java
// ❌ Optional.get() without isPresent()
String name = optional.get(); // throws if empty

// ✅
String name = optional.orElse("default");
// or: optional.orElseThrow(() -> new IllegalStateException("name required"));
```

```java
// ❌ Optional as a field or parameter (anti-pattern)
class User { private Optional<String> nickname; }

// ✅ — Optional is for return types only
class User { private String nickname; } // nullable field
public Optional<String> getNickname() { return Optional.ofNullable(nickname); }
```

---

## 3. Records & Data Classes {#records}

```java
// ❌ Manual POJO
class Point {
    private final int x, y;
    public Point(int x, int y) { this.x = x; this.y = y; }
    public int getX() { return x; }
    public int getY() { return y; }
    // + equals, hashCode, toString...
}

// ✅ (Java 16+)
record Point(int x, int y) {}
```

```java
// ❌ Builder pattern for a 2-field object
User user = new User.Builder().name("Alice").age(30).build();

// ✅ — use record or constructor directly for small objects
record User(String name, int age) {}
var user = new User("Alice", 30);
```

**Use `record` for any immutable data carrier. Keep builders only for objects with many optional fields.**

---

## 4. Switch Expressions {#switch}

```java
// ❌ Switch statement with fall-through and break
String label;
switch (status) {
    case ACTIVE: label = "Active"; break;
    case INACTIVE: label = "Inactive"; break;
    default: label = "Unknown";
}

// ✅ (Java 14+)
String label = switch (status) {
    case ACTIVE -> "Active";
    case INACTIVE -> "Inactive";
    default -> "Unknown";
};
```

```java
// ❌ instanceof + cast
if (shape instanceof Circle) {
    Circle c = (Circle) shape;
    return c.radius() * c.radius() * Math.PI;
}

// ✅ Pattern matching (Java 16+)
if (shape instanceof Circle c) {
    return c.radius() * c.radius() * Math.PI;
}
```

---

## 5. Concurrency {#concurrency}

```java
// ❌ Raw Thread creation
Thread t = new Thread(() -> doWork());
t.start();

// ✅
ExecutorService exec = Executors.newVirtualThreadPerTaskExecutor(); // Java 21
exec.submit(() -> doWork());
```

```java
// ❌ synchronized on this for fine-grained state
synchronized(this) { counter++; }

// ✅
AtomicInteger counter = new AtomicInteger();
counter.incrementAndGet();
```

**Prefer `CompletableFuture.allOf()` over blocking `.get()` chains for parallel async work.**

---

## 6. Error Handling {#errors}

```java
// ❌ Catching Exception to log and swallow
try {
    risky();
} catch (Exception e) {
    log.error("error", e);
}

// ✅ — rethrow as unchecked if you can't handle it
try {
    risky();
} catch (IOException e) {
    throw new UncheckedIOException(e);
}
```

```java
// ❌ Checked exceptions declared on every method
public void process() throws IOException, SQLException, ParseException { ... }

// ✅ — wrap at the boundary; internal methods throw unchecked
```

---

## 7. Anti-patterns specific to Java {#antipatterns}

| Anti-pattern | Preferred |
|---|---|
| `new ArrayList<String>()` (Java 7+) | `new ArrayList<>()` (diamond) |
| `"string".equals(variable)` (Yoda) | `Objects.equals(variable, "string")` |
| `for (int i = 0; i < list.size(); i++)` | enhanced for or stream |
| `StringBuffer` in single-threaded code | `StringBuilder` |
| `e.printStackTrace()` | `log.error("msg", e)` |
| `null` return for "not found" | `Optional<T>` return type |
| Public fields | private + accessor, or `record` |
| Mutable `static` fields | avoid; use dependency injection |
| `instanceof` + cast without pattern matching | pattern matching (Java 16+) |

## Limitations
- These are language-specific guidelines and do not cover overall architectural decisions.
- Over-compression might reduce readability; apply judgement.