Swadhin Biswas refactor: rename package to 'cortexa' and repo to 'cortexa' · 3/6/2026
34324f9
176 lines · 5.2 KB
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
"""
GCC(Git-Context-Controller) Data Models Code by @swadhinbiswas

Based on: arXiv:2508.00031v2 - "Git Context Controller: Manage the Context of
LLM-based Agents like Git" by Junde Wu et al.

The paper defines agent memory as a versioned, hierarchical file system with
four core commands: COMMIT, BRANCH, MERGE, and CONTEXT.

"""

from __future__ import annotations

from dataclasses import dataclass, field
from datetime import datetime
from typing import Dict, Optional
import yaml


def _sanitize(text: str) -> str:
    """Escape separator sequences in user-provided content.

    Lines that are exactly ``---`` (the markdown/OTA block separator)
    would break all parsers that split on ``---\\n``.  We prepend a
    backslash so the separator is preserved in the stored markdown
    without confusing the splitter.
    """
    return text.replace("\n---\n", "\n\\---\n")


def _desanitize(text: str) -> str:
    """Reverse the escaping applied by :func:`_sanitize`."""
    return text.replace("\n\\---\n", "\n---\n")


def _split_blocks(text: str) -> list[str]:
    """Split markdown text on ``---\\n`` while respecting escaped separators.

    After naive splitting on ``---\\n``, blocks whose predecessor ends
    with ``\\`` are rejoined (the backslash means ``\\---\\n`` was an
    escaped separator produced by :func:`_sanitize`).
    """
    raw = text.split("---\n")
    blocks: list[str] = []
    i = 0
    while i < len(raw):
        block = raw[i]
        while block.endswith("\\") and i + 1 < len(raw):
            i += 1
            block = block + "---\n" + raw[i]
        blocks.append(block)
        i += 1
    return blocks


@dataclass
class OTARecord:
    """
    Observation-Thought-Action record (OTA cycle).
    The paper logs continuous OTA cycles in log.md for each branch.
    """

    timestamp: str
    observation: str
    thought: str
    action: str
    step: int

    def to_markdown(self) -> str:
        return (
            f"### Step {self.step} — {self.timestamp}\n"
            f"**Observation:** {_sanitize(self.observation)}\n\n"
            f"**Thought:** {_sanitize(self.thought)}\n\n"
            f"**Action:** {_sanitize(self.action)}\n\n"
            "---\n"
        )

    @staticmethod
    def from_dict(d: Dict) -> "OTARecord":
        return OTARecord(
            timestamp=d["timestamp"],
            observation=d["observation"],
            thought=d["thought"],
            action=d["action"],
            step=d["step"],
        )


@dataclass
class CommitRecord:
    commit_id: str
    branch_name: str
    branch_purpose: str
    previous_progress_summary: str
    this_commit_contribution: str
    timestamp: str

    def to_markdown(self) -> str:
        return (
            f"## Commit `{self.commit_id}`\n"
            f"**Timestamp:** {self.timestamp}\n\n"
            f"**Branch Purpose:** {_sanitize(self.branch_purpose)}\n\n"
            f"**Previous Progress Summary:** {_sanitize(self.previous_progress_summary)}\n\n"
            f"**This Commit's Contribution:** {_sanitize(self.this_commit_contribution)}\n\n"
            "---\n"
        )


@dataclass
class BranchMetadata:
    """
    Structured metadata stored in metadata.yaml per branch.
    Records architectural intent and motivation (per paper S3.1).
    """

    name: str
    purpose: str
    created_from: str
    created_at: str
    status: str = "active"
    merged_into: Optional[str] = None
    merged_at: Optional[str] = None

    def to_yaml(self) -> str:
        d = {
            "name": self.name,
            "purpose": self.purpose,
            "created_from": self.created_from,
            "created_at": self.created_at,
            "status": self.status,
            "merged_into": self.merged_into,
            "merged_at": self.merged_at,
        }
        return yaml.dump(d, default_flow_style=False)

    @staticmethod
    def from_yaml(text: str) -> "BranchMetadata":
        d = yaml.safe_load(text)
        return BranchMetadata(
            name=d["name"],
            purpose=d["purpose"],
            created_from=d["created_from"],
            created_at=d["created_at"],
            status=d.get("status", "active"),
            merged_into=d.get("merged_into"),
            merged_at=d.get("merged_at"),
        )


@dataclass
class ContextResult:
    """
    Result returned by the CONTEXT command.
    The paper specifies hierarchical retrieval at varying resolutions
    (K = number of recent commit records to reveal; default K=1).
    """

    branch_name: str
    k: int
    commits: list[CommitRecord] = field(default_factory=list)
    ota_records: list[OTARecord] = field(default_factory=list)
    main_roadmap: str = ""
    metadata: Optional[BranchMetadata] = None

    def summary(self) -> str:
        lines = [f"# CONTEXT — branch `{self.branch_name}` (K={self.k})\n"]
        lines.append("## Global Roadmap\n" + self.main_roadmap + "\n")
        lines.append(f"## Last {self.k} Commit(s)\n")
        for c in self.commits:
            lines.append(c.to_markdown())
        if self.ota_records:
            lines.append(f"## Recent OTA steps ({len(self.ota_records)} total)\n")
            for rec in self.ota_records[-5:]:
                lines.append(rec.to_markdown())
        return "\n".join(lines)