File size: 2,233 Bytes
a02272f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Workspace runtime generation — the .brain/ bridge directory."""

import json
from pathlib import Path


def generate_workspace_runtime(
    workspace_brain_dir: Path,
    brain_name: str,
    brain_path: Path,
    project_name: str = "",
) -> None:
    """Create the .brain/ workspace runtime with all metadata files."""
    workspace_brain_dir.mkdir(parents=True, exist_ok=True)

    # linked_brain — absolute path to Brain Instance
    (workspace_brain_dir / "linked_brain").write_text(
        str(brain_path.resolve()), encoding="utf-8"
    )

    # current_project — project identity (empty until attach)
    (workspace_brain_dir / "current_project").write_text(
        project_name, encoding="utf-8"
    )

    # BRAIN.json — machine-readable metadata
    version = _get_current_version(brain_path)
    brain_json = {
        "brain": brain_name,
        "project": project_name,
        "version": version,
        "brain_path": str(brain_path.resolve()),
    }
    (workspace_brain_dir / "BRAIN.json").write_text(
        json.dumps(brain_json, indent=2), encoding="utf-8"
    )

    # runtime/ — ephemeral session metadata (non-authoritative)
    runtime_dir = workspace_brain_dir / "runtime"
    runtime_dir.mkdir(exist_ok=True)
    session_file = runtime_dir / "session.md"
    if not session_file.exists():
        session_file.write_text(
            "# Session\n\n## Started\n\n## Agent\n\n## Notes\n",
            encoding="utf-8",
        )

    # AGENT.md — generated workspace-specific protocol
    from brain.templates.agent_protocol import generate_agent_md

    agent_md = generate_agent_md(brain_name, brain_path, project_name)
    (workspace_brain_dir / "AGENT.md").write_text(agent_md, encoding="utf-8")


def _get_current_version(brain_path: Path) -> str:
    """Determine the current version label from versions/ directory."""
    versions_dir = brain_path / "versions"
    if not versions_dir.exists():
        return "v0"
    version_dirs = sorted(
        [d for d in versions_dir.iterdir() if d.is_dir() and d.name.startswith("v")],
        key=lambda d: int(d.name[1:]) if d.name[1:].isdigit() else 0,
    )
    if not version_dirs:
        return "v0"
    return version_dirs[-1].name