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d
 
 
 
5f229e4
 
5c3badd
 
 
 
 
 
 
 
 
5f229e4
 
 
 
 
 
 
5c3badd
 
 
 
 
 
 
 
 
 
 
5f229e4
b84a979
5f229e4
 
 
 
 
 
b84a979
 
 
 
 
 
 
5f229e4
b84a979
5f229e4
 
 
 
 
 
b84a979
 
 
 
 
 
 
 
 
 
5c3badd
 
 
 
 
 
 
 
 
 
386ee13
5c3badd
 
 
 
 
 
5f229e4
5c3badd
 
 
 
 
 
 
5f229e4
5c3badd
 
 
 
386ee13
5c3badd
5f229e4
5c3badd
 
 
 
 
5f229e4
5c3badd
 
5f229e4
5c3badd
 
5f229e4
 
 
5c3badd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
#!/usr/bin/env python3
"""Background task manager for the physics solver."""

import os
import sys
import json
import time
import shutil
import subprocess
import threading
import urllib.request
from datetime import datetime, timezone

# Solver source location
SOLVER_SRC = "/app/solver"
WORKSPACE_BASE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "workspaces")
# Files that come from the repo — excluded from downloads
SOLVER_SOURCE_FILES = {"run.py", "spawn.py", "outline.md"}
DEFAULT_SOLVER_URL = os.environ.get(
    "SOLVER_REPO_URL",
    "https://github.com/Usami-Mira/CC_Integrater/raw/refs/heads/main/",
)

tasks = {}
tasks_lock = threading.Lock()


def _log(task_id, msg):
    """Append a line to the task's log file AND print to stdout."""
    task = tasks.get(task_id)
    log_path = None
    if task:
        log_path = os.path.join(task["workspace"], "solver.log")
    if log_path:
        try:
            with open(log_path, "a", encoding="utf-8") as f:
                f.write(f"[{_now()}] {msg}\n")
        except Exception:
            pass
    print(f"[{task_id}] {msg}", flush=True)


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


def fetch_solver_files(repo_url):
    """Download solver files from GitHub raw URL into /app/solver/."""
    os.makedirs(SOLVER_SRC, exist_ok=True)
    for name in ("run.py", "spawn.py", "outline.md", "config.json"):
        p = os.path.join(SOLVER_SRC, name)
        if os.path.exists(p):
            os.remove(p)

    print(f"[INIT] Fetching solver files from: {repo_url}", flush=True)
    files = ["run.py", "spawn.py", "outline.md", "config.json"]
    downloaded = []
    errors = []
    for name in files:
        url = f"{repo_url.rstrip('/')}/{name}"
        try:
            with urllib.request.urlopen(url, timeout=30) as resp:
                data = resp.read()
                with open(os.path.join(SOLVER_SRC, name), "wb") as f:
                    f.write(data)
                downloaded.append(name)
                print(f"[INIT] Downloaded {name}", flush=True)
        except Exception as e:
            errors.append(f"{name}: {e}")
            print(f"[INIT] Failed to download {name}: {e}", flush=True)

    if not downloaded:
        print(f"[INIT] CRITICAL: No solver files downloaded. Errors: {errors}", flush=True)
        return False
    if errors:
        print(f"[INIT] Partial download. Missing: {errors}", flush=True)
    return True


def active_count():
    """Caller must hold tasks_lock."""
    return sum(1 for t in tasks.values() if t["status"] in ("pending", "running"))


