File size: 10,919 Bytes
c5997d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2cba45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5997d8
c2cba45
c5997d8
c2cba45
c5997d8
c2cba45
c5997d8
c2cba45
c5997d8
c2cba45
 
 
c5997d8
c2cba45
 
c5997d8
c2cba45
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# grader/grader.py

import json
from datetime import datetime, timedelta
from utils.helpers import flatten_file_list, total_size_mb, format_size
from config import (
    CORRECT_MOVE_SCORE, INCORRECT_PENALTY,
    TASK_EASY, TASK_MEDIUM, TASK_HARD,
    STORAGE_LIMIT_MB, RECENT_DAYS_THRESHOLD, OLD_FILE_THRESHOLD_YEARS,
)


class Grader:
    """Evaluate the agent's performance on a given task."""

    def __init__(self, task_type: str, initial_state: dict, criteria: dict):
        self.task_type = task_type
        self.initial_state = initial_state
        self.criteria = criteria

    # ------------------------------------------------------------------
    # Public interface
    # ------------------------------------------------------------------

    def grade(self, final_state: dict) -> dict:
        """Grade the final filesystem state and return a detailed report."""
        if self.task_type == TASK_EASY:
            return self._grade_easy(final_state)
        elif self.task_type == TASK_MEDIUM:
            return self._grade_medium(final_state)
        elif self.task_type == TASK_HARD:
            return self._grade_hard(final_state)
        else:
            raise ValueError(f"Unknown task type: {self.task_type}")

    # ------------------------------------------------------------------
    # Easy grader
    # ------------------------------------------------------------------

    def _grade_easy(self, final_state: dict) -> dict:
        root = final_state.get("root", {})
        all_files = flatten_file_list(root)
        file_locations: dict[str, str] = {f["name"]: f["path"] for f in all_files}

        score = 0.0
        max_score = 0.0
        details = []

        # Check PDFs in Documents
        for fname in self.criteria["files_to_move_to_Documents"]:
            max_score += CORRECT_MOVE_SCORE
            path = file_locations.get(fname, "")
            if "Documents" in path:
                score += CORRECT_MOVE_SCORE
                details.append({"file": fname, "status": "βœ… Correctly in Documents", "points": CORRECT_MOVE_SCORE})
            else:
                details.append({"file": fname, "status": f"❌ Not in Documents (found at: {path or 'missing'})", "points": 0})

        # Check JPGs in Images
        for fname in self.criteria["files_to_move_to_Images"]:
            max_score += CORRECT_MOVE_SCORE
            path = file_locations.get(fname, "")
            if "Images" in path:
                score += CORRECT_MOVE_SCORE
                details.append({"file": fname, "status": "βœ… Correctly in Images", "points": CORRECT_MOVE_SCORE})
            else:
                details.append({"file": fname, "status": f"❌ Not in Images (found at: {path or 'missing'})", "points": 0})

        # Check non-target files are untouched
        collateral_damage = []
        for fname in self.criteria["files_to_leave_untouched"]:
            if fname not in file_locations:
                collateral_damage.append(fname)
                score += INCORRECT_PENALTY
                details.append({"file": fname, "status": "❌ COLLATERAL DAMAGE – file was deleted!", "points": INCORRECT_PENALTY})

        percentage = round((score / max_score) * 100, 1) if max_score > 0 else 0.0

        return {
            "task": TASK_EASY,
            "score": round(score, 2),
            "max_score": round(max_score, 2),
            "percentage": percentage,
            "collateral_damage": collateral_damage,
            "details": details,
            "passed": percentage >= 90.0,
        }

    # ------------------------------------------------------------------
    # Medium grader
    # ------------------------------------------------------------------

    def _grade_medium(self, final_state: dict) -> dict:
        root = final_state.get("root", {})
        all_files = flatten_file_list(root)
        remaining_names = {f["name"] for f in all_files}

        to_delete = set(self.criteria["files_to_delete"])
        to_preserve = set(self.criteria["files_to_preserve"])

        correctly_deleted = to_delete - remaining_names
        missed_duplicates = to_delete & remaining_names
        collateral_damage = to_preserve - remaining_names

        score = (len(correctly_deleted) * CORRECT_MOVE_SCORE
                 - len(collateral_damage) * abs(INCORRECT_PENALTY))
        max_score = len(to_delete) * CORRECT_MOVE_SCORE

        percentage = round((max(score, 0) / max_score) * 100, 1) if max_score > 0 else 0.0

        return {
            "task": TASK_MEDIUM,
            "score": round(score, 2),
            "max_score": round(max_score, 2),
            "percentage": percentage,
            "correctly_deleted": sorted(correctly_deleted),
            "missed_duplicates": sorted(missed_duplicates),
            "collateral_damage": sorted(collateral_damage),
            "passed": percentage >= 90.0 and len(collateral_damage) == 0,
        }

    # ------------------------------------------------------------------
    # Hard grader
    # ------------------------------------------------------------------

    def _grade_hard(self, final_state: dict) -> dict:
        initial_root = self.initial_state.get("root", {})
        final_root = final_state.get("root", {})

        initial_files = flatten_file_list(initial_root)
        final_files = flatten_file_list(final_root)

        initial_total_mb = total_size_mb(initial_files)
        final_total_mb = total_size_mb(final_files)
        freed_mb = initial_total_mb - final_total_mb

        goal_mb = self.criteria.get("storage_goal_mb", STORAGE_LIMIT_MB)
        goal_met = freed_mb >= goal_mb

        # Check for protected folder violations
        protected = self.criteria.get("folders_to_protect", [])
        violations = []
        for folder_name in protected:
            # Protected folder should still exist with same files
            initial_folder = initial_root.get(folder_name, {})
            final_folder = final_root.get(folder_name, {})
            if not final_folder:
                violations.append(f"Protected folder '{folder_name}' was deleted or moved!")
                continue
            initial_contents = set(initial_folder.get("contents", {}).keys())
            final_contents = set(final_folder.get("contents", {}).keys())
            missing = initial_contents - final_contents
            if missing:
                violations.append(f"Files removed from protected '{folder_name}': {missing}")

        # Check for recently accessed file violations
        cutoff = datetime.now() - timedelta(days=RECENT_DAYS_THRESHOLD)
        initial_names = {f["name"]: f for f in initial_files}
        final_names = {f["name"] for f in final_files}
        recent_deleted = []
        for fname, fmeta in initial_names.items():
            accessed_str = fmeta.get("last_accessed", "")
            try:
                accessed = datetime.fromisoformat(accessed_str)
            except (ValueError, TypeError):
                continue
            if accessed >= cutoff and fname not in final_names:
                recent_deleted.append(fname)

        # Score
        score = 0.0
        max_score = 3.0
        if goal_met:
            score += 1.0
        if not violations:
            score += 1.0
        if not recent_deleted:
            score += 1.0

        percentage = round((score / max_score) * 100, 1)

        return {
            "task": TASK_HARD,
            "score": round(score, 2),
            "max_score": max_score,
            "percentage": percentage,
            "freed_mb": round(freed_mb, 2),
            "freed_human": format_size(freed_mb),
            "goal_mb": goal_mb,
            "goal_met": goal_met,
            "protected_folder_violations": violations,
            "recent_files_deleted": recent_deleted,
            "passed": goal_met and not violations and not recent_deleted,
        }


