File size: 6,275 Bytes
2e818da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import os
from pathlib import Path
from typing import Any

from fastapi import APIRouter, HTTPException

from app.services.observability_summary import observability_summary
from app.services.project_activity import ProjectActivityService
from app.services.project_intelligence import ProjectIntelligenceService
from app.services.project_service import ProjectService
from app.services.student_memory import StudentMemoryService

router = APIRouter(prefix="/api/projects", tags=["control-room"])

_project_service = ProjectService()
_activity = ProjectActivityService()


def _is_demo_mode() -> bool:
    return os.getenv("DEPLOYMENT_ENV", "desktop") == "demo"


def _artifact_roots() -> dict[str, str]:
    home = Path.home() / ".studybuddy"
    return {
        "graphs": str(home / "graphs"),
        "sessions": str(home / "sessions"),
        "citation_graphs": str(home / "citation_graphs"),
        "cache": str(home / "cache"),
        "annotations": str(home / "annotations"),
        "summaries": str(home / "summaries"),
        "cognee": str(home / "cognee"),
    }


def _exists(path: str) -> bool:
    return bool(path) and os.path.exists(path)


def _count_files(path: str, suffix: str = "") -> int:
    if not os.path.isdir(path):
        return 0
    return len([name for name in os.listdir(path) if not suffix or name.endswith(suffix)])


def _file_meta(path: str) -> tuple[int, float]:
    if not _exists(path):
        return 0, 0.0
    try:
        return os.path.getsize(path), os.path.getmtime(path)
    except OSError:
        return 0, 0.0


def _artifact(id_: str, label: str, saved: bool, detail: str = "", path: str = "") -> dict[str, Any]:
    size, updated_at = _file_meta(path) if path else (0, 0.0)
    return {
        "id": id_,
        "key": id_,
        "label": label,
        "status": "saved" if saved else "missing",
        "exists": saved,
        "detail": detail,
        "path": path or detail,
        "size_bytes": size,
        "updated_at": updated_at,
    }


def project_artifacts(project_id: str, document_id: str = "") -> list[dict[str, Any]]:
    roots = _artifact_roots()
    graph_path = os.path.join(roots["graphs"], f"{project_id}.json")
    doc_graph_path = os.path.join(roots["graphs"], f"doc_{document_id}.json") if document_id else ""
    session_path = os.path.join(roots["sessions"], f"{project_id}.json")
    citation_path = os.path.join(roots["citation_graphs"], f"{project_id}.json")
    annotation_count = _count_files(roots["annotations"], ".json")
    summary_count = _count_files(roots["summaries"], ".md")
    cache_count = _count_files(roots["cache"], ".json")
    return [
        _artifact("project_graph", "Project graph", _exists(graph_path), graph_path, graph_path),
        _artifact("document_graph_cache", "Document graph cache", _exists(doc_graph_path), doc_graph_path, doc_graph_path),
        _artifact("project_snapshot", "Project snapshot", _exists(session_path), session_path, session_path),
        _artifact("citation_graph", "Citation Graph", _exists(citation_path), citation_path, citation_path),
        _artifact("output_cache", "Generated output cache", cache_count > 0, f"{cache_count} cached item(s)"),
        _artifact("annotations", "Annotations", annotation_count > 0, f"{annotation_count} annotation file(s)"),
        _artifact("summary", "Summary artifacts", summary_count > 0, f"{summary_count} markdown summary file(s)"),
        _artifact("cognee", "Cognee memory store", os.path.isdir(roots["cognee"]), roots["cognee"], roots["cognee"]),
    ]


@router.get("/{project_id}/activity")
def get_project_activity(project_id: str, limit: int = 50):
    if _project_service.load(project_id) is None:
        raise HTTPException(404, "Project not found")
    return {"project_id": project_id, "items": [row.model_dump() for row in _activity.list(project_id, limit=limit)]}


@router.get("/{project_id}/artifacts")
def get_project_artifacts(project_id: str):
    project = _project_service.load(project_id)
    if project is None:
        raise HTTPException(404, "Project not found")
    document_id = _project_service.derive_document_id(project)
    return {"project_id": project_id, "items": project_artifacts(project_id, document_id=document_id)}


@router.get("/{project_id}/control-room")
async def get_control_room(project_id: str, fast: bool = True):
    project = _project_service.load(project_id)
    if project is None:
        raise HTTPException(404, "Project not found")
    document_id = _project_service.derive_document_id(project)
    activities = [row.model_dump() for row in _activity.list(project_id, limit=25)]
    artifacts = project_artifacts(project_id, document_id=document_id)
    active_jobs = [row for row in activities if row.get("status") == "running"][:5]
    memory = (
        {
            "project_id": project_id,
            "state": "disabled",
            "profile_dataset": False,
            "project_dataset": False,
            "inventory_ok": False,
            "provenance_ok": False,
            "export_ok": False,
            "last_error": "Cognee memory is disabled in demo mode.",
        }
        if _is_demo_mode()
        else {
            "project_id": project_id,
            "state": "refreshing" if active_jobs else "cached",
            "profile_dataset": None,
            "project_dataset": None,
            "inventory_ok": False,
            "provenance_ok": False,
            "export_ok": False,
            "last_error": "Memory inspection is loading in the background.",
        }
        if fast
        else await StudentMemoryService().memory_status(project_id, include_liveness=True)
    )
    intelligence = ProjectIntelligenceService().status(project)
    return {
        "project": {**project.model_dump(), "document_id": document_id},
        "brief": intelligence["brief"],
        "stats": intelligence["stats"],
        "settings_summary": intelligence["settings_summary"],
        "live_log": activities,
        "memory": memory,
        "memory_status": memory,
        "activity": activities,
        "artifacts": artifacts,
        "debug_artifacts": artifacts,
        "active_jobs": active_jobs,
        "observability": observability_summary(),
    }