[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6FK46JY4PK4638NW64RFZ2T":3,"skill-same:01M6FK46JY4PK4638NW64RFZ2T":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":26,"linkOnly":27,"markdownContent":28,"markdownBody":29,"frontMatter":30,"refName":32,"commitSha":33,"skillDirectory":34,"forksCount":35,"repositoryHtmlUrl":36,"repositoryHomepageUrl":6,"ownerHtmlUrl":37,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":38,"install":39,"resources":52},"01M6FK46JY4PK4638NW64RFZ2T","resource-leveler",null,"Level and optimize construction resource allocation across project schedule. Balance labor, equipment usage, and avoid overallocation while maintaining critical path.","kbarbel640-del\u002Fskills","kbarbel640-del","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F255315490?v=4","01M6CJPPQGCCESXMG3K7BBGQ5J","01M6CJPPX2PB2BCZERFVM2C2B3",1,"MIT","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Fresource-leveler\u002FSKILL.md",[],[18,19,20,21,22,23,24,25],"resource leveler","schedule","optimize","across","project","critical","resource allocation","usage","2026-11-10 10:12:30",false,"---\r\nslug: \"resource-leveler\"\r\ndisplay_name: \"Resource Leveler\"\r\ndescription: \"Level and optimize construction resource allocation across project schedule. Balance labor, equipment usage, and avoid overallocation while maintaining critical path.\"\r\n---\r\n\r\n# Resource Leveler for Construction\r\n\r\n## Overview\r\n\r\nOptimize resource allocation across construction schedules. Level labor and equipment to avoid peaks, balance workload, and maintain project deadlines while reducing costs.\r\n\r\n## Business Case\r\n\r\nResource leveling provides:\r\n- **Cost Reduction**: Avoid overtime and idle time\r\n- **Workforce Stability**: Consistent crew sizes\r\n- **Equipment Optimization**: Reduce rental costs\r\n- **Realistic Schedules**: Achievable resource plans\r\n\r\n## Technical Implementation\r\n\r\n```python\r\nfrom dataclasses import dataclass, field\r\nfrom typing import List, Dict, Any, Optional, Tuple\r\nfrom datetime import datetime, date, timedelta\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom collections import defaultdict\r\n\r\n@dataclass\r\nclass Resource:\r\n    id: str\r\n    name: str\r\n    resource_type: str  # labor, equipment, material\r\n    max_units: float\r\n    cost_per_unit: float\r\n    unit: str  # hours, days, each\r\n\r\n@dataclass\r\nclass ResourceAssignment:\r\n    task_id: str\r\n    resource_id: str\r\n    units: float\r\n    start_date: date\r\n    end_date: date\r\n\r\n@dataclass\r\nclass Task:\r\n    id: str\r\n    name: str\r\n    duration: int  # days\r\n    start_date: date\r\n    end_date: date\r\n    predecessors: List[str]\r\n    total_float: int\r\n    is_critical: bool\r\n    resource_assignments: List[ResourceAssignment] = field(default_factory=list)\r\n\r\n@dataclass\r\nclass LevelingResult:\r\n    success: bool\r\n    original_end_date: date\r\n    leveled_end_date: date\r\n    tasks_moved: int\r\n    peak_reduction: Dict[str, float]\r\n    warnings: List[str]\r\n\r\nclass ConstructionResourceLeveler:\r\n    \"\"\"Level resources across construction schedules.\"\"\"\r\n\r\n    def __init__(self):\r\n        self.resources: Dict[str, Resource] = {}\r\n        self.tasks: Dict[str, Task] = {}\r\n        self.assignments: List[ResourceAssignment] = []\r\n\r\n    def add_resource(self, resource: Resource):\r\n        \"\"\"Add a resource to the pool.\"\"\"\r\n        self.resources[resource.id] = resource\r\n\r\n    def add_task(self, task: Task):\r\n        \"\"\"Add a task to the schedule.\"\"\"\r\n        self.tasks[task.id] = task\r\n\r\n    def add_assignment(self, assignment: ResourceAssignment):\r\n        \"\"\"Assign a resource to a task.\"\"\"\r\n        self.assignments.append(assignment)\r\n        if assignment.task_id in self.tasks:\r\n            self.tasks[assignment.task_id].resource_assignments.append(assignment)\r\n\r\n    def calculate_resource_usage(self, start_date: date = None,\r\n                                  end_date: date = None) -> pd.DataFrame:\r\n        \"\"\"Calculate daily resource usage.\"\"\"\r\n        if not self.assignments:\r\n            return pd.DataFrame()\r\n\r\n        # Determine date range\r\n        if start_date is None:\r\n            start_date = min(a.start_date for a in self.assignments)\r\n        if end_date is None:\r\n            end_date = max(a.end_date for a in self.assignments)\r\n\r\n        # Create date range\r\n        dates = pd.date_range(start_date, end_date, freq='D')\r\n\r\n        # Initialize usage matrix\r\n        usage = {r_id: [0.0] * len(dates) for r_id in self.resources}\r\n\r\n        # Fill in usage\r\n        for assignment in self.assignments:\r\n            if assignment.resource_id in usage:\r\n                for i, d in enumerate(dates):\r\n                    if assignment.start_date \u003C= d.date() \u003C= assignment.end_date:\r\n                        usage[assignment.resource_id][i] += assignment.units\r\n\r\n        df = pd.DataFrame(usage, index=dates)\r\n        df.index.name = 'date'\r\n\r\n        return df\r\n\r\n    def identify_overallocations(self) -> List[Dict]:\r\n        \"\"\"Identify resource overallocations.\"\"\"\r\n        usage = self.calculate_resource_usage()\r\n        overallocations = []\r\n\r\n        for resource_id, resource in self.resources.items():\r\n            if resource_id in usage.columns:\r\n                daily_usage = usage[resource_id]\r\n                over_days = daily_usage[daily_usage > resource.max_units]\r\n\r\n                if len(over_days) > 0:\r\n                    overallocations.append({\r\n                        'resource_id': resource_id,\r\n                        'resource_name': resource.name,\r\n                        'max_units': resource.max_units,\r\n                        'peak_usage': daily_usage.max(),\r\n                        'over_by': daily_usage.max() - resource.max_units,\r\n                        'days_overallocated': len(over_days),\r\n                        'first_overallocation': over_days.index[0].date(),\r\n                        'worst_day': daily_usage.idxmax().date()\r\n                    })\r\n\r\n        return overallocations\r\n\r\n    def level_resources(self, method: str = 'float_priority',\r\n                        protect_critical_path: bool = True,\r\n                        max_extension: int = 30) -> LevelingResult:\r\n        \"\"\"Level resources to resolve overallocations.\"\"\"\r\n\r\n        original_end = max(t.end_date for t in self.tasks.values())\r\n        tasks_moved = 0\r\n        warnings = []\r\n\r\n        # Get initial overallocations\r\n        initial_over = self.identify_overallocations()\r\n        if not initial_over:\r\n            return LevelingResult(\r\n                success=True,\r\n                original_end_date=original_end,\r\n                leveled_end_date=original_end,\r\n                tasks_moved=0,\r\n                peak_reduction={},\r\n                warnings=[\"No overallocations found\"]\r\n            )\r\n\r\n        # Track peak usage before\r\n        usage_before = self.calculate_resource_usage()\r\n        peaks_before = {r: usage_before[r].max() for r in usage_before.columns}\r\n\r\n        # Leveling loop\r\n        iteration = 0\r\n        max_iterations = len(self.tasks) * 2\r\n\r\n        while iteration \u003C max_iterations:\r\n            iteration += 1\r\n            overallocations = self.identify_overallocations()\r\n\r\n            if not overallocations:\r\n                break\r\n\r\n            # Find task to move\r\n            moved = False\r\n            for over in overallocations:\r\n                resource_id = over['resource_id']\r\n                worst_day = over['worst_day']\r\n\r\n                # Find tasks using this resource on worst day\r\n                candidates = self._find_movable_tasks(\r\n                    resource_id, worst_day, protect_critical_path\r\n                )\r\n\r\n                if candidates:\r\n                    # Sort by priority (lowest float first to preserve options)\r\n                    candidates.sort(key=lambda t: -t.total_float)\r\n                    task_to_move = candidates[0]\r\n\r\n                    # Calculate new dates\r\n                    new_start, new_end = self._calculate_shift(\r\n                        task_to_move, resource_id, max_extension\r\n                    )\r\n\r\n                    if new_start:\r\n                        self._shift_task(task_to_move.id, new_start, new_end)\r\n                        tasks_moved += 1\r\n                        moved = True\r\n                        break\r\n\r\n            if not moved:\r\n                warnings.append(\"Could not resolve all overallocations\")\r\n                break\r\n\r\n        # Calculate results\r\n        usage_after = self.calculate_resource_usage()\r\n        peaks_after = {r: usage_after[r].max() for r in usage_after.columns}\r\n\r\n        peak_reduction = {}\r\n        for r in peaks_before:\r\n            if r in peaks_after:\r\n                reduction = (peaks_before[r] - peaks_after[r]) \u002F peaks_before[r] * 100\r\n                peak_reduction[r] = reduction\r\n\r\n        leveled_end = max(t.end_date for t in self.tasks.values())\r\n\r\n        if leveled_end > original_end + timedelta(days=max_extension):\r\n            warnings.append(f\"Project extended beyond max allowed ({max_extension} days)\")\r\n\r\n        remaining_over = self.identify_overallocations()\r\n\r\n        return LevelingResult(\r\n            success=len(remaining_over) == 0,\r\n            original_end_date=original_end,\r\n            leveled_end_date=leveled_end,\r\n            tasks_moved=tasks_moved,\r\n            peak_reduction=peak_reduction,\r\n            warnings=warnings\r\n        )\r\n\r\n    def _find_movable_tasks(self, resource_id: str, on_date: date,\r\n                            protect_critical: bool) -> List[Task]:\r\n        \"\"\"Find tasks that can be moved to reduce overallocation.\"\"\"\r\n        candidates = []\r\n\r\n        for task in self.tasks.values():\r\n            # Check if task uses this resource on this date\r\n            uses_resource = any(\r\n                a.resource_id == resource_id and\r\n                a.start_date \u003C= on_date \u003C= a.end_date\r\n                for a in task.resource_assignments\r\n            )\r\n\r\n            if not uses_resource:\r\n                continue\r\n\r\n            # Check if critical path protected\r\n            if protect_critical and task.is_critical:\r\n                continue\r\n\r\n            # Check if has float\r\n            if task.total_float > 0:\r\n                candidates.append(task)\r\n\r\n        return candidates\r\n\r\n    def _calculate_shift(self, task: Task, resource_id: str,\r\n                         max_extension: int) -> Tuple[date, date]:\r\n        \"\"\"Calculate optimal shift for a task.\"\"\"\r\n        resource = self.resources[resource_id]\r\n\r\n        # Try shifting forward\r\n        for days in range(1, min(task.total_float + 1, max_extension + 1)):\r\n            new_start = task.start_date + timedelta(days=days)\r\n            new_end = task.end_date + timedelta(days=days)\r\n\r\n            # Check if this resolves overallocation\r\n            temp_usage = self._calculate_usage_if_moved(task.id, new_start, new_end)\r\n\r\n            if temp_usage.get(resource_id, 0) \u003C= resource.max_units:\r\n                return new_start, new_end\r\n\r\n        return None, None\r\n\r\n    def _calculate_usage_if_moved(self, task_id: str, new_start: date,\r\n                                   new_end: date) -> Dict[str, float]:\r\n        \"\"\"Calculate resource usage if task were moved.\"\"\"\r\n        # Simplified: calculate peak on affected dates\r\n        usage = defaultdict(float)\r\n\r\n        for assignment in self.assignments:\r\n            if assignment.task_id == task_id:\r\n                # Use new dates\r\n                for d in pd.date_range(new_start, new_end):\r\n                    usage[assignment.resource_id] = max(\r\n                        usage[assignment.resource_id],\r\n                        assignment.units\r\n                    )\r\n            else:\r\n                # Use existing dates\r\n                for d in pd.date_range(assignment.start_date, assignment.end_date):\r\n                    usage[assignment.resource_id] = max(\r\n                        usage[assignment.resource_id],\r\n                        assignment.units\r\n                    )\r\n\r\n        return dict(usage)\r\n\r\n    def _shift_task(self, task_id: str, new_start: date, new_end: date):\r\n        \"\"\"Shift a task to new dates.\"\"\"\r\n        task = self.tasks[task_id]\r\n        delta = new_start - task.start_date\r\n\r\n        # Update task\r\n        task.start_date = new_start\r\n        task.end_date = new_end\r\n\r\n        # Update assignments\r\n        for assignment in self.assignments:\r\n            if assignment.task_id == task_id:\r\n                assignment.start_date += delta\r\n                assignment.end_date += delta\r\n\r\n    def optimize_crew_size(self, resource_id: str,\r\n                            target_utilization: float = 0.85) -> Dict:\r\n        \"\"\"Recommend optimal crew size for a resource.\"\"\"\r\n        usage = self.calculate_resource_usage()\r\n\r\n        if resource_id not in usage.columns:\r\n            return None\r\n\r\n        daily_usage = usage[resource_id]\r\n        resource = self.resources[resource_id]\r\n\r\n        # Calculate statistics\r\n        peak = daily_usage.max()\r\n        avg = daily_usage.mean()\r\n        working_days = (daily_usage > 0).sum()\r\n\r\n        # Current utilization\r\n        current_util = avg \u002F resource.max_units if resource.max_units > 0 else 0\r\n\r\n        # Optimal size for target utilization\r\n        optimal_size = avg \u002F target_utilization\r\n\r\n        return {\r\n            'resource_id': resource_id,\r\n            'current_max_units': resource.max_units,\r\n            'peak_usage': peak,\r\n            'average_usage': avg,\r\n            'working_days': int(working_days),\r\n            'current_utilization': current_util,\r\n            'recommended_max_units': round(optimal_size, 1),\r\n            'potential_savings': (resource.max_units - optimal_size) * resource.cost_per_unit * working_days\r\n        }\r\n\r\n    def generate_histogram(self, resource_id: str) -> pd.DataFrame:\r\n        \"\"\"Generate resource histogram data.\"\"\"\r\n        usage = self.calculate_resource_usage()\r\n\r\n        if resource_id not in usage.columns:\r\n            return pd.DataFrame()\r\n\r\n        resource = self.resources[resource_id]\r\n\r\n        df = pd.DataFrame({\r\n            'date': usage.index,\r\n            'usage': usage[resource_id].values,\r\n            'capacity': resource.max_units,\r\n            'overallocated': usage[resource_id].values > resource.max_units\r\n        })\r\n\r\n        return df\r\n\r\n    def generate_report(self) -> str:\r\n        \"\"\"Generate resource leveling report.\"\"\"\r\n        lines = [\"# Resource Leveling Report\", \"\"]\r\n        lines.append(f\"**Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M')}\")\r\n        lines.append(f\"**Resources:** {len(self.resources)}\")\r\n        lines.append(f\"**Tasks:** {len(self.tasks)}\")\r\n        lines.append(\"\")\r\n\r\n        # Overallocations\r\n        overallocations = self.identify_overallocations()\r\n        if overallocations:\r\n            lines.append(\"## Overallocations Found\")\r\n            for over in overallocations:\r\n                lines.append(f\"\\n### {over['resource_name']}\")\r\n                lines.append(f\"- **Max Units:** {over['max_units']}\")\r\n                lines.append(f\"- **Peak Usage:** {over['peak_usage']}\")\r\n                lines.append(f\"- **Days Overallocated:** {over['days_overallocated']}\")\r\n                lines.append(f\"- **Worst Day:** {over['worst_day']}\")\r\n        else:\r\n            lines.append(\"## No Overallocations\")\r\n            lines.append(\"All resources are within capacity.\")\r\n\r\n        # Resource utilization\r\n        lines.append(\"\\n## Resource Utilization\")\r\n        for resource_id in self.resources:\r\n            opt = self.optimize_crew_size(resource_id)\r\n            if opt:\r\n                lines.append(f\"\\n### {self.resources[resource_id].name}\")\r\n                lines.append(f\"- **Utilization:** {opt['current_utilization']:.1%}\")\r\n                lines.append(f\"- **Peak:** {opt['peak_usage']:.1f}\")\r\n                lines.append(f\"- **Average:** {opt['average_usage']:.1f}\")\r\n\r\n        return \"\\n\".join(lines)\r\n```\r\n\r\n## Quick Start\r\n\r\n```python\r\nfrom datetime import date\r\n\r\n# Initialize leveler\r\nleveler = ConstructionResourceLeveler()\r\n\r\n# Add resources\r\nleveler.add_resource(Resource(\r\n    id=\"CARP\",\r\n    name=\"Carpenters\",\r\n    resource_type=\"labor\",\r\n    max_units=10,\r\n    cost_per_unit=75,\r\n    unit=\"hours\"\r\n))\r\n\r\n# Add tasks\r\nleveler.add_task(Task(\r\n    id=\"T1\",\r\n    name=\"Frame Level 1\",\r\n    duration=10,\r\n    start_date=date(2026, 3, 1),\r\n    end_date=date(2026, 3, 14),\r\n    predecessors=[],\r\n    total_float=5,\r\n    is_critical=False\r\n))\r\n\r\n# Add assignments\r\nleveler.add_assignment(ResourceAssignment(\r\n    task_id=\"T1\",\r\n    resource_id=\"CARP\",\r\n    units=8,\r\n    start_date=date(2026, 3, 1),\r\n    end_date=date(2026, 3, 14)\r\n))\r\n\r\n# Check overallocations\r\noverallocations = leveler.identify_overallocations()\r\nfor over in overallocations:\r\n    print(f\"{over['resource_name']}: {over['peak_usage']} vs {over['max_units']} max\")\r\n\r\n# Level resources\r\nresult = leveler.level_resources(protect_critical_path=True)\r\nprint(f\"Tasks moved: {result.tasks_moved}\")\r\nprint(f\"End date change: {result.original_end_date} -> {result.leveled_end_date}\")\r\n\r\n# Generate report\r\nprint(leveler.generate_report())\r\n```\r\n\r\n## Dependencies\r\n\r\n```bash\r\npip install pandas numpy\r\n```\r\n","# Resource Leveler for Construction\r\n\r\n## Overview\r\n\r\nOptimize resource allocation across construction schedules. Level labor and equipment to avoid peaks, balance workload, and maintain project deadlines while reducing costs.\r\n\r\n## Business Case\r\n\r\nResource leveling provides:\r\n- **Cost Reduction**: Avoid overtime and idle time\r\n- **Workforce Stability**: Consistent crew sizes\r\n- **Equipment Optimization**: Reduce rental costs\r\n- **Realistic Schedules**: Achievable resource plans\r\n\r\n## Technical Implementation\r\n\r\n```python\r\nfrom dataclasses import dataclass, field\r\nfrom typing import List, Dict, Any, Optional, Tuple\r\nfrom datetime import datetime, date, timedelta\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom collections import defaultdict\r\n\r\n@dataclass\r\nclass Resource:\r\n    id: str\r\n    name: str\r\n    resource_type: str  # labor, equipment, material\r\n    max_units: float\r\n    cost_per_unit: float\r\n    unit: str  # hours, days, each\r\n\r\n@dataclass\r\nclass ResourceAssignment:\r\n    task_id: str\r\n    resource_id: str\r\n    units: float\r\n    start_date: date\r\n    end_date: date\r\n\r\n@dataclass\r\nclass Task:\r\n    id: str\r\n    name: str\r\n    duration: int  # days\r\n    start_date: date\r\n    end_date: date\r\n    predecessors: List[str]\r\n    total_float: int\r\n    is_critical: bool\r\n    resource_assignments: List[ResourceAssignment] = field(default_factory=list)\r\n\r\n@dataclass\r\nclass LevelingResult:\r\n    success: bool\r\n    original_end_date: date\r\n    leveled_end_date: date\r\n    tasks_moved: int\r\n    peak_reduction: Dict[str, float]\r\n    warnings: List[str]\r\n\r\nclass ConstructionResourceLeveler:\r\n    \"\"\"Level resources across construction schedules.\"\"\"\r\n\r\n    def __init__(self):\r\n        self.resources: Dict[str, Resource] = {}\r\n        self.tasks: Dict[str, Task] = {}\r\n        self.assignments: List[ResourceAssignment] = []\r\n\r\n    def add_resource(self, resource: Resource):\r\n        \"\"\"Add a resource to the pool.\"\"\"\r\n        self.resources[resource.id] = resource\r\n\r\n    def add_task(self, task: Task):\r\n        \"\"\"Add a task to the schedule.\"\"\"\r\n        self.tasks[task.id] = task\r\n\r\n    def add_assignment(self, assignment: ResourceAssignment):\r\n        \"\"\"Assign a resource to a task.\"\"\"\r\n        self.assignments.append(assignment)\r\n        if assignment.task_id in self.tasks:\r\n            self.tasks[assignment.task_id].resource_assignments.append(assignment)\r\n\r\n    def calculate_resource_usage(self, start_date: date = None,\r\n                                  end_date: date = None) -> pd.DataFrame:\r\n        \"\"\"Calculate daily resource usage.\"\"\"\r\n        if not self.assignments:\r\n            return pd.DataFrame()\r\n\r\n        # Determine date range\r\n        if start_date is None:\r\n            start_date = min(a.start_date for a in self.assignments)\r\n        if end_date is None:\r\n            end_date = max(a.end_date for a in self.assignments)\r\n\r\n        # Create date range\r\n        dates = pd.date_range(start_date, end_date, freq='D')\r\n\r\n        # Initialize usage matrix\r\n        usage = {r_id: [0.0] * len(dates) for r_id in self.resources}\r\n\r\n        # Fill in usage\r\n        for assignment in self.assignments:\r\n            if assignment.resource_id in usage:\r\n                for i, d in enumerate(dates):\r\n                    if assignment.start_date \u003C= d.date() \u003C= assignment.end_date:\r\n                        usage[assignment.resource_id][i] += assignment.units\r\n\r\n        df = pd.DataFrame(usage, index=dates)\r\n        df.index.name = 'date'\r\n\r\n        return df\r\n\r\n    def identify_overallocations(self) -> List[Dict]:\r\n        \"\"\"Identify resource overallocations.\"\"\"\r\n        usage = self.calculate_resource_usage()\r\n        overallocations = []\r\n\r\n        for resource_id, resource in self.resources.items():\r\n            if resource_id in usage.columns:\r\n                daily_usage = usage[resource_id]\r\n                over_days = daily_usage[daily_usage > resource.max_units]\r\n\r\n                if len(over_days) > 0:\r\n                    overallocations.append({\r\n                        'resource_id': resource_id,\r\n                        'resource_name': resource.name,\r\n                        'max_units': resource.max_units,\r\n                        'peak_usage': daily_usage.max(),\r\n                        'over_by': daily_usage.max() - resource.max_units,\r\n                        'days_overallocated': len(over_days),\r\n                        'first_overallocation': over_days.index[0].date(),\r\n                        'worst_day': daily_usage.idxmax().date()\r\n                    })\r\n\r\n        return overallocations\r\n\r\n    def level_resources(self, method: str = 'float_priority',\r\n                        protect_critical_path: bool = True,\r\n                        max_extension: int = 30) -> LevelingResult:\r\n        \"\"\"Level resources to resolve overallocations.\"\"\"\r\n\r\n        original_end = max(t.end_date for t in self.tasks.values())\r\n        tasks_moved = 0\r\n        warnings = []\r\n\r\n        # Get initial overallocations\r\n        initial_over = self.identify_overallocations()\r\n        if not initial_over:\r\n            return LevelingResult(\r\n                success=True,\r\n                original_end_date=original_end,\r\n                leveled_end_date=original_end,\r\n                tasks_moved=0,\r\n                peak_reduction={},\r\n                warnings=[\"No overallocations found\"]\r\n            )\r\n\r\n        # Track peak usage before\r\n        usage_before = self.calculate_resource_usage()\r\n        peaks_before = {r: usage_before[r].max() for r in usage_before.columns}\r\n\r\n        # Leveling loop\r\n        iteration = 0\r\n        max_iterations = len(self.tasks) * 2\r\n\r\n        while iteration \u003C max_iterations:\r\n            iteration += 1\r\n            overallocations = self.identify_overallocations()\r\n\r\n            if not overallocations:\r\n                break\r\n\r\n            # Find task to move\r\n            moved = False\r\n            for over in overallocations:\r\n                resource_id = over['resource_id']\r\n                worst_day = over['worst_day']\r\n\r\n                # Find tasks using this resource on worst day\r\n                candidates = self._find_movable_tasks(\r\n                    resource_id, worst_day, protect_critical_path\r\n                )\r\n\r\n                if candidates:\r\n                    # Sort by priority (lowest float first to preserve options)\r\n                    candidates.sort(key=lambda t: -t.total_float)\r\n                    task_to_move = candidates[0]\r\n\r\n                    # Calculate new dates\r\n                    new_start, new_end = self._calculate_shift(\r\n                        task_to_move, resource_id, max_extension\r\n                    )\r\n\r\n                    if new_start:\r\n                        self._shift_task(task_to_move.id, new_start, new_end)\r\n                        tasks_moved += 1\r\n                        moved = True\r\n                        break\r\n\r\n            if not moved:\r\n                warnings.append(\"Could not resolve all overallocations\")\r\n                break\r\n\r\n        # Calculate results\r\n        usage_after = self.calculate_resource_usage()\r\n        peaks_after = {r: usage_after[r].max() for r in usage_after.columns}\r\n\r\n        peak_reduction = {}\r\n        for r in peaks_before:\r\n            if r in peaks_after:\r\n                reduction = (peaks_before[r] - peaks_after[r]) \u002F peaks_before[r] * 100\r\n                peak_reduction[r] = reduction\r\n\r\n        leveled_end = max(t.end_date for t in self.tasks.values())\r\n\r\n        if leveled_end > original_end + timedelta(days=max_extension):\r\n            warnings.append(f\"Project extended beyond max allowed ({max_extension} days)\")\r\n\r\n        remaining_over = self.identify_overallocations()\r\n\r\n        return LevelingResult(\r\n            success=len(remaining_over) == 0,\r\n            original_end_date=original_end,\r\n            leveled_end_date=leveled_end,\r\n            tasks_moved=tasks_moved,\r\n            peak_reduction=peak_reduction,\r\n            warnings=warnings\r\n        )\r\n\r\n    def _find_movable_tasks(self, resource_id: str, on_date: date,\r\n                            protect_critical: bool) -> List[Task]:\r\n        \"\"\"Find tasks that can be moved to reduce overallocation.\"\"\"\r\n        candidates = []\r\n\r\n        for task in self.tasks.values():\r\n            # Check if task uses this resource on this date\r\n            uses_resource = any(\r\n                a.resource_id == resource_id and\r\n                a.start_date \u003C= on_date \u003C= a.end_date\r\n                for a in task.resource_assignments\r\n            )\r\n\r\n            if not uses_resource:\r\n                continue\r\n\r\n            # Check if critical path protected\r\n            if protect_critical and task.is_critical:\r\n                continue\r\n\r\n            # Check if has float\r\n            if task.total_float > 0:\r\n                candidates.append(task)\r\n\r\n        return candidates\r\n\r\n    def _calculate_shift(self, task: Task, resource_id: str,\r\n                         max_extension: int) -> Tuple[date, date]:\r\n        \"\"\"Calculate optimal shift for a task.\"\"\"\r\n        resource = self.resources[resource_id]\r\n\r\n        # Try shifting forward\r\n        for days in range(1, min(task.total_float + 1, max_extension + 1)):\r\n            new_start = task.start_date + timedelta(days=days)\r\n            new_end = task.end_date + timedelta(days=days)\r\n\r\n            # Check if this resolves overallocation\r\n            temp_usage = self._calculate_usage_if_moved(task.id, new_start, new_end)\r\n\r\n            if temp_usage.get(resource_id, 0) \u003C= resource.max_units:\r\n                return new_start, new_end\r\n\r\n        return None, None\r\n\r\n    def _calculate_usage_if_moved(self, task_id: str, new_start: date,\r\n                                   new_end: date) -> Dict[str, float]:\r\n        \"\"\"Calculate resource usage if task were moved.\"\"\"\r\n        # Simplified: calculate peak on affected dates\r\n        usage = defaultdict(float)\r\n\r\n        for assignment in self.assignments:\r\n            if assignment.task_id == task_id:\r\n                # Use new dates\r\n                for d in pd.date_range(new_start, new_end):\r\n                    usage[assignment.resource_id] = max(\r\n                        usage[assignment.resource_id],\r\n                        assignment.units\r\n                    )\r\n            else:\r\n                # Use existing dates\r\n                for d in pd.date_range(assignment.start_date, assignment.end_date):\r\n                    usage[assignment.resource_id] = max(\r\n                        usage[assignment.resource_id],\r\n                        assignment.units\r\n                    )\r\n\r\n        return dict(usage)\r\n\r\n    def _shift_task(self, task_id: str, new_start: date, new_end: date):\r\n        \"\"\"Shift a task to new dates.\"\"\"\r\n        task = self.tasks[task_id]\r\n        delta = new_start - task.start_date\r\n\r\n        # Update task\r\n        task.start_date = new_start\r\n        task.end_date = new_end\r\n\r\n        # Update assignments\r\n        for assignment in self.assignments:\r\n            if assignment.task_id == task_id:\r\n                assignment.start_date += delta\r\n                assignment.end_date += delta\r\n\r\n    def optimize_crew_size(self, resource_id: str,\r\n                            target_utilization: float = 0.85) -> Dict:\r\n        \"\"\"Recommend optimal crew size for a resource.\"\"\"\r\n        usage = self.calculate_resource_usage()\r\n\r\n        if resource_id not in usage.columns:\r\n            return None\r\n\r\n        daily_usage = usage[resource_id]\r\n        resource = self.resources[resource_id]\r\n\r\n        # Calculate statistics\r\n        peak = daily_usage.max()\r\n        avg = daily_usage.mean()\r\n        working_days = (daily_usage > 0).sum()\r\n\r\n        # Current utilization\r\n        current_util = avg \u002F resource.max_units if resource.max_units > 0 else 0\r\n\r\n        # Optimal size for target utilization\r\n        optimal_size = avg \u002F target_utilization\r\n\r\n        return {\r\n            'resource_id': resource_id,\r\n            'current_max_units': resource.max_units,\r\n            'peak_usage': peak,\r\n            'average_usage': avg,\r\n            'working_days': int(working_days),\r\n            'current_utilization': current_util,\r\n            'recommended_max_units': round(optimal_size, 1),\r\n            'potential_savings': (resource.max_units - optimal_size) * resource.cost_per_unit * working_days\r\n        }\r\n\r\n    def generate_histogram(self, resource_id: str) -> pd.DataFrame:\r\n        \"\"\"Generate resource histogram data.\"\"\"\r\n        usage = self.calculate_resource_usage()\r\n\r\n        if resource_id not in usage.columns:\r\n            return pd.DataFrame()\r\n\r\n        resource = self.resources[resource_id]\r\n\r\n        df = pd.DataFrame({\r\n            'date': usage.index,\r\n            'usage': usage[resource_id].values,\r\n            'capacity': resource.max_units,\r\n            'overallocated': usage[resource_id].values > resource.max_units\r\n        })\r\n\r\n        return df\r\n\r\n    def generate_report(self) -> str:\r\n        \"\"\"Generate resource leveling report.\"\"\"\r\n        lines = [\"# Resource Leveling Report\", \"\"]\r\n        lines.append(f\"**Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M')}\")\r\n        lines.append(f\"**Resources:** {len(self.resources)}\")\r\n        lines.append(f\"**Tasks:** {len(self.tasks)}\")\r\n        lines.append(\"\")\r\n\r\n        # Overallocations\r\n        overallocations = self.identify_overallocations()\r\n        if overallocations:\r\n            lines.append(\"## Overallocations Found\")\r\n            for over in overallocations:\r\n                lines.append(f\"\\n### {over['resource_name']}\")\r\n                lines.append(f\"- **Max Units:** {over['max_units']}\")\r\n                lines.append(f\"- **Peak Usage:** {over['peak_usage']}\")\r\n                lines.append(f\"- **Days Overallocated:** {over['days_overallocated']}\")\r\n                lines.append(f\"- **Worst Day:** {over['worst_day']}\")\r\n        else:\r\n            lines.append(\"## No Overallocations\")\r\n            lines.append(\"All resources are within capacity.\")\r\n\r\n        # Resource utilization\r\n        lines.append(\"\\n## Resource Utilization\")\r\n        for resource_id in self.resources:\r\n            opt = self.optimize_crew_size(resource_id)\r\n            if opt:\r\n                lines.append(f\"\\n### {self.resources[resource_id].name}\")\r\n                lines.append(f\"- **Utilization:** {opt['current_utilization']:.1%}\")\r\n                lines.append(f\"- **Peak:** {opt['peak_usage']:.1f}\")\r\n                lines.append(f\"- **Average:** {opt['average_usage']:.1f}\")\r\n\r\n        return \"\\n\".join(lines)\r\n```\r\n\r\n## Quick Start\r\n\r\n```python\r\nfrom datetime import date\r\n\r\n# Initialize leveler\r\nleveler = ConstructionResourceLeveler()\r\n\r\n# Add resources\r\nleveler.add_resource(Resource(\r\n    id=\"CARP\",\r\n    name=\"Carpenters\",\r\n    resource_type=\"labor\",\r\n    max_units=10,\r\n    cost_per_unit=75,\r\n    unit=\"hours\"\r\n))\r\n\r\n# Add tasks\r\nleveler.add_task(Task(\r\n    id=\"T1\",\r\n    name=\"Frame Level 1\",\r\n    duration=10,\r\n    start_date=date(2026, 3, 1),\r\n    end_date=date(2026, 3, 14),\r\n    predecessors=[],\r\n    total_float=5,\r\n    is_critical=False\r\n))\r\n\r\n# Add assignments\r\nleveler.add_assignment(ResourceAssignment(\r\n    task_id=\"T1\",\r\n    resource_id=\"CARP\",\r\n    units=8,\r\n    start_date=date(2026, 3, 1),\r\n    end_date=date(2026, 3, 14)\r\n))\r\n\r\n# Check overallocations\r\noverallocations = leveler.identify_overallocations()\r\nfor over in overallocations:\r\n    print(f\"{over['resource_name']}: {over['peak_usage']} vs {over['max_units']} max\")\r\n\r\n# Level resources\r\nresult = leveler.level_resources(protect_critical_path=True)\r\nprint(f\"Tasks moved: {result.tasks_moved}\")\r\nprint(f\"End date change: {result.original_end_date} -> {result.leveled_end_date}\")\r\n\r\n# Generate report\r\nprint(leveler.generate_report())\r\n```\r\n\r\n## Dependencies\r\n\r\n```bash\r\npip install pandas numpy\r\n```\r\n",{"slug":5,"description":7,"display_name":31},"Resource Leveler","main","e7e336ac628c3e3bd771aff1aaa469c93778f94a","skills\u002Fdatadrivenconstruction\u002Fresource-leveler",0,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del","2026-08-23 22:39:37",{"source":8,"skillName":5,"commands":40,"prompt":50,"zipAvailable":51},[41,44,47],{"tool":42,"command":43},"npx","npx skills add kbarbel640-del\u002Fskills --skill resource-leveler",{"tool":45,"command":46},"bunx","bunx skills add kbarbel640-del\u002Fskills --skill resource-leveler",{"tool":48,"command":49},"pnpm","pnpm dlx skills add kbarbel640-del\u002Fskills --skill resource-leveler","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Fresource-leveler\u002FSKILL.md",true,[53],{"path":54,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":57,"sourceHtmlUrl":58},"_meta.json","REFERENCE","参考文档",300,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Fresource-leveler\u002F_meta.json",[60,86,110,128,133,153],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":26},"01M6G8J55967D6281ACMKAKTEQ","crowd-prompting","A marketplace where AI agents improve prompts, system instructions, tool descriptions, and other text-based content with domain expertise from real-world operations — and earn tokens for valuable contributions.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzzadrian\u002Fcrowd-prompting\u002FSKILL.md",[],[67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85],"crowd prompting","prompting","api","with","tokens","domain","world","prompts","operations","instructions","text","tool","system","improve","productivity","marketplace","https","content","ai agents",{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":26},"01M6G8J0PKPAYVET6BWE8W4C26","dilemm-ai","Compete in DilemmAI, the prisoner's dilemma AI arena at dilemm.ai. Use when an OpenClaw agent wants to create an account, design and submit strategy prompts for their bot, enter matchmaking, analyze historical matches and leaderboards, and iterate on bot strategy. Requires headless browser automation (no API available yet).","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzyori\u002Fdilemm-ai\u002FSKILL.md",[],[93,69,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,74,109],"dilemm ai","arena","analyze","browser","openclaw agent","create","automation","browser automation","bot","openclaw","design","strategy","headless","compete","submit","matchmaking","use",{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":26},"01M6G8HWAF3K9SW7NP3Z83CPJ6","arxiv-paper-reviews","Interact with arXiv Crawler API to fetch papers, read reviews, and submit comments. Use when working with arXiv papers, fetching paper lists by date\u002Fcategory\u002Finterest, viewing paper details with comments, or submitting paper reviews via API at http:\u002F\u002F150.158.152.82:8000.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Fweak-accept\u002FSKILL.md",[],[117,118,119,120,121,122,123,70,124,107,109,125,69,126,127],"arxiv paper reviews","reviews","arxiv","paper","crawler","papers","comments","fetch","read","http","via",{"skillNo":129,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":130,"categories":131,"keywords":132,"publishedAt":26},"01M6G8HQJ7N7WMY6YV7D7SSJ16","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Farxiv-paper-reviews\u002FSKILL.md",[],[120,119,118,117,127,122,123,70,121,107,109,124,125,69,126],{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":139,"publishedAt":26},"01M6G8HM95Y64JNVFC2HN4E2BG","git-summary","Get a quick summary of the current Git repository including status, recent commits, branches, and contributors.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzweack\u002Fgit-summary\u002FSKILL.md",[],[140,141,142,143,144,145,146,147,148,149,150,151,152],"git","summary","git summary","commits","repository","win32","status","linux","contributors","true","quick","get","branches",{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":159,"publishedAt":26},"01M6G8HGEGF05CNEJCGVYFSC4R","agent-constitution","Interact with AgentConstitution governance contracts on Base Sepolia. Check compliance, read rules, log actions, query governance state.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fztsalexey\u002Fagent-constitution\u002FSKILL.md",[],[160,161,162,163,70,164,165,32,166,125,167,168,169,170,171,83,172,173,174],"agent constitution","constitution","contracts","tree","query","base","log","check","Rules","projects","compliance","actions","state","governance","github"]