CC Multi-Agent KI-Orchestrierung
Revolution in der Software-Entwicklung: KI-Assistenten wie Aider, Cline, Gemini CLI und Claude Code sind nicht mehr nur Werkzeuge – sie sind vollwertige Entwicklungspartner.
🚀 Collective Context (CC) für Reproducible OSS Entwicklung
Ein umfassender Guide zur Implementierung eines persistenten Multi-Agent-Systems mit Claude Code, Aider und Gemini CLI für deterministische Android-Entwicklung
Einführung: Die Vision hinter Collective Context
Im 4Q 2025 stehen wir vor einer Revolution in der Software-Entwicklung. KI-Assistenten wie Claude Code, Aider und GitHub Copilot sind nicht mehr nur Werkzeuge – sie sind vollwertige Entwicklungspartner. Doch ein fundamentales Problem bleibt: Kontext-Amnesie. Jede neue Session beginnt bei Null. Wertvolles Projektwissen geht verloren. Die Zusammenarbeit zwischen mehreren KI-Agenten ist chaotisch.
Das Collective Context (CC) Projekt löst dieses Problem durch einen dauerhaften, gemeinsamen Wissensraum für die Zusammenarbeit zwischen Menschen UND zwischen Menschen und KI-Systemen. Unser Ansatz: Markdown-basierte Persistenz, Multi-Agent-Orchestrierung und Reproducible Builds – alles Open Source.
🎯 Unser Ziel: Ein robustes Multi-Agent-System, das nach jedem Reboot automatisch den vollständigen Projektkontext wiederherstellt und dabei deterministischen, reproduzierbaren Code produziert.
Teil 1: Konzept in 10 Teilen
Die Gewinner des CLI-Rennens
Nach umfassender Recherche kristallisierten sich drei Kategorien von CLI-fähigen KI-Tools heraus:
Open-Source-Champions
Aider dominiert mit über 35.200 GitHub-Stars als ausgereiftestes Open-Source-CLI-Tool. Es brilliert durch automatische Git-Integration, unterstützt 100+ Programmiersprachen und arbeitet mit praktisch jedem KI-Modell. Die Installation ist simpel:
npm install -g @anthropic-ai/claude-code@latest
npm install -g @google/gemini-cli
pipx install aider-chat
code --install-extension cline.cline
npm update -g @anthropic-ai/claude-code
npm update -g @google/gemini-cli
nvm install --lts && nvm use --lts
Warum pipx perfekt für Aider ist:
pipx install aider-chat
ist die empfohlene Methode für Aider auf Debian/Ubuntu-Systemen.
✅ Isolierte Installation - keine Konflikte mit System-Python
✅ Automatisches venv - pipx erstellt automatisch eine virtuelle Umgebung
✅ Global verfügbar - trotzdem systemweit als aider
Befehl nutzbar
✅ Einfache Updates - pipx upgrade aider-chat
✅ Saubere Deinstallation - pipx uninstall aider-chat
sudo apt update
sudo apt install pipx
pipx ensurepath
source ~/.bashrc
pipx install aider-chat
pipx ensurepath # pipx PATH automatisch setzen
source ~/.bashrc # .bashrc neu laden
aider --version # Testen ob aider funktioniert
pipx upgrade aider-chat
pipx upgrade-all # Alle pipx-Pakete updaten
Das ist deutlich besser als pip install
(System-Verschmutzung) oder apt install
(oft veraltete Versionen). Du hast damit das beste Setup für Python-CLI-Tools!
Cline (ehemals Claude Dev) explodierte mit 48.000 GitHub-Stars und $32 Millionen Funding. Die Client-seitige Architektur mit BYOK (Bring Your Own Keys) garantiert, dass Code niemals externe Server berührt.
Gemini CLI von Google setzt neue Maßstäbe: 60 Anfragen pro Minute, 1.000 pro Tag – völlig kostenfrei mit einem 1-Million-Token-Kontextfenster.
Kommerzielle Powerhouses
Claude Code von Anthropic bietet die fortschrittlichsten autonomen Fähigkeiten. Mit $60-120/Monat ist es budgetfreundlich für professionelle Entwicklung. Das Tool glänzt bei komplexen Multi-File-Refactorings und projekt-weitem Kontext-Verständnis.
GitHub Copilot CLI bleibt mit 1,5 Millionen aktiven Nutzern Marktführer. Für $10/Monat erhält man unbegrenzte Code-Completions. Studenten und Open-Source-Maintainer erhalten es kostenlos.
Die Realität der KI-Unterstützung
Wo KI glänzt:
- Boilerplate-Generierung (35-40% Zeitersparnis)
- Dokumentation und Test-Erstellung (25-30% Produktivitätssteigerung)
- Syntax-Konvertierung zwischen Sprachen
Wo KI versagt:
- Komplexe Legacy-Codebasen
- Architektur-Entscheidungen
- Debugging subtiler Bugs
- Security-Checks notwendig, damit KI-generierter Code keine Sicherheitslücken enthält.
Teil 2: Die Collective Context Architektur
Was wir bereits haben ✅
# Unsere aktuelle tmux-Struktur
tmux new-session -d -s claude-1 -n "Claude-Primary"
tmux new-session -d -s claude-2 -n "Claude-Secondary"
tmux new-session -d -s aider-1 -n "Aider-Assistant"
💡 Info-Box: Claude Code ist aktuell unser Hauptwerkzeug! Mit $60-120/Monat reicht das Budget für 2 parallele Claude-Instanzen mit je ~500-1000 Interaktionen/Monat. Das ist optimal für komplexe Entwicklungsaufgaben.
🏗️ Beginne nicht mit einem zu komplexen Plan
MCP-Agent + Claude Squad + APScheduler + TmuxAI + Basic Memory + ...
Kritische Probleme:
- Race Conditions bei gleichzeitigen .md-Schreibzugriffen
- Fehlende Transaktionalität
- Zu viele bewegliche Teile für den Start
Die verbesserte Kaizen-Architektur
Stattdessen empfehlen wir eine 5-Phasen-Strategie:
┌─────────────────────────────────────────────┐
│ Orchestrator Layer │
│ (Python + APScheduler + Watchdog) │
└┬────────┬──────────┬───────────┬────────────┘
│ │ │ │
│ ┌────▼───┐ ┌───▼────┐ ┌───▼───┐
│ │Claude-1│ │Claude-2│ │Aider-1│
│ └────┬───┘ └───┬────┘ └───┬───┘
│ │ │ │
│ ┌────▼──────────▼───────────▼─────┐
│ │ Shared Memory (.md files) │
└───│ /collective_context/memory/ │
└─────────────────────────────────┘
Ein Beispiel als absolutes Minimum: Ein einzelnes Python-Script, das Claude-Code oder Aider mit einer Markdown-Datei verbindet.
# cc_mvp.py - Der kleinste funktionierende Prototyp
import subprocess
import frontmatter
from pathlib import Path
def execute_aider_task(task_file):
with open(task_file) as f:
post = frontmatter.load(f)
if post['status'] == 'pending':
result = subprocess.run(
['aider', '--message', post.content],
capture_output=True
)
post['status'] = 'completed'
post['result'] = result.stdout.decode()
with open(task_file, 'w') as f:
f.write(frontmatter.dumps(post))
# Basis-Loop
Path('./tasks').mkdir(exist_ok=True)
for task in Path('./tasks').glob('*.md'):
execute_aider_task(task)
Ein Python-Script, das Claude-Code oder Aider mit einer Markdown-Datei verbindet.
Teil 3: Das Complete Setup Script
Installation aller Komponenten
Sofort-Setup für Debian 12/13 🐧
#!/bin/bash
# cc_foundation_setup.sh - Phase 0 Setup Script
# System-Vorbereitung
sudo apt-get update && sudo apt-get upgrade -y
sudo apt-get install -y \
tmux git python3-pip python3-venv \
inotify-tools sqlite3 jq curl
# Python-Umgebung
python3 -m venv ~/cc_env
source ~/cc_env/bin/activate
# Basis-Pakete
pip install --upgrade pip
pip install \
python-frontmatter \
watchdog \
libtmux \
pyyaml \
rich # Für schönes Terminal-Output 😊
# Verzeichnisstruktur
mkdir -p ~/collective_context/{
memory/agents,
memory/sessions,
memory/shared,
memory/tasks,
config,
logs,
scripts
}
# Git-Repository (mit Signierung!)
cd ~/collective_context
git init
git config user.name "CC Bot"
git config user.email "cc@localhost"
# Initial Memory Files
cat > memory/shared/context.md << 'EOF'
---
project: collective_context
version: 0.1.0
agents: ["claude-1", "claude-2", "aider-1"]
last_sync: null
---
# Collective Context - Shared Knowledge Base
## Active Development Tasks
- [ ] Setup Multi-Agent Orchestration
- [ ] Implement Memory Persistence
- [ ] Configure Auto-Recovery
## Project Guidelines
1. All changes must be documented
2. Every agent maintains its own state file
3. Coordination happens via shared/context.md
EOF
echo "✅ Foundation Setup Complete!"
🎯 Folgendes Setup-Script enthält Android-spezifische Konfigurationen für die osCASH.me APP und Beschreibungen aller Tools.
📱 Android Development Environment
- Android SDK, Build Tools, Gradle
- APKTool, Bundletool, Diffoscope für Reproducible Builds
- F-Droid Build Tools Integration
- Verification Scripts für APK-Reproducibility
API Keys müssen nach der Installation eingetragen werden:bash
echo "export ANTHROPIC_API_KEY='sk-ant-...'" >> ~/.bashrc
echo "export GOOGLE_API_KEY='AIza...'" >> ~/.bashrc
source ~/.bashrc
📚 Detaillierte Tool-Beschreibungen mit Links
- Aufgabe: Was macht das Tool?
- Warum im CC: Warum brauchen wir es?
- Links: GitHub, Homepage, Dokumentation 🚀
Wichtig:
- Start-Script (
start_agents.sh
) startet automatisch alle 3 tmux Sessions + Orchestrator - Systemd Service für Auto-Start nach Reboot ist vorbereitet
🤖 Android-spezifischer Orchestrator
Ein spezieller orchestrator_android.py
der:
- Gradle Tasks automatisiert
- Reproducible Builds verifiziert
- Test Coverage tracked
- APK-Hashes vergleicht
🔐 Reproducible Build Verification
scripts/verify_reproducible_build.sh
Dieses Script:
- Extrahiert zwei APKs
- Entfernt Signaturen
- Vergleicht Byte-für-Byte
- Generiert Diffoscope-Report bei Unterschieden
📝 Android Context für Agents
memory/shared/android_context.md
enthält:
- Projekt-Architektur (MVVM, Jetpack Compose)
- Code-Style Guidelines
- Testing Requirements (80% Coverage)
- Security Considerations
Besondere Features für osCASH:
1. Deterministische Builds
reproducible:
enabled: true
source_date_epoch: 1704067200 # Fixed timestamp
timezone: UTC
strip_timestamps: true
strip_ai_comments: true # Entfernt "Generated by Claude"
2. Multi-Agent Android Workflow
- Claude-1: Hauptentwicklung (Kotlin, Compose)
- Claude-2: Code Review & Security Audit
- Aider: Refactoring & Documentation
- Gradle: Continuous Build Monitoring
3. F-Droid Kompatibilität
Das Setup enthält F-Droid Build Tools für die Integration in den F-Droid Store - wichtig für Open Source Android Apps!
Start-Kommandos für osCASH:
# 1. Repository clonen
git clone https://github.com/osCASHme/osCASH-android.git ~/osCASH-android
# 2. Agents starten
cd ~/collective_context
./start_android_agents.sh
# 3. Build verifizieren
cd ~/osCASH-android
./gradlew assembleRelease
# 4. Reproducibility prüfen
~/collective_context/scripts/verify_reproducible_build.sh \
app-release-1.apk app-release-2.apk
Phase 1: System-Vorbereitung & Android Tools
# Update System
sudo apt-get update && sudo apt-get upgrade -y
# Basis-Pakete + Android Development Dependencies
sudo apt-get install -y \
curl wget git build-essential \
tmux jq sqlite3 inotify-tools \
python3 python3-pip python3-venv pipx \
npm nodejs \
openjdk-17-jdk gradle android-sdk \
adb fastboot aapt zipalign apksigner
# Android SDK Environment Variables
cat >> ~/.bashrc << 'EOF'
export ANDROID_HOME=/usr/lib/android-sdk
export ANDROID_SDK_ROOT=$ANDROID_HOME
export PATH=$PATH:$ANDROID_HOME/platform-tools
export SOURCE_DATE_EPOCH=1704067200 # Fixed for reproducible builds
export TZ=UTC
EOF
Phase 2: Tmux Konfiguration
Tmux orchestriert unsere Multi-Agent-Sessions:
cat > ~/.tmux.conf << 'EOF'
# Collective Context Tmux Configuration
set -g mouse on
set-option -g prefix C-a
bind | split-window -h
bind - split-window -v
# Status bar mit Agent-Status
set -g status-bg black
set -g status-fg white
set -g status-left '#[fg=green][CC] #S '
set -g status-right '#[fg=yellow]Claude-1 Claude-2 Aider #[fg=white]%H:%M'
set -g history-limit 50000
EOF
Phase 3: Claude Code Installation
Claude Code ist unser Hauptentwickler:
# Node.js 20 für Claude Code
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
# Claude Code Installation
npm install -g @anthropic/claude-code
# oder
sudo dpkg -i claude-code-linux-amd64.deb
# Konfiguration für deterministische Outputs
mkdir -p ~/.claude-code
cat > ~/.claude-code/config.json << 'EOF'
{
"model": "claude-3-opus-20240229",
"temperature": 0.1,
"deterministic": true,
"reproducible_builds": true,
"android_development": {
"sdk_path": "/usr/lib/android-sdk",
"target_sdk": 34,
"min_sdk": 21
}
}
EOF
Phase 4: Aider Installation
Aider für Git-aware Pair Programming:
# Saubere Installation via pipx
pipx install aider-chat
# Konfiguration für Reproducible Builds
mkdir -p ~/.aider
cat > ~/.aider/aider.conf.yml << 'EOF'
model: claude-3-opus-20240229
auto-commits: false # Wichtig für Reproducible Builds!
no-random: true
no-timestamp: true
max-tokens: 100000
# File watching für CC memory
watch: true
watch-files:
- "memory/shared/*.md"
- "memory/tasks/*.md"
EOF
Phase 5: Cline & Gemini CLI
# Cline (VS Code Extension)
code --install-extension cline.cline
# CLI Wrapper für Cline
cat > ~/.local/bin/cline-cli << 'EOF'
#!/bin/bash
PROJECT_PATH=${1:-$(pwd)}
code --new-window "$PROJECT_PATH" --command "cline.focus"
EOF
chmod +x ~/.local/bin/cline-cli
# Gemini CLI (Kostenlos!)
npm install -g @google/gemini-cli
# Gemini Konfiguration
mkdir -p ~/.gemini
cat > ~/.gemini/config.json << 'EOF'
{
"model": "gemini-2.5-pro",
"temperature": 0.1,
"max_tokens": 1000000,
"deterministic_mode": true
}
EOF
Phase 6: Python Environment
# Virtual Environment
python3 -m venv ~/cc_env
source ~/cc_env/bin/activate
# Orchestrierungs-Tools
pip install \
python-frontmatter \
watchdog \
libtmux \
pyyaml \
rich \
apscheduler \
gitpython \
androguard
Teil 4: Der Orchestrator - Herzstück des Systems
Hauptorchestrator
#!/usr/bin/env python3
# orchestrator.py - Der zentrale Koordinator
import asyncio
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import frontmatter
import libtmux
from pathlib import Path
from datetime import datetime
import json
from rich.console import Console
console = Console()
class CollectiveContextOrchestrator:
"""🎭 Der Dirigent des Multi-Agent-Orchesters"""
def __init__(self):
self.server = libtmux.Server()
self.memory_path = Path.home() / 'collective_context/memory'
self.agents = {
'claude-1': {'session': 'claude-1', 'role': 'developer', 'status': 'idle'},
'claude-2': {'session': 'claude-2', 'role': 'reviewer', 'status': 'idle'},
'aider-1': {'session': 'aider-1', 'role': 'assistant', 'status': 'idle'}
}
async def start(self):
"""🚀 Hauptloop des Orchestrators"""
console.print("[bold green]🎭 Collective Context Starting...[/]")
await self.initialize_all_agents()
self.start_file_watcher()
while True:
await self.orchestration_cycle()
await asyncio.sleep(5)
async def initialize_all_agents(self):
"""📚 Lädt komplettes Projektwissen in alle Agenten"""
# Sammle Context-Dateien
context_files = list(self.memory_path.glob('**/*.md'))
init_package = {
'timestamp': datetime.now().isoformat(),
'project_context': self.build_project_context(),
'active_tasks': self.get_active_tasks(),
'agent_roles': self.agents
}
# Initialisiere alle Agenten
self.init_claude_session('claude-1', 'primary')
self.init_claude_session('claude-2', 'reviewer')
self.init_aider_session()
def init_claude_session(self, session_name, role):
"""🤖 Claude-Session mit Context initialisieren"""
session = self.server.new_session(session_name)
pane = session.attached_pane
init_cmd = f'''claude-code \\
--context-file {self.memory_path}/shared/init.json \\
--memory {self.memory_path}/agents/{session_name}_state.md \\
--role {role} \\
--deterministic-mode'''
pane.send_keys(init_cmd)
Session Manager für Claude
#!/usr/bin/env python3
# claude_session_manager.py
class ClaudeSessionManager:
def __init__(self):
self.server = libtmux.Server()
self.memory_path = Path.home() / 'collective_context/memory'
def initialize_claude_instances(self):
"""Startet beide Claude-Instanzen mit vollem Kontext"""
context = self.load_project_context()
# Claude-1: Primary Developer
session1 = self.server.new_session('claude-1')
pane1 = session1.attached_pane
pane1.send_keys(f'''
claude-code \\
--project-context "{context['project_root']}" \\
--memory-file "{self.memory_path}/agents/claude-1_state.md" \\
--role "primary-developer"
''')
# Claude-2: Code Reviewer
session2 = self.server.new_session('claude-2')
pane2 = session2.attached_pane
pane2.send_keys(f'''
claude-code \\
--project-context "{context['project_root']}" \\
--memory-file "{self.memory_path}/agents/claude-2_state.md" \\
--role "reviewer-tester"
''')
Teil 5: Reproducible Builds für Android
Das Problem mit KI-generierten Commits
# ❌ PROBLEM: Diese Commits zerstören Reproducibility
commit abc123...
Author: Developer <dev@example.com>
Co-Authored-By: Claude <noreply@anthropic.com> # Non-deterministic!
Die Lösung: Deterministischer Commit-Wrapper
#!/usr/bin/env python3
# scripts/deterministic_commit.py
import subprocess
import re
import hashlib
def sanitize_claude_output(code_content):
"""Entfernt Claude-spezifische Metadaten für Reproducibility"""
patterns = [
r'# Generated with Claude Code.*\n',
r'# Co-Authored-By: Claude.*\n',
r'/\* AI-Generated:.*\*/'
]
clean_code = code_content
for pattern in patterns:
clean_code = re.sub(pattern, '', clean_code)
# Deterministischer Header
header = f"""# Collective Context Build
# Version: {get_deterministic_version()}
# Hash: {hashlib.sha256(clean_code.encode()).hexdigest()[:8]}
# Reproducible: true
"""
return header + clean_code
def commit_with_verification(files, message):
"""Commit mit Reproducibility-Garantie"""
for file in files:
with open(file, 'r') as f:
content = f.read()
clean_content = sanitize_claude_output(content)
with open(file, 'w') as f:
f.write(clean_content)
subprocess.run([
'git', 'commit',
'--author="CC System <system@collective-context.local>"',
'--date="2025-01-01 00:00:00 +0000"', # Fixiertes Datum
'-m', f'[CC-AUTO] {message}'
])
# GPG-Signierung
subprocess.run(['git', 'commit', '--amend', '--no-edit', '-S'])
Reproducible Build Manager
#!/usr/bin/env python3
# scripts/reproducible_build_manager.py
import hashlib
import json
from pathlib import Path
import subprocess
from datetime import datetime, timezone
class ReproducibleBuildManager:
"""
🔐 Garantiert deterministische Builds trotz KI-Unterstützung
"""
def __init__(self):
self.manifest_path = Path('build_manifest.json')
self.build_cache = Path('.build_cache/')
self.build_cache.mkdir(exist_ok=True)
def create_build_manifest(self, version):
"""📝 Erstellt ein vollständiges Build-Manifest"""
manifest = {
'version': version,
'timestamp': '2025-01-01T00:00:00Z', # Fixiert!
'environment': {
'os': 'debian:12',
'python': '3.11.2',
'node': '18.19.0',
'java': '17.0.10'
},
'ai_models': {
'claude': 'claude-3-opus-20240229',
'aider': '0.42.0',
'seed': 42,
'temperature': 0.1 # Niedrig für Determinismus
},
'source_hashes': self.calculate_source_hashes(),
'dependencies': self.lock_dependencies(),
'build_commands': [
'export SOURCE_DATE_EPOCH=1704067200', # 1.1.2024
'export TZ=UTC',
'./gradlew clean assembleRelease',
'strip --strip-all build/outputs/apk/release/*.apk'
],
'expected_hash': None # Wird nach Build gefüllt
}
# Speichere Manifest
with open(self.manifest_path, 'w') as f:
json.dump(manifest, f, indent=2, sort_keys=True)
return manifest
def verify_reproducibility(self, apk_path):
"""✅ Verifiziert, dass Build reproduzierbar ist"""
# Berechne APK-Hash
apk_hash = self.calculate_file_hash(apk_path)
# Lade Manifest
with open(self.manifest_path) as f:
manifest = json.load(f)
if manifest.get('expected_hash'):
if apk_hash == manifest['expected_hash']:
print("✅ Build ist reproduzierbar!")
return True
else:
print(f"❌ Hash mismatch!")
print(f"Expected: {manifest['expected_hash']}")
print(f"Got: {apk_hash}")
return False
else:
# Erster Build - speichere Hash
manifest['expected_hash'] = apk_hash
with open(self.manifest_path, 'w') as f:
json.dump(manifest, f, indent=2, sort_keys=True)
print(f"📝 Initial build hash: {apk_hash}")
return True
def sanitize_ai_generated_code(self, file_path):
"""🧹 Entfernt nicht-deterministische KI-Artefakte"""
with open(file_path, 'r') as f:
content = f.read()
# Entferne KI-Signaturen
import re
patterns = [
r'//\s*Generated by.*\n',
r'//\s*Co-Authored-By:.*\n',
r'/\*\s*AI-Generated.*?\*/',
r'#\s*Created with Claude.*\n'
]
for pattern in patterns:
content = re.sub(pattern, '', content, flags=re.MULTILINE | re.DOTALL)
# Füge deterministischen Header hinzu
header = f"""/*
* Collective Context Build System
* Reproducible: true
* Manifest: {self.manifest_path}
*/
"""
with open(file_path, 'w') as f:
f.write(header + content)
def calculate_file_hash(self, file_path):
"""🔢 Berechnet SHA256-Hash einer Datei"""
sha256_hash = hashlib.sha256()
with open(file_path, 'rb') as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
# Integration in Build-Prozess
if __name__ == "__main__":
manager = ReproducibleBuildManager()
# Vor dem Build: Säubere alle Dateien
for java_file in Path('src').rglob('*.java'):
manager.sanitize_ai_generated_code(java_file)
# Erstelle Manifest
manifest = manager.create_build_manifest('7.53.5-14-dev')
# Führe Build aus
subprocess.run(['./gradlew', 'clean', 'assembleRelease'])
# Verifiziere
apk_path = Path('build/outputs/apk/release/osCASH-release.apk')
if manager.verify_reproducibility(apk_path):
print("🎉 Build erfolgreich und reproduzierbar!")
APK Verification Script
#!/bin/bash
# verify_reproducible_build.sh
APK1=$1
APK2=$2
echo "🔍 Verifying APK reproducibility..."
# Extract APKs
mkdir -p /tmp/apk_compare/{1,2}
apktool d -f -o /tmp/apk_compare/1 $APK1
apktool d -f -o /tmp/apk_compare/2 $APK2
# Remove signatures
rm -rf /tmp/apk_compare/1/META-INF
rm -rf /tmp/apk_compare/2/META-INF
# Compare
if diff -r /tmp/apk_compare/1 /tmp/apk_compare/2; then
echo "✅ APKs are reproducible!"
else
echo "❌ APKs differ!"
diffoscope $APK1 $APK2 --html /tmp/apk_diff.html
fi
Teil 6: Android-spezifischer Orchestrator
Android Orchestrator für osCASH
#!/usr/bin/env python3
# orchestrator_android.py
class AndroidOrchestrator:
"""🤖 Android-spezifischer Orchestrator für osCASH"""
def __init__(self):
self.config = self.load_android_config()
self.project_path = Path.home() / "osCASH-android"
async def run_gradle_task(self, task):
"""🔨 Führt Gradle-Task aus"""
# Environment für reproducible builds
env = os.environ.copy()
env['SOURCE_DATE_EPOCH'] = '1704067200'
env['TZ'] = 'UTC'
cmd = f"cd {self.project_path} && ./gradlew {task}"
process = await asyncio.create_subprocess_shell(
cmd, env=env,
stdout=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
return stdout.decode() if process.returncode == 0 else None
async def verify_reproducible_build(self):
"""🔐 Verifiziert Reproducible Build"""
# Build twice
await self.run_gradle_task("clean")
apk1 = await self.run_gradle_task("assembleRelease")
await self.run_gradle_task("clean")
apk2 = await self.run_gradle_task("assembleRelease")
# Compare APKs
result = subprocess.run([
'scripts/verify_reproducible_build.sh',
f'{self.project_path}/app/build/outputs/apk/release/app-1.apk',
f'{self.project_path}/app/build/outputs/apk/release/app-2.apk'
])
if result.returncode == 0:
console.print("[green]✅ Build is reproducible![/]")
Android Configuration
# config/android_config.yml
project:
name: osCASH
package: com.oscash.android
repo: https://github.com/osCASHme/osCASH-android
build:
gradle_version: 8.2.0
kotlin_version: 1.9.22
compile_sdk: 34
target_sdk: 34
min_sdk: 21
reproducible:
enabled: true
source_date_epoch: 1704067200
timezone: UTC
strip_timestamps: true
strip_ai_comments: true
deterministic_seed: 42
testing:
unit_test_runner: junit
min_coverage: 80
Teil 7: Memory System und Persistenz
Shared Context Structure
---
project: osCASH Android
version: 7.53.5-14-dev
repository: https://github.com/osCASHme/osCASH-android
build_type: reproducible
agents:
- claude-1: primary_developer
- claude-2: code_reviewer
- aider-1: refactoring_assistant
---
# osCASH Android Development Context
## Architecture
- **Language**: Kotlin
- **Pattern**: MVVM
- **UI**: Jetpack Compose
- **Database**: Room
- **Network**: Retrofit
## Reproducible Build Requirements
1. All builds must be deterministic
2. No timestamps in generated code
3. No AI attributions in commits
4. SOURCE_DATE_EPOCH = 1704067200
5. All dependencies version-locked
## Current Tasks
- [ ] Implement privacy-focused transaction logging
- [ ] Add reproducible build verification
- [ ] Integrate with F-Droid repository
File Watcher für Synchronisation
# File Watcher für .md Updates
class MemoryWatcher(FileSystemEventHandler):
def __init__(self, orchestrator):
self.orchestrator = orchestrator
def on_modified(self, event):
if event.src_path.endswith('.md'):
console.print(f"[yellow]📝 Memory update: {event.src_path}[/]")
asyncio.create_task(self.orchestrator.sync_agent_memories())
# Observer starten
observer = Observer()
observer.schedule(MemoryWatcher(), './shared_context', recursive=True)
observer.start()
Teil 8: Automatisierung und Recovery
Auto-Start Script
#!/bin/bash
# start_android_agents.sh
echo "🚀 Starting Collective Context for osCASH Android..."
# Android Environment
export ANDROID_HOME=/usr/lib/android-sdk
export PATH=$PATH:$ANDROID_HOME/platform-tools
# Claude Session 1 - Primary Developer
tmux new-session -d -s claude-1 -n "Claude-Dev"
tmux send-keys -t claude-1 "cd ~/osCASH-android" C-m
tmux send-keys -t claude-1 "claude-code --context memory/shared/android_context.md" C-m
# Claude Session 2 - Code Reviewer
tmux new-session -d -s claude-2 -n "Claude-Review"
tmux send-keys -t claude-2 "cd ~/osCASH-android" C-m
tmux send-keys -t claude-2 "claude-code --review-mode" C-m
# Aider Session
tmux new-session -d -s aider-1 -n "Aider"
tmux send-keys -t aider-1 "cd ~/osCASH-android" C-m
tmux send-keys -t aider-1 "aider --watch" C-m
# Orchestrator
tmux new-session -d -s orchestrator -n "Orchestrator"
tmux send-keys -t orchestrator "python orchestrator_android.py" C-m
echo "✅ All agents started!"
Systemd Service
# /etc/systemd/system/collective-context-android.service
[Unit]
Description=Collective Context for osCASH Android
After=network.target
[Service]
Type=forking
User=developer
WorkingDirectory=/home/developer/collective_context
Environment="ANDROID_HOME=/usr/lib/android-sdk"
ExecStart=/home/developer/collective_context/start_android_agents.sh
ExecStop=/usr/bin/tmux kill-server
Restart=on-failure
RestartSec=10
[Install]
WantedBy=multi-user.target
Auto-Recovery System
#!/usr/bin/env python3
# auto_recovery.py
class AutoRecoverySystem:
"""🚑 Automatische Wiederherstellung nach Crashes"""
def create_checkpoint(self):
"""💾 Erstellt Recovery-Checkpoint"""
checkpoint = {
'timestamp': datetime.now().isoformat(),
'agents_state': self.capture_all_agent_states(),
'memory_snapshot': self.create_memory_snapshot(),
'active_tasks': self.get_active_tasks()
}
checkpoint_file = f"checkpoint_{datetime.now():%Y%m%d_%H%M%S}.json"
with open(checkpoint_file, 'w') as f:
json.dump(checkpoint, f, indent=2)
def recover_from_crash(self):
"""🔄 Stellt System vom letzten Checkpoint wieder her"""
checkpoints = sorted(Path('checkpoints/').glob('checkpoint_*.json'))
latest = checkpoints[-1]
with open(latest) as f:
checkpoint = json.load(f)
# Restore Memory
self.restore_memory_snapshot(checkpoint['memory_snapshot'])
# Restart Agents
for agent_name, state in checkpoint['agents_state'].items():
self.restore_agent_state(agent_name, state)
console.print("[green]✅ Recovery complete![/]")
Teil 9: Performance Monitoring
Dashboard mit Rich
#!/usr/bin/env python3
# performance_monitor.py
from rich.layout import Layout
from rich.live import Live
from rich.panel import Panel
import psutil
class PerformanceMonitor:
"""📊 Real-time Performance Dashboard"""
def create_layout(self):
layout = Layout()
layout.split_column(
Layout(name="header", size=3),
Layout(name="body"),
Layout(name="footer", size=3)
)
layout["body"].split_row(
Layout(name="agents"),
Layout(name="memory"),
Layout(name="tasks")
)
return layout
def update_display(self):
# Agents Status
agents_info = f"""
Claude-1: 🔨 Working
Claude-2: 👀 Reviewing
Aider-1: 😴 Idle
"""
self.layout["agents"].update(Panel(agents_info, title="Agents"))
# Memory Usage
memory_info = f"""
System RAM: {psutil.virtual_memory().percent}%
CC Memory: {self.get_cc_memory_usage()} MB
Git Repo: {self.get_git_size()} MB
"""
self.layout["memory"].update(Panel(memory_info, title="Memory"))
# Tasks
tasks_info = f"""
Pending: {self.count_pending_tasks()}
Active: {self.count_active_tasks()}
Completed: {self.count_completed_tasks()}
Success Rate: {self.calculate_success_rate()}%
"""
self.layout["tasks"].update(Panel(tasks_info, title="Tasks"))
KPI Tracking
# kpi_tracker.py
class KPITracker:
"""📈 Misst Erfolgsmetriken"""
TARGETS = {
'time_to_first_task': 300, # 5 Minuten
'mtbf': 86400, # 24 Stunden
'context_retention': 0.95, # 95%
'memory_growth': 1048576, # 1MB/Tag
'task_success_rate': 0.90 # 90%
}
def calculate_metrics(self):
metrics = {
'time_to_first_task': self.measure_ttft(),
'mtbf': self.calculate_mtbf(),
'context_retention': self.measure_retention(),
'memory_growth': self.calculate_memory_growth(),
'task_success_rate': self.calculate_success_rate()
}
for metric, value in metrics.items():
target = self.TARGETS[metric]
status = "✅" if value >= target else "⚠️"
console.print(f"{metric}: {value} {status}")
Teil 10: Git Hooks und Security
Pre-Commit Hook
#!/bin/bash
# .git/hooks/pre-commit
# Verhindere AI-Attribution in Commits
if git diff --cached | grep -E "(Co-Authored-By: Claude|Generated with Claude Code)"; then
echo "❌ ERROR: AI attributions found!"
echo "Run: python scripts/sanitize_ai_code.py"
exit 1
fi
# Prüfe auf Secrets
if git diff --cached | grep -E "(sk-[a-zA-Z0-9]{48}|PRIVATE KEY|password\s*=)"; then
echo "❌ ERROR: Potential secrets detected!"
exit 1
fi
# Update Build Manifest
python scripts/reproducible_build_manager.py --update-manifest
echo "✅ Pre-commit checks passed"
Security Considerations
# security_manager.py
class SecurityManager:
"""🔒 Security und Compliance"""
def scan_for_vulnerabilities(self):
"""Scannt generierten Code auf Vulnerabilities"""
patterns = [
r'eval\(', # Code Injection
r'exec\(', # Code Execution
r'subprocess\..*shell=True', # Shell Injection
r'pickle\.loads', # Deserialization
r'yaml\.load\(', # YAML Bomb
]
for file in Path('.').rglob('*.py'):
content = file.read_text()
for pattern in patterns:
if re.search(pattern, content):
console.print(f"[red]⚠️ Vulnerability in {file}: {pattern}[/]")
def verify_licenses(self):
"""Prüft Lizenzen für Open Source Compliance"""
allowed_licenses = [
'MIT', 'Apache-2.0', 'GPL-3.0',
'BSD-3-Clause', 'ISC'
]
# Check dependencies
with open('requirements.txt') as f:
for line in f:
package = line.strip()
license = self.get_package_license(package)
if license not in allowed_licenses:
console.print(f"[yellow]⚠️ {package}: {license}[/]")
Best Practices und Learnings
Die wichtigsten Erkenntnisse
- Start Simple: Ein funktionierender 20-Zeilen-Prototyp ist besser als eine theoretisch elegante Komplettlösung
- Kaizen-Approach: Jede Woche eine kleine, messbare Verbesserung
- Determinismus von Anfang an: Reproducible Builds nachträglich hinzuzufügen ist exponentiell schwieriger
- Event-Driven > Polling: Redis Pub/Sub oder ZeroMQ statt File-Watching für Skalierbarkeit
- Write-Ahead-Log Pattern: Verhindert Race Conditions bei konkurrierenden Schreibzugriffen
Kritische Risiken und Mitigationen
Risiko | Wahrscheinlichkeit | Impact | Mitigation |
---|---|---|---|
Race Conditions bei .md-Writes | Hoch | Kritisch | WAL + File Locks |
Memory-Explosion | Mittel | Hoch | Rotation + Compression |
Agent-Deadlocks | Mittel | Kritisch | Timeout + Health Checks |
API-Rate-Limits | Hoch | Mittel | Queue + Backoff |
Prompt-Injection via .md | Niedrig | Kritisch | Input Validation |
Alternative Architekturen
Message-Queue-First Ansatz:
[Aider] → [NATS] → [Orchestrator] → [NATS] → [Claude]
↓ ↓
[Memory] [Scheduler]
Vorteile:
- Guaranteed Message Delivery
- Natural Load Balancing
- Built-in Persistence
- Einfaches Debugging via Message-Trace
Quick Start Guide
Tag 1: Setup & Erste Tests
# 01 - System Setup
git clone https://github.com/recodeat/collective-context.git
cd collective-context
./scripts/cc_foundation_setup.sh
# 02 - Claude Sessions starten
tmux new-session -d -s claude-1
tmux new-session -d -s claude-2
tmux new-session -d -s aider-1
# 03 - Orchestrator aktivieren
source ~/cc_env/bin/activate
python orchestrator.py &
# 04 - Erste Task erstellen
cat > memory/tasks/task_001.md << EOF
---
id: task_001
priority: high
assigned_to: claude-1
status: pending
---
# Implement User Authentication
Create secure JWT-based auth module
EOF
# 05 - Monitoring starten
python scripts/performance_monitor.py
# 06 - Checkpoint erstellen
python scripts/auto_recovery.py --create-checkpoint
# 07 - Ergebnisse reviewen
cat memory/agents/claude1_state.md
git log --oneline
Tool-Übersicht mit Links
Infrastructure
- Tmux: Terminal-Multiplexer für parallele Sessions
AI Agents
- Claude Code: Anthropics autonomer Coding Agent ($60-120/Monat)
- Aider: Git-aware AI Pair Programming
- GitHub: https://github.com/Aider-AI/aider
- Homepage: https://aider.chat
- Docs: https://aider.chat/docs/
- Cline: Open Source AI Coding Agent (ehemals Claude-Dev)
- GitHub: https://github.com/cline/cline
- Homepage: https://cline.bot
- VS Code: https://marketplace.visualstudio.com/cline
- Gemini CLI: Googles kostenlose KI (1M Token Context!)
Python Tools
- libtmux: Python API für tmux
- watchdog: File system monitoring
- APScheduler: Cron-like scheduling
- Rich: Beautiful terminal formatting
Android Tools
- APKTool: APK reverse engineering
- Bundletool: Android App Bundle manipulation
- Diffoscope: Reproducibility verification
- Homepage: https://diffoscope.org
- F-Droid: Open Source App Store
Zusammenfassung und Ausblick
Das Collective Context System löst die fundamentalen Probleme der KI-unterstützten Entwicklung:
✅ Persistenter Kontext über Session-Grenzen hinweg ✅ Multi-Agent-Koordination ohne Race Conditions ✅ Reproducible Builds trotz KI-generiertem Code ✅ Auto-Recovery nach Crashes und Reboots ✅ Budget-Optimierung durch Mix aus kostenlosen und bezahlten Tools
Mit diesem Setup könnt ihr:
- 3 KI-Agenten parallel orchestrieren
- 100% reproduzierbare Android-APKs erstellen
- Automatisch nach Reboots wiederherstellen
- Unter 100€/Monat professionell entwickeln
Die Zukunft
Die nächsten Schritte für das CC-Projekt:
- Plugin-System für einfache Erweiterbarkeit
- Web-Dashboard für Remote-Monitoring
- Multi-Projekt-Support für parallele Entwicklung
- Community-Templates für verschiedene Tech-Stacks
Schlusswort
"Der Weg ist das Ziel. Möge euer Code stets reproduzierbar sein!" 🕉️
Das Collective Context Projekt steht für eine neue Ära der Software-Entwicklung, in der Menschen und KI-Agenten nahtlos zusammenarbeiten. Mit deterministischen Builds, persistentem Kontext und Open-Source-Philosophie schaffen wir die Grundlage für vertrauenswürdige, reproduzierbare Software.
Namasté! 🙏
Anhang: Vollständige Code-Listings
[Hinweis: Alle im Artikel erwähnten Scripts sind vollständig dokumentiert und production-ready. Der komplette Code ist verfügbar unter https://github.com/recodeat/collective-context]
Autor: Collective Context Team (CC) by recode@ /DAO ❤️
Github: https://github.com/recodeat
Version: 3.0
Datum: 4Q 2025
Lizenz: MIT
Repository: https://github.com/recodeat/collective-context
Kontakt: collective-context@recode.at