File size: 5,876 Bytes
c5997d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# utils/helpers.py

import json
import os
from datetime import datetime, timedelta
from typing import Any
from config import OLD_FILE_THRESHOLD_YEARS, RECENT_DAYS_THRESHOLD, FILE_CATEGORIES


def load_json(filepath: str) -> dict:
    """Load and return a JSON file as a dict."""
    with open(filepath, "r") as f:
        return json.load(f)


def save_json(data: dict, filepath: str):
    """Save a dict to a JSON file (creates parent dirs if needed)."""
    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    with open(filepath, "w") as f:
        json.dump(data, f, indent=2)


def parse_date(date_str: str) -> datetime:
    """Parse an ISO-format date string to a datetime object."""
    try:
        return datetime.fromisoformat(date_str)
    except (ValueError, TypeError):
        return datetime.min


def is_old_file(last_accessed_str: str, threshold_years: int = OLD_FILE_THRESHOLD_YEARS) -> bool:
    """Return True if the file hasn't been accessed within the threshold."""
    last_accessed = parse_date(last_accessed_str)
    cutoff = datetime.now() - timedelta(days=365 * threshold_years)
    return last_accessed < cutoff


def is_recent_file(last_accessed_str: str, threshold_days: int = RECENT_DAYS_THRESHOLD) -> bool:
    """Return True if the file was accessed within the recent threshold."""
    last_accessed = parse_date(last_accessed_str)
    cutoff = datetime.now() - timedelta(days=threshold_days)
    return last_accessed >= cutoff


def get_category_for_extension(extension: str) -> str:
    """Return the folder category for a given file extension."""
    ext = extension.lower()
    for category, extensions in FILE_CATEGORIES.items():
        if ext in extensions:
            return category
    return "Misc"


def format_size(size_mb: float) -> str:
    """Human-readable file size."""
    if size_mb >= 1024:
        return f"{size_mb / 1024:.2f} GB"
    if size_mb >= 1:
        return f"{size_mb:.2f} MB"
    return f"{size_mb * 1024:.2f} KB"


def flatten_file_list(root: dict, path: str = "") -> list:
    """
    Recursively flatten the file system tree into a list of file dicts.
    Each entry: {name, path, type, extension, size_mb, created_date, last_accessed}
    """
    results = []
    for name, meta in root.items():
        current_path = f"{path}/{name}" if path else name
        if not isinstance(meta, dict):
            continue
        if meta.get("type") == "file":
            results.append({
                "name": name,
                "path": current_path,
                **meta,
            })
        elif meta.get("type") == "folder":
            results.extend(flatten_file_list(meta.get("contents", {}), current_path))
    return results


def find_duplicates(file_list: list) -> list:
    """
    Find duplicate files: same base name (ignoring trailing numbers like (1), (2))
    and same size.
    Returns a list of lists, where each sub-list is a group of duplicate paths.
    """
    import re
    groups: dict[tuple, list] = {}
    for f in file_list:
        if f.get("type") != "file":
            continue
        name = f["name"]
        size = f.get("size_mb", 0)
        # Strip trailing duplicate markers: "file(1).pdf" → "file.pdf"
        base = re.sub(r"\(\d+\)(\.[^.]+)$", r"\1", name)
        key = (base.lower(), round(size, 3))
        groups.setdefault(key, []).append(f)

    return [group for group in groups.values() if len(group) > 1]


def total_size_mb(file_list: list) -> float:
    """Return the total size in MB of a list of file dicts."""
    return sum(f.get("size_mb", 0) for f in file_list)


def summarize_filesystem(root: dict) -> dict:
    """Return a high-level summary of the filesystem."""
    all_files = flatten_file_list(root)
    total_files = len(all_files)
    total_mb = total_size_mb(all_files)
    by_category: dict[str, float] = {}
    for f in all_files:
        cat = get_category_for_extension(f.get("extension", ""))
        by_category[cat] = by_category.get(cat, 0) + f.get("size_mb", 0)

    return {
        "total_files": total_files,
        "total_size_mb": round(total_mb, 2),
        "total_size_human": format_size(total_mb),
        "by_category": {k: round(v, 2) for k, v in by_category.items()},
    }


def build_prompt_context(observation: dict) -> str:
    """Convert the observation dict into a compact string for LLM prompts."""
    root = observation.get("root", {})
    summary = summarize_filesystem(root)
    all_files = flatten_file_list(root)

    lines = [
        f"Total files: {summary['total_files']}",
        f"Total size: {summary['total_size_human']}",
        "Files:",
    ]
    for f in all_files:
        accessed = f.get("last_accessed", "unknown")
        size = format_size(f.get("size_mb", 0))
        lines.append(f"  - {f['path']} | {size} | last accessed: {accessed}")

    return "\n".join(lines)

# ------------------------------------------------------------------
# OpenEnv helpers
# ------------------------------------------------------------------

from config import INITIAL_STATE_FILE
import os


def load_initial_state():
    """
    Load the initial filesystem state from JSON.
    """

    if not os.path.exists(INITIAL_STATE_FILE):
        raise FileNotFoundError(
            f"Initial state file not found: {INITIAL_STATE_FILE}"
        )

    with open(INITIAL_STATE_FILE, "r") as f:
        return json.load(f)


def load_task_criteria(task_name: str):
    """
    Load task criteria file based on task name.
    Example:
        data/criteria_easy.json
        data/criteria_medium.json
        data/criteria_hard.json
    """

    filename = f"criteria_{task_name}.json"

    path = os.path.join(
        "data",
        filename
    )

    if not os.path.exists(path):

        # fallback empty criteria
        return {}

    with open(path, "r") as f:
        return json.load(f)