feat(shared): implement shared data architecture (v3.1.0)

Phase 1: Multi-profile shared data via symlinks

Added:

- SharedManager class for symlink orchestration (bin/shared-manager.js)

- Auto-migration from ~/.claude/ to ~/.ccs/shared/ on first run

- Shared directories: commands/, skills/, agents/

- Windows fallback: copies dirs if symlinks fail

Fixed:

- Migration logic now detects empty directories

- Previously skipped migration when postinstall created empty dirs

- Now properly copies from ~/.claude/ when shared dirs are empty

Changed:

- Instance initialization symlinks to shared dirs instead of copying

- Postinstall creates ~/.ccs/shared/ structure automatically

- All implementations (Node.js, bash, PowerShell) updated for consistency

- Help text includes agents/ in shared data section

Technical:

- Profile-specific data remains isolated (settings, sessions, todolists, logs)

- Migration is idempotent: safe to run multiple times

- Cross-platform symlink support with graceful fallback

Closes #4
This commit is contained in:
kaitranntt committed 2025-11-10 20:45:21 -05:00
1 parent df549ddf4b
commit d925dfc169
15 files changed
+929 -708

No files matched your search

+239
View File
@@ -0,0 +1,239 @@
# Why Session Sharing Fails Across Profiles: Technical Analysis
## Overview
Claude CLI sessions cannot be directly shared across CCS profiles due to authentication architecture constraints. When a user starts a thread on a "work" profile and the account expires, resuming from a "personal" profile fails despite the local session file being present.
**Core Problem**: Thread IDs stored locally, but API-side validation requires matching OAuth credentials. Session "ownership" bound to account that created it, preventing cross-account continuation.
## Technical Architecture: How Claude CLI Sessions Work
### Session Storage Structure
```
~/.claude/
├── .credentials.json # OAuth tokens (access, refresh, expiry)
├── projects/
│ └── <project-hash>/
│ └── <sessionId>.jsonl # Thread conversation history
├── session-env/ # Ephemeral runtime state (empty dirs)
└── todos/ # Task tracking
```
### Session File Format (JSONL)
Each thread stored as newline-delimited JSON:
```jsonl
{"type":"user","sessionId":"<uuid>","message":{"role":"user","content":"..."},"uuid":"<msg-id>","timestamp":"..."}
{"type":"assistant","sessionId":"<uuid>","message":{"role":"assistant","content":[...]},"requestId":"req_...","uuid":"<msg-id>","timestamp":"..."}
```
**Key Fields**:
- `sessionId`: Thread UUID (e.g., `58921318-0aed-4238-b6cb-d0d6222fc095`)
- `message`: User/assistant conversation turns
- `requestId`: API request ID (server-generated, scoped to original auth)
- **No embedded auth tokens**: Credentials stored separately in `.credentials.json`
### OAuth 2.0 Authentication Model
**Credential File** (`~/.claude/.credentials.json`):
```json
{
"claudeAiOauth": {
"accessToken": "sk-ant-oat01-...",
"refreshToken": "sk-ant-ort01-...",
"expiresAt": 1762851849221,
"scopes": ["user:inference", "user:profile"],
"subscriptionType": "max"
}
}
```
**Flow**:
1. User runs `claude --resume <sessionId>`
2. CLI reads `~/.claude/projects/<project>/<sessionId>.jsonl`
3. CLI reconstructs full conversation history
4. CLI submits request to API with OAuth token from `.credentials.json`
5. **API validates token + session ownership (inferred)**
6. API responds (session context maintained client-side only)
### API-Side Validation
Claude API is stateless. "Sessions" are client-side constructs:
- Thread ID alone does NOT authorize continuation
- Each request requires valid OAuth token
- Server likely validates session creator identity (undocumented but inferred from org ID headers)
- No server-side session state tied to thread IDs
## Why Direct Sharing Fails: Core Technical Blockers
| Component | Transferable? | Blocker |
|-----------|--------------|---------|
| Session JSONL file | ✅ Yes | None (plain text) |
| Thread ID (UUID) | ✅ Yes | None (identifier only) |
| Conversation history | ✅ Yes | None (embedded in JSONL) |
| OAuth token | ❌ No | Account-specific, expires |
| API authorization | ❌ No | Server-side session ownership validation |
### OAuth Token Mismatch
- Work profile session created with `work_oauth_token`
- Personal profile uses `personal_oauth_token`
- API rejects requests where token doesn't match session creator (inferred)
### Organization ID Boundaries
Anthropic returns `anthropic-organization-id` header in responses. Sessions may be scoped to:
- User account ID
- Organization ID (for team accounts)
- Subscription tier
Cross-account access would violate organizational isolation.
### Session Ownership Enforcement
No documented API for "transferring" session ownership. Thread ID is identifier, not authorization:
- Like a file path: knowing the path doesn't grant read access
- Requires matching credentials to prove ownership
- No "share session" endpoint exists in Claude API
### Documentation Gaps
- No cross-account access docs in official Claude API documentation
- No session sharing/transfer APIs in CLI or Agent SDK
- Security model not explicitly documented (inferred from OAuth behavior)
## Security Implications: Why This Is By Design
### Risks if Session Sharing Were Possible
| Risk | Impact |
|------|--------|
| Context Leak | Conversation history exposed to unintended accounts |
| Privilege Escalation | Lower-tier account accessing higher-tier sessions |
| Organizational Data Breach | Work conversations leaked to personal accounts |
| Audit Trail Corruption | Session actions attributed to wrong user |
### Current Security Posture
- **Credential Isolation**: OAuth tokens stored per-profile (CCS architecture)
- **POSIX Permissions**: `~/.claude/` readable only by user (`700` permissions)
- **No Session Encryption**: JSONL files plain text (relies on OS security)
- **Profile Separation**: CCS v3.0 login-per-profile prevents credential mixing
### Design Intent
Session isolation prevents:
1. **Cross-account context leakage**: Alice's work threads stay with work account
2. **Subscription boundary violations**: Free account can't "resume" Pro sessions
3. **Organizational data governance**: Company data stays within company accounts
## Alternative Approaches: What Works Instead
### Manual JSONL Copy (Workaround, Not Recommended)
**Process**:
1. Copy session file: `~/.ccs/instances/work/.claude/projects/<project>/<sessionId>.jsonl`
2. Generate new UUID: `new_id=$(uuidgen | tr '[:upper:]' '[:lower:]')`
3. Replace `sessionId` in JSONL: `sed 's/<old_id>/<new_id>/g' file.jsonl > new.jsonl`
4. Place in personal profile: `~/.ccs/instances/personal/.claude/projects/<project>/<new_id>.jsonl`
5. Resume: `ccs personal` → `claude --resume <new_id>`
**Issues**:
- Fragile (breaks if JSONL structure changes)
- No UUID regeneration for `parentUuid`, message `uuid` fields
- Risk of malformed JSON breaking CLI
- Manual process prone to errors
### Context Export/Import (PARTIALLY FEASIBLE, Not Implemented)
**Concept**:
```bash
# Work profile (before expiration)
ccs export-context --session <id> --output work-context.json
# Personal profile (after expiration)
ccs import-context work-context.json --new-session
```
**Process**:
1. **Export**: Read JSONL → extract message history → strip metadata → save portable JSON
2. **Import**: Parse JSON → generate new session UUID → reconstruct JSONL with personal auth context
3. **Resume**: Use new session ID with personal OAuth token
**Advantages**:
- ✅ Preserves conversation history
- ✅ New session = clear ownership (personal account)
- ✅ No cross-account authorization issues
- ✅ Explicit user action (no silent credential sharing)
- ✅ Audit-friendly (new session ID)
**Status**: DEFERRED (not implemented in CCS v3.0)
### User Experience Flow (Proposed)
```
$ ccs export-session 58921318-0aed-4238-b6cb-d0d6222fc095
✓ Exported 47 messages to ~/ccs-export-58921318.json
[Account expires]
$ ccs personal
$ ccs import-session ~/ccs-export-58921318.json
✓ Imported as new thread: a1b2c3d4-5678-9012-3456-789012345678
✓ Resume with: claude --resume a1b2c3d4-5678-9012-3456-789012345678
$ claude --resume a1b2c3d4-5678-9012-3456-789012345678 "Continue from earlier"
[Claude continues with full context under personal auth]
```
## Recommendations: Clear Guidance
### REJECT: Direct Session Sharing
**Do NOT implement**:
- Copying session files between profiles without regeneration
- Reusing thread IDs across accounts
- "Resuming" sessions created by different OAuth tokens
**Reason**: Violates inferred security model; likely fails API-side validation.
### DEFER: Export/Import Feature
**Status**: Feasible but not critical for CCS v3.0.
**Priority**: Phase 3 (post-launch).
**Effort**: Medium (~3-5 days implementation + testing).
**Dependencies**:
- JSONL parsing/reconstruction logic
- UUID generation for new sessions
- Profile-aware file I/O
### Document: Manual Workaround
**For Advanced Users** (FAQ section):
1. Manually copy JSONL file
2. Edit `sessionId` fields (use `jq` or `sed`)
3. Regenerate UUIDs for messages (optional but safer)
4. Place in target profile's `.claude/projects/` directory
5. Resume with `claude --resume <new_id>`
**Warning**: Unsupported; may break with Claude CLI updates.
## Unresolved Questions
1. **Does Claude API enforce server-side session ownership?**
Inferred from OAuth architecture; no official docs confirm. Would require API testing.
2. **What is `~/.claude/session-env/` used for?**
Contains empty UUID directories; possibly ephemeral runtime state. Doesn't affect persistence.
3. **Can malformed JSONL crash Claude CLI?**
Likely yes (JSON parsing errors). Manual editing risky without validation.
4. **What happens if imported session references inaccessible resources?**
E.g., work git repo personal account can't access. Claude will continue but may request clarification.
-418
View File
@@ -1,418 +0,0 @@
# CCS Testing Requirements & Procedures
**Version:** 2.4.4
**Last Updated:** 2025-11-05
**Status:** Active
## Overview
This document outlines the comprehensive testing requirements and procedures for the CCS (Claude Code Switch) project. Following these guidelines ensures consistent, reliable, and cross-platform compatible releases across both npm package and shell installer methods.
## Test Suite Structure
### Core Test Files
| Test Type | Files | Purpose | Coverage | Platforms |
|-----------|-------|---------|----------|-----------|
| **npm Package Tests** | `tests/npm/*.test.js` | npm package functionality | 4 files | Cross-platform |
| **Unit Tests** | `tests/shared/unit/*.test.js` | Core utilities testing | 1 file | Cross-platform |
| **Native Shell Tests** | `tests/native/unix/*.sh` | Shell installer testing | 3 files | Unix/Linux/macOS |
| **Edge Case Tests** | `tests/edge-cases.sh` | Comprehensive edge cases | 1 file | Unix/Linux/macOS |
| **Comprehensive Testing** | `plans/251105-*/` | 5-phase testing framework | 5 phases | Cross-platform |
### Test Categories
#### 1. npm Package Tests (39 tests)
**Files:** `tests/npm/*.test.js`, `tests/shared/unit/*.test.js`
**Coverage Areas:**
- **Installation Testing** (npm global install, postinstall script)
- **Configuration Management** (auto-creation, JSON validation)
- **CLI Functionality** (version, help, profile switching)
- **Error Handling** (invalid profiles, missing configs)
- **Performance Testing** (startup times, memory usage)
- **Cross-Platform Testing** (bash, zsh, different PATH configurations)
#### 2. Shell Installer Tests (57 tests)
**Files:** `tests/native/unix/*.sh`, `tests/edge-cases.sh`
**Coverage Areas:**
- **Installation Process** (curl installer, directory creation)
- **Uninstall Functionality** (complete cleanup, PATH restoration)
- **Shell Script Logic** (jq integration, platform detection)
- **Edge Cases** (partial installs, error scenarios)
- **Configuration Management** (profile handling, file validation)
- **Integration Testing** (Claude CLI connectivity)
#### 3. Comprehensive Cross-Compatibility Testing
**Framework:** 5-Phase Testing (`plans/251105-comprehensive-ccs-testing/`)
**Phases:**
1. **Environment Assessment & Cleanup** (System state validation)
2. **npm Package Testing** (Full npm package validation)
3. **Shell Installer Testing** (Shell method validation)
4. **Cross-Compatibility Testing** (Migration between methods)
5. **Final Cleanup & Validation** (System restoration)
**Key Findings from Latest Testing:**
- npm version: 21ms startup, Node.js based, cross-platform
- Shell version: 5ms startup (4x faster), bash based, Unix-like only
- Configuration: Fully compatible between methods
- Migration: Seamless switching between installation methods
## Testing Environment Requirements
### Environment Variable Isolation
**Critical Requirement:** All tests must use isolated HOME directories to prevent impact on user data.
**Implementation Pattern:**
```bash
# Unix/Linux/macOS
HOME=/tmp/test-ccs-home ./ccs --install
HOME=/tmp/test-ccs-home ./ccs --uninstall
# Windows PowerShell
$env:HOME = "C:\temp\test-ccs-home"
.\ccs.ps1 --install
.\ccs.ps1 --uninstall
```
**Validation Requirements:**
- ✅ Install uses test directory (not `~/.claude`)
- ✅ Uninstall removes files from test directory only
- ✅ Real user directories completely unaffected
- ✅ Perfect test isolation achieved
### Cross-Platform Compatibility
**Platform-Specific Patterns:**
- **Bash Version:** Uses `$HOME/.claude` directly
- **PowerShell Version:** Uses HOME-first pattern with USERPROFILE fallback
**PowerShell Pattern:**
```powershell
$HomeDir = if ($env:HOME) { $env:HOME } else { $env:USERPROFILE }
```
## Test Execution Procedures
### Prerequisites
1. **Clean Test Environment**
```bash
# Remove any existing CCS installation
rm -rf ~/.ccs ~/.local/bin/ccs
```
2. **Required Tools**
- bash 3.2+ (Unix/Linux/macOS)
- PowerShell 5.1+ (Windows)
- Claude CLI 2.0.31+
- jq 1.6+ (optional, for JSON validation)
### Running Tests
#### Unix/Linux/macOS
```bash
# Navigate to CCS directory
cd /path/to/ccs
# Run uninstall tests
./tests/uninstall-test.sh
# Run edge case tests
./tests/edge-cases.sh
# Run all tests (full suite)
./tests/uninstall-test.sh && ./tests/edge-cases.sh
```
#### Windows
```powershell
# Navigate to CCS directory
cd C:\path\to\ccs
# Run uninstall tests
.\tests\uninstall-test.ps1
# Run edge case tests
.\tests\edge-cases.ps1
# Run all tests (full suite)
.\tests\uninstall-test.ps1; .\tests\edge-cases.ps1
```
### Expected Results
**Success Criteria:**
- **Total Test Pass Rate:** 100%
- **Individual Test Suites:** Each must pass 100%
- **Environment Isolation:** No impact on user data
- **Cross-Platform Consistency:** Identical behavior across platforms
**Sample Output:**
```
=== CCS Uninstall Test Results ===
Total Tests: 20
Passed: 20 (100%)
Failed: 0 (0%)
Status: ✅ ALL TESTS PASSED
```
## Quality Assurance Standards
### Code Quality Requirements
1. **Syntax Validation**
```bash
# Bash syntax check
bash -n ccs
bash -n install.sh
bash -n uninstall.sh
# PowerShell syntax check
Get-Command Test-Path -Syntax ccs.ps1
```
2. **Pattern Consistency**
- HOME-first environment variable pattern
- Consistent error handling
- Uniform output formatting
3. **Security Validation**
- No impact on user data
- Proper file permissions
- No unauthorized directory access
### Functional Testing Requirements
1. **Happy Path Testing**
- Standard operations work perfectly
- Default behaviors function as expected
- User workflows complete successfully
2. **Edge Case Handling**
- Robust handling of unexpected inputs
- Graceful failure modes
- Clear error messages with actionable solutions
3. **Integration Testing**
- CLI integration with all commands
- Path operations work correctly
- Environment variable handling is reliable
## Test Coverage Metrics
### Current Coverage (v2.4.5)
| Test Category | Tests | Pass Rate | Status |
|---------------|-------|-----------|--------|
| npm Package Tests | 39 | 100% | ✅ Complete |
| Unit Tests | 3 | 100% | ✅ Complete |
| Shell Installer Tests | 57 | 100% | ✅ Complete |
| Cross-Compatibility Tests | 15 | 100% | ✅ Complete |
| Environment Isolation | 114 | 100% | ✅ Complete |
| **Total Coverage** | **114** | **100%** | **✅ Complete** |
### Coverage Goals for Future Releases
| Metric | Target | Current Status |
|--------|--------|----------------|
| Test Pass Rate | >95% | 100% ✅ |
| Cross-Platform Coverage | 100% | 100% ✅ |
| Edge Case Coverage | >90% | 100% ✅ |
| Environment Isolation | 100% | 100% ✅ |
| Security Validation | 100% | 100% ✅ |
| npm Package Testing | 100% | 100% ✅ |
| Installation Method Compatibility | 100% | 100% ✅ |
## Automated Testing Integration
### CI/CD Pipeline Requirements
**Recommended Integration:**
```yaml
# GitHub Actions example
- name: Run CCS Tests
run: |
npm test
# This runs: npm run test:unit && npm run test:npm
```
**Enhanced Pipeline:**
```yaml
# Comprehensive testing
- name: Environment Assessment
run: ./scripts/clean-test-environment.sh
- name: npm Package Testing
run: npm test
- name: Shell Installer Testing
run: ./tests/native/unix/installer-tests.sh
- name: Cross-Compatibility Testing
run: ./scripts/test-installation-methods.sh
```
**Test Automation Benefits:**
- Consistent test execution across all installation methods
- Early detection of regressions
- Cross-platform validation
- Automated quality gates
- Installation method compatibility verification
### Performance Testing
**Test Execution Benchmarks (Latest Results):**
- **npm Package Tests:** ~45 seconds
- **Shell Installer Tests:** ~60 seconds
- **Cross-Compatibility Tests:** ~90 seconds
- **Total Suite:** ~3-4 minutes (comprehensive 5-phase testing)
- **Memory Usage:** Minimal
- **Disk I/O:** Controlled and temporary
**Performance Comparison:**
- **npm version startup:** 21ms
- **Shell version startup:** 5ms (4x faster)
- **Installation time:** npm (1.5s) vs Shell (3s)
## Test Maintenance Procedures
### When to Update Tests
1. **New Features Added**
- Add corresponding test cases
- Update test documentation
- Validate cross-platform compatibility
2. **Bug Fixes Implemented**
- Add regression tests for fixed bugs
- Verify fix doesn't break existing functionality
- Update test coverage metrics
3. **Platform Changes**
- Test on new platform versions
- Update platform-specific test cases
- Validate compatibility
### Test Review Process
1. **Code Review Integration**
- Tests reviewed alongside code changes
- Ensure test coverage for new functionality
- Validate test quality and effectiveness
2. **Release Validation**
- Full test suite execution before releases
- Cross-platform validation
- Performance benchmarking
## Troubleshooting Test Failures
### Common Issues
1. **Environment Variable Conflicts**
- **Symptom:** Tests affecting user directories
- **Solution:** Verify HOME isolation pattern
- **Prevention:** Always use isolated test environments
2. **Permission Issues**
- **Symptom:** File operation failures
- **Solution:** Check file permissions and paths
- **Prevention:** Validate prerequisites before testing
3. **Platform-Specific Failures**
- **Symptom:** Tests pass on one platform, fail on another
- **Solution:** Review platform-specific code paths
- **Prevention:** Test on all supported platforms
### Debug Procedures
1. **Enable Verbose Output**
```bash
# Add debug flags to test scripts
./tests/uninstall-test.sh --verbose
```
2. **Isolate Failing Tests**
```bash
# Run individual test sections
./tests/uninstall-test.sh --section=empty-uninstall
```
3. **Validate Environment**
```bash
# Check environment variables
echo "HOME: $HOME"
echo "USERPROFILE: $USERPROFILE"
```
## Best Practices
### Test Development Guidelines
1. **Test Isolation**
- Never modify user data during tests
- Use temporary directories for all file operations
- Clean up all test artifacts
2. **Cross-Platform Considerations**
- Test on all supported platforms
- Use platform-agnostic patterns where possible
- Handle platform-specific differences explicitly
3. **Maintainability**
- Clear test documentation
- Consistent test structure
- Reusable test utilities
### Continuous Improvement
1. **Test Coverage Analysis**
- Regular coverage assessment
- Identify untested code paths
- Prioritize high-risk areas
2. **Performance Monitoring**
- Track test execution times
- Identify performance regressions
- Optimize slow test cases
3. **Quality Metrics**
- Monitor test pass rates
- Track bug detection rates
- Measure test effectiveness
## References
### Related Documentation
- **Project Roadmap:** `/docs/project-roadmap.md`
- **Implementation Plans:** `/plans/`
- **Code Standards:** `/docs/code-standards.md`
- **System Architecture:** `/docs/system-architecture.md`
### Test Reports
- **Uninstall Test Report:** `/plans/reports/241103-from-qa-engineer-to-development-team-ccs-uninstall-testing-report.md`
- **Code Review Reports:** `/plans/reports/251103-code-review-phase1-phase2.md`
### External Resources
- **Claude CLI Documentation:** https://docs.anthropic.com/claude/reference/claude-cli
- **PowerShell Best Practices:** https://docs.microsoft.com/en-us/powershell/scripting/dev-cross-plat/writing-portable-cmdlets
---
**Maintained By:** Development Team
**Review Frequency:** After major releases or significant code changes
**Last Updated:** 2025-11-05
**Recent Changes:**
- Added npm package testing framework (39 tests)
- Comprehensive cross-compatibility testing (5-phase framework)
- Updated performance benchmarks and comparisons
- Enhanced CI/CD pipeline recommendations
**Unresolved Questions:** None
**Blockers:** None
**Next Review:** Post v2.4.5 release or after next major code simplification