# 设计方案 1: VGCS (Virtual Git Context System) [详细设计版]

## 1. 定位与目标

VGCS 是底层存储引擎，提供版本化、高性能、支持大文件的分布式文件系统接口。
它基于 **git2-rs (libgit2)** 实现，直接操作 Git Object DB。

## 2. 物理存储规范 (Specification)

所有服务共享挂载卷 `/mnt/workflow_data`。

### 2.1 目录结构
```text
/mnt/workflow_data/
  ├── repos/
  │   └── {request_id}.git/     <-- Bare Git Repo
  │         ├── HEAD
  │         ├── config
  │         ├── objects/        <-- Standard Git Objects
  │         └── refs/
  └── blobs/
      └── {request_id}/         <-- Blob Store Root
            ├── ab/
            │   └── ab1234...   <-- Raw File (SHA-256 of content)
            └── cd/
                └── cd5678...
```

### 2.2 Blob 引用文件格式 (.ref)
当文件 > 1MB 时，Git Blob 存储如下 JSON 内容：
```json
{
  "$vgcs_ref": "v1",
  "sha256": "ab1234567890...", 
  "size": 10485760,
  "mime_type": "application/json",
  "original_name": "data.json"
}
```

## 3. 核心接口定义 (Rust Trait)

### 3.1 ContextStore Trait

```rust
use anyhow::Result;
use std::io::Read;

pub trait ContextStore {
    /// 初始化仓库
    fn init_repo(&self, req_id: &str) -> Result<()>;

    /// 读取文件内容
    /// 自动逻辑：读取 Git Blob -> 解析 JSON -> 如果是 Ref，读 Blob Store；否则直接返回
    fn read_file(&self, req_id: &str, commit_hash: &str, path: &str) -> Result<Box<dyn Read>>;

    /// 读取目录
    fn list_dir(&self, req_id: &str, commit_hash: &str, path: &str) -> Result<Vec<DirEntry>>;

    /// 获取变更
    fn diff(&self, req_id: &str, from_commit: &str, to_commit: &str) -> Result<Vec<FileChange>>;
    
    /// 三路合并 (In-Memory)
    /// 返回新生成的 Tree OID，不生成 Commit
    fn merge_trees(&self, req_id: &str, base: &str, ours: &str, theirs: &str) -> Result<String>;
    
    /// 创建写事务
    fn begin_transaction(&self, req_id: &str, base_commit: &str) -> Result<Box<dyn Transaction>>;
}

#[derive(Debug)]
pub struct DirEntry {
    pub name: String,
    pub kind: EntryKind, // File | Dir
    pub object_id: String,
}

#[derive(Debug)]
pub enum FileChange {
    Added(String),
    Modified(String),
    Deleted(String),
}
```

### 3.2 Transaction Trait (写操作)

```rust
pub trait Transaction {
    /// 写入文件
    /// 内部逻辑：
    /// 1. 计算 content SHA-256
    /// 2. if size > 1MB: 写 Blob Store，构造 Ref JSON
    /// 3. 写 Git Blob (Raw 或 Ref)
    /// 4. 更新内存中的 Index/TreeBuilder
    fn write(&mut self, path: &str, content: &[u8]) -> Result<()>;

    /// 删除文件
    fn remove(&mut self, path: &str) -> Result<()>;

    /// 提交更改
    /// 1. Write Tree Object
    /// 2. Create Commit Object (Parent = base_commit)
    /// 3. Return new Commit Hash
    fn commit(self, message: &str, author: &str) -> Result<String>;
}
```

## 4. 实现细节规范

### 4.1 读操作流程 (read_file)
1.  Open Repo: `/mnt/workflow_data/repos/{req_id}.git`
2.  Locate Tree: Parse `commit_hash` -> `tree_id`.
3.  Find Entry: 在 Tree 中查找 `path`.
4.  Read Blob: 读取 Git Blob 内容。
5.  **Check Ref**: 尝试解析为 `BlobRef` 结构。
    *   **Success**: 构建 Blob Store 路径 `/mnt/workflow_data/blobs/{req_id}/{sha256[0..2]}/{sha256}`，打开文件流。
    *   **Fail** (说明是普通小文件): 返回 `Cursor::new(blob_content)`.

### 4.2 写操作流程 (write)
1.  Check Size: `content.len()`.
2.  **Large File Path**:
    *   Calc SHA-256.
    *   Write to Blob Store (Ensure parent dir exists).
    *   Content = JSON String of `BlobRef`.
3.  **Git Write**:
    *   `odb.write(Blob, content)`.
    *   Update in-memory `git2::TreeBuilder`.

### 4.3 合并流程 (merge_trees)
1.  Load Trees: `base_tree`, `our_tree`, `their_tree`.
2.  `repo.merge_trees(base, our, their, opts)`.
3.  Check Conflicts: `index.has_conflicts()`.
    *   If conflict: Return Error (Complex resolution left to Orchestrator Agent).
4.  Write Result: `index.write_tree_to(repo)`.
5.  Return Tree Hash.

## 5. Web UI & Fuse
*   **Web**: 基于 Axum，路由 `GET /api/v1/repo/:req_id/tree/:commit/*path`。复用 `ContextStore` 接口。
*   **Fuse**: 基于 `fuser`。
    *   Mount Point: `/mnt/vgcs_view/{req_id}/{commit}`.
    *   `read()` -> `store.read_file()`.
    *   `readdir()` -> `store.list_dir()`.
    *   只读挂载，用于 Debug。

## 6. 依赖库
*   `git2` (0.18): 核心操作。
*   `sha2` (0.10): 哈希计算。
*   `serde_json`: Ref 序列化。
*   `anyhow`: 错误处理。
