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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
import json
import os
import uuid
import tempfile
import threading
from datetime import datetime, timezone
from flask import Blueprint, request, jsonify

bp = Blueprint("experiments", __name__, url_prefix="/api/experiments")

DASHBOARD_REPO = "reasoning-degeneration-dev/RESEARCH_DASHBOARD"
LOCAL_DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data")

_cache: dict[str, list[dict]] = {}
_cache_loaded: set[str] = set()
_lock = threading.Lock()

FILES = ["experiments", "runs", "sub_experiments", "experiment_notes"]


def _ensure_local_dir():
    os.makedirs(LOCAL_DATA_DIR, exist_ok=True)


def _local_path(name: str) -> str:
    _ensure_local_dir()
    return os.path.join(LOCAL_DATA_DIR, f"{name}.json")


def _download_file(name: str) -> list[dict]:
    try:
        from huggingface_hub import hf_hub_download
        path = hf_hub_download(
            DASHBOARD_REPO,
            f"{name}.json",
            repo_type="dataset",
        )
        with open(path) as f:
            data = json.load(f)
        with open(_local_path(name), "w") as f:
            json.dump(data, f, indent=2)
        return data
    except Exception:
        local = _local_path(name)
        if os.path.exists(local):
            with open(local) as f:
                return json.load(f)
        return []


def _upload_file(name: str, data: list[dict]):
    with open(_local_path(name), "w") as f:
        json.dump(data, f, indent=2)

    def _do_upload():
        try:
            from huggingface_hub import HfApi
            api = HfApi()
            try:
                api.create_repo(DASHBOARD_REPO, repo_type="dataset", exist_ok=True)
            except Exception:
                pass
            with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f:
                json.dump(data, f, indent=2)
                tmp = f.name
            api.upload_file(
                path_or_fileobj=tmp,
                path_in_repo=f"{name}.json",
                repo_id=DASHBOARD_REPO,
                repo_type="dataset",
            )
            os.unlink(tmp)
        except Exception as e:
            print(f"[experiments] HF upload failed for {name}: {e}")

    threading.Thread(target=_do_upload, daemon=True).start()


def _get(name: str) -> list[dict]:
    with _lock:
        if name not in _cache_loaded:
            _cache[name] = _download_file(name)
            _cache_loaded.add(name)
        return list(_cache.get(name, []))


def _set(name: str, data: list[dict]):
    with _lock:
        _cache[name] = data
        _cache_loaded.add(name)
    _upload_file(name, data)


def _now() -> str:
    return datetime.now(timezone.utc).isoformat()


# --- Experiments CRUD ---

@bp.route("/", methods=["GET"])
def list_experiments():
    experiments = _get("experiments")
    runs = _get("runs")
    subs = _get("sub_experiments")
    notes = _get("experiment_notes")

    # Enrich with counts
    result = []
    for exp in experiments:
        exp_runs = [r for r in runs if r.get("experiment_id") == exp["id"]]
        exp_subs = [s for s in subs if s.get("experiment_id") == exp["id"]]
        exp_notes = [n for n in notes if n.get("experiment_id") == exp["id"]]
        result.append({
            **exp,
            "run_count": len(exp_runs),
            "sub_count": len(exp_subs),
            "note_count": len(exp_notes),
        })
    return jsonify(result)


@bp.route("/", methods=["POST"])
def create_experiment():
    data = request.get_json()
    name = data.get("name", "").strip()
    if not name:
        return jsonify({"error": "name is required"}), 400

    exp_id = data.get("id", name.lower().replace(" ", "_"))

    experiments = _get("experiments")
    if any(e["id"] == exp_id for e in experiments):
        return jsonify({"error": f"Experiment '{exp_id}' already exists"}), 409

    experiment = {
        "id": exp_id,
        "name": name,
        "research_project": data.get("research_project", ""),
        "hypothesis": data.get("hypothesis", {
            "statement": "",
            "type": "exploration",
            "status": "pending",
            "success_criteria": "",
        }),
        "stage": data.get("stage", "idea"),
        "completeness": data.get("completeness", 0),
        "models": data.get("models", []),
        "tasks": data.get("tasks", []),
        "tags": data.get("tags", []),
        "hf_repos": data.get("hf_repos", []),
        "wandb_url": data.get("wandb_url", ""),
        "notes": data.get("notes", ""),
        "created": _now(),
        "updated": _now(),
    }

    experiments.append(experiment)
    _set("experiments", experiments)
    return jsonify(experiment), 201