def submit_task(problem_text, name=None, config_override=None, secret_key=None):
    """Create a new task, return task_id."""
    print("[SUBMIT] submit_task() called", flush=True)
    try:
        task_id = f"task-{int(time.time()*1000)}"
        workspace = os.path.join(WORKSPACE_BASE, task_id)
        print(f"[SUBMIT] Creating workspace: {workspace}", flush=True)
        os.makedirs(workspace, exist_ok=True)

        # Write problem
        with open(os.path.join(workspace, "problem.md"), "w", encoding="utf-8") as f:
            f.write(problem_text)
        print(f"[SUBMIT] Wrote problem.md", flush=True)

        # Copy solver source into workspace
        copied = []
        for fname in ("run.py", "spawn.py", "outline.md", "config.json"):
            src = os.path.join(SOLVER_SRC, fname)
            exists = os.path.exists(src)
            print(f"[SUBMIT]   {fname}: exists={exists} at {src}", flush=True)
            if exists:
                shutil.copy2(src, os.path.join(workspace, fname))
                copied.append(fname)
        print(f"[SUBMIT] Copied: {copied}", flush=True)

        # Apply config override if provided
        if config_override:
            config_path = os.path.join(workspace, "config.json")
            if os.path.exists(config_path):
                with open(config_path, "r", encoding="utf-8") as f:
                    current = json.load(f)
                current.update(config_override)
                with open(config_path, "w", encoding="utf-8") as f:
                    json.dump(current, f, indent=2, ensure_ascii=False)
                print(f"[SUBMIT] Applied config override: {list(config_override.keys())}", flush=True)
            else:
                with open(config_path, "w", encoding="utf-8") as f:
                    json.dump(config_override, f, indent=2, ensure_ascii=False)
                print(f"[SUBMIT] Created config from override", flush=True)

        # Save secret key if provided (private mode)
        is_private = bool(secret_key)
        if is_private:
            with open(os.path.join(workspace, ".secret"), "w", encoding="utf-8") as f:
                f.write(secret_key)

        task = {
            "task_id": task_id,
            "name": name or f"Problem {len(tasks)+1}",
            "status": "pending",
            "phase": "waiting",
            "workspace": workspace,
            "problem_preview": problem_text[:120],
            "problem_length": len(problem_text),
            "created_at": _now(),
            "started_at": None,
            "finished_at": None,
            "error": None,
            "is_private": is_private,
        }
        with tasks_lock:
            tasks[task_id] = task
        print(f"[SUBMIT] Task registered in memory", flush=True)

        # Create log file
        log_path = os.path.join(workspace, "solver.log")
        with open(log_path, "w", encoding="utf-8") as f:
            f.write(f"[{_now()}] Task {task_id} created\n")

        print(f"[SUBMIT] Created task {task_id} -> {workspace}", flush=True)

        # Spawn background thread — run.py manages its own timeout & concurrency
        t = threading.Thread(target=_run_solver, args=(task_id, workspace), daemon=True)
        t.start()
        print(f"[SUBMIT] Thread started", flush=True)
        return task_id
    except Exception as e:
        import traceback
        tb = traceback.format_exc()
        print(f"[SUBMIT] ERROR: {e}", flush=True)
        print(f"[SUBMIT] Traceback:\n{tb}", flush=True)
        raise


