Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions PROVENANCE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Provenance Tracking

This document maintains a record of commit references for audit and legal traceability purposes. All commits related to the patent application are cross-referenced in the manifest and blockchain-anchored records.

---

## Core Implementation Commits

### Commit: 975de8d
**Message:** Add core Python modules (699 lines total)

**Files:**
- triangle_test.py
- guardian.py
- context_router.py
- canonical_json.py
- identity_manager.py

**Description:** Initial implementation of core Python modules demonstrating reduction to practice.

**Cross-Reference:** This commit is cross-referenced in the manifest and blockchain proof for audit and legal traceability.

---

## Automation Guidelines

For future updates, automate provenance tracking by recording:
- Commit hashes
- Timestamps
- Affected files
- Commit messages

Record this information in both:
1. This manifest file
2. Blockchain-anchored records

---

## Additional Commits

*Future commits will be documented here with the same structure as above.*
62 changes: 61 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,61 @@
# .github
# .github

**Status:** ✅ UPDATED (v1.1)
**Last Updated:** 2025-12-24
**Entity:** Contruil LLC
**Patent Application:** Pending (Q1 2026)
**Reduction to Practice:** Documented
**Reviewer:** [Pending attorney assignment]

---

## Package Index

**Status:** ✅ UPDATED (2025-12-24)
**Documents Listed:** 16 total
**Filing-Ready Package Marker:** Line R11
**Last Modified:** 2025-12-24

### Core Documents (7)
1. **README.md** - Package index and metadata (this document)
2. **schemas/layer1_envelope_v1_1.json** - Layer 1 envelope schema (5.7KB, PRODUCTION_READY)
3. **repository-mappings.csv** - Repository label to local path mappings
4. **triangle_test.py** - Triangle validation and testing module (70 lines)
5. **guardian.py** - Security and access control module (118 lines)
6. **context_router.py** - Context routing and management module (146 lines)
7. **canonical_json.py** - Canonical JSON serialization module (131 lines)

### Additional Documents (9)
8. **identity_manager.py** - Identity management and authentication module (225 lines)
9. **PROVENANCE.md** - Provenance tracking and commit references for legal audit trail (41 lines)
10. [Document 10 - Pending]
11. [Document 11 - Pending]
12. [Document 12 - Pending]
13. [Document 13 - Pending]
14. [Document 14 - Pending]
15. [Document 15 - Pending]
16. [Document 16 - Pending]

### Supporting Documents (0)
*All documents currently categorized above*

---

## Attorney Review Checklist

- [ ] 8
- [ ] 7
- [ ] 6
- [ ] 5
- [ ] 4
- [ ] 3
- [ ] 2
- [ ] 1

---

## Version History

| Version | Date | Changes | Status |
| --- | --- | --- | --- |
| 1.0 | 2025-12-23 | Initial frozen specification for legal review | FROZEN |
137 changes: 137 additions & 0 deletions canonical_json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""
Canonical JSON Module
Part of Contruil LLC Patent Application - Pending Q1 2026

This module provides canonical JSON serialization for deterministic output.
Reduction to Practice: Documented
"""

import json
import hashlib
from typing import Any, Dict, List, Union
from collections import OrderedDict


class CanonicalJSON:
"""Provides canonical JSON serialization functionality."""

@staticmethod
def _sort_dict(obj: Any) -> Any:
"""Recursively sort dictionary keys and process nested structures."""
if isinstance(obj, dict):
return OrderedDict(sorted((k, CanonicalJSON._sort_dict(v))
for k, v in obj.items()))
elif isinstance(obj, list):
return [CanonicalJSON._sort_dict(item) for item in obj]
else:
return obj

@staticmethod
def serialize(obj: Any, **kwargs) -> str:
"""
Serialize an object to canonical JSON format.

Args:
obj: The object to serialize
**kwargs: Additional arguments passed to json.dumps

Returns:
Canonical JSON string
"""
# Sort all dictionary keys recursively
sorted_obj = CanonicalJSON._sort_dict(obj)

# Serialize with consistent formatting
return json.dumps(
sorted_obj,
ensure_ascii=True,
sort_keys=True,
separators=(',', ':'),
**kwargs
)

@staticmethod
def serialize_pretty(obj: Any) -> str:
"""
Serialize an object to canonical JSON format with pretty printing.

Args:
obj: The object to serialize

Returns:
Pretty-printed canonical JSON string
"""
sorted_obj = CanonicalJSON._sort_dict(obj)

return json.dumps(
sorted_obj,
ensure_ascii=True,
sort_keys=True,
indent=2,
separators=(',', ': ')
)

@staticmethod
def deserialize(json_str: str) -> Any:
"""
Deserialize a JSON string to a Python object.

Args:
json_str: The JSON string to deserialize

Returns:
Python object
"""
return json.loads(json_str)

@staticmethod
def canonicalize(json_str: str) -> str:
"""
Canonicalize an existing JSON string.

Args:
json_str: The JSON string to canonicalize

