Emergent Learning Framework (ELF)

repository·main·Indexed 42 days ago

https://github.com/spacehunterz/emergent-learning-framework_elf

A persistent memory and pattern-tracking system for Claude Code sessions. ELF enables AI agents to build institutional knowledge through heuristics, golden rules, and a local dashboard, featuring a QuerySystem Python API, a FastAPI backend, and a React frontend for monitoring agent runs, anomalies, and session history.

Tokens
346.6K
Snippets
946
Records
1.4K
Agent score
52%

What's inside ELF

  1. Overview of the Emergent Learning Framework (ELF)

    main

    The Emergent Learning Framework (ELF) is a persistent memory system designed for AI coding agents (like Claude Code). It solves the problem of 'context loss' where AI sessions start from zero every time. Instead of re-explaining project quirks, ELF records successes, failures, and patterns to provide structured, persistent memory that can be surfaced during new tasks.

    Core Capabilities:

    • Automatic Recording: Uses hooks to capture failures and successes automatically.
    • Heuristic Tracking: Tracks patterns (heuristics) that gain confidence over time.
    • Visualization: Includes a dashboard to visualize learned knowledge.
    • Searchable Memory: A query system to search through past learnings.
    • Multi-agent Coordination: Supports complex tasks through multi-agent workflows.
  2. Summary of Error Handling Improvements in ELF Scripts

    main

    The Emergent Learning Framework (ELF) scripts have been updated to follow a robust error handling pattern. When interacting with or extending the framework via shell scripts, you should aim for the following standards to ensure system stability:

    • Comprehensive Error Checking: Ensure 100% of commands are checked for success.
    • Specific Exit Codes: Use specific exit codes in the range 0-99 instead of generic 1 to indicate the nature of the failure.
    • Rich Error Messaging: Error messages should include Context, a suggested Fix, an error Code, and an error Category.
    • Retry Logic: Implement retry mechanisms (e.g., 5 attempts with exponential backoff) for transient failures.
    • Rollback Mechanisms: Ensure complete rollbacks with backups are performed if an operation fails midway.
    • Validation: Use comprehensive validation for all inputs and states.
    • Logging: Maintain complete logs for all operations.
    • Security: Protect against common vulnerabilities like SQL injection in database operations.
    • Graceful Degradation: Implement fallbacks so the system fails gracefully rather than hard-failing.
  3. Available Developer Guides in ELF

    main

    The following specialized guides are available for deep dives into specific development areas:

    • Testing Guide (testing.md): Covers test organization, pytest usage, fixture patterns (bb, results, test_dir, runner), mocking SQLite, and concurrency testing.
    • Performance Guide (performance.md): Covers query optimization (LIMIT/OFFSET, indexes), token cost optimization (Tier 0-3 context), memory profiling, and dashboard performance.
    • Extensions Guide (extensions.md): Instructions for extending ELF functionality.
  4. Summary of BaseRepository capabilities

    main

    BaseRepository is designed to provide a standardized interface for CRUD operations, reducing boilerplate code (by approximately 64%) and ensuring a single source of truth for data access logic. It provides:

    • Standard CRUD operations
    • Consistent error handling
    • Pagination and filter support
    • Helper methods such as exists and count
    • High testability and extensibility
  5. Implementation Overview of the Fraud Detection System (Phase 2)

    main

    The Phase 2 Fraud Detection System is designed to enhance security by detecting adversarial agent logic, such as pump-and-dump attacks, selective validation, and coordinated manipulation. It uses an ensemble of 6 detection algorithms combined via Bayesian fusion to produce a fraud score.

    Key Components:

    • Detection Algorithms: 6 specialized detectors (e.g., success rate, temporal, coordinated manipulation).
    • Scoring: Bayesian fusion of weak signals to achieve high accuracy.
    • Response Actions: Automated actions including freeze (hard quarantine), reset, or escalate (CEO escalation).
    • Baselines: Domain-specific statistical baselines to identify anomalies.

    Dependencies: The system relies exclusively on the Python Standard Library (sqlite3, statistics, datetime, json, collections).

    Database Requirements:

    • Requires SQLite FTS5 for full-text search context matching.
    • Windows/MSYS Fallback: If FTS5 is unavailable, the system should fallback to FTS4 or LIKE queries.
    # Main fraud detection flow
    def run_fraud_detection(heuristic_id: int) -> FraudReport:
        # Run all detectors
        signals = [
            detect_success_rate_anomaly(heuristic_id),
            detect_temporal_manipulation(heuristic_id),
            detect_coordinated_manipulation(heuristic_id),
            detect_unnatural_confidence_growth(heuristic_id),
            detect_application_selectivity(heuristic_id),
            detect_revival_gaming(heuristic_id)
        ]
    
        # Bayesian fusion
        fraud_score = bayesian_combine(signals, prior=0.05)
    
        # Classify
        classification = classify_fraud_score(fraud_score)
    
        # Store report
        report_id = store_fraud_report(heuristic_id, fraud_score, classification, signals)
    
        # Take action
        if classification == "fraud_confirmed":
            freeze_confidence(heuristic_id, report_id)
            escalate_to_ceo(heuristic_id, report_id)
        elif classification == "fraud_likely":
            tighten_rate_limits(heuristic_id, report_id)
            escalate_to_ceo(heuristic_id, report_id)
        elif classification == "suspicious":
            log_warning(heuristic_id, report_id)
    
        return FraudReport(...)
  6. Explore Dashboard Tabs and Features

    main

    The dashboard provides several views to monitor and interact with the emergent learning process:

    TabPurpose
    OverviewVisualizes hotspots via a D3.js treemap, shows anomalies, and displays golden rules.
    HeuristicsLists all learned patterns with their confidence levels; allows promoting or demoting patterns.
    RunsDisplays agent execution history and provides options to retry failed runs.
    TimelineProvides an event-by-event history with playback capabilities.
    SessionsBrowses Claude Code session history (search, filter, and expand conversations).
    QueryEnables natural language search across the system.
  7. Explore Dashboard Views and Components

    main

    The dashboard is organized into several tabs, each providing different perspectives on the learning system:

    • Overview Tab: Provides a high-level summary including a stats bar with key metrics, an interactive hotspot treemap (D3.js), anomaly alerts, and a summary of golden rules.
    • Heuristics Tab: A searchable and filterable list of heuristics. It includes lifecycle visualization, confidence tracking, and one-click buttons to promote or demote rules.
    • Runs Tab: Displays agent execution history with status filtering, file touchpoints, and the ability to retry failed runs.
    • Timeline Tab: An event-by-event history with playback controls and event type filtering to step through agent activity.
    • Query Tab: A natural language interface for asking questions about your data, featuring smart result rendering, query suggestions, and search history.
  8. Overview of ELF Hooks

    main

    ELF utilizes Claude Code's hooks system to inject semantic context and validate actions throughout the workflow. The framework uses five primary hook points to manage the learning loop:

    • UserPromptSubmit: Fires after a user sends a message. Used to load baseline context like Golden Rules and domain heuristics.
    • PreToolUse: Fires before a tool executes. Used for mid-stream semantic memory injection and detecting 'Plan Mode'.
    • PostToolUse: Fires after a tool succeeds. Used to validate outcomes, update heuristic confidence, and validate plan files.
    • SubagentStart: Fires when spawning a subagent (reserved for future plan subagent context).
    • SessionEnd: Fires when a session terminates to perform cleanup and save session state.
  9. Enhanced Secret Detection Patterns in AdvisoryVerifier

    main

    The AdvisoryVerifier system uses security_patterns.py to perform non-blocking, advisory-only scans for hardcoded secrets and risky code patterns. This system is designed to catch security vulnerabilities such as hardcoded passwords, API keys, tokens, and dangerous function calls (like eval() or exec()).

    Key Characteristics

    • Advisory-only: The system is non-blocking; it logs warnings to building metrics rather than preventing operations.
    • Scope: It only scans added or modified lines to maintain efficiency.
    • Integration: The patterns are defined in security_patterns.py and are automatically imported and used by post_tool_learning.py during Edit/Write operations.
  10. Understand QuerySystem's Readonly Mode behavior

    main

    The QuerySystem is designed to handle read-only database environments gracefully. If a database operation that requires write access (such as ANALYZE) fails due to a readonly error, the system:

    1. Catches the sqlite3.OperationalError.
    2. Sets an internal _readonly_mode flag to True.
    3. Continues operation in a degraded mode rather than crashing.

    This allows the framework to function in environments where the underlying storage is immutable.

  11. Build User-Facing Apps in the Application Layer

    main

    The Application Layer (apps/) contains user-facing applications such as UIs, CLIs, or APIs.

    Key Principles:

    • Acts as thin adapters over the Service Layer.
    • Implements API versioning (e.g., /api/v1/).
    • Handles input validation, transformation, error handling, and user feedback.
    # apps/dashboard/backend/api/v1/heuristics.py
    from fastapi import APIRouter, Depends, HTTPException
    from elf.services import HeuristicsService, IHeuristicsService
    
    router = APIRouter(prefix="/api/v1/heuristics", tags=["heuristics-v1"])
    
    @router.post("/{id}/promote")
    async def promote_heuristic(
        id: int,
        service: IHeuristicsService = Depends(get_heuristics_service)
    ):
        """
        Promote heuristic to golden rule.
    
        **Requires:** Confidence >= 0.8
        **Version:** 1.0 (stable)
        """
        try:
            heuristic = await service.promote_to_golden(id)
            return {"success": True, "heuristic": heuristic.dict()}
        except ValueError as e:
            raise HTTPException(400, detail=str(e))
  12. Verify confidence updates with Exponential Moving Average (EMA)

    main

    The system uses Exponential Moving Average (EMA) to smooth confidence updates for heuristics, preventing single anomalous events from causing large swings in confidence.

    When testing or implementing confidence updates, you can verify the smoothing effect using the following behaviors:

    • Single Update Smoothing: A single UpdateType.SUCCESS or UpdateType.FAILURE should have a fractional impact rather than a discrete jump. For example, with an $\alpha=0.30$ (warmup), a single update should result in a much smaller delta than a discrete update.
    • Noise Rejection: Random alternating updates (SUCCESS and FAILURE) should cause the confidence to stabilize near its baseline rather than oscillating wildly.
    • Trend Detection: Sustained consecutive updates in one direction (e.g., 20 consecutive successes) should still allow the confidence to trend upward, albeit more slowly than a discrete system.
    • Asymmetric Smoothing: The system is designed to be conservative. Increases in confidence should typically use a smaller $\alpha$ (smoother/slower) than decreases (faster/more reactive), following security best practices where trust is built slowly but lost quickly.
    # Example of verifying a single update's smoothed impact
    def test_single_update_smoothing():
        h_id = create_heuristic("test", "Test rule", confidence=0.5)
    
        # Apply one SUCCESS
        result = update_confidence(h_id, UpdateType.SUCCESS, force=True)
    
        # With EMA (α=0.30 warmup), the jump is damped
        assert result['new_confidence'] < 0.52
        assert result['new_confidence'] > 0.51
        assert result['smoothing_effect'] > 0.03