# BranchPy Governance Toolkit (v0.8.6)

## Overview

The Governance Toolkit provides enterprise-grade policy enforcement, role-based access control (RBAC), and audit management for BranchPy projects.

## Quick Start

### 1. Migrate Legacy Project

```bash
cd your-branchpy-project
branchpy migrate --governance
```

This creates:
- `.branchpy/policy.json` — Policy rules configuration
- `.branchpy/team.toml` — Team roles and assignments
- `.branchpy/.cert_secret` — Certificate signing key (keep secure!)
- `.branchpy/session/` — Session certificate storage

### 2. Verify Setup

```bash
# List team members
branchpy team list

# Show current policy
branchpy team policy

# View recent audit events
branchpy team audit --last 20
```

### 3. Issue Session Certificate

```bash
# Issue 60-minute certificate for CLI use
branchpy team cert issue --scope cli --ttl 60

# List active certificates
branchpy team cert list

# Clean up expired certificates
branchpy team cert cleanup
```

---

## Core Components

### 1. Policy Engine

**File**: `.branchpy/policy.json`

Defines enforcement rules for actions across the project.

**Example Policy**:

```json
{
  "version": "1.0",
  "team_id": "studio-alpha",
  "default_enforcement": "warn",
  "rules": [
    {
      "id": "NO_FORCE_CONTRIBUTORS",
      "description": "Contributors cannot use --force flag",
      "action_type": "cli_command",
      "conditions": {
        "flags": ["--force"]
      },
      "enforcement": "deny",
      "roles_affected": ["contributor"]
    },
    {
      "id": "RESTRICT_MAIN_PUSH",
      "description": "Cannot push directly to main branch",
      "action_type": "git_operation",
      "conditions": {
        "operation": "push",
        "branch": "main"
      },
      "enforcement": "deny",
      "roles_affected": ["contributor", "auditor"]
    }
  ]
}
```

**Action Types**:
- `cli_command` — CLI command execution
- `daemon_request` — WebSocket/HTTP API calls
- `file_access` — File read/write operations
- `git_operation` — Git operations (commit, push, etc.)

**Enforcement Levels**:
- `allow` — Permit action (no restrictions)
- `warn` — Permit but log warning
- `deny` — Block action (exit with error)

### 2. Team Configuration

**File**: `.branchpy/team.toml`

Defines team members, roles, and capabilities.

**Example Team Config**:

```toml
[team]
team_id = "studio-alpha"
name = "Studio Alpha Team"

[roles]
owner = { 
  admin=true, 
  audit_write=true, 
  audit_verify=true, 
  replay=true, 
  policy_manage=true 
}
contributor = { 
  admin=false, 
  audit_write=true, 
  audit_verify=true, 
  replay=true, 
  policy_manage=false 
}
auditor = { 
  admin=false, 
  audit_write=false, 
  audit_verify=true, 
  replay=true, 
  policy_manage=false 
}

[assignments]
"550e8400-e29b-41d4-a716-446655440000" = "owner"
"aa1b2c3d-4e5f-6789-abcd-ef0123456789" = "contributor"
```

**Capabilities**:
- `admin` — Full administrative access
- `audit_write` — Can emit audit entries (normal operations)
- `audit_verify` — Can verify audit chain integrity
- `replay` — Can replay audit log
- `policy_manage` — Can modify policies and team config

### 3. Session Certificates

Short-lived signed tokens for authenticated operations.

**Usage**:

```python
from branchpy.core.governance import CertificateManager, load_or_create_secret_key

# Initialize manager
secret_key = load_or_create_secret_key(Path(".branchpy/.cert_secret"))
cert_mgr = CertificateManager(Path(".branchpy/session"), secret_key)

# Issue certificate
cert = cert_mgr.issue("user-uuid", "contributor", scope="cli", ttl_minutes=60)

# Validate certificate
is_valid, reason, loaded_cert = cert_mgr.validate(cert.session_id)
if not is_valid:
    raise AuthenticationError(reason)
```

### 4. Audit Export

Export audit logs for compliance reporting.

```bash
# Export to JSON
branchpy audit export --format json --output audit-2025-11.json

# Export to CSV
branchpy audit export --format csv --output audit-2025-11.csv

# Export to PDF report
branchpy audit export --format pdf --output audit-report.pdf
```

**Programmatic Usage**:

```python
from branchpy.core.governance import AuditExporter
from branchpy.core.audit import AuditLog

# Read audit entries
audit_log = AuditLog(Path(".branchpy/audit.jsonl"))
entries = list(audit_log.read_entries())

# Export
exporter = AuditExporter(entries)
exporter.export_pdf(
    Path("report.pdf"),
    metadata={"team_name": "Studio Alpha", "date_range": "2025-11"}
)
```

---

## Governance Guards (Developers)

Wrap functions with governance enforcement.

### Decorator Usage

```python
from branchpy.core.governance.guards import governed_action
from branchpy.core.governance import ActionType

@governed_action(ActionType.CLI_COMMAND, required_capability="stats:run")
def stats_command(args):
    """Run stats analysis (governed)."""
    # Implementation...
```

### Context Manager Usage