def _run_solver(task_id, workspace):
    print(f"[{task_id}] _run_solver thread started", flush=True)
    with tasks_lock:
        tasks[task_id].update({"status": "running", "started_at": _now()})

    _log(task_id, f"Starting solver in {workspace}")
    _log(task_id, f"ANTHROPIC_API_KEY: {'set' if os.environ.get('ANTHROPIC_API_KEY') else 'NOT SET'}")
    _log(task_id, f"ANTHROPIC_BASE_URL: {os.environ.get('ANTHROPIC_BASE_URL', '(default)')}")

    env = os.environ.copy()
    start = time.time()
    proc = None

    try:
        cmd = [sys.executable, os.path.join(workspace, "run.py"), workspace]
        print(f"[{task_id}] Running: {' '.join(cmd)}", flush=True)

        proc = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            cwd=workspace,
            env=env,
        )
        _log(task_id, f"spawned run.py with PID {proc.pid}")

        # Read stdout line by line, append to log
        def _read_output():
            if proc.stdout:
                for line in iter(proc.stdout.readline, b""):
                    decoded = line.decode("utf-8", errors="replace").strip()
                    if decoded:
                        _log(task_id, f"[stdout] {decoded}")

        reader = threading.Thread(target=_read_output, daemon=True)
        reader.start()

        # Monitor workspace for progress (no timeout — run.py handles its own)
        last_phase = "starting"
        last_state = _read_state(workspace)
        with tasks_lock:
            tasks[task_id]["file_history"] = []

        while proc.poll() is None:
            phase = _infer_phase(workspace)
            if phase != last_phase:
                _log(task_id, f"Phase: {phase}")
                last_phase = phase

            # Track .state changes for history
            state = _read_state(workspace)
            if state and state != last_state:
                _log(task_id, f"State: {state}")
                history = STATE_TO_HISTORY.get(state, [])
                with tasks_lock:
                    tasks[task_id]["file_history"] = [dict(h) for h in history]
                last_state = state

            with tasks_lock:
                tasks[task_id]["phase"] = phase
                tasks[task_id]["elapsed_s"] = round(time.time() - start)

            time.sleep(10)

        reader.join(timeout=3)
        _log(task_id, f"run.py exited with code {proc.returncode}")

        if proc.returncode != 0:
            _log(task_id, "Solver returned non-zero exit code")
            with tasks_lock:
                tasks[task_id].update({
                    "status": "error",
                    "error": f"Solver exited with code {proc.returncode}",
                    "finished_at": _now(),
                })
            return

        summary = os.path.join(workspace, "final_summary.md")
        if os.path.exists(summary):
            _log(task_id, "Solver completed successfully")
            with tasks_lock:
                tasks[task_id].update({
                    "status": "complete",
                    "phase": "complete",
                    "finished_at": _now(),
                })
        else:
            _log(task_id, "Solver finished but no summary file found")
            with tasks_lock:
                tasks[task_id].update({
                    "status": "error",
                    "error": "Solver finished but no summary file was produced.",
                    "finished_at": _now(),
                })

    except FileNotFoundError:
        _log(task_id, f"FileNotFoundError: run.py not found")
        with tasks_lock:
            tasks[task_id].update({
                "status": "error",
                "error": "run.py not found in workspace.",
                "finished_at": _now(),
            })
    except Exception as e:
        import traceback
        tb = traceback.format_exc()
        _log(task_id, f"Exception: {e}")
        _log(task_id, tb)
        print(f"[{task_id}] Traceback:\n{tb}", flush=True)
        with tasks_lock:
            tasks[task_id].update({
                "status": "error",
                "error": str(e),
                "finished_at": _now(),
            })


# Known solver workflow steps in execution order. Unknown files append at end alphabetically.
WORKFLOW_STEPS = ["plan", "solution", "review", "final_summary"]
# Mapping from .state value to completed steps
STATE_TO_HISTORY = {
    "planner": [],  # not started yet
    "builder": [{"step": "plan", "status": "history"}],
    "evaluator": [{"step": "plan", "status": "history"}, {"step": "solution", "status": "history"}],
    "done": [{"step": "plan", "status": "history"}, {"step": "solution", "status": "history"},
             {"step": "review", "status": "history"}, {"step": "final_summary", "status": "history"}],
}
STATE_TO_PHASE = {
    "planner": "starting",
    "builder": "building",
    "evaluator": "evaluating",
    "done": "complete",
}
# Files to exclude from progress tracking
PROGRESS_EXCLUDES = {"problem.md", "solver.log", "outline.md"}


def _read_state(workspace):
    """Read .state file. Returns phase string (planner/builder/evaluator/done) or None."""
    path = os.path.join(workspace, ".state")
    if not os.path.isfile(path):
        return None
    try:
        with open(path, encoding="utf-8") as f:
            return f.read().strip()
    except Exception:
        return None


