Skip to main content

scripts-test-post-session

#!/usr/bin/env python3 """โ€‹

title: "Sample session transcript with patterns to extract" component_type: script version: "1.0.0" audience: contributor status: stable summary: "Test script for post-session processing system." keywords: ['api', 'database', 'post', 'security', 'session'] tokens: ~500 created: 2025-12-22 updated: 2025-12-22 script_name: "test-post-session.py" language: python executable: true usage: "python3 scripts/test-post-session.py [options]" python_version: "3.10+" dependencies: [] modifies_files: false network_access: false requires_auth: falseโ€‹

Test script for post-session processing system.

Creates a sample session transcript and runs post-session processing to verify all components are working correctly. """

import asyncio import json import sys from datetime import datetime, timezone from pathlib import Path import tempfile import shutil

Sample session transcript with patterns to extract

SAMPLE_TRANSCRIPT = """ Session Start: 2025-12-22 14:30:00

I'll implement the authentication system using JWT tokens.

Architecture Decision: I decided to use JWT tokens because they provide stateless authentication and can be easily validated without database lookups. This is better than session cookies for our microservices architecture.

Creating file: src/auth/jwt_handler.py

import jwt
from datetime import datetime, timedelta

async def generate_token(user_id: str) -> str:
'''Generate JWT token for user authentication.'''
payload = {
'user_id': user_id,
'exp': datetime.utcnow() + timedelta(hours=24)
}
return jwt.encode(payload, SECRET_KEY, algorithm='HS256')

class AuthenticationService:
def __init__(self):
self.secret = SECRET_KEY

async def verify_token(self, token: str):
try:
return jwt.decode(token, self.secret, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise AuthenticationError("Token expired")

โš ๏ธ Important: Always validate tokens on every request. Never trust client-side token validation.

Modified: src/api/routes.py Modified: src/middleware/auth.py

Error: Token validation failed with "Invalid signature" Solution: Ensure SECRET_KEY is consistent across all services. Use environment variable.

Note: JWT tokens should be short-lived (24 hours max) for security.

Session metrics:

  • Files created: 1
  • Files modified: 2
  • Functions implemented: 2
  • Classes implemented: 1

Session End: 2025-12-22 15:15:00 """

async def test_post_session_processing(): """Test post-session processing with sample transcript.""" print("\n" + "="*70) print("๐Ÿงช POST-SESSION PROCESSING TEST") print("="*70)

# Get CODITECT root (assuming we're in scripts/)
root = Path(__file__).parent.parent.resolve()
print(f"\n๐Ÿ“‚ CODITECT root: {root}")

# Create temporary context storage for test
context_dir = root / "context-storage"
context_dir.mkdir(exist_ok=True)

# Generate test session ID
session_id = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S_test")
print(f"๐Ÿ”‘ Test session ID: {session_id}")

# Write sample transcript
transcript_file = context_dir / f"session_{session_id}.txt"
print(f"\n๐Ÿ“ Writing test transcript: {transcript_file.name}")
with open(transcript_file, 'w') as f:
f.write(SAMPLE_TRANSCRIPT)

# Import and run processor
print("\nโš™๏ธ Initializing post-session processor...")

# Add scripts directory to path
scripts_dir = root / "scripts"
sys.path.insert(0, str(scripts_dir))

try:
# Import the processor module
import importlib.util
spec = importlib.util.spec_from_file_location(
"post_session_processor",
scripts_dir / "post-session-processor.py"
)
if not spec or not spec.loader:
raise ImportError("Could not load post-session-processor.py")

module = importlib.util.module_from_spec(spec)
sys.modules["post_session_processor"] = module
spec.loader.exec_module(module)

PostSessionProcessor = module.PostSessionProcessor

processor = PostSessionProcessor(root)

# Process the test session
print("\n๐Ÿ”„ Processing test session...\n")
results = await processor.process_session(
SAMPLE_TRANSCRIPT,
session_id=session_id,
task_id="TEST-001"
)

# Verify results
print("\n" + "="*70)
print("โœ… TEST RESULTS")
print("="*70)

assert results["status"] == "completed", "Processing should complete successfully"
print("โœ“ Processing completed successfully")

insights = results["insights"]

# Check patterns
patterns = insights.get("patterns", [])
print(f"\n๐Ÿ“Š Patterns Extracted: {len(patterns)}")
assert len(patterns) > 0, "Should extract at least one pattern"
for pattern in patterns[:3]:
print(f" - {pattern['type']}: {pattern.get('name', pattern.get('description', 'N/A'))}")

# Check decisions
decisions = insights.get("decisions", [])
print(f"\n๐ŸŽฏ Decisions Extracted: {len(decisions)}")
assert len(decisions) > 0, "Should extract at least one decision"
for decision in decisions[:2]:
print(f" - {decision['decision'][:60]}...")

# Check gotchas
gotchas = insights.get("gotchas", [])
print(f"\nโš ๏ธ Gotchas Extracted: {len(gotchas)}")
for gotcha in gotchas[:2]:
print(f" - {gotcha['message'][:60]}...")

# Check errors
errors = insights.get("errors", [])
print(f"\n๐Ÿ”ง Error Solutions Extracted: {len(errors)}")
for error in errors[:2]:
print(f" - Error: {error['error'][:40]}...")
if error.get('solution'):
print(f" Solution: {error['solution'][:40]}...")

# Check file modifications
files = insights.get("file_modifications", [])
print(f"\n๐Ÿ“ File Modifications: {len(files)}")
for file in files[:3]:
print(f" - {file['operation'].upper()}: {file['file']}")

# Check metrics
metrics = insights.get("metrics", {})
print(f"\n๐Ÿ“ˆ Session Metrics:")
print(f" - Transcript length: {metrics.get('transcript_length', 0)} chars")
print(f" - Patterns found: {metrics.get('patterns_found', 0)}")
print(f" - Decisions made: {metrics.get('decisions_made', 0)}")
print(f" - Files modified: {metrics.get('files_modified', 0)}")

# Verify state files created
print(f"\n๐Ÿ“‚ State Files:")
insights_file = root / ".coditect" / "session-insights.json"
if insights_file.exists():
print(f" โœ“ {insights_file.name} exists")
with open(insights_file, 'r') as f:
saved_insights = json.load(f)
assert session_id in saved_insights, "Session should be in insights file"
else:
print(f" โœ— {insights_file.name} not found")

task_status_file = root / ".coditect" / "task-status.json"
if task_status_file.exists():
print(f" โœ“ {task_status_file.name} exists")
with open(task_status_file, 'r') as f:
task_status = json.load(f)
assert "TEST-001" in task_status, "Task should be in status file"
else:
print(f" โœ— {task_status_file.name} not found")

print("\n" + "="*70)
print("๐ŸŽ‰ ALL TESTS PASSED")
print("="*70)

# Cleanup test files
print(f"\n๐Ÿงน Cleaning up test files...")
transcript_file.unlink()

return True

except ImportError as e:
print(f"\nโŒ Failed to import post_session_processor: {e}")
print("\nMake sure you're running from coditect-core root directory.")
return False

except AssertionError as e:
print(f"\nโŒ Test assertion failed: {e}")
return False

except Exception as e:
print(f"\nโŒ Test failed with error: {e}")
import traceback
traceback.print_exc()
return False

async def main(): """Run test suite.""" success = await test_post_session_processing() sys.exit(0 if success else 1)

if name == "main": asyncio.run(main())