# v0.0.14 – Developer Design Notes

## Enhanced Claude Code Agent Context Sharing Architecture

### Executive Summary
This document outlines the design considerations and future improvements for context sharing between Claude Code agents in MassGen v0.0.14. The current implementation relies on implicit prompt-based access control, which we aim to replace with an explicit, system-level permission framework.

### Table of Contents
1. [Current Implementation](#current-implementation)
2. [User Impact](#user-impact)
3. [Developer Considerations](#developer-considerations)
4. [Proposed Solution Architecture](#proposed-solution-architecture)
5. [Implementation Roadmap](#implementation-roadmap)
6. [Related Files and Components](#related-files-and-components)

---

## Current Implementation

### Background
In v0.0.14, MassGen's Claude Code agents share workspace context through a snapshot-based mechanism (introduced in v0.0.12). The orchestrator maintains:

- **Workspace Snapshots**: Stored in `claude_code_snapshots/` directory
- **Temporary Workspaces**: Located in `claude_code_temp_workspaces/` for agent isolation
- **Access Control**: Currently managed through **prompt engineering** rather than system-level enforcement

### Technical Details
The current context sharing flow works as follows:

1. **Agent Initialization**: Each Claude Code agent starts with its own isolated workspace
2. **Snapshot Creation**: The orchestrator creates snapshots of agent workspaces at key points
3. **Context Sharing**: Agents can theoretically access their own workspaces and temorary workspace based on prompt instructions
4. **Coordination**: The `orchestrator.py` manages this process through coordination actions

### Limitations
The current approach has several critical limitations:

1. **Over-reliance on prompt engineering** – Permissions are not enforced at a system level, only by how we phrase the prompt
2. **Lack of fine-grained control** – We cannot explicitly restrict or grant access to specific directories or resources on a per-agent basis
3. **No audit trail** – It's difficult to track which agent accessed which resources and when
4. **Potential for prompt injection** – Malicious or confused prompts could bypass intended restrictions

---

## User Impact

### For End Users
- **Current State**: Users may experience unpredictable behavior when multiple Claude Code agents collaborate
- **Security Concerns**: Sensitive data in one workspace could potentially be accessed by unintended agents
- **Performance**: No direct performance impact, but lack of proper boundaries may lead to confusion in agent outputs

### For Developers Using MassGen
- **Configuration Complexity**: Currently must carefully craft prompts to control access
- **Debugging Challenges**: Hard to trace context sharing issues when they occur

### Example User Scenarios
```yaml
# Current (Implicit) Approach - Fragile and Error-prone
agents:
  - id: "frontend-developer"
    system_message: "Work on frontend code in /frontend. DO NOT access /backend or /database directories."

  - id: "backend-developer"
    system_message: "Work on backend code in /backend. You may read from /frontend but DO NOT modify it."

# Proposed (Explicit) Approach - Clear and Enforceable
agents:
  - id: "frontend-developer"
    permissions:
      /frontend: read-write
      /backend: none
      /database: none

  - id: "backend-developer"
    permissions:
      /backend: read-write
      /frontend: read-only
      /database: read-only
```

---

## Developer Considerations

### Architecture Impact
The proposed changes will affect several core components:

1. **Orchestrator (`massgen/orchestrator.py`)**: Need to add permission checking logic
2. **Claude Code Backend (`massgen/claude_code_backend.py`)**: Must respect and enforce permissions
3. **Configuration System**: Extension of YAML/JSON config format to include permissions
4. **Logging System**: Need to add audit logging for access attempts

### Code Integration Points
Key files that will need modification:

```python
# orchestrator.py - Add permission validation
def validate_agent_access(agent_id: str, resource_path: str, access_type: str) -> bool:
    """Check if agent has required permission for resource."""
    pass

# claude_code_backend.py - Enforce permissions during operations
def execute_with_permissions(self, operation, path):
    """Execute operation only if permissions allow."""
    if not self.check_permission(path, operation.type):
        raise PermissionError(f"Agent {self.agent_id} lacks {operation.type} access to {path}")
```

---

## Proposed Solution Architecture

### A. Explicit Access Control Layer

#### System-Level Enforcement
- Implement a **PermissionManager** class that maintains and enforces access rules
- Integrate with file system operations at the backend level
- Provide clear error messages when permissions are violated

#### Permission Types
```python
class Permission(Enum):
    NONE = "none"           # No access
    READ = "read"          # Read-only access
    WRITE = "write"        # Write-only access (rare use case)
    READ_WRITE = "read-write"  # Full access
    EXECUTE = "execute"    # Can run scripts/programs
```

### B. Context-Aware Sharing Contracts

#### Agent Capability Declaration
Each agent declares its required permissions at initialization:

```yaml
agents:
  claude-code:
    capabilities:
      requires:
        - path: "/shared/configs"
          access: "read"
          reason: "Need to read shared configuration files"
      provides:
        - path: "/claude-output"
          access: "read"
          description: "Analysis results available for other agents"
```

#### Dynamic Permission Negotiation
- Agents can request additional permissions during runtime
- Orchestrator validates requests against security policies
- User approval required for elevated permissions

### C. Configurable Policy Framework

#### Policy File Structure
```yaml
# massgen-permissions.yaml
version: "1.0"
default_policy: "deny"  # Deny by default, explicitly grant

global_rules:
  - path: "/tmp/*"
    access: "read-write"
    for: "all"
  - path: "/secrets/*"
    access: "none"
    for: "all"

agent_permissions:
  claude-code:
    base_workspace: "/workspace/claude"
    permissions:
      - path: "/workspace/claude/*"
        access: "read-write"
      - path: "/workspace/shared/*"
        access: "read"
      - path: "/workspace/other-agents/*"
        access: "none"

  gpt-analysis:
    base_workspace: "/workspace/gpt"
    permissions:
      - path: "/workspace/gpt/*"
        access: "read-write"
      - path: "/workspace/shared/*"
        access: "read-write"
      - path: "/workspace/claude/public/*"
        access: "read"

audit:
  log_access_attempts: true
  log_file: "massgen_access.log"
  alert_on_violation: true
```

#### Policy Validation
- Schema validation for policy files
- Conflict detection (e.g., contradictory rules)
- Inheritance support for rule hierarchies

### D. Implementation Benefits

#### Prompt Simplification
```python
# Before: Complex prompt with security instructions
system_prompt = """
You are a frontend developer. You MUST ONLY work in the /frontend directory.
DO NOT access /backend, /database, or /secrets directories under ANY circumstances.
If you need backend data, request it through the API endpoints only.
REMEMBER: You have no permission to modify backend code...
"""

# After: Clean, focused prompt
system_prompt = """
You are a frontend developer responsible for the user interface.
Focus on creating responsive, accessible components.
"""
# Permissions handled by system configuration, not prompts
```

#### Security Improvements
- **Defense in depth**: Multiple layers of protection
- **Audit trail**: Complete log of all access attempts
- **Principle of least privilege**: Agents only get necessary permissions
- **Separation of concerns**: Security separate from business logic

---
## Related Files and Components

### Core Implementation Files
- `massgen/orchestrator.py` - Main orchestration logic, needs permission integration
- `massgen/claude_code_backend.py` - Claude Code agent backend, enforcement point
- `massgen/configs/` - Configuration examples showing permission usage
- `massgen/utils.py` - Utility functions for permission checking

### Documentation Files
- `docs/release_notes/v0.0.14.md` - User-facing release notes about logging features
- `docs/dev_notes/v0.0.14-context.md` - This file (developer design notes)
- `README.md` - Main documentation entry point

### Configuration Examples
See `massgen/configs/claude_code_*.yaml` for examples of how permissions will be configured in practice.

---

## Conclusion

The enhanced context sharing architecture will transform MassGen from a prompt-controlled system to a robust, permission-based multi-agent platform. This change will improve security, simplify configuration, and enable more complex agent collaborations while maintaining clear boundaries and audit trails.

For questions or contributions to this design, please refer to the [Contributing Guidelines](../../CONTRIBUTING.md) or open an issue on GitHub.
