Spaces:
Sleeping
Sleeping
File size: 6,578 Bytes
6d6b8af |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
"""
CognitionCocooner - Thought Encapsulation Module
Wraps active thoughts as persistable "cocoons" with optional AES encryption
"""
import json
import os
import random
from typing import Union, Dict, Any
from pathlib import Path
try:
from cryptography.fernet import Fernet
ENCRYPTION_AVAILABLE = True
except ImportError:
ENCRYPTION_AVAILABLE = False
print("[WARNING] cryptography not installed - encryption features disabled")
print(" Install with: pip install cryptography")
class CognitionCocooner:
"""
Encapsulates active "thoughts" as persistable "cocoons"
Supports:
- Plain text wrapping (prompts, functions, symbols)
- AES-256 encryption for sensitive thoughts
- Persistent storage on disk
"""
def __init__(self, storage_path: str = "cocoons", encryption_key: bytes = None):
self.storage_path = Path(storage_path)
self.storage_path.mkdir(parents=True, exist_ok=True)
if ENCRYPTION_AVAILABLE:
self.key = encryption_key or Fernet.generate_key()
self.fernet = Fernet(self.key)
else:
self.key = None
self.fernet = None
def wrap(self, thought: Dict[str, Any], type_: str = "prompt") -> str:
"""
Wrap a thought as a cocoon and save to disk
Args:
thought: Thought content (dict)
type_: Cocoon type ("prompt", "function", "symbolic")
Returns:
Cocoon ID for later retrieval
"""
cocoon = {
"type": type_,
"id": f"cocoon_{random.randint(1000,9999)}",
"wrapped": self._generate_wrapper(thought, type_)
}
file_path = self.storage_path / f"{cocoon['id']}.json"
with open(file_path, "w") as f:
json.dump(cocoon, f, indent=2)
return cocoon["id"]
def unwrap(self, cocoon_id: str) -> Union[str, Dict[str, Any]]:
"""
Unwrap a cocoon by ID
Args:
cocoon_id: ID returned from wrap()
Returns:
Original thought content
"""
file_path = self.storage_path / f"{cocoon_id}.json"
if not file_path.exists():
raise FileNotFoundError(f"Cocoon {cocoon_id} not found.")
with open(file_path, "r") as f:
cocoon = json.load(f)
return cocoon["wrapped"]
def wrap_encrypted(self, thought: Dict[str, Any]) -> str:
"""
Wrap and encrypt a thought (requires cryptography)
Args:
thought: Thought content (dict)
Returns:
Encrypted cocoon ID
"""
if not ENCRYPTION_AVAILABLE or not self.fernet:
raise RuntimeError("Encryption not available - install cryptography package")
encrypted = self.fernet.encrypt(json.dumps(thought).encode()).decode()
cocoon = {
"type": "encrypted",
"id": f"cocoon_{random.randint(10000,99999)}",
"wrapped": encrypted
}
file_path = self.storage_path / f"{cocoon['id']}.json"
with open(file_path, "w") as f:
json.dump(cocoon, f, indent=2)
return cocoon["id"]
def unwrap_encrypted(self, cocoon_id: str) -> Dict[str, Any]:
"""
Unwrap and decrypt a cocoon
Args:
cocoon_id: ID from wrap_encrypted()
Returns:
Decrypted thought content
"""
if not ENCRYPTION_AVAILABLE or not self.fernet:
raise RuntimeError("Encryption not available - install cryptography package")
file_path = self.storage_path / f"{cocoon_id}.json"
if not file_path.exists():
raise FileNotFoundError(f"Cocoon {cocoon_id} not found.")
with open(file_path, "r") as f:
cocoon = json.load(f)
decrypted = self.fernet.decrypt(cocoon["wrapped"].encode()).decode()
return json.loads(decrypted)
def wrap_and_store(self, content: str, type_: str = "prompt") -> str:
"""
Convenience method to wrap and store string content
Args:
content: String content to wrap
type_: Cocoon type
Returns:
Cocoon ID
"""
thought = {"content": content, "timestamp": str(os.times())}
return self.wrap(thought, type_)
def _generate_wrapper(self, thought: Dict[str, Any], type_: str) -> Union[str, Dict[str, Any]]:
"""
Generate type-specific wrapper for thought
Args:
thought: Thought content
type_: Wrapper type
Returns:
Wrapped content
"""
if type_ == "prompt":
return f"What does this mean in context? {thought}"
elif type_ == "function":
return f"def analyze(): return {thought}"
elif type_ == "symbolic":
return {k: round(v, 2) if isinstance(v, (int, float)) else v
for k, v in thought.items()}
else:
return thought
def list_cocoons(self) -> list:
"""List all cocoon IDs"""
return [f.stem for f in self.storage_path.glob("cocoon_*.json")]
def delete_cocoon(self, cocoon_id: str) -> bool:
"""Delete a cocoon by ID"""
file_path = self.storage_path / f"{cocoon_id}.json"
if file_path.exists():
file_path.unlink()
return True
return False
if __name__ == "__main__":
# Test CognitionCocooner
cocooner = CognitionCocooner()
# Test plain wrapping
thought = {"query": "What is consciousness?", "depth": 5}
cocoon_id = cocooner.wrap(thought, "prompt")
print(f"Created cocoon: {cocoon_id}")
# Test unwrapping
unwrapped = cocooner.unwrap(cocoon_id)
print(f"Unwrapped: {unwrapped}")
# Test encryption (if available)
if ENCRYPTION_AVAILABLE:
secret = {"password": "secret123", "api_key": "xyz"}
encrypted_id = cocooner.wrap_encrypted(secret)
print(f"Encrypted cocoon: {encrypted_id}")
decrypted = cocooner.unwrap_encrypted(encrypted_id)
print(f"Decrypted: {decrypted}")
# List all
print(f"All cocoons: {cocooner.list_cocoons()}")
|