def _read_secret(workspace):
    """Read .secret file. Returns secret key string or None."""
    path = os.path.join(workspace, ".secret")
    if not os.path.isfile(path):
        return None
    try:
        with open(path, encoding="utf-8") as f:
            return f.read().strip()
    except Exception:
        return None


def _check_access(workspace, provided_key=None):
    """Check if provided_key grants access to a private task. Returns True if public or key matches."""
    secret = _read_secret(workspace)
    if not secret:
        return True  # not a private task
    if provided_key and provided_key == secret:
        return True
    return False


def _build_history_from_state(workspace, state=None):
    """Build progress history from .state file, marking last completed step as 'current'."""
    if state is None:
        state = _read_state(workspace)
    if state is None:
        return None  # no .state → caller should fall back to file scanning

    history = STATE_TO_HISTORY.get(state)
    if history is None:
        return []

    result = list(history)
    if result:
        result[-1] = dict(result[-1], status="current")
    return result


def _check_files(workspace, file_history=None):
    """Return list of steps with history. file_history is an ordered list from monitoring."""
    if file_history and len(file_history) > 0:
        # Use monitored history
        result = list(file_history)
        if result:
            result[-1] = dict(result[-1], status="current")
        return result

    # Priority 1: .state file
    from_state = _build_history_from_state(workspace)
    if from_state is not None:
        return from_state

    # Fallback: scan by mtime (for tasks created before this change or without .state)
    if not os.path.isdir(workspace):
        return []
    mtimes = {}
    for fname in os.listdir(workspace):
        if fname.endswith(".md") and fname not in PROGRESS_EXCLUDES:
            step = fname[:-3]
            if step in WORKFLOW_STEPS:
                mtimes[step] = os.path.getmtime(os.path.join(workspace, fname))
    if not mtimes:
        return []
    latest = max(mtimes, key=mtimes.get)
    result = []
    for step in WORKFLOW_STEPS:
        if step in mtimes:
            status = "current" if step == latest else "history"
            result.append({"step": step, "status": status})
    other = sorted(s for s in mtimes if s not in set(WORKFLOW_STEPS))
    for s in other:
        result.append({"step": s, "status": "history"})
    return result


def _infer_phase(workspace):
    # Priority: .state file first
    state = _read_state(workspace)
    if state and state in STATE_TO_PHASE:
        return STATE_TO_PHASE[state]
    # Fallback: scan .md files
    if os.path.exists(os.path.join(workspace, "final_summary.md")):
        return "complete"
    if os.path.exists(os.path.join(workspace, "review.md")):
        return "evaluating"
    if os.path.exists(os.path.join(workspace, "solution.md")):
        return "building"
    if os.path.exists(os.path.join(workspace, "plan.md")):
        return "planning"
    return "starting"


def get_task(task_id, secret_key=None):
    with tasks_lock:
        task = tasks.get(task_id)
        if task:
            # Check access for private tasks
            if not _check_access(task["workspace"], secret_key):
                return None
            result = dict(task)
            result.pop("problem_preview", None)
            history = result.get("file_history")
            result["files_done"] = _check_files(task["workspace"], history)
            return result
        return None


def get_task_result(task_id, secret_key=None):
    task = get_task(task_id, secret_key)
    if not task:
        return None
    summary = os.path.join(task.get("workspace", ""), "final_summary.md")
    if os.path.exists(summary):
        with open(summary, encoding="utf-8") as f:
            return f.read()
    return None


def get_task_logs(task_id, lines=100, secret_key=None):
    with tasks_lock:
        task = tasks.get(task_id)
        if not task:
            return [f"Task {task_id} not found in memory."]
        if not _check_access(task["workspace"], secret_key):
            return ["Access denied: invalid or missing secret key."]
    log_path = os.path.join(task["workspace"], "solver.log")
    if not os.path.exists(log_path):
        return ["Waiting for solver to start..."]
    try:
        with open(log_path, encoding="utf-8") as f:
            all_lines = f.readlines()
            return [l.rstrip() for l in all_lines[-lines:]]
    except Exception as e:
        return [f"Error reading log: {e}"]