@bp.route("/<exp_id>", methods=["GET"])
def get_experiment(exp_id):
    experiments = _get("experiments")
    exp = next((e for e in experiments if e["id"] == exp_id), None)
    if not exp:
        return jsonify({"error": "not found"}), 404

    runs = [r for r in _get("runs") if r.get("experiment_id") == exp_id]
    subs = [s for s in _get("sub_experiments") if s.get("experiment_id") == exp_id]
    notes = [n for n in _get("experiment_notes") if n.get("experiment_id") == exp_id]

    return jsonify({**exp, "runs": runs, "sub_experiments": subs, "experiment_notes": notes})


@bp.route("/<exp_id>", methods=["PUT"])
def update_experiment(exp_id):
    data = request.get_json()
    experiments = _get("experiments")

    for exp in experiments:
        if exp["id"] == exp_id:
            for key in ["name", "research_project", "hypothesis", "stage",
                        "completeness", "models", "tasks", "tags", "hf_repos",
                        "wandb_url", "notes"]:
                if key in data:
                    exp[key] = data[key]
            exp["updated"] = _now()
            _set("experiments", experiments)
            return jsonify(exp)

    return jsonify({"error": "not found"}), 404


@bp.route("/<exp_id>", methods=["DELETE"])
def delete_experiment(exp_id):
    experiments = _get("experiments")
    experiments = [e for e in experiments if e["id"] != exp_id]
    _set("experiments", experiments)

    # Also delete associated runs, subs, and notes
    runs = [r for r in _get("runs") if r.get("experiment_id") != exp_id]
    _set("runs", runs)
    subs = [s for s in _get("sub_experiments") if s.get("experiment_id") != exp_id]
    _set("sub_experiments", subs)
    notes = [n for n in _get("experiment_notes") if n.get("experiment_id") != exp_id]
    _set("experiment_notes", notes)

    return jsonify({"status": "ok"})


# --- Run records ---

@bp.route("/<exp_id>/runs", methods=["POST"])
def create_run(exp_id):
    experiments = _get("experiments")
    if not any(e["id"] == exp_id for e in experiments):
        return jsonify({"error": "experiment not found"}), 404

    data = request.get_json()
    run = {
        "id": data.get("id", f"run_{uuid.uuid4().hex[:8]}"),
        "experiment_id": exp_id,
        "condition": data.get("condition", ""),
        "model": data.get("model", ""),
        "cluster": data.get("cluster", ""),
        "status": data.get("status", "completed"),
        "hf_dataset": data.get("hf_dataset", ""),
        "metrics": data.get("metrics", {}),
        "timestamp": data.get("timestamp", _now()),
        "notes": data.get("notes", ""),
    }

    runs = _get("runs")
    runs.append(run)
    _set("runs", runs)

    # Touch experiment updated timestamp
    for exp in experiments:
        if exp["id"] == exp_id:
            exp["updated"] = _now()
    _set("experiments", experiments)

    return jsonify(run), 201


@bp.route("/<exp_id>/runs/<run_id>", methods=["PUT"])
def update_run(exp_id, run_id):
    data = request.get_json()
    runs = _get("runs")

    for run in runs:
        if run["id"] == run_id and run["experiment_id"] == exp_id:
            for key in ["condition", "model", "cluster", "status",
                        "hf_dataset", "metrics", "notes"]:
                if key in data:
                    run[key] = data[key]
            _set("runs", runs)
            return jsonify(run)

    return jsonify({"error": "not found"}), 404