```python
from branchpy.core.governance.guards import GovernanceContext
from branchpy.core.governance import ActionType

with GovernanceContext(action_type=ActionType.FILE_ACCESS) as gov:
    gov.check_policy(context={
        "path": "sensitive.txt",
        "operation": "write"
    })
    # Perform operation...
```

---

## Cross-System Integration

### Structured Logging Integration

```python
from branchpy.core.governance.schemas import (
    emit_governance_event,
    PolicyContext,
    EVENT_STATS_COMPUTED
)

# Emit governance event
emit_governance_event(
    event_type=EVENT_STATS_COMPUTED,
    action="compute_stats",
    context=PolicyContext(
        role="contributor",
        enforcement_decision="allow",
        policy_id="studio-alpha"
    ),
    metadata={"violations": 0}
)
```

### Audit Correlation

Every policy enforcement decision is logged to `audit.jsonl` with a correlation ID for cross-referencing.

```python
from branchpy.core.governance.policy_engine import log_policy_decision

# Log decision to audit
log_policy_decision(violation, auditor)
```

---

## CLI Reference

### Team Commands

```bash
# List team members and roles
branchpy team list [--format table|json]

# Show current policy status
branchpy team policy [--violations] [--summary]

# View recent audit events
branchpy team audit [--last N]
```

### Certificate Commands

```bash
# Issue new session certificate
branchpy team cert issue [--scope cli|daemon|api] [--ttl MINUTES]

# List active certificates
branchpy team cert list

# Revoke certificate
branchpy team cert revoke SESSION_ID

# Clean up expired certificates
branchpy team cert cleanup
```

### Migration Commands

```bash
# Add governance to legacy project
branchpy migrate --governance [--dry-run]
```

---

## Architecture

### Enforcement Flow

```
User Action
    ↓
Resolve Identity (identity.toml)
    ↓
Get Role (team.toml)
    ↓
Check RBAC Capability
    ↓ (if required)
Load Policy (policy.json)
    ↓
Match Rules (conditions + role)
    ↓
Evaluate Enforcement (allow/deny/warn)
    ↓
Log to Audit (audit.jsonl)
    ↓
Execute or Block Action
```

### Exit Codes

- **0** — Success
- **65** — RBAC violation (missing capability)
- **66** — Policy violation (enforcement=deny)

---

## Security

### Certificate Security

- **Algorithm**: HMAC-SHA256
- **Key Length**: 256 bits (32 bytes)
- **Storage**: `.branchpy/.cert_secret` (0600 permissions)
- **TTL**: Default 60 minutes (configurable)

### Policy Validation

- JSON Schema validation on load
- Fail-closed on malformed policies
- All decisions logged to audit

### Backward Compatibility

If no policy or team config exists:
- **Policy**: Permissive mode (allow all)
- **Team**: Solo mode (single owner)
- **Audit**: Still emits events for visibility

---

## Troubleshooting

### "Permission denied: audit_write capability required"

**Cause**: Your user UUID is not assigned a role in `team.toml`.

**Solution**:
1. Check your UUID: `branchpy whoami`
2. Add to `team.toml`:
   ```toml
   [assignments]
   "YOUR-UUID-HERE" = "contributor"
   ```

### "Policy violation: Rule NO_FORCE_CONTRIBUTORS"

**Cause**: Your role (contributor) is denied by policy.

**Solution**:
- Remove `--force` flag, or
- Ask team owner to update policy

### "Certificate expired"

**Cause**: Session certificate has exceeded TTL.

**Solution**:
```bash
# Issue new certificate
branchpy team cert issue --ttl 120  # 2 hours
```

---

## Examples

### Example 1: Restrict Force Operations

```json
{
  "id": "NO_FORCE_OPS",
  "description": "Prevent --force flag in production",
  "action_type": "cli_command",
  "conditions": {
    "flags": ["--force"]
  },
  "enforcement": "deny",
  "roles_affected": ["contributor"]
}
```

### Example 2: Warn on Main Branch Push

```json
{
  "id": "WARN_MAIN_PUSH",
  "description": "Warn when pushing to main",
  "action_type": "git_operation",
  "conditions": {
    "operation": "push",
    "branch": "main"
  },
  "enforcement": "warn",
  "roles_affected": []
}
```

### Example 3: Restrict Configuration Edits

```json
{
  "id": "PROTECT_CONFIG",
  "description": "Only owners can edit .branchpy/",
  "action_type": "file_access",
  "conditions": {
    "path": ".branchpy/*",
    "operation": "write"
  },
  "enforcement": "deny",
  "roles_affected": ["contributor", "auditor"]
}
```

---

## Documentation

- **Policy Guide**: [`docs/v0.9.0/Policy/governance-guide.md`](../../docs/v0.9.0/Policy/governance-guide.md)
- **RBAC Reference**: [`docs/v0.9.0/Policy/RBAC.md`](../../docs/v0.9.0/Policy/RBAC.md)
- **Implementation Plan**: [`docs/v0.9.0/Policy/v0.8.6-IMPLEMENTATION-PLAN.md`](../../docs/v0.9.0/Policy/v0.8.6-IMPLEMENTATION-PLAN.md)

---

## Version

**v0.8.6** — Governance Toolkit & Role Policies  
**Released**: TBD  
**Dependencies**: v0.8.1+ (Team Audit Log + RBAC foundations)

---

## License

Part of BranchPy project. See LICENSE for details.