Returns:
Canonical JSON string
"""
obj = json.loads(json_str)
return CanonicalJSON.serialize(obj)

@staticmethod
def hash_object(obj: Any, algorithm: str = 'sha256') -> str:
"""
Create a deterministic hash of an object via canonical JSON.

Args:
obj: The object to hash
algorithm: Hash algorithm to use (default: sha256)
Allowed: sha256, sha512, sha1, md5

Returns:
Hexadecimal hash string
"""
# Validate algorithm against whitelist
allowed_algorithms = {'sha256', 'sha512', 'sha1', 'md5'}
if algorithm not in allowed_algorithms:
raise ValueError(f"Algorithm must be one of {allowed_algorithms}")

canonical = CanonicalJSON.serialize(obj)
hash_obj = hashlib.new(algorithm)
hash_obj.update(canonical.encode('utf-8'))
return hash_obj.hexdigest()

@staticmethod
def compare(obj1: Any, obj2: Any) -> bool:
"""
Compare two objects for equality using canonical JSON.

Args:
obj1: First object
obj2: Second object

Returns:
True if objects are equal, False otherwise
"""
return CanonicalJSON.serialize(obj1) == CanonicalJSON.serialize(obj2)
146 changes: 146 additions & 0 deletions context_router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
#!/usr/bin/env python3
"""
Context Router Module
Part of Contruil LLC Patent Application - Pending Q1 2026

This module provides routing and context management functionality.
Reduction to Practice: Documented
"""

from typing import Dict, List, Optional, Callable, Any
from dataclasses import dataclass
from enum import Enum
import re


class RouteMethod(Enum):
"""HTTP-like method types for routing."""
GET = "GET"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
PATCH = "PATCH"


@dataclass
class Route:
"""Represents a route in the routing system."""
pattern: str
method: RouteMethod
handler: Callable
middleware: List[Callable] = None

def __post_init__(self):
if self.middleware is None:
self.middleware = []
# Convert pattern to regex
self.regex = self._pattern_to_regex(self.pattern)

def _pattern_to_regex(self, pattern: str) -> re.Pattern:
"""Convert a route pattern to a regex."""
# Replace :param with named groups
regex_pattern = re.sub(r':(\w+)', r'(?P<\1>[^/]+)', pattern)
regex_pattern = f'^{regex_pattern}$'
return re.compile(regex_pattern)

def match(self, path: str) -> Optional[Dict[str, str]]:
"""Check if a path matches this route and extract parameters."""
match = self.regex.match(path)
if match:
return match.groupdict()
return None


class Context:
"""Represents the execution context for a request."""

def __init__(self, path: str, method: RouteMethod, data: Optional[Dict] = None):
"""Initialize a context."""
self.path = path
self.method = method
self.data = data or {}
self.params: Dict[str, str] = {}
self.state: Dict[str, Any] = {}
self.response: Optional[Any] = None

def set_param(self, key: str, value: str) -> None:
"""Set a route parameter."""
self.params[key] = value

def get_param(self, key: str, default: Optional[str] = None) -> Optional[str]:
"""Get a route parameter."""
return self.params.get(key, default)

def set_state(self, key: str, value: Any) -> None:
"""Set a state value in the context."""
self.state[key] = value

def get_state(self, key: str, default: Optional[Any] = None) -> Any:
"""Get a state value from the context."""
return self.state.get(key, default)


class ContextRouter:
"""Main router class for managing routes and contexts."""

def __init__(self):
"""Initialize the router."""
self.routes: List[Route] = []
self.global_middleware: List[Callable] = []

def add_route(self, pattern: str, method: RouteMethod, handler: Callable,
middleware: Optional[List[Callable]] = None) -> None:
"""Add a route to the router."""
route = Route(pattern, method, handler, middleware)
self.routes.append(route)

def use(self, middleware: Callable) -> None:
"""Add global middleware."""
self.global_middleware.append(middleware)

def get(self, pattern: str, handler: Callable,
middleware: Optional[List[Callable]] = None) -> None:
"""Add a GET route."""
self.add_route(pattern, RouteMethod.GET, handler, middleware)

def post(self, pattern: str, handler: Callable,
middleware: Optional[List[Callable]] = None) -> None:
"""Add a POST route."""
self.add_route(pattern, RouteMethod.POST, handler, middleware)

def find_route(self, path: str, method: RouteMethod) -> Optional[tuple]:
"""Find a matching route for the given path and method."""
for route in self.routes:
if route.method == method:
params = route.match(path)
if params is not None:
return route, params
return None

def route(self, context: Context) -> Any:
"""Route a context through the system."""
# Find matching route
result = self.find_route(context.path, context.method)
if not result:
return {'error': 'Route not found', 'status': 404}

route, params = result

# Set parameters in context
for key, value in params.items():
context.set_param(key, value)

# Execute global middleware
for middleware in self.global_middleware:
middleware(context)

# Execute route-specific middleware
if route.middleware:
for middleware in route.middleware:
middleware(context)

# Execute handler
response = route.handler(context)
context.response = response

return response
Loading