@bp.route("/<exp_id>/runs/<run_id>", methods=["DELETE"])
def delete_run(exp_id, run_id):
    runs = _get("runs")
    runs = [r for r in runs if not (r["id"] == run_id and r["experiment_id"] == exp_id)]
    _set("runs", runs)
    return jsonify({"status": "ok"})


# --- Sub-experiments ---

@bp.route("/<exp_id>/subs", methods=["POST"])
def create_sub(exp_id):
    experiments = _get("experiments")
    if not any(e["id"] == exp_id for e in experiments):
        return jsonify({"error": "experiment not found"}), 404

    data = request.get_json()
    name = data.get("name", "").strip()
    if not name:
        return jsonify({"error": "name is required"}), 400

    sub_id = data.get("id", f"{exp_id}__{name.lower().replace(' ', '_')}")

    sub = {
        "id": sub_id,
        "experiment_id": exp_id,
        "name": name,
        "hypothesis": data.get("hypothesis", ""),
        "status": data.get("status", "active"),
        "content_md": data.get("content_md", ""),
        "hf_repos": data.get("hf_repos", []),
        "created": _now(),
        "updated": _now(),
    }

    subs = _get("sub_experiments")
    subs.append(sub)
    _set("sub_experiments", subs)

    # Touch experiment updated timestamp
    for exp in experiments:
        if exp["id"] == exp_id:
            exp["updated"] = _now()
    _set("experiments", experiments)

    return jsonify(sub), 201


@bp.route("/<exp_id>/subs/<sub_id>", methods=["PUT"])
def update_sub(exp_id, sub_id):
    data = request.get_json()
    subs = _get("sub_experiments")

    for sub in subs:
        if sub["id"] == sub_id and sub["experiment_id"] == exp_id:
            for key in ["name", "hypothesis", "status", "content_md", "hf_repos"]:
                if key in data:
                    sub[key] = data[key]
            sub["updated"] = _now()
            _set("sub_experiments", subs)
            return jsonify(sub)

    return jsonify({"error": "not found"}), 404


@bp.route("/<exp_id>/subs/<sub_id>", methods=["DELETE"])
def delete_sub(exp_id, sub_id):
    subs = _get("sub_experiments")
    subs = [s for s in subs if not (s["id"] == sub_id and s["experiment_id"] == exp_id)]
    _set("sub_experiments", subs)
    return jsonify({"status": "ok"})


# --- Experiment Notes ---

@bp.route("/<exp_id>/notes", methods=["POST"])
def create_note(exp_id):
    experiments = _get("experiments")
    if not any(e["id"] == exp_id for e in experiments):
        return jsonify({"error": "experiment not found"}), 404

    data = request.get_json()
    title = data.get("title", "").strip()
    if not title:
        return jsonify({"error": "title is required"}), 400

    note_id = data.get("id", f"{exp_id}__note_{uuid.uuid4().hex[:8]}")

    note = {
        "id": note_id,
        "experiment_id": exp_id,
        "title": title,
        "filename": data.get("filename", ""),
        "content_md": data.get("content_md", ""),
        "created": _now(),
        "updated": _now(),
    }

    notes = _get("experiment_notes")
    notes.append(note)
    _set("experiment_notes", notes)
    return jsonify(note), 201


@bp.route("/<exp_id>/notes/<note_id>", methods=["GET"])
def get_note(exp_id, note_id):
    notes = _get("experiment_notes")
    note = next((n for n in notes if n["id"] == note_id and n["experiment_id"] == exp_id), None)
    if not note:
        return jsonify({"error": "not found"}), 404
    return jsonify(note)


@bp.route("/<exp_id>/notes/<note_id>", methods=["PUT"])
def update_note(exp_id, note_id):
    data = request.get_json()
    notes = _get("experiment_notes")

    for note in notes:
        if note["id"] == note_id and note["experiment_id"] == exp_id:
            for key in ["title", "content_md"]:
                if key in data:
                    note[key] = data[key]
            note["updated"] = _now()
            _set("experiment_notes", notes)
            return jsonify(note)

    return jsonify({"error": "not found"}), 404