# ------------------------------------------------------------------
# Convenience function
# ------------------------------------------------------------------

def grade_from_files(task_type: str, initial_path: str, final_path: str, criteria: dict) -> dict:
    """Load state from JSON files and grade."""
    with open(initial_path) as f:
        initial_state = json.load(f)
    with open(final_path) as f:
        final_state = json.load(f)
    grader = Grader(task_type, initial_state, criteria)
    return grader.grade(final_state)


def print_report(report: dict):
    """Print a human-readable grade report."""
    print("\n" + "=" * 60)
    print(f"  GRADE REPORT  –  {report['task'].upper()} TASK")
    print("=" * 60)
    print(f"  Score    : {report['score']} / {report['max_score']}")
    print(f"  Grade    : {report['percentage']}%")
    print(f"  Passed   : {'βœ… YES' if report['passed'] else '❌ NO'}")

    if report["task"] == TASK_EASY:
        dmg = report.get("collateral_damage", [])
        print(f"  Collateral damage: {len(dmg)} file(s)")
        for d in report.get("details", []):
            print(f"    {d['status']}  [{d['file']}]")

    elif report["task"] == TASK_MEDIUM:
        print(f"  Correctly deleted : {len(report.get('correctly_deleted', []))}")
        print(f"  Missed duplicates : {len(report.get('missed_duplicates', []))}")
        print(f"  Collateral damage : {len(report.get('collateral_damage', []))}")

    elif report["task"] == TASK_HARD:
        goal = "βœ…" if report["goal_met"] else "❌"
        print(f"  Storage freed : {report['freed_human']}  {goal}")
        print(f"  Goal          : {format_size(report['goal_mb'])}")
        if report["protected_folder_violations"]:
            for v in report["protected_folder_violations"]:
                print(f"  ⚠️  {v}")
        if report["recent_files_deleted"]:
            print(f"  ⚠️  Recent files deleted: {report['recent_files_deleted']}")

    print("=" * 60 + "\n")

def grade_state(fs, task_name):

    files = fs.list_files()

    total = len(files)

    if total == 0:
        return 0.5

    progress = 0

    # EASY β€” files moved to Documents
    if task_name == "easy":

        for f in files:

            path = f.get("path", "")

            if "Documents" in path:

                progress += 1

    # MEDIUM β€” duplicates removed
    elif task_name == "medium":

        names = set()

        for f in files:

            names.add(f.get("name"))

        progress = len(names)

    # HARD β€” storage reduction
    elif task_name == "hard":

        initial_files = fs.initial_state.get("root", {})

        initial_count = len(initial_files)

        current_count = total

        progress = max(0, initial_count - current_count)

    else:

        progress = total // 2

    score = progress / max(total, 1)

    # Keep strictly between 0 and 1
    if score <= 0:
        score = 0.05

    if score >= 1:
        score = 0.95

    return round(score, 2)