Skip to content

Token Simplification: Before and After Examples

Example 1: Phase System Integration

Before (Current Implementation)

# In analyzer.py - Complex token detection
def _analyze_resource_dependencies(self, resource):
    dependencies = []
    for attr_name, attr_value in resource.get_all_attributes(include_tokens=True):
        if isinstance(attr_value, Token):
            # Complex extraction of internal token state
            if hasattr(attr_value, "_resolvable"):
                resolvable = attr_value._resolvable
                if resolvable.__class__.__name__ == "ResourceAttribute":
                    # More complex logic to extract dependencies
                    target = resolvable.resource
                    dependencies.append(target)
        elif isinstance(attr_value, str):
            # Check for encoded tokens ${TOKEN:...} or ${TOKEN[...]}
            if "${TOKEN" in attr_value:
                # Complex regex parsing
                pass

After (New Implementation)

# In analyzer.py - Protocol-based detection
def _analyze_resource_dependencies(self, resource):
    dependencies = []
    for attr_name, attr_value in resource.get_all_attributes():
        # Clean protocol-based approach
        deps = self._get_dependencies(attr_value)
        dependencies.extend(deps)


def _get_dependencies(self, value: Any) -> list[ResourceReference]:
    # Simple protocol check
    if isinstance(value, DeferredValue):
        return value.get_dependencies()
    elif isinstance(value, dict):
        return sum((self._get_dependencies(v) for v in value.values()), [])
    elif isinstance(value, list):
        return sum((self._get_dependencies(v) for v in value), [])
    return []

Example 4: Token Serialization

Before (Current Implementation)

# Complex encoding with global registry
class TokenEncoding:
    _token_registry = {}

    @classmethod
    def encode_token(cls, token: Token) -> str:
        # Generate complex token ID
        token_id = hashlib.sha256(f"{id(token)}:{time.time()}".encode()).hexdigest()[:16]

        # Store in global registry
        cls._token_registry[token_id] = token

        # Return encoded format
        return f"${{TOKEN[{token_id}]}}"


# In phase planning
def serialize_value(value):
    if isinstance(value, Token):
        return TokenEncoding.encode_token(value)
    # More complex logic

After (New Implementation)

# Explicit serialization without global state
class DeferredValueSerializer:
    def serialize(self, value: DeferredValue) -> dict:
        if isinstance(value, ResourceReference):
            return {"type": "resource_ref", "resource_type": value.resource._type, "resource_id": value.resource._id, "attribute": value.attribute}
        elif isinstance(value, MappedValue):
            return {"type": "mapped", "source": self.serialize(value.source), "function": value.function.__name__}
        # Other cases

    def deserialize(self, data: dict, context: DeserializationContext) -> DeferredValue:
        if data["type"] == "resource_ref":
            resource = context.get_resource(data["resource_type"], data["resource_id"])
            return ResourceReference(resource, data["attribute"])
        # Other cases

Benefits Summary

  1. Better Protocols: Clean separation of concerns
  2. Simpler Phase Integration: Protocol-based dependency detection
  3. No Global State: Explicit serialization without registries

The new design maintains all the safety of the current system while being much simpler to understand, implement, and maintain.