@bp.route("/<exp_id>/notes/<note_id>", methods=["DELETE"])
def delete_note(exp_id, note_id):
    notes = _get("experiment_notes")
    notes = [n for n in notes if not (n["id"] == note_id and n["experiment_id"] == exp_id)]
    _set("experiment_notes", notes)
    return jsonify({"status": "ok"})


# --- Sync & Import ---

@bp.route("/sync", methods=["POST"])
def sync():
    with _lock:
        _cache.clear()
        _cache_loaded.clear()
    for name in FILES:
        _get(name)
    return jsonify({"status": "ok"})


@bp.route("/import", methods=["POST"])
def import_experiments():
    """Bulk import from experiment.yaml format (as produced by exp-runner)."""
    data = request.get_json()
    items = data if isinstance(data, list) else [data]
    imported = []

    experiments = _get("experiments")
    runs = _get("runs")
    subs = _get("sub_experiments")
    existing_ids = {e["id"] for e in experiments}

    for item in items:
        exp_id = item.get("name", "").lower().replace(" ", "_").replace("-", "_")
        if not exp_id:
            continue

        hypothesis = item.get("hypothesis", {})
        models = item.get("models", [])
        model_names = [m.get("id", "") if isinstance(m, dict) else str(m) for m in models]

        if exp_id not in existing_ids:
            experiment = {
                "id": exp_id,
                "name": item.get("name", exp_id),
                "research_project": item.get("research_project", ""),
                "hypothesis": {
                    "statement": hypothesis.get("statement", "") if isinstance(hypothesis, dict) else str(hypothesis),
                    "type": hypothesis.get("type", "exploration") if isinstance(hypothesis, dict) else "exploration",
                    "status": hypothesis.get("status", "pending") if isinstance(hypothesis, dict) else "pending",
                    "success_criteria": hypothesis.get("success_criteria", "") if isinstance(hypothesis, dict) else "",
                },
                "stage": "active",
                "completeness": 0,
                "models": model_names,
                "tasks": [],
                "tags": item.get("observability", {}).get("tags", []) if isinstance(item.get("observability"), dict) else [],
                "hf_repos": [],
                "wandb_url": "",
                "notes": "",
                "created": item.get("created", _now()),
                "updated": _now(),
            }
            experiments.append(experiment)
            existing_ids.add(exp_id)

        # Import runs
        for run_data in item.get("runs", []):
            run_id = run_data.get("run_id", f"run_{uuid.uuid4().hex[:8]}")
            if any(r["id"] == run_id and r["experiment_id"] == exp_id for r in runs):
                continue
            run = {
                "id": run_id,
                "experiment_id": exp_id,
                "condition": run_data.get("condition", ""),
                "model": run_data.get("model", ""),
                "cluster": run_data.get("cluster", ""),
                "status": run_data.get("status", "completed"),
                "hf_dataset": run_data.get("hf_dataset", ""),
                "metrics": run_data.get("metrics", {}),
                "timestamp": run_data.get("timestamp", _now()),
                "notes": run_data.get("notes", ""),
            }
            runs.append(run)

            # Add HF repo to experiment if present
            if run.get("hf_dataset"):
                for exp in experiments:
                    if exp["id"] == exp_id:
                        existing_repos = {r["repo"] for r in exp.get("hf_repos", [])}
                        if run["hf_dataset"] not in existing_repos:
                            exp.setdefault("hf_repos", []).append({
                                "repo": run["hf_dataset"],
                                "description": f"{run['condition']} - {run['model']}",
                                "date": run["timestamp"][:10] if run["timestamp"] else "",
                            })

        imported.append(exp_id)

    _set("experiments", experiments)
    _set("runs", runs)
    _set("sub_experiments", subs)

    return jsonify({"imported": imported, "count": len(imported)})