def get_workspace_file(task_id, filename, secret_key=None):
    """Read a file from a task's workspace. Returns content or None if not found."""
    with tasks_lock:
        task = tasks.get(task_id)
        if not task:
            return None
        if not _check_access(task["workspace"], secret_key):
            return None
    fpath = os.path.join(task["workspace"], filename)
    if not os.path.isfile(fpath):
        return None
    with open(fpath, encoding="utf-8") as f:
        return f.read()


def list_workspace_files(task_id, secret_key=None):
    """List all non-hidden .md files in a task's workspace."""
    with tasks_lock:
        task = tasks.get(task_id)
        if not task:
            return []
        if not _check_access(task["workspace"], secret_key):
            return []
    ws = task["workspace"]
    if not os.path.isdir(ws):
        return []
    result = []
    for fname in sorted(os.listdir(ws)):
        if fname.endswith(".md") and not fname.startswith("."):
            result.append(fname)
    return result


def get_running_tasks():
    """Return list of currently running tasks (for frontend recovery after page refresh)."""
    with tasks_lock:
        return [
            {
                "task_id": t["task_id"],
                "status": t["status"],
                "phase": t["phase"],
                "problem": t["problem"],
                "created_at": t["created_at"],
                "files_done": _check_files(t["workspace"], t.get("file_history")),
            }
            for t in tasks.values()
            if t["status"] in ("pending", "running")
        ]


def list_tasks(secret_key=None):
    with tasks_lock:
        return [
            {
                "task_id": t["task_id"],
                "name": t["name"],
                "status": t["status"],
                "phase": t["phase"],
                "problem_preview": t.get("problem_preview", "") if not t.get("is_private") else "🔒",
                "problem_length": t.get("problem_length", 0),
                "created_at": t["created_at"],
                "started_at": t.get("started_at"),
                "finished_at": t.get("finished_at"),
                "files_done": _check_files(t["workspace"], t.get("file_history")),
                "error": t.get("error"),
                "is_private": t.get("is_private", False),
            }
            for t in sorted(tasks.values(), key=lambda x: x["created_at"], reverse=True)
        ]


def delete_task(task_id, secret_key=None):
    """Remove a task from memory and delete its workspace. Returns True if found."""
    with tasks_lock:
        task = tasks.get(task_id)
        if not task:
            return False
        if task.get("is_private") and not _check_access(task["workspace"], secret_key):
            return False
        task = tasks.pop(task_id, None)
    workspace = task.get("workspace", "")
    if os.path.isdir(workspace):
        shutil.rmtree(workspace)
    _log(task_id, f"Task {task_id} deleted")
    return True


def cleanup_completed_tasks():
    """Delete all completed and errored tasks. Returns count of deleted tasks."""
    with tasks_lock:
        to_delete = [
            tid for tid, t in tasks.items()
            if t["status"] in ("complete", "error")
        ]
    count = 0
    for tid in to_delete:
        if delete_task(tid):
            count += 1
    return count


def update_task_config(task_id, config_dict):
    """Update config.json in a task's workspace. Only allowed for pending tasks."""
    with tasks_lock:
        task = tasks.get(task_id)
        if not task:
            return None, "Task not found"
        if task["status"] != "pending":
            return None, f"Cannot update config for task in '{task['status']}' status (only 'pending')"
    config_path = os.path.join(task["workspace"], "config.json")
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            current = json.load(f)
        current.update(config_dict)
        with open(config_path, "w", encoding="utf-8") as f:
            json.dump(current, f, indent=2, ensure_ascii=False)
        return current, None
    except FileNotFoundError:
        return None, "config.json not found in workspace"
    except json.JSONDecodeError:
        return None, "Invalid config.json in workspace"