From a61e62f14e7f39386636a1466c20447ee85cc902 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 23 May 2026 08:44:54 +0000 Subject: [PATCH] Implement Execution Academy JavaScript library with ExplainableWorker and NicheConstructor Agent-Logs-Url: https://github.com/HyperCogWizard/ServiceWorker/sessions/b369419a-be1e-4f3b-b6ea-5b51312f5dd2 Co-authored-by: drzo <15202748+drzo@users.noreply.github.com> --- docs/execution-academy/README.md | 149 +++ docs/execution-academy/academy-spec.md | 640 ++++++++++++ docs/execution-academy/src/academy.js | 711 +++++++++++++ docs/execution-academy/src/dashboard.html | 888 +++++++++++++++++ .../src/explainable-worker.js | 784 +++++++++++++++ docs/execution-academy/src/index.js | 45 + .../src/niche-constructor.js | 935 ++++++++++++++++++ 7 files changed, 4152 insertions(+) create mode 100644 docs/execution-academy/README.md create mode 100644 docs/execution-academy/academy-spec.md create mode 100644 docs/execution-academy/src/academy.js create mode 100644 docs/execution-academy/src/dashboard.html create mode 100644 docs/execution-academy/src/explainable-worker.js create mode 100644 docs/execution-academy/src/index.js create mode 100644 docs/execution-academy/src/niche-constructor.js diff --git a/docs/execution-academy/README.md b/docs/execution-academy/README.md new file mode 100644 index 00000000..726abdae --- /dev/null +++ b/docs/execution-academy/README.md @@ -0,0 +1,149 @@ +# ๐ŸŽ“ The Execution Academy + +> **ECMA-262 as a Neuro-Symbolic Training System** + +A human-readable, explainable mapping of ECMAScript execution semantics to intuitive project-based role analogies, enhanced with adaptive neuro-symbolic optimization capabilities. + +## Overview + +The Execution Academy transforms abstract JavaScript runtime concepts into tangible, understandable metaphors. Instead of thinking about "execution contexts" and "realms," developers and learners can reason about "project roles" and "departments"โ€”concepts that mirror how teams actually collaborate. + +``` +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ THE EXECUTION ACADEMY โ”‚ +โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค +โ”‚ โ”‚ +โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ +โ”‚ โ”‚ DEPARTMENT A โ”‚ โ”‚ DEPARTMENT B โ”‚ โ”‚ DEPARTMENT C โ”‚ โ”‚ +โ”‚ โ”‚ (Realm 1) โ”‚ โ”‚ (Realm 2) โ”‚ โ”‚ (Realm 3) โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ +โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚Role: Init โ”‚ โ”‚ โ”‚ โ”‚Role: API โ”‚ โ”‚ โ”‚ โ”‚Role: Data โ”‚ โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚(Global EC)โ”‚ โ”‚ โ”‚ โ”‚Handler โ”‚ โ”‚ โ”‚ โ”‚Transform โ”‚ โ”‚ โ”‚ +โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ +โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚Role: Eventโ”‚ โ”‚ โ”‚ โ”‚Role: Fetchโ”‚ โ”‚ โ”‚ โ”‚Role: Cacheโ”‚ โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚Coordinatorโ”‚ โ”‚ โ”‚ โ”‚Specialist โ”‚ โ”‚ โ”‚ โ”‚Manager โ”‚ โ”‚ โ”‚ +โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ +โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚Role: UI โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚Renderer โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ +โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ +โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ +โ”‚ โ”‚ +โ”‚ โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• โ”‚ +โ”‚ โ”‚ SHARED FACILITIES โ”‚ โ”‚ +โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚ Message Hall โ”‚ โ”‚ Archive Room โ”‚ โ”‚Training Yard โ”‚ โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚ (Job Queues) โ”‚ โ”‚ (Heap/Memory)โ”‚ โ”‚(Optimization)โ”‚ โ”‚ โ”‚ +โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ +โ”‚ โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• โ”‚ +โ”‚ โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ +``` + +## Core Concepts + +### Mapping ECMA-262 Primitives to Academy Concepts + +| ECMA-262 Concept | Academy Analogy | Neuro-Symbolic Adaptation | +|------------------|-----------------|---------------------------| +| **Execution Context** | **Project Role** - A team member with specific responsibilities, tools, and knowledge scope | Role boundaries expand/contract based on task complexity | +| **Realm** | **Department** - An isolated organizational unit with its own culture, resources, and protocols | Departments form "joint ventures" when problems span boundaries | +| **Agent** | **Employee** - The actual worker performing tasks, bound to a department | Workers develop specializations over time | +| **Job Queue** | **Task Board** - Prioritized work items waiting to be picked up | Priority reordering based on learned urgency patterns | +| **Call Stack** | **Chain of Delegation** - "Who asked you to do this?" traceability | Stack depth optimizes based on recursion patterns | +| **Scope Chain** | **Access Hierarchy** - Who you can ask for information/resources | Access patterns adapt based on common query paths | +| **Lexical Environment** | **Personal Workspace** - Your desk, notes, tools accessible to you | Workspace organization emerges from usage patterns | +| **Variable Environment** | **Shared Supplies** - Resources available to your whole team | Supply chains optimize based on consumption patterns | + +## Key Features + +### 1. Human-Readable Explainability + +Every execution decision can be explained in natural language: + +``` +๐Ÿ“– NARRATIVE EXPLANATION: +"The UI Renderer asked the Event Coordinator for user data. + The Event Coordinator delegated to the Fetch Specialist, who + noticed this endpoint was requested 47 times today. Based on + learned patterns, the Specialist chose the CACHE-FIRST strategy + (cache hit rate: 94%). Result: Served from cache in 0.3ms." +``` + +### 2. Adaptive Neuro-Symbolic Intelligence + +Rather than strictly deterministic execution, the Academy framework introduces: + +- **Type Inference as Learning**: Expected types learned from patterns +- **Promise Confidence Scoring**: Each `.then()` carries confidence weights +- **Adaptive Fallbacks**: Rejection handlers auto-suggested from failure modes +- **Skill Trees**: Operations have proficiency levels that improve with use + +### 3. Niche Construction + +The system doesn't just adapt to its environmentโ€”it shapes it: + +1. **Observation Phase**: Monitor execution patterns across all roles +2. **Hypothesis Generation**: Propose optimizations based on patterns +3. **Safe Experimentation**: A/B test optimizations safely +4. **Integration**: Promote successful experiments to standard practice +5. **Environmental Modification**: Reshape scope chains, pre-warm caches + +## Quick Start + +```javascript +import { ExecutionAcademy, Role, Department, NicheConstructor } from './src/academy.js'; + +// Create an academy instance +const academy = new ExecutionAcademy(); + +// Create a department (realm) +const apiDepartment = academy.createDepartment('API Services'); + +// Create roles (execution contexts) +const fetchSpecialist = apiDepartment.createRole('FetchSpecialist', { + skills: ['fetch', 'cache-first', 'network-first'], + responsibilities: ['Handle all network requests'] +}); + +// Enable explainability +academy.enableExplainability(); + +// Get human-readable explanation for any operation +const explanation = await academy.explain(fetchOperation); +console.log(explanation.narrative); +``` + +## Documentation + +- [๐Ÿ“‹ Academy Specification](./academy-spec.md) - Formal specification document +- [๐Ÿ”ง API Reference](./src/academy.js) - Core library implementation +- [๐ŸŽจ Dashboard](./src/dashboard.html) - Visual explainability interface +- [๐Ÿงฌ Niche Constructor](./src/niche-constructor.js) - Adaptive optimization engine + +## Integration with Service Workers + +The Execution Academy framework is designed to integrate seamlessly with the Service Worker specification, providing: + +- **ExplainableWorker interface**: Adds explainability methods to service workers +- **adaptationevent**: New event fired when the neuro-symbolic engine suggests changes +- **NicheConstructor API**: For observing patterns and proposing optimizations + +See [academy-spec.md](./academy-spec.md) for the formal specification extension. + +## Philosophy + +> *"The best way to understand complex systems is through metaphor. The Execution Academy transforms the abstract machinery of JavaScript runtime into a living, breathing organizationโ€”complete with employees, departments, and collaborative protocols."* + +The framework draws inspiration from: +- **Ecological Niche Construction Theory**: Systems shape their environments +- **Situated Cognition**: Knowledge is context-dependent +- **Distributed Cognition**: Intelligence emerges from system interactions + +## License + +This work is part of the Service Workers specification project and follows the same licensing terms. diff --git a/docs/execution-academy/academy-spec.md b/docs/execution-academy/academy-spec.md new file mode 100644 index 00000000..db802ad0 --- /dev/null +++ b/docs/execution-academy/academy-spec.md @@ -0,0 +1,640 @@ +# ServiceWorkerAcademy Specification + +**Status**: Draft +**Version**: 1.0.0 +**Last Updated**: 2026-05-23 + +## Abstract + +This specification defines the ServiceWorkerAcademy extension to the Service Workers API, introducing neuro-symbolic adaptation capabilities and human-readable explainability for execution contexts. The framework maps ECMA-262 execution primitives to intuitive role-based analogies, enabling developers and systems to reason about, optimize, and explain JavaScript execution in natural language. + +--- + +## 1. Terminology + +### 1.1 Academy Primitives + +
+
Role
+
A conceptual wrapper around an execution context, representing a team member with specific responsibilities, tools, and knowledge scope. A Role has associated skill proficiencies that evolve based on execution patterns.
+ +
Department
+
An organizational wrapper around a Realm, representing an isolated unit with its own culture, resources, and protocols. Departments can form joint ventures when problems span boundaries.
+ +
Employee
+
The actual worker entity corresponding to an Agent, bound to a Department and capable of developing specializations over time.
+ +
Task Board
+
A priority-aware queue corresponding to Job Queues, with adaptive priority reordering based on learned urgency patterns.
+ +
Delegation Chain
+
The traceable path of responsibility corresponding to the Call Stack, supporting depth optimization based on recursion patterns.
+ +
Access Hierarchy
+
The queryable resource path corresponding to the Scope Chain, with access patterns adapting based on common query paths.
+ +
Personal Workspace
+
Individual resources corresponding to a Lexical Environment, with organization emerging from usage patterns.
+ +
Shared Supplies
+
Team-available resources corresponding to Variable Environment, with supply chains optimizing based on consumption patterns.
+
+ +### 1.2 Neuro-Symbolic Primitives + +
+
Skill Tree
+
A hierarchical structure of operation proficiencies associated with a Role, where each skill has a proficiency level (0-5 stars) that increases through successful use.
+ +
Commitment Chain
+
An explainable representation of a Promise chain, where each step carries confidence scores, fallback plans, and adaptation strategies.
+ +
Joint Venture
+
A temporary collaboration between Departments formed when problems span realm boundaries.
+ +
Fast Path
+
An optimized execution route learned from frequently traversed delegation chains, bypassing intermediate roles.
+ +
Knowledge Sharing Agreement
+
A contract between entities specifying data sharing semantics (clone, transfer, sync) with learned optimizations.
+
+ +--- + +## 2. Interfaces + +### 2.1 ExplainableWorker Interface + +```webidl +[Exposed=ServiceWorker] +partial interface ServiceWorkerGlobalScope { + [SameObject] readonly attribute ExecutionAcademy academy; +}; + +[Exposed=(Window,Worker)] +interface ExecutionAcademy { + Promise getDecisionExplanation(DOMString operationId); + SkillTree getSkillTree(); + sequence getAdaptationSuggestions(); + + // Department management + Department createDepartment(DOMString name, optional DepartmentOptions options = {}); + Department? getDepartment(DOMString name); + sequence listDepartments(); + + // Global settings + void enableExplainability(); + void disableExplainability(); + readonly attribute boolean explainabilityEnabled; + + // Event handling + attribute EventHandler onadaptation; +}; + +dictionary DepartmentOptions { + sequence protocols = []; + boolean allowJointVentures = true; +}; +``` + +### 2.2 ExecutionExplanation Interface + +```webidl +[Exposed=(Window,Worker)] +interface ExecutionExplanation { + readonly attribute DOMString operationId; + readonly attribute DOMString narrative; + readonly attribute DecisionFactors factors; + readonly attribute sequence alternativesConsidered; + readonly attribute double confidence; + readonly attribute DOMTimeStamp timestamp; + + DOMString toMarkdown(); + object toJSON(); +}; + +dictionary DecisionFactors { + double cacheHitRate; + double dataFreshness; + double freshnessToleranceSeconds; + DOMString networkConditions; + DOMString interactionContext; + record customFactors; +}; + +dictionary AlternativePath { + DOMString strategy; + DOMString rejectionReason; + double estimatedConfidence; +}; +``` + +### 2.3 Department Interface + +```webidl +[Exposed=(Window,Worker)] +interface Department { + readonly attribute DOMString name; + readonly attribute DOMString id; + readonly attribute sequence roles; + readonly attribute sequence protocols; + + Role createRole(DOMString name, optional RoleOptions options = {}); + Role? getRole(DOMString name); + void removeRole(DOMString name); + + // Joint ventures + JointVenture formJointVenture(Department partner, DOMString purpose); + sequence activeJointVentures(); +}; + +dictionary RoleOptions { + sequence skills = []; + sequence responsibilities = []; + Role? supervisor; + double initialProficiency = 1.0; +}; +``` + +### 2.4 Role Interface + +```webidl +[Exposed=(Window,Worker)] +interface Role { + readonly attribute DOMString name; + readonly attribute DOMString id; + readonly attribute Department department; + readonly attribute Role? supervisor; + readonly attribute sequence subordinates; + readonly attribute SkillTree skills; + readonly attribute Workspace workspace; + + // Delegation + Promise delegate(DOMString taskType, any payload, optional DelegationOptions options = {}); + void reportCompletion(DOMString taskId, any result); + void reportFailure(DOMString taskId, any error); + + // Skill development + void recordSkillUse(DOMString skill, boolean success); + double getSkillProficiency(DOMString skill); +}; + +dictionary DelegationOptions { + double timeoutMs; + DOMString priority = "normal"; + boolean allowFastPath = true; +}; +``` + +### 2.5 SkillTree Interface + +```webidl +[Exposed=(Window,Worker)] +interface SkillTree { + readonly attribute sequence skills; + + Skill? getSkill(DOMString name); + void addSkill(DOMString name, optional SkillOptions options = {}); + void removeSkill(DOMString name); + + // Learning + void recordSuccess(DOMString skillName); + void recordFailure(DOMString skillName); + + // Querying + sequence getSkillsByProficiency(double minProficiency); + sequence getUnlockedSkills(); + sequence getLockedSkills(); +}; + +dictionary SkillOptions { + double initialProficiency = 0.0; + sequence prerequisites = []; + DOMString description; +}; + +[Exposed=(Window,Worker)] +interface Skill { + readonly attribute DOMString name; + readonly attribute double proficiency; // 0.0 to 5.0 + readonly attribute unsigned long successCount; + readonly attribute unsigned long failureCount; + readonly attribute sequence prerequisites; + readonly attribute sequence unlocks; + readonly attribute boolean isUnlocked; + + double getSuccessRate(); +}; +``` + +### 2.6 NicheConstructor Interface + +```webidl +[Exposed=(Window,Worker)] +interface NicheConstructor { + constructor(ExecutionAcademy academy); + + // Observation + PatternObserver observe(DOMString pattern, optional ObservationOptions options = {}); + void stopObserving(DOMString pattern); + sequence getObservations(); + + // Hypothesis + Hypothesis hypothesize(DOMString optimization); + sequence getPendingHypotheses(); + + // Experimentation + Experiment experiment(Hypothesis hypothesis, optional ExperimentOptions options = {}); + sequence getActiveExperiments(); + + // Integration + IntegrationResult integrate(ExperimentResults results); + + // Events + attribute EventHandler onhypothesis; + attribute EventHandler onexperimentcomplete; + attribute EventHandler onintegration; +}; + +dictionary ObservationOptions { + double samplingRate = 1.0; + unsigned long maxSamples = 1000; + double timeWindowSeconds = 3600; +}; + +dictionary ExperimentOptions { + double trafficPercentage = 0.1; + unsigned long minSamples = 100; + double maxDurationSeconds = 3600; + boolean autoIntegrate = false; +}; +``` + +### 2.7 CommitmentChain Interface (Promise Explainability) + +```webidl +[Exposed=(Window,Worker)] +interface CommitmentChain { + readonly attribute sequence commitments; + readonly attribute double overallConfidence; + readonly attribute DOMString status; // "pending", "fulfilled", "rejected" + + static CommitmentChain from(Promise promise); + + ExecutionExplanation explain(); + DOMString toNarrative(); +}; + +[Exposed=(Window,Worker)] +interface Commitment { + readonly attribute DOMString description; + readonly attribute double confidence; + readonly attribute FallbackPlan? fallback; + readonly attribute AdaptationStrategy? adaptation; + readonly attribute DOMString status; +}; + +dictionary FallbackPlan { + DOMString description; + DOMString triggerCondition; +}; + +dictionary AdaptationStrategy { + DOMString description; + sequence alternatives; +}; +``` + +--- + +## 3. Events + +### 3.1 AdaptationEvent + +```webidl +[Exposed=(Window,Worker)] +interface AdaptationEvent : Event { + constructor(DOMString type, optional AdaptationEventInit eventInitDict = {}); + + readonly attribute DOMString adaptationType; + readonly attribute any suggestion; + readonly attribute double confidence; + readonly attribute DOMString rationale; + + void approve(); + void reject(optional DOMString reason); + void defer(); +}; + +dictionary AdaptationEventInit : EventInit { + DOMString adaptationType; + any suggestion; + double confidence; + DOMString rationale; +}; +``` + +The `adaptationevent` is fired when the neuro-symbolic engine suggests a configuration change. Event handlers can approve, reject, or defer the suggestion. + +**Event types:** +- `skillunlock` - A new skill has been unlocked in a skill tree +- `fastpathsuggestion` - A fast path optimization is available +- `jointventureproposal` - A joint venture between departments is suggested +- `priorityreorder` - Task board priority reordering is suggested +- `cachestrategychange` - A cache strategy adaptation is suggested + +--- + +## 4. Algorithms + +### 4.1 Explain Operation + +When the `getDecisionExplanation(operationId)` method is called: + +1. Let *operation* be the operation record identified by *operationId*. +2. Let *role* be the Role that executed *operation*. +3. Let *delegationChain* be the delegation chain leading to *operation*. +4. Let *factors* be an empty DecisionFactors dictionary. +5. For each *factor* in *operation*'s recorded decision factors: + 1. Set *factors*[*factor*.name] to *factor*.value. +6. Let *alternatives* be an empty sequence. +7. For each *path* considered but not taken: + 1. Append a new AlternativePath with *path*.strategy, *path*.rejectionReason, and *path*.estimatedConfidence. +8. Let *narrative* be the result of generating a natural language explanation from *role*, *delegationChain*, *factors*, and *alternatives*. +9. Let *confidence* be the calculated confidence score based on historical success rates. +10. Return a new ExecutionExplanation with the collected data. + +### 4.2 Record Skill Use + +When the `recordSkillUse(skill, success)` method is called: + +1. Let *skillRecord* be the Skill identified by *skill*. +2. If *success* is true: + 1. Increment *skillRecord*.successCount. + 2. Let *delta* be `0.1 * (1 - skillRecord.proficiency / 5.0)`. + 3. Set *skillRecord*.proficiency to min(5.0, *skillRecord*.proficiency + *delta*). +3. Else: + 1. Increment *skillRecord*.failureCount. + 2. Let *delta* be `0.05 * skillRecord.proficiency`. + 3. Set *skillRecord*.proficiency to max(0.0, *skillRecord*.proficiency - *delta*). +4. Check if any dependent skills should be unlocked. +5. Fire an `adaptationevent` of type `skillunlock` for each newly unlocked skill. + +### 4.3 Niche Construction Cycle + +The Niche Construction Engine runs continuously in the background: + +1. **Observation Phase**: + 1. For each registered pattern observer: + 1. Collect samples from matching operations. + 2. Compute statistics (frequency, duration, success rate). + 3. Identify anomalies and trends. + +2. **Hypothesis Generation**: + 1. For each observed pattern with optimization potential: + 1. Generate a Hypothesis describing the proposed change. + 2. Calculate expected improvement and confidence. + 3. Fire an `adaptationevent` of type appropriate to the optimization. + +3. **Experimentation**: + 1. For each approved Hypothesis: + 1. Create a shadow implementation. + 2. Route a percentage of traffic to the shadow. + 3. Collect comparative metrics. + 4. Determine statistical significance. + +4. **Integration**: + 1. For each successful Experiment: + 1. If auto-integrate is enabled or explicitly approved: + 1. Promote shadow implementation to primary. + 2. Update skill trees and delegation chains. + 3. Log the adaptation in the Academy Journal. + +--- + +## 5. Integration with Service Workers + +### 5.1 ServiceWorkerGlobalScope Extension + +The `academy` attribute on ServiceWorkerGlobalScope provides access to the ExecutionAcademy for the current service worker context. + +```javascript +self.addEventListener('fetch', async (event) => { + const academy = self.academy; + + if (academy.explainabilityEnabled) { + const operationId = crypto.randomUUID(); + + event.respondWith((async () => { + const response = await handleFetch(event.request, operationId); + + // Log explanation for debugging + const explanation = await academy.getDecisionExplanation(operationId); + console.log(explanation.narrative); + + return response; + })()); + } else { + event.respondWith(handleFetch(event.request)); + } +}); +``` + +### 5.2 AdaptationEvent Handling + +```javascript +self.academy.addEventListener('adaptation', (event) => { + switch (event.adaptationType) { + case 'fastpathsuggestion': + console.log(`Fast path suggested: ${event.rationale}`); + if (event.confidence > 0.9) { + event.approve(); + } else { + event.defer(); + } + break; + + case 'cachestrategychange': + // Require manual approval for cache strategy changes + self.clients.matchAll().then(clients => { + clients.forEach(client => { + client.postMessage({ + type: 'ADAPTATION_SUGGESTION', + data: event.suggestion, + confidence: event.confidence, + rationale: event.rationale + }); + }); + }); + break; + + default: + event.defer(); + } +}); +``` + +--- + +## 6. Security Considerations + +### 6.1 Information Leakage + +Execution explanations may reveal sensitive information about system behavior. Implementations MUST: + +1. Sanitize explanations before exposing to untrusted contexts. +2. Rate-limit explanation requests to prevent timing attacks. +3. Not include raw timing data that could enable side-channel attacks. + +### 6.2 Adaptation Safety + +Neuro-symbolic adaptations could be exploited to degrade service. Implementations MUST: + +1. Require explicit approval for security-sensitive adaptations. +2. Maintain rollback capability for all adaptations. +3. Rate-limit adaptation events to prevent denial-of-service. +4. Log all adaptations for audit purposes. + +### 6.3 Cross-Origin Considerations + +Knowledge Sharing Agreements between Departments in different origins MUST respect the same-origin policy unless explicitly configured with appropriate CORS headers. + +--- + +## 7. Privacy Considerations + +### 7.1 Pattern Learning + +The Niche Construction Engine observes execution patterns that may include user behavior signals. Implementations MUST: + +1. Anonymize pattern data before storage. +2. Provide users with controls to disable pattern learning. +3. Clear learned patterns when browsing data is cleared. + +### 7.2 Skill Trees + +Skill proficiency data could fingerprint browser behavior. Implementations SHOULD: + +1. Initialize skill trees with randomized baseline values. +2. Limit skill tree data to session scope by default. + +--- + +## 8. Examples + +### 8.1 Complete Fetch Handler with Explainability + +```javascript +// sw.js - Service Worker with Execution Academy +import { CommitmentChain } from './academy.js'; + +self.addEventListener('activate', () => { + self.academy.enableExplainability(); + + // Set up niche construction + const constructor = new NicheConstructor(self.academy); + constructor.observe('fetch:*', { samplingRate: 0.1 }); + constructor.observe('cache:hit', { samplingRate: 1.0 }); + constructor.observe('cache:miss', { samplingRate: 1.0 }); +}); + +self.addEventListener('fetch', (event) => { + const operationId = crypto.randomUUID(); + + event.respondWith((async () => { + // Create commitment chain for explainability + const chain = CommitmentChain.from( + caches.match(event.request) + .then(cached => { + if (cached) { + return { source: 'cache', response: cached }; + } + return fetch(event.request) + .then(response => ({ source: 'network', response })); + }) + ); + + // Record skill use based on outcome + const role = self.academy.getDepartment('Fetch').getRole('CacheSpecialist'); + + try { + const result = await chain; + role.recordSkillUse(result.source === 'cache' ? 'cache-first' : 'network-first', true); + return result.response; + } catch (error) { + role.recordSkillUse('fallback', false); + throw error; + } + })()); +}); +``` + +### 8.2 Skill Tree Visualization + +```javascript +function visualizeSkillTree(skillTree) { + const skills = skillTree.skills; + + return skills.map(skill => ({ + name: skill.name, + proficiency: 'โ˜…'.repeat(Math.floor(skill.proficiency)) + + 'โ˜†'.repeat(5 - Math.floor(skill.proficiency)), + successRate: (skill.getSuccessRate() * 100).toFixed(1) + '%', + unlocked: skill.isUnlocked ? 'โœ“' : '๐Ÿ”’', + prerequisites: skill.prerequisites.map(p => p.name) + })); +} + +// Example output: +// [ +// { name: 'fetch', proficiency: 'โ˜…โ˜…โ˜…โ˜…โ˜…', successRate: '99.2%', unlocked: 'โœ“', prerequisites: [] }, +// { name: 'cache-first', proficiency: 'โ˜…โ˜…โ˜…โ˜…โ˜†', successRate: '94.1%', unlocked: 'โœ“', prerequisites: ['fetch'] }, +// { name: 'predictive-prefetch', proficiency: 'โ˜…โ˜†โ˜†โ˜†โ˜†', successRate: '67.3%', unlocked: 'โœ“', prerequisites: ['cache-first'] } +// ] +``` + +--- + +## Appendix A: Glossary + +| Term | Definition | +|------|------------| +| Academy | The overall framework for explainable, adaptive execution | +| Adaptation | A learned optimization applied to execution patterns | +| Commitment | A single step in a promise chain with confidence scoring | +| Delegation | The act of one Role assigning work to another | +| Department | A realm wrapper representing an organizational unit | +| Employee | An agent wrapper representing the actual worker | +| Fast Path | An optimized shortcut through a frequent delegation chain | +| Hypothesis | A proposed optimization awaiting experimental validation | +| Joint Venture | Collaboration between Departments across boundaries | +| Niche Construction | The process of shaping the environment to facilitate adaptation | +| Proficiency | A skill's competence level (0-5 stars) | +| Role | An execution context wrapper representing a team member | +| Skill Tree | Hierarchical structure of operation proficiencies | + +--- + +## Appendix B: References + +### Normative References + +- [ECMA-262] ECMAScriptยฎ 2024 Language Specification + https://tc39.es/ecma262/ + +- [SERVICE-WORKERS] Service Workers Nightly + https://w3c.github.io/ServiceWorker/ + +- [FETCH] Fetch Standard + https://fetch.spec.whatwg.org/ + +### Informative References + +- Niche Construction: The Neglected Process in Evolution + Odling-Smee, F. J., Laland, K. N., & Feldman, M. W. (2003) + +- Situated Cognition and the Culture of Learning + Brown, J. S., Collins, A., & Duguid, P. (1989) + +- Distributed Cognition: Toward a New Foundation for Human-Computer Interaction Research + Hollan, J., Hutchins, E., & Kirsh, D. (2000) diff --git a/docs/execution-academy/src/academy.js b/docs/execution-academy/src/academy.js new file mode 100644 index 00000000..f1a63cb9 --- /dev/null +++ b/docs/execution-academy/src/academy.js @@ -0,0 +1,711 @@ +/** + * @fileoverview The Execution Academy - Neuro-Symbolic Training System + * + * Maps ECMA-262 execution primitives to human-readable "academy" concepts: + * - Execution Context โ†’ Role (Project Role with responsibilities) + * - Realm โ†’ Department (Isolated organizational unit) + * - Agent โ†’ Employee (Actual worker performing tasks) + * - Job Queue โ†’ Task Board (Prioritized work items) + * - Call Stack โ†’ Chain of Delegation (Traceability) + * - Scope Chain โ†’ Access Hierarchy (Information access) + * - Lexical Environment โ†’ Personal Workspace (Tools accessible) + * - Variable Environment โ†’ Shared Supplies (Team resources) + * + * @license W3C Software and Document License + * @see https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + */ + +'use strict'; + +/** + * Core Role class - wraps ECMA-262 Execution Context concept + * A Role represents a team member with specific responsibilities, + * tools, and knowledge scope that can expand/contract based on task complexity. + */ +class Role { + /** + * @param {string} name - Human-readable role name + * @param {Department} department - Parent department (realm) + * @param {Object} options - Configuration options + */ + constructor(name, department, options = {}) { + this.name = name; + this.department = department; + this.id = `role_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; + + // Role boundaries (can expand/contract) + this.responsibilities = new Set(options.responsibilities || []); + this.tools = new Map(); // tool name โ†’ proficiency level (1-5) + this.knowledgeScope = new Set(options.knowledgeScope || []); + + // Delegation chain (call stack analog) + this.delegator = options.delegator || null; + this.delegates = []; + + // Access hierarchy (scope chain analog) + this.accessHierarchy = []; + + // Personal workspace (lexical environment) + this.workspace = new Map(); + + // Statistics for niche construction + this.stats = { + invocations: 0, + successRate: 1.0, + avgResolutionTime: 0, + commonPatterns: new Map() + }; + + // Adaptation history + this.adaptations = []; + } + + /** + * Expand role boundaries when beneficial + * @param {string} capability - New capability to add + * @param {string} reason - Reason for expansion + */ + expandBoundary(capability, reason) { + this.responsibilities.add(capability); + this.adaptations.push({ + type: 'expand', + capability, + reason, + timestamp: Date.now() + }); + return this; + } + + /** + * Contract role boundaries when over-specialized + * @param {string} capability - Capability to remove + * @param {string} reason - Reason for contraction + */ + contractBoundary(capability, reason) { + this.responsibilities.delete(capability); + this.adaptations.push({ + type: 'contract', + capability, + reason, + timestamp: Date.now() + }); + return this; + } + + /** + * Delegate work to another role (push to delegation chain) + * @param {Role} targetRole - Role to delegate to + * @param {string} task - Task description + * @returns {DelegationContext} + */ + delegate(targetRole, task) { + targetRole.delegator = this; + this.delegates.push(targetRole); + + return new DelegationContext(this, targetRole, task); + } + + /** + * Access resource through hierarchy + * @param {string} resourceName - Name of resource to access + * @returns {*} Resource value or undefined + */ + access(resourceName) { + // First check personal workspace + if (this.workspace.has(resourceName)) { + return this.workspace.get(resourceName); + } + + // Then check access hierarchy + for (const scope of this.accessHierarchy) { + if (scope.has(resourceName)) { + return scope.get(resourceName); + } + } + + // Finally check department shared supplies + return this.department?.sharedSupplies.get(resourceName); + } + + /** + * Store resource in personal workspace + * @param {string} name - Resource name + * @param {*} value - Resource value + */ + store(name, value) { + this.workspace.set(name, value); + return this; + } + + /** + * Record invocation for statistics + * @param {number} duration - Duration in milliseconds + * @param {boolean} success - Whether invocation succeeded + */ + recordInvocation(duration, success) { + const stats = this.stats; + stats.invocations++; + + // Update success rate (rolling average) + const alpha = 0.1; // smoothing factor + stats.successRate = stats.successRate * (1 - alpha) + (success ? 1 : 0) * alpha; + + // Update average resolution time + stats.avgResolutionTime = stats.avgResolutionTime * (1 - alpha) + duration * alpha; + } + + /** + * Get explanation of role's current state + * @returns {Object} Human-readable explanation + */ + explain() { + return { + identity: `Role: ${this.name}`, + department: this.department?.name || 'Independent', + responsibilities: Array.from(this.responsibilities), + toolProficiencies: Object.fromEntries(this.tools), + delegationDepth: this.getDelegationDepth(), + statistics: { + invocations: this.stats.invocations, + successRate: `${(this.stats.successRate * 100).toFixed(1)}%`, + avgResolutionTime: `${this.stats.avgResolutionTime.toFixed(2)}ms` + }, + recentAdaptations: this.adaptations.slice(-5) + }; + } + + /** + * Calculate current delegation depth + * @returns {number} + */ + getDelegationDepth() { + let depth = 0; + let current = this; + while (current.delegator) { + depth++; + current = current.delegator; + } + return depth; + } +} + +/** + * Department class - wraps ECMA-262 Realm concept + * An isolated organizational unit with its own culture, resources, and protocols. + * Can form "joint ventures" when problems span boundaries. + */ +class Department { + /** + * @param {string} name - Department name + * @param {Object} options - Configuration options + */ + constructor(name, options = {}) { + this.name = name; + this.id = `dept_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; + + // Roles within this department + this.roles = new Map(); + + // Shared supplies (variable environment analog) + this.sharedSupplies = new Map(); + + // Department protocols + this.protocols = new Map(); + + // Joint ventures with other departments + this.jointVentures = []; + + // Global role (execution context for global code) + this.globalRole = new Role('Global Coordinator', this, { + responsibilities: ['initialization', 'event-coordination'] + }); + this.roles.set('global', this.globalRole); + } + + /** + * Create a new role in this department + * @param {string} name - Role name + * @param {Object} options - Role options + * @returns {Role} + */ + createRole(name, options = {}) { + const role = new Role(name, this, options); + this.roles.set(role.id, role); + return role; + } + + /** + * Form a joint venture with another department + * @param {Department} other - Other department + * @param {string} purpose - Purpose of joint venture + * @returns {JointVenture} + */ + formJointVenture(other, purpose) { + const venture = new JointVenture([this, other], purpose); + this.jointVentures.push(venture); + other.jointVentures.push(venture); + return venture; + } + + /** + * Share supply with all roles + * @param {string} name - Supply name + * @param {*} value - Supply value + */ + shareSupply(name, value) { + this.sharedSupplies.set(name, value); + return this; + } + + /** + * Get explanation of department's current state + * @returns {Object} + */ + explain() { + return { + identity: `Department: ${this.name}`, + roleCount: this.roles.size, + roles: Array.from(this.roles.values()).map(r => r.name), + sharedSupplies: Array.from(this.sharedSupplies.keys()), + jointVentures: this.jointVentures.map(jv => jv.purpose), + protocols: Array.from(this.protocols.keys()) + }; + } +} + +/** + * Employee class - wraps ECMA-262 Agent concept + * The actual worker performing tasks, bound to a department. + * Develops specializations over time and can mentor across departments. + */ +class Employee { + /** + * @param {string} name - Employee name + * @param {Department} department - Bound department + */ + constructor(name, department) { + this.name = name; + this.department = department; + this.id = `emp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; + + // Current role being performed + this.currentRole = null; + + // Task board (job queue) + this.taskBoard = new TaskBoard(); + + // Specializations developed over time + this.specializations = new Map(); // skill โ†’ proficiency + + // Mentorship relationships + this.mentees = []; + this.mentors = []; + + // Performance history + this.history = []; + } + + /** + * Assume a role + * @param {Role} role - Role to assume + */ + assumeRole(role) { + if (this.currentRole) { + this.history.push({ + role: this.currentRole.name, + duration: Date.now() - this.roleStartTime + }); + } + this.currentRole = role; + this.roleStartTime = Date.now(); + return this; + } + + /** + * Pick up next task from board + * @returns {Task|null} + */ + pickupTask() { + return this.taskBoard.dequeue(); + } + + /** + * Develop a specialization + * @param {string} skill - Skill name + * @param {number} experience - Experience points gained + */ + develop(skill, experience) { + const current = this.specializations.get(skill) || 0; + this.specializations.set(skill, Math.min(5, current + experience)); + return this; + } + + /** + * Mentor another employee + * @param {Employee} mentee - Employee to mentor + * @param {string} skill - Skill to teach + */ + mentor(mentee, skill) { + if (this.specializations.has(skill)) { + this.mentees.push({ employee: mentee, skill }); + mentee.mentors.push({ employee: this, skill }); + + // Transfer some proficiency + const myLevel = this.specializations.get(skill); + mentee.develop(skill, myLevel * 0.1); + } + return this; + } + + /** + * Get explanation of employee's current state + * @returns {Object} + */ + explain() { + return { + identity: `Employee: ${this.name}`, + department: this.department.name, + currentRole: this.currentRole?.name || 'Idle', + pendingTasks: this.taskBoard.size(), + specializations: Object.fromEntries(this.specializations), + menteeCount: this.mentees.length, + mentorCount: this.mentors.length + }; + } +} + +/** + * TaskBoard class - wraps ECMA-262 Job Queue concept + * Prioritized work items with learned urgency patterns. + */ +class TaskBoard { + constructor() { + this.tasks = []; + this.urgencyPatterns = new Map(); + } + + /** + * Add task to board + * @param {Task} task - Task to add + * @param {string} priority - Priority level + */ + enqueue(task, priority = 'normal') { + // Learn urgency from task type + const learnedPriority = this.urgencyPatterns.get(task.type) || priority; + + const entry = { + task, + priority: learnedPriority, + timestamp: Date.now() + }; + + // Insert based on priority + const priorityOrder = { critical: 0, high: 1, normal: 2, low: 3 }; + const insertIdx = this.tasks.findIndex( + t => priorityOrder[t.priority] > priorityOrder[entry.priority] + ); + + if (insertIdx === -1) { + this.tasks.push(entry); + } else { + this.tasks.splice(insertIdx, 0, entry); + } + + return this; + } + + /** + * Get next task + * @returns {Task|null} + */ + dequeue() { + const entry = this.tasks.shift(); + return entry?.task || null; + } + + /** + * Update urgency pattern based on observed behavior + * @param {string} taskType - Type of task + * @param {string} observedPriority - Observed urgency + */ + learnUrgency(taskType, observedPriority) { + this.urgencyPatterns.set(taskType, observedPriority); + return this; + } + + /** + * Get board size + * @returns {number} + */ + size() { + return this.tasks.length; + } +} + +/** + * Task class - represents a unit of work + */ +class Task { + constructor(type, description, handler) { + this.type = type; + this.description = description; + this.handler = handler; + this.id = `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; + this.createdAt = Date.now(); + this.state = 'pending'; + } + + /** + * Execute the task + * @param {Role} executingRole - Role executing this task + * @returns {Promise} + */ + async execute(executingRole) { + this.state = 'running'; + const startTime = Date.now(); + + try { + const result = await this.handler(executingRole); + this.state = 'completed'; + executingRole.recordInvocation(Date.now() - startTime, true); + return result; + } catch (error) { + this.state = 'failed'; + this.error = error; + executingRole.recordInvocation(Date.now() - startTime, false); + throw error; + } + } +} + +/** + * DelegationContext - wraps delegation chain state + */ +class DelegationContext { + constructor(delegator, delegate, task) { + this.delegator = delegator; + this.delegate = delegate; + this.task = task; + this.depth = delegate.getDelegationDepth(); + this.startTime = Date.now(); + } + + /** + * Get chain explanation + * @returns {string} + */ + explainChain() { + const chain = []; + let current = this.delegate; + + while (current) { + chain.unshift(current.name); + current = current.delegator; + } + + return chain.join(' โ†’ '); + } +} + +/** + * JointVenture - collaboration between departments + */ +class JointVenture { + constructor(departments, purpose) { + this.departments = departments; + this.purpose = purpose; + this.id = `jv_${Date.now()}`; + this.sharedKnowledge = new Map(); + this.protocols = new Map(); + } + + /** + * Share knowledge across venture + * @param {string} key - Knowledge key + * @param {*} value - Knowledge value + */ + share(key, value) { + this.sharedKnowledge.set(key, value); + return this; + } + + /** + * Access shared knowledge + * @param {string} key - Knowledge key + * @returns {*} + */ + access(key) { + return this.sharedKnowledge.get(key); + } +} + +/** + * The Execution Academy - main entry point + * Container for all academy operations + */ +class ExecutionAcademy { + constructor(name = 'Main Academy') { + this.name = name; + this.departments = new Map(); + this.employees = new Map(); + this.nicheConstructor = new NicheConstructor(this); + this.explainabilityLayer = new ExplainabilityLayer(this); + + // Shared facilities + this.messageHall = new TaskBoard(); // Global job queue + this.archiveRoom = new Map(); // Heap/memory + this.trainingYard = new TrainingYard(this); // Optimization engine + } + + /** + * Create a new department (realm) + * @param {string} name - Department name + * @returns {Department} + */ + createDepartment(name) { + const dept = new Department(name); + this.departments.set(dept.id, dept); + return dept; + } + + /** + * Hire a new employee (agent) + * @param {string} name - Employee name + * @param {Department} department - Department to join + * @returns {Employee} + */ + hire(name, department) { + const employee = new Employee(name, department); + this.employees.set(employee.id, employee); + return employee; + } + + /** + * Archive data (store in heap) + * @param {string} key - Archive key + * @param {*} value - Value to archive + */ + archive(key, value) { + this.archiveRoom.set(key, { + value, + archivedAt: Date.now(), + accessCount: 0 + }); + return this; + } + + /** + * Retrieve from archive + * @param {string} key - Archive key + * @returns {*} + */ + retrieve(key) { + const entry = this.archiveRoom.get(key); + if (entry) { + entry.accessCount++; + return entry.value; + } + return undefined; + } + + /** + * Get full academy explanation + * @returns {Object} + */ + explain() { + return { + academy: this.name, + departments: Array.from(this.departments.values()).map(d => d.explain()), + employees: Array.from(this.employees.values()).map(e => e.explain()), + messageHallSize: this.messageHall.size(), + archiveSize: this.archiveRoom.size, + adaptationSuggestions: this.nicheConstructor.getSuggestions() + }; + } +} + +/** + * TrainingYard - optimization engine + */ +class TrainingYard { + constructor(academy) { + this.academy = academy; + this.experiments = []; + this.successfulOptimizations = []; + } + + /** + * Run an optimization experiment + * @param {Object} hypothesis - Optimization hypothesis + * @returns {Object} Experiment results + */ + async experiment(hypothesis) { + const experiment = { + id: `exp_${Date.now()}`, + hypothesis, + startTime: Date.now(), + state: 'running' + }; + + this.experiments.push(experiment); + + // Simulate experiment (in real impl, would do shadow testing) + experiment.result = await this.runShadowTest(hypothesis); + experiment.state = 'completed'; + experiment.endTime = Date.now(); + + if (experiment.result.improvement > 0) { + this.successfulOptimizations.push(experiment); + } + + return experiment; + } + + /** + * Run shadow test for hypothesis + * @param {Object} hypothesis - Hypothesis to test + * @returns {Object} Test results + */ + async runShadowTest(hypothesis) { + // Placeholder for actual shadow testing logic + return { + improvement: Math.random() * 0.2 - 0.05, // -5% to +15% + confidence: Math.random() * 0.3 + 0.7, // 70-100% + sampleSize: Math.floor(Math.random() * 1000) + 100 + }; + } +} + +// Forward declarations for circular dependencies +class NicheConstructor { + constructor(academy) { + this.academy = academy; + } + getSuggestions() { + return []; // Implemented in niche-constructor.js + } +} + +class ExplainabilityLayer { + constructor(academy) { + this.academy = academy; + } +} + +// Export all classes +export { + ExecutionAcademy, + Department, + Role, + Employee, + TaskBoard, + Task, + DelegationContext, + JointVenture, + TrainingYard, + NicheConstructor, + ExplainabilityLayer +}; + +// Default export +export default ExecutionAcademy; diff --git a/docs/execution-academy/src/dashboard.html b/docs/execution-academy/src/dashboard.html new file mode 100644 index 00000000..d0a2f43b --- /dev/null +++ b/docs/execution-academy/src/dashboard.html @@ -0,0 +1,888 @@ + + + + + + Execution Academy Dashboard + + + +
+
+

๐ŸŽ“ The Execution Academy

+

ECMA-262 as a Neuro-Symbolic Training System

+
+ + +
+
+
+
3
+
Departments
+
+
+
12
+
Active Roles
+
+
+
47
+
Tasks Completed
+
+
+
97%
+
Avg. Confidence
+
+
+
+ +
+ +
+
+ ๐Ÿข +

Departments (Realms)

+
+
+
+
Department A
+
+ + Global Coordinator +
+
+ + Event Handler +
+
+ + UI Renderer +
+
+
+
Department B
+
+ + API Handler +
+
+ + Fetch Specialist +
+
+
+
Department C
+
+ + Data Transform +
+
+ + Cache Manager +
+
+
+
+ + +
+
+ ๐ŸŒณ +

Fetch Specialist Skill Tree

+
+
+
+ โ””โ”€โ”€ FETCH (Base) + โ˜…โ˜…โ˜…โ˜…โ˜… +
+
+ โ”œโ”€โ”€ CACHE-FIRST + โ˜…โ˜…โ˜…โ˜…โ˜† +
+
+ โ””โ”€โ”€ PREDICTIVE-PREFETCH + โ˜…โ˜†โ˜†โ˜†โ˜† +
+
+ โ”œโ”€โ”€ NETWORK-FIRST + โ˜…โ˜…โ˜…โ˜†โ˜† +
+
+ โ””โ”€โ”€ ADAPTIVE-TIMEOUT + โ˜…โ˜…โ˜…โ˜†โ˜† +
+
+ โ””โ”€โ”€ STALE-WHILE-REVALIDATE + โ˜…โ˜…โ˜†โ˜†โ˜† +
+
+
+ + +
+
+ + +
+
+ ๐Ÿ“‹ +

Task Board (Job Queue)

+
+
+
+
+
+
fetch
+
GET /api/users (cache miss)
+
+
+
+
+
+
cache
+
Update manifest v2.3.1
+
+
+
+
+
+
sync
+
Background sync pending
+
+
+
+
+
+
cleanup
+
Prune stale cache entries
+
+
+
+
+ + +
+
+ ๐Ÿ” +

Execution Explanation Panel

+
+
+
+

๐Ÿ“– Current Operation: fetch('/api/users')

+

The UI Renderer asked the Event Coordinator for user data. The Event Coordinator delegated to the Fetch Specialist, who noticed this endpoint was requested 47 times today.

+
+
+

๐Ÿง  Decision Factors

+
Cache hit rate: 94%
+
Data freshness: 3s (tolerance: 30s)
+
Network conditions: Good
+
Context: Browsing (non-critical)
+
+
+

๐Ÿ“Š Confidence

+
97% (based on 847 similar decisions)
+
+
+
+
+
+
+ + +
+
+ ๐Ÿ”ง +

Niche Construction Engine

+
+
+
+
1
+
+
Observation
+
1,247 observations โ€ข 23 patterns detected
+
+
+
+
2
+
+
Hypothesis Generation
+
8 hypotheses โ€ข 3 ready for testing
+
+
+
+
3
+
+
Safe Experimentation
+
2 running โ€ข 12 completed
+
+
+
+
4
+
+
Integration
+
7 optimizations active
+
+
+
+
5
+
+
Environmental Modification
+
15 scope reshapes โ€ข 3 priority adjustments
+
+
+
+
+ + +
+
+ ๐Ÿ’ก +

Adaptation Suggestions

+
+
+
+
+ pattern-detected + HIGH +
+
+ fetch('/api/users') operations account for 52% of recent activity. + Consider creating a FastPath optimization. +
+
+
+
+ integration-ready + MEDIUM +
+
+ Validated optimization "Cache-First for static assets" ready for integration. + Expected improvement: 23%. +
+
+
+
+ skill-unlock + LOW +
+
+ 2 skills are still locked in Cache Manager tree. + Focus on prerequisite skills to unlock new capabilities. +
+
+
+
+ + +
+
+ + +
+
+ ๐Ÿค +

Knowledge Sharing Agreement

+
+

+ ServiceWorker "Cache Manager" โ†” Window "UI Render" +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+ ๐Ÿ”— +

Commitment Chain (Promise)

+
+
+
+ ๐Ÿ“‹ COMMITMENT CHAIN +
+
+ โ”œโ”€โ”€ ๐Ÿค "I will fetch data from /api/users" +
+
+ โ””โ”€โ”€ Confidence: HIGH (network available) +
+
+ โ””โ”€โ”€ Fallback: Use cached version if network fails +
+
+ โ”œโ”€โ”€ ๐Ÿ”„ "When data arrives, I will parse it as JSON" +
+
+ โ””โ”€โ”€ Confidence: MEDIUM (depends on format) +
+
+ โ””โ”€โ”€ Adaptation: Try XML, then plain text +
+
+ โ””โ”€โ”€ โœจ "I will process the parsed data" +
+
+ โ””โ”€โ”€ Confidence: Variable (depends on data) +
+
+
+
+ +
+

+ Execution Academy Dashboard โ€ข Part of the + W3C Service Workers Specification +

+

+ Based on ECMA-262 execution model with neuro-symbolic adaptations +

+
+
+ + + + diff --git a/docs/execution-academy/src/explainable-worker.js b/docs/execution-academy/src/explainable-worker.js new file mode 100644 index 00000000..8f9568a6 --- /dev/null +++ b/docs/execution-academy/src/explainable-worker.js @@ -0,0 +1,784 @@ +/** + * @fileoverview ExplainableWorker - Human-readable execution explainability layer + * + * Provides natural language explanations for every execution decision, + * implementing the Execution Explanation Panel concept from the Academy. + * + * @license W3C Software and Document License + * @see https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + */ + +'use strict'; + +import { ExecutionAcademy, Role, Task } from './academy.js'; + +/** + * Decision record for explanations + */ +class Decision { + /** + * @param {string} operationId - Unique operation identifier + * @param {string} operationType - Type of operation (fetch, cache, compute, etc.) + * @param {Object} context - Decision context + */ + constructor(operationId, operationType, context = {}) { + this.operationId = operationId; + this.operationType = operationType; + this.context = context; + this.timestamp = Date.now(); + this.factors = []; + this.alternativesConsidered = []; + this.chosenPath = null; + this.confidence = 0; + this.narrative = ''; + } + + /** + * Add a decision factor + * @param {string} name - Factor name + * @param {*} value - Factor value + * @param {number} weight - Factor weight in decision + */ + addFactor(name, value, weight = 1) { + this.factors.push({ name, value, weight }); + return this; + } + + /** + * Add an alternative that was considered + * @param {string} alternative - Alternative path + * @param {string} rejectionReason - Why it was rejected + */ + addAlternative(alternative, rejectionReason) { + this.alternativesConsidered.push({ alternative, rejectionReason }); + return this; + } + + /** + * Set the chosen path + * @param {string} path - Chosen execution path + * @param {number} confidence - Confidence level (0-1) + */ + choose(path, confidence) { + this.chosenPath = path; + this.confidence = confidence; + return this; + } + + /** + * Generate narrative explanation + * @returns {string} + */ + generateNarrative() { + const parts = []; + + // Opening + parts.push(`Operation: ${this.operationType}`); + + // Context + if (this.context.requester) { + parts.push(`The ${this.context.requester} requested this operation.`); + } + + // Factors considered + if (this.factors.length > 0) { + parts.push('Decision factors:'); + this.factors.forEach(f => { + parts.push(` โ€ข ${f.name}: ${f.value}`); + }); + } + + // Chosen path + if (this.chosenPath) { + parts.push(`Chosen strategy: ${this.chosenPath}`); + parts.push(`Confidence: ${(this.confidence * 100).toFixed(1)}%`); + } + + // Alternatives + if (this.alternativesConsidered.length > 0) { + parts.push('Alternatives considered:'); + this.alternativesConsidered.forEach(alt => { + parts.push(` โ€ข ${alt.alternative}: ${alt.rejectionReason}`); + }); + } + + this.narrative = parts.join('\n'); + return this.narrative; + } +} + +/** + * Skill in a skill tree + */ +class Skill { + /** + * @param {string} name - Skill name + * @param {string} category - Skill category + * @param {Skill[]} prerequisites - Required prerequisite skills + */ + constructor(name, category, prerequisites = []) { + this.name = name; + this.category = category; + this.prerequisites = prerequisites; + this.proficiency = 0; // 0-5 stars + this.usageCount = 0; + this.successCount = 0; + this.children = []; + } + + /** + * Record skill usage + * @param {boolean} success - Whether usage was successful + */ + recordUsage(success) { + this.usageCount++; + if (success) { + this.successCount++; + // Gain proficiency on success + this.proficiency = Math.min(5, this.proficiency + 0.01); + } else { + // Slight decrease on failure + this.proficiency = Math.max(0, this.proficiency - 0.005); + } + return this; + } + + /** + * Check if skill is unlocked (prerequisites met) + * @returns {boolean} + */ + isUnlocked() { + return this.prerequisites.every(p => p.proficiency >= 1); + } + + /** + * Get skill display + * @returns {string} + */ + getDisplay() { + const stars = 'โ˜…'.repeat(Math.floor(this.proficiency)) + + 'โ˜†'.repeat(5 - Math.floor(this.proficiency)); + const locked = this.isUnlocked() ? '' : ' ๐Ÿ”’'; + return `${this.name} ${stars}${locked}`; + } +} + +/** + * SkillTree - collection of skills with dependencies + */ +class SkillTree { + /** + * @param {string} name - Tree name (e.g., "Fetch Specialist") + */ + constructor(name) { + this.name = name; + this.skills = new Map(); + this.rootSkills = []; + } + + /** + * Add a skill to the tree + * @param {Skill} skill - Skill to add + * @param {Skill} parent - Parent skill (optional) + */ + addSkill(skill, parent = null) { + this.skills.set(skill.name, skill); + + if (parent) { + parent.children.push(skill); + } else { + this.rootSkills.push(skill); + } + + return skill; + } + + /** + * Get skill by name + * @param {string} name - Skill name + * @returns {Skill|undefined} + */ + getSkill(name) { + return this.skills.get(name); + } + + /** + * Get tree visualization + * @returns {string} + */ + visualize() { + const lines = [`โ”Œโ”€ ${this.name} โ”€โ”`]; + + const renderSkill = (skill, prefix = '') => { + lines.push(`${prefix}โ”œโ”€โ”€ ${skill.getDisplay()}`); + skill.children.forEach((child, idx) => { + const isLast = idx === skill.children.length - 1; + const newPrefix = prefix + (isLast ? ' ' : 'โ”‚ '); + renderSkill(child, newPrefix); + }); + }; + + this.rootSkills.forEach(skill => renderSkill(skill)); + lines.push('โ””' + 'โ”€'.repeat(this.name.length + 4) + 'โ”˜'); + + return lines.join('\n'); + } + + /** + * Get proficiency summary + * @returns {Object} + */ + getSummary() { + const skills = Array.from(this.skills.values()); + const totalProficiency = skills.reduce((sum, s) => sum + s.proficiency, 0); + const maxProficiency = skills.length * 5; + + return { + name: this.name, + skillCount: skills.length, + unlockedCount: skills.filter(s => s.isUnlocked()).length, + averageProficiency: totalProficiency / skills.length, + completionPercent: (totalProficiency / maxProficiency * 100).toFixed(1) + }; + } +} + +/** + * ExplainableWorker - main interface for explainability + * Extends ServiceWorker conceptually with explanation capabilities + */ +class ExplainableWorker { + /** + * @param {ExecutionAcademy} academy - Parent academy + */ + constructor(academy) { + this.academy = academy; + this.decisions = new Map(); // operationId โ†’ Decision + this.skillTrees = new Map(); // treeName โ†’ SkillTree + this.explanationHistory = []; + + // Initialize default skill trees + this._initializeSkillTrees(); + } + + /** + * Initialize default skill trees for Service Worker operations + * @private + */ + _initializeSkillTrees() { + // Fetch Specialist Skill Tree + const fetchTree = new SkillTree('Fetch Specialist'); + + const fetchBase = fetchTree.addSkill(new Skill('FETCH', 'core')); + fetchBase.proficiency = 5; // Base skill is maxed + + const cacheFirst = fetchTree.addSkill( + new Skill('CACHE-FIRST', 'strategy', [fetchBase]), + fetchBase + ); + const networkFirst = fetchTree.addSkill( + new Skill('NETWORK-FIRST', 'strategy', [fetchBase]), + fetchBase + ); + const staleWhileRevalidate = fetchTree.addSkill( + new Skill('STALE-WHILE-REVALIDATE', 'strategy', [fetchBase]), + fetchBase + ); + + fetchTree.addSkill( + new Skill('PREDICTIVE-PREFETCH', 'optimization', [cacheFirst]), + cacheFirst + ); + fetchTree.addSkill( + new Skill('ADAPTIVE-TIMEOUT', 'optimization', [networkFirst]), + networkFirst + ); + + this.skillTrees.set('fetch', fetchTree); + + // Cache Manager Skill Tree + const cacheTree = new SkillTree('Cache Manager'); + + const cacheBase = cacheTree.addSkill(new Skill('CACHE-API', 'core')); + cacheBase.proficiency = 5; + + const cacheMatch = cacheTree.addSkill( + new Skill('CACHE-MATCH', 'operation', [cacheBase]), + cacheBase + ); + const cachePut = cacheTree.addSkill( + new Skill('CACHE-PUT', 'operation', [cacheBase]), + cacheBase + ); + const cacheDelete = cacheTree.addSkill( + new Skill('CACHE-DELETE', 'operation', [cacheBase]), + cacheBase + ); + + cacheTree.addSkill( + new Skill('CACHE-VERSIONING', 'advanced', [cacheMatch, cachePut]), + cachePut + ); + cacheTree.addSkill( + new Skill('CACHE-CLEANUP', 'advanced', [cacheDelete]), + cacheDelete + ); + + this.skillTrees.set('cache', cacheTree); + + // Event Handler Skill Tree + const eventTree = new SkillTree('Event Handler'); + + const eventBase = eventTree.addSkill(new Skill('EVENT-LISTENER', 'core')); + eventBase.proficiency = 5; + + const installEvent = eventTree.addSkill( + new Skill('INSTALL-EVENT', 'lifecycle', [eventBase]), + eventBase + ); + const activateEvent = eventTree.addSkill( + new Skill('ACTIVATE-EVENT', 'lifecycle', [eventBase]), + eventBase + ); + const fetchEvent = eventTree.addSkill( + new Skill('FETCH-EVENT', 'functional', [eventBase]), + eventBase + ); + const messageEvent = eventTree.addSkill( + new Skill('MESSAGE-EVENT', 'functional', [eventBase]), + eventBase + ); + + eventTree.addSkill( + new Skill('SKIP-WAITING', 'advanced', [installEvent, activateEvent]), + activateEvent + ); + eventTree.addSkill( + new Skill('CLIENTS-CLAIM', 'advanced', [activateEvent]), + activateEvent + ); + + this.skillTrees.set('event', eventTree); + } + + /** + * Record a decision for later explanation + * @param {string} operationId - Operation identifier + * @param {string} operationType - Type of operation + * @param {Object} context - Decision context + * @returns {Decision} + */ + recordDecision(operationId, operationType, context = {}) { + const decision = new Decision(operationId, operationType, context); + this.decisions.set(operationId, decision); + return decision; + } + + /** + * Get explanation for a specific operation + * @param {string} operationId - Operation identifier + * @returns {Object} Human-readable explanation + */ + getDecisionExplanation(operationId) { + const decision = this.decisions.get(operationId); + + if (!decision) { + return { + error: 'Decision not found', + operationId, + suggestion: 'The operation may have completed before tracking started.' + }; + } + + const explanation = { + operationId, + operationType: decision.operationType, + timestamp: new Date(decision.timestamp).toISOString(), + + narrative: decision.generateNarrative(), + + decisionFactors: decision.factors.map(f => ({ + factor: f.name, + value: String(f.value), + weight: `${(f.weight * 100).toFixed(0)}%` + })), + + alternativePaths: decision.alternativesConsidered.map(alt => ({ + path: alt.alternative, + rejectionReason: alt.rejectionReason + })), + + chosenStrategy: decision.chosenPath, + confidence: `${(decision.confidence * 100).toFixed(1)}%`, + + basedOnSimilarDecisions: this._findSimilarDecisions(decision).length + }; + + // Store in history + this.explanationHistory.push({ + timestamp: Date.now(), + operationId, + explanation + }); + + return explanation; + } + + /** + * Find similar past decisions + * @param {Decision} decision - Current decision + * @returns {Decision[]} + * @private + */ + _findSimilarDecisions(decision) { + const similar = []; + + for (const [id, past] of this.decisions) { + if (id === decision.operationId) continue; + + // Check similarity based on operation type and factors + if (past.operationType === decision.operationType) { + const sharedFactors = past.factors.filter(pf => + decision.factors.some(df => df.name === pf.name) + ); + if (sharedFactors.length >= decision.factors.length * 0.5) { + similar.push(past); + } + } + } + + return similar; + } + + /** + * Get skill tree for a category + * @param {string} category - Skill category (fetch, cache, event) + * @returns {Object} Skill tree information + */ + getSkillTree(category = 'fetch') { + const tree = this.skillTrees.get(category); + + if (!tree) { + return { + error: 'Skill tree not found', + category, + available: Array.from(this.skillTrees.keys()) + }; + } + + return { + category, + visualization: tree.visualize(), + summary: tree.getSummary(), + skills: Array.from(tree.skills.values()).map(s => ({ + name: s.name, + category: s.category, + proficiency: s.proficiency, + proficiencyDisplay: s.getDisplay(), + unlocked: s.isUnlocked(), + usageCount: s.usageCount, + successRate: s.usageCount > 0 + ? `${(s.successCount / s.usageCount * 100).toFixed(1)}%` + : 'N/A' + })) + }; + } + + /** + * Get all skill trees + * @returns {Object} + */ + getAllSkillTrees() { + const trees = {}; + + for (const [name, tree] of this.skillTrees) { + trees[name] = { + visualization: tree.visualize(), + summary: tree.getSummary() + }; + } + + return trees; + } + + /** + * Record skill usage + * @param {string} treeName - Skill tree name + * @param {string} skillName - Skill name + * @param {boolean} success - Whether usage was successful + */ + recordSkillUsage(treeName, skillName, success) { + const tree = this.skillTrees.get(treeName); + if (tree) { + const skill = tree.getSkill(skillName); + if (skill) { + skill.recordUsage(success); + } + } + return this; + } + + /** + * Get adaptation suggestions from niche constructor + * @returns {Object[]} Array of suggestions + */ + getAdaptationSuggestions() { + if (this.academy?.nicheConstructor) { + return this.academy.nicheConstructor.getSuggestions(); + } + + // Generate basic suggestions from skill data + const suggestions = []; + + for (const [name, tree] of this.skillTrees) { + const summary = tree.getSummary(); + + // Suggest unlocking skills if many are locked + const lockedCount = summary.skillCount - summary.unlockedCount; + if (lockedCount > 0) { + suggestions.push({ + type: 'skill-unlock', + tree: name, + message: `${lockedCount} skills are still locked in ${tree.name}. ` + + `Focus on prerequisite skills to unlock new capabilities.`, + priority: 'medium' + }); + } + + // Suggest practice for low proficiency + if (summary.averageProficiency < 2) { + suggestions.push({ + type: 'skill-practice', + tree: name, + message: `Average proficiency in ${tree.name} is ${summary.averageProficiency.toFixed(1)}/5. ` + + `More practice recommended.`, + priority: 'low' + }); + } + } + + // Suggest based on decision patterns + const recentDecisions = Array.from(this.decisions.values()) + .filter(d => Date.now() - d.timestamp < 3600000) // Last hour + .slice(-100); + + if (recentDecisions.length > 50) { + const typeFreq = new Map(); + recentDecisions.forEach(d => { + typeFreq.set(d.operationType, (typeFreq.get(d.operationType) || 0) + 1); + }); + + const mostCommon = Array.from(typeFreq.entries()) + .sort((a, b) => b[1] - a[1])[0]; + + if (mostCommon && mostCommon[1] > recentDecisions.length * 0.5) { + suggestions.push({ + type: 'pattern-detected', + pattern: mostCommon[0], + message: `${mostCommon[0]} operations account for ${(mostCommon[1] / recentDecisions.length * 100).toFixed(0)}% ` + + `of recent activity. Consider creating a FastPath optimization.`, + priority: 'high' + }); + } + } + + return suggestions; + } + + /** + * Generate comprehensive explanation panel + * @param {string} operationId - Operation to explain + * @returns {string} Formatted explanation panel + */ + generateExplanationPanel(operationId) { + const explanation = this.getDecisionExplanation(operationId); + + if (explanation.error) { + return ` +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ ๐Ÿ” EXECUTION EXPLANATION PANEL โ”‚ +โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค +โ”‚ โš ๏ธ ${explanation.error} +โ”‚ Operation ID: ${operationId} +โ”‚ ${explanation.suggestion || ''} +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜`; + } + + const factors = explanation.decisionFactors + .map(f => `โ”‚ โ”œโ”€โ”€ ${f.factor}: ${f.value}`) + .join('\n'); + + const alternatives = explanation.alternativePaths + .map(alt => `โ”‚ โ”œโ”€โ”€ ${alt.path}: ${alt.rejectionReason}`) + .join('\n'); + + return ` +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ ๐Ÿ” EXECUTION EXPLANATION PANEL โ”‚ +โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค +โ”‚ +โ”‚ Current Operation: ${explanation.operationType} +โ”‚ Operation ID: ${operationId} +โ”‚ +โ”‚ ๐Ÿ“– NARRATIVE EXPLANATION: +โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +${explanation.narrative.split('\n').map(line => `โ”‚ ${line}`).join('\n')} +โ”‚ +โ”‚ ๐Ÿง  DECISION FACTORS: +${factors} +โ”‚ +โ”‚ ๐Ÿ”„ ALTERNATIVE PATHS CONSIDERED: +${alternatives || 'โ”‚ โ””โ”€โ”€ None'} +โ”‚ +โ”‚ ๐Ÿ“Š CONFIDENCE: ${explanation.confidence} (based on ${explanation.basedOnSimilarDecisions} similar decisions) +โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜`; + } +} + +/** + * CommitmentChain - Typed Promise Logic as Commitment Protocols + * Wraps promises with confidence scoring and adaptive fallbacks + */ +class CommitmentChain { + /** + * @param {string} description - Human-readable commitment description + * @param {Function} executor - Promise executor + */ + constructor(description, executor) { + this.commitments = [{ + description, + confidence: 1.0, + fallbackPlan: null, + state: 'pending' + }]; + + this.executor = executor; + this.adaptations = []; + } + + /** + * Set confidence level for current commitment + * @param {number} level - Confidence (0-1) + * @param {string} reason - Reason for confidence level + */ + withConfidence(level, reason) { + const current = this.commitments[this.commitments.length - 1]; + current.confidence = level; + current.confidenceReason = reason; + return this; + } + + /** + * Set fallback plan + * @param {string} description - Fallback description + * @param {Function} fallback - Fallback function + */ + withFallback(description, fallback) { + const current = this.commitments[this.commitments.length - 1]; + current.fallbackPlan = { description, handler: fallback }; + return this; + } + + /** + * Add follow-up commitment (then) + * @param {string} description - Commitment description + * @param {Function} handler - Handler function + */ + thenCommit(description, handler) { + // Calculate propagated confidence + const prevConfidence = this.commitments[this.commitments.length - 1].confidence; + + this.commitments.push({ + description, + confidence: prevConfidence * 0.9, // Confidence decays through chain + fallbackPlan: null, + state: 'pending', + handler + }); + + return this; + } + + /** + * Execute the commitment chain + * @returns {Promise} + */ + async execute() { + let result; + + for (let i = 0; i < this.commitments.length; i++) { + const commitment = this.commitments[i]; + commitment.state = 'executing'; + + try { + if (i === 0) { + result = await this.executor(); + } else { + result = await commitment.handler(result); + } + commitment.state = 'fulfilled'; + } catch (error) { + commitment.state = 'rejected'; + commitment.error = error; + + // Try fallback if available + if (commitment.fallbackPlan) { + try { + this.adaptations.push({ + commitment: commitment.description, + usedFallback: commitment.fallbackPlan.description + }); + result = await commitment.fallbackPlan.handler(error, result); + commitment.state = 'fulfilled-via-fallback'; + } catch (fallbackError) { + throw fallbackError; + } + } else { + throw error; + } + } + } + + return result; + } + + /** + * Get chain explanation + * @returns {string} + */ + explain() { + const lines = ['๐Ÿ“‹ COMMITMENT CHAIN']; + + this.commitments.forEach((c, i) => { + const prefix = i === this.commitments.length - 1 ? 'โ””โ”€โ”€' : 'โ”œโ”€โ”€'; + const emoji = { + pending: 'โณ', + executing: '๐Ÿ”„', + fulfilled: 'โœ…', + 'fulfilled-via-fallback': '๐Ÿ”„', + rejected: 'โŒ' + }[c.state]; + + lines.push(`${prefix} ${emoji} ${c.description}`); + lines.push(` โ””โ”€โ”€ Confidence: ${(c.confidence * 100).toFixed(0)}%`); + + if (c.fallbackPlan) { + lines.push(` โ””โ”€โ”€ Fallback: ${c.fallbackPlan.description}`); + } + }); + + return lines.join('\n'); + } +} + +// Export classes +export { + ExplainableWorker, + Decision, + Skill, + SkillTree, + CommitmentChain +}; + +export default ExplainableWorker; diff --git a/docs/execution-academy/src/index.js b/docs/execution-academy/src/index.js new file mode 100644 index 00000000..31a74fd7 --- /dev/null +++ b/docs/execution-academy/src/index.js @@ -0,0 +1,45 @@ +/** + * @fileoverview Entry point for the Execution Academy + * + * Exports all public APIs for the neuro-symbolic training system. + * + * @license W3C Software and Document License + */ + +'use strict'; + +// Core Academy classes +export { + ExecutionAcademy, + Department, + Role, + Employee, + TaskBoard, + Task, + DelegationContext, + JointVenture, + TrainingYard +} from './academy.js'; + +// Explainability layer +export { + ExplainableWorker, + Decision, + Skill, + SkillTree, + CommitmentChain +} from './explainable-worker.js'; + +// Niche construction engine +export { + NicheConstructor, + Observation, + Pattern, + Hypothesis, + Experiment, + KnowledgeSharingAgreement +} from './niche-constructor.js'; + +// Default export: main academy class +import ExecutionAcademy from './academy.js'; +export default ExecutionAcademy; diff --git a/docs/execution-academy/src/niche-constructor.js b/docs/execution-academy/src/niche-constructor.js new file mode 100644 index 00000000..2eaafbac --- /dev/null +++ b/docs/execution-academy/src/niche-constructor.js @@ -0,0 +1,935 @@ +/** + * @fileoverview NicheConstructor - Ecological Niche Construction Engine + * + * Based on ecological niche construction theory, this system doesn't just + * adapt to its environmentโ€”it shapes its environment to make future + * adaptations easier. + * + * Phases: + * 1. OBSERVATION - Monitor execution patterns + * 2. HYPOTHESIS - Generate optimization hypotheses + * 3. EXPERIMENTATION - Safe A/B testing + * 4. INTEGRATION - Promote successful experiments + * 5. MODIFICATION - Reshape environment + * + * @license W3C Software and Document License + * @see https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + */ + +'use strict'; + +/** + * Observation record + */ +class Observation { + /** + * @param {string} type - Observation type + * @param {Object} data - Observation data + */ + constructor(type, data) { + this.type = type; + this.data = data; + this.timestamp = Date.now(); + this.id = `obs_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; + } +} + +/** + * Pattern detected from observations + */ +class Pattern { + /** + * @param {string} name - Pattern name + * @param {string} description - Human-readable description + */ + constructor(name, description) { + this.name = name; + this.description = description; + this.occurrences = 0; + this.firstSeen = Date.now(); + this.lastSeen = Date.now(); + this.observations = []; + this.confidence = 0; + } + + /** + * Record pattern occurrence + * @param {Observation} observation - Related observation + */ + recordOccurrence(observation) { + this.occurrences++; + this.lastSeen = Date.now(); + this.observations.push(observation.id); + + // Confidence increases with occurrences + this.confidence = Math.min(1, this.occurrences / 100); + + return this; + } + + /** + * Check if pattern is significant + * @returns {boolean} + */ + isSignificant() { + return this.occurrences >= 10 && this.confidence >= 0.1; + } +} + +/** + * Hypothesis for optimization + */ +class Hypothesis { + /** + * @param {string} description - What we think will improve + * @param {Pattern} pattern - Pattern this hypothesis addresses + * @param {Object} optimization - Proposed optimization + */ + constructor(description, pattern, optimization) { + this.id = `hyp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; + this.description = description; + this.pattern = pattern; + this.optimization = optimization; + this.state = 'proposed'; + this.expectedImprovement = 0; + this.actualImprovement = null; + this.experiments = []; + this.createdAt = Date.now(); + } + + /** + * Estimate expected improvement + * @param {number} estimate - Estimated improvement (0-1) + * @param {string} rationale - Why we expect this improvement + */ + estimateImprovement(estimate, rationale) { + this.expectedImprovement = estimate; + this.improvementRationale = rationale; + return this; + } +} + +/** + * Experiment for testing hypotheses + */ +class Experiment { + /** + * @param {Hypothesis} hypothesis - Hypothesis being tested + * @param {Object} config - Experiment configuration + */ + constructor(hypothesis, config = {}) { + this.id = `exp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; + this.hypothesis = hypothesis; + this.config = { + sampleSize: config.sampleSize || 100, + controlRatio: config.controlRatio || 0.5, // 50% control, 50% treatment + maxDuration: config.maxDuration || 3600000, // 1 hour max + ...config + }; + + this.state = 'pending'; + this.startTime = null; + this.endTime = null; + + this.controlGroup = { + samples: 0, + successes: 0, + totalDuration: 0, + errors: 0 + }; + + this.treatmentGroup = { + samples: 0, + successes: 0, + totalDuration: 0, + errors: 0 + }; + + this.results = null; + } + + /** + * Start the experiment + */ + start() { + this.state = 'running'; + this.startTime = Date.now(); + this.hypothesis.state = 'testing'; + return this; + } + + /** + * Record a sample result + * @param {boolean} isTreatment - Whether sample used treatment + * @param {boolean} success - Whether operation succeeded + * @param {number} duration - Operation duration in ms + */ + recordSample(isTreatment, success, duration) { + const group = isTreatment ? this.treatmentGroup : this.controlGroup; + + group.samples++; + if (success) { + group.successes++; + } else { + group.errors++; + } + group.totalDuration += duration; + + // Check if experiment is complete + const totalSamples = this.controlGroup.samples + this.treatmentGroup.samples; + const elapsed = Date.now() - this.startTime; + + if (totalSamples >= this.config.sampleSize || elapsed >= this.config.maxDuration) { + this.complete(); + } + + return this; + } + + /** + * Determine if sample should use treatment (A/B assignment) + * @returns {boolean} + */ + shouldUseTreatment() { + // Maintain control ratio while running + const currentRatio = this.treatmentGroup.samples / + (this.controlGroup.samples + this.treatmentGroup.samples + 1); + + return currentRatio < (1 - this.config.controlRatio); + } + + /** + * Complete the experiment and calculate results + */ + complete() { + this.state = 'completed'; + this.endTime = Date.now(); + + const control = this.controlGroup; + const treatment = this.treatmentGroup; + + // Calculate metrics + const controlSuccessRate = control.samples > 0 + ? control.successes / control.samples + : 0; + const treatmentSuccessRate = treatment.samples > 0 + ? treatment.successes / treatment.samples + : 0; + + const controlAvgDuration = control.samples > 0 + ? control.totalDuration / control.samples + : 0; + const treatmentAvgDuration = treatment.samples > 0 + ? treatment.totalDuration / treatment.samples + : 0; + + // Calculate improvement + const successRateImprovement = treatmentSuccessRate - controlSuccessRate; + const durationImprovement = controlAvgDuration > 0 + ? (controlAvgDuration - treatmentAvgDuration) / controlAvgDuration + : 0; + + // Overall improvement (weighted) + const overallImprovement = successRateImprovement * 0.7 + durationImprovement * 0.3; + + // Statistical significance (simplified) + const totalSamples = control.samples + treatment.samples; + const confidence = Math.min(1, totalSamples / this.config.sampleSize); + + this.results = { + controlGroup: { + samples: control.samples, + successRate: controlSuccessRate, + avgDuration: controlAvgDuration, + errorRate: control.errors / Math.max(1, control.samples) + }, + treatmentGroup: { + samples: treatment.samples, + successRate: treatmentSuccessRate, + avgDuration: treatmentAvgDuration, + errorRate: treatment.errors / Math.max(1, treatment.samples) + }, + improvement: { + successRate: successRateImprovement, + duration: durationImprovement, + overall: overallImprovement + }, + confidence, + recommendation: this._generateRecommendation(overallImprovement, confidence), + duration: this.endTime - this.startTime + }; + + // Update hypothesis + this.hypothesis.actualImprovement = overallImprovement; + this.hypothesis.state = overallImprovement > 0 ? 'validated' : 'invalidated'; + + return this; + } + + /** + * Generate recommendation based on results + * @param {number} improvement - Overall improvement + * @param {number} confidence - Statistical confidence + * @returns {string} + * @private + */ + _generateRecommendation(improvement, confidence) { + if (confidence < 0.5) { + return 'INCONCLUSIVE - Need more samples'; + } + + if (improvement > 0.1) { + return 'STRONG_ADOPT - Significant improvement observed'; + } else if (improvement > 0.02) { + return 'ADOPT - Moderate improvement observed'; + } else if (improvement > -0.02) { + return 'NEUTRAL - No significant difference'; + } else if (improvement > -0.1) { + return 'REJECT - Slight degradation observed'; + } else { + return 'STRONG_REJECT - Significant degradation observed'; + } + } + + /** + * Get experiment summary + * @returns {Object} + */ + getSummary() { + return { + id: this.id, + hypothesis: this.hypothesis.description, + state: this.state, + samples: this.controlGroup.samples + this.treatmentGroup.samples, + targetSamples: this.config.sampleSize, + results: this.results, + duration: this.endTime + ? `${((this.endTime - this.startTime) / 1000).toFixed(1)}s` + : `${((Date.now() - (this.startTime || Date.now())) / 1000).toFixed(1)}s (running)` + }; + } +} + +/** + * Knowledge Sharing Agreement between workers + */ +class KnowledgeSharingAgreement { + /** + * @param {string} party1 - First party name + * @param {string} party2 - Second party name + */ + constructor(party1, party2) { + this.id = `ksa_${Date.now()}`; + this.parties = [party1, party2]; + this.sharedKnowledge = new Map(); + this.accessRules = new Map(); + this.optimizations = []; + this.createdAt = Date.now(); + } + + /** + * Define shared data element + * @param {string} element - Element name + * @param {string} access - Access type (R, W, R/W, Clone, Transfer) + * @param {Object} options - Additional options + */ + defineSharing(element, access, options = {}) { + this.sharedKnowledge.set(element, { + access, + syncStrategy: options.syncStrategy || 'on-demand', + freshnessTolerance: options.freshnessTolerance || 30000, // 30s default + lastOptimized: null, + accessCount: 0, + avgAccessTime: 0 + }); + return this; + } + + /** + * Record access to shared element + * @param {string} element - Element accessed + * @param {number} accessTime - Time taken to access + */ + recordAccess(element, accessTime) { + const config = this.sharedKnowledge.get(element); + if (config) { + config.accessCount++; + // Rolling average + config.avgAccessTime = config.avgAccessTime * 0.9 + accessTime * 0.1; + } + return this; + } + + /** + * Analyze and suggest optimizations + * @returns {Object[]} + */ + analyzeOptimizations() { + const suggestions = []; + + for (const [element, config] of this.sharedKnowledge) { + // High access, slow response โ†’ suggest caching + if (config.accessCount > 100 && config.avgAccessTime > 50) { + suggestions.push({ + element, + suggestion: 'Enable aggressive caching', + reason: `High access (${config.accessCount}) with slow response (${config.avgAccessTime.toFixed(1)}ms)`, + expectedImprovement: '40-60% latency reduction' + }); + } + + // Low access โ†’ suggest batch sync + if (config.accessCount < 10 && config.syncStrategy === 'immediate') { + suggestions.push({ + element, + suggestion: 'Switch to batch sync', + reason: `Low access (${config.accessCount}) doesn't justify immediate sync`, + expectedImprovement: '10-20% bandwidth reduction' + }); + } + + // Transfer candidate + if (config.access === 'Clone' && config.avgAccessTime > 100) { + suggestions.push({ + element, + suggestion: 'Consider Transfer instead of Clone', + reason: `Large data (${config.avgAccessTime.toFixed(1)}ms clone time)`, + expectedImprovement: 'Near zero-copy performance' + }); + } + } + + return suggestions; + } + + /** + * Get agreement visualization + * @returns {string} + */ + visualize() { + const lines = [ + 'โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”', + 'โ”‚ KNOWLEDGE SHARING AGREEMENT โ”‚', + 'โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค', + `โ”‚ PARTIES: ${this.parties.join(' โ†” ')}`, + 'โ”‚', + 'โ”‚ SHARED KNOWLEDGE:', + 'โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”', + 'โ”‚ โ”‚ Data Element โ”‚ Access โ”‚ Sync Strategy โ”‚', + 'โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค' + ]; + + for (const [element, config] of this.sharedKnowledge) { + const padElement = element.padEnd(15); + const padAccess = config.access.padEnd(7); + const padSync = config.syncStrategy.padEnd(24); + lines.push(`โ”‚ โ”‚ ${padElement} โ”‚ ${padAccess} โ”‚ ${padSync} โ”‚`); + } + + lines.push( + 'โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜', + 'โ”‚', + 'โ”‚ LEARNED OPTIMIZATIONS:', + ...this.analyzeOptimizations().map(opt => + `โ”‚ โ€ข ${opt.element}: ${opt.suggestion}` + ), + 'โ”‚', + 'โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜' + ); + + return lines.join('\n'); + } +} + +/** + * NicheConstructor - Main niche construction engine + */ +class NicheConstructor { + /** + * @param {Object} academy - Parent ExecutionAcademy + */ + constructor(academy) { + this.academy = academy; + + // Observation storage + this.observations = []; + this.observationLimit = 10000; + + // Detected patterns + this.patterns = new Map(); + + // Generated hypotheses + this.hypotheses = []; + + // Running experiments + this.experiments = new Map(); + this.completedExperiments = []; + + // Integrated optimizations + this.integrations = []; + + // Knowledge sharing agreements + this.sharingAgreements = new Map(); + + // Environment modifications + this.modifications = []; + + // Configuration + this.config = { + patternThreshold: 10, // Min occurrences to consider pattern + experimentSampleSize: 100, + autoExperiment: false, // Auto-run experiments on significant patterns + maxConcurrentExperiments: 3 + }; + } + + /** + * Phase 1: OBSERVATION - Register a pattern to monitor + * @param {string} patternType - Type of pattern + * @param {Object} data - Observation data + * @returns {Observation} + */ + observe(patternType, data) { + const observation = new Observation(patternType, data); + + // Add to observations (with limit) + this.observations.push(observation); + if (this.observations.length > this.observationLimit) { + this.observations.shift(); + } + + // Update pattern detection + this._detectPatterns(observation); + + return observation; + } + + /** + * Detect patterns from observation + * @param {Observation} observation - New observation + * @private + */ + _detectPatterns(observation) { + const key = this._generatePatternKey(observation); + + if (!this.patterns.has(key)) { + this.patterns.set(key, new Pattern( + key, + `Pattern: ${observation.type} with similar characteristics` + )); + } + + const pattern = this.patterns.get(key); + pattern.recordOccurrence(observation); + + // Auto-generate hypothesis for significant patterns + if (pattern.isSignificant() && this.config.autoExperiment) { + this._autoGenerateHypothesis(pattern); + } + } + + /** + * Generate pattern key from observation + * @param {Observation} observation - Observation + * @returns {string} + * @private + */ + _generatePatternKey(observation) { + // Create key from type and data characteristics + const dataKeys = Object.keys(observation.data).sort().join(','); + return `${observation.type}:${dataKeys}`; + } + + /** + * Auto-generate hypothesis for pattern + * @param {Pattern} pattern - Significant pattern + * @private + */ + _autoGenerateHypothesis(pattern) { + // Check if we already have a hypothesis for this pattern + const existing = this.hypotheses.find(h => + h.pattern.name === pattern.name && h.state === 'proposed' + ); + + if (existing) return; + + // Generate optimization based on pattern type + const optimization = this._suggestOptimization(pattern); + + if (optimization) { + this.hypothesize( + `Optimize ${pattern.name}`, + pattern, + optimization + ); + } + } + + /** + * Suggest optimization for pattern + * @param {Pattern} pattern - Pattern to optimize + * @returns {Object|null} + * @private + */ + _suggestOptimization(pattern) { + // Common optimization suggestions + if (pattern.name.includes('fetch')) { + return { + type: 'caching', + strategy: 'cache-first', + ttl: 60000 + }; + } + + if (pattern.name.includes('compute')) { + return { + type: 'memoization', + maxSize: 100 + }; + } + + if (pattern.name.includes('delegation')) { + return { + type: 'fastpath', + bypass: true + }; + } + + return null; + } + + /** + * Phase 2: HYPOTHESIS - Propose an optimization + * @param {string} description - Hypothesis description + * @param {Pattern} pattern - Related pattern (or null) + * @param {Object} optimization - Proposed optimization + * @returns {Hypothesis} + */ + hypothesize(description, pattern, optimization) { + const hypothesis = new Hypothesis(description, pattern, optimization); + this.hypotheses.push(hypothesis); + + return hypothesis; + } + + /** + * Phase 3: EXPERIMENTATION - Test a hypothesis safely + * @param {Hypothesis} hypothesis - Hypothesis to test + * @param {Object} config - Experiment configuration + * @returns {Experiment} + */ + experiment(hypothesis, config = {}) { + // Check concurrent experiment limit + const runningCount = Array.from(this.experiments.values()) + .filter(e => e.state === 'running').length; + + if (runningCount >= this.config.maxConcurrentExperiments) { + throw new Error('Maximum concurrent experiments reached'); + } + + const experiment = new Experiment(hypothesis, { + sampleSize: this.config.experimentSampleSize, + ...config + }); + + this.experiments.set(experiment.id, experiment); + hypothesis.experiments.push(experiment.id); + + experiment.start(); + + return experiment; + } + + /** + * Record sample for active experiment + * @param {string} experimentId - Experiment ID + * @param {boolean} isTreatment - Is treatment group + * @param {boolean} success - Operation success + * @param {number} duration - Operation duration + */ + recordExperimentSample(experimentId, isTreatment, success, duration) { + const experiment = this.experiments.get(experimentId); + + if (experiment && experiment.state === 'running') { + experiment.recordSample(isTreatment, success, duration); + + // Move to completed if done + if (experiment.state === 'completed') { + this.experiments.delete(experimentId); + this.completedExperiments.push(experiment); + + // Auto-integrate successful experiments + if (experiment.results.recommendation.includes('ADOPT')) { + this.integrate(experiment.results); + } + } + } + + return this; + } + + /** + * Phase 4: INTEGRATION - Promote successful experiments + * @param {Object} experimentResults - Results to integrate + * @returns {Object} Integration record + */ + integrate(experimentResults) { + const integration = { + id: `int_${Date.now()}`, + results: experimentResults, + integratedAt: Date.now(), + status: 'active' + }; + + this.integrations.push(integration); + + // Record environment modification + this.modifications.push({ + type: 'integration', + integration: integration.id, + timestamp: Date.now() + }); + + return integration; + } + + /** + * Phase 5: ENVIRONMENT MODIFICATION - Reshape environment + * @param {string} modificationType - Type of modification + * @param {Object} modification - Modification details + */ + modifyEnvironment(modificationType, modification) { + const record = { + id: `mod_${Date.now()}`, + type: modificationType, + modification, + timestamp: Date.now(), + status: 'applied' + }; + + this.modifications.push(record); + + // Apply modification based on type + switch (modificationType) { + case 'scope-reshape': + // Reshape scope chains based on access patterns + this._reshapeScopeChains(modification); + break; + + case 'cache-prewarm': + // Pre-warm caches based on predicted needs + this._prewarmCaches(modification); + break; + + case 'priority-adjust': + // Adjust job queue priorities + this._adjustPriorities(modification); + break; + } + + return record; + } + + /** + * Reshape scope chains + * @param {Object} modification - Modification details + * @private + */ + _reshapeScopeChains(modification) { + // Implementation would modify academy scope structures + console.log('Reshaping scope chains:', modification); + } + + /** + * Pre-warm caches + * @param {Object} modification - Modification details + * @private + */ + _prewarmCaches(modification) { + // Implementation would pre-populate caches + console.log('Pre-warming caches:', modification); + } + + /** + * Adjust priorities + * @param {Object} modification - Modification details + * @private + */ + _adjustPriorities(modification) { + // Implementation would adjust task board priorities + console.log('Adjusting priorities:', modification); + } + + /** + * Create knowledge sharing agreement + * @param {string} party1 - First party + * @param {string} party2 - Second party + * @returns {KnowledgeSharingAgreement} + */ + createSharingAgreement(party1, party2) { + const agreement = new KnowledgeSharingAgreement(party1, party2); + this.sharingAgreements.set(agreement.id, agreement); + return agreement; + } + + /** + * Get adaptation suggestions + * @returns {Object[]} + */ + getSuggestions() { + const suggestions = []; + + // Suggestions from significant patterns without experiments + for (const [name, pattern] of this.patterns) { + if (pattern.isSignificant()) { + const hasExperiment = this.hypotheses.some(h => + h.pattern?.name === name && + (h.state === 'testing' || h.state === 'validated') + ); + + if (!hasExperiment) { + suggestions.push({ + type: 'pattern-opportunity', + pattern: name, + occurrences: pattern.occurrences, + confidence: pattern.confidence, + message: `Significant pattern detected: ${pattern.description}. ` + + `Consider creating an optimization hypothesis.`, + action: 'hypothesize', + priority: pattern.confidence > 0.5 ? 'high' : 'medium' + }); + } + } + } + + // Suggestions from validated hypotheses not yet integrated + for (const hypothesis of this.hypotheses) { + if (hypothesis.state === 'validated' && hypothesis.actualImprovement > 0) { + const isIntegrated = this.integrations.some(i => + i.results?.hypothesis === hypothesis.description + ); + + if (!isIntegrated) { + suggestions.push({ + type: 'integration-ready', + hypothesis: hypothesis.description, + improvement: `${(hypothesis.actualImprovement * 100).toFixed(1)}%`, + message: `Validated optimization ready for integration.`, + action: 'integrate', + priority: hypothesis.actualImprovement > 0.1 ? 'high' : 'medium' + }); + } + } + } + + // Suggestions from sharing agreement analysis + for (const [, agreement] of this.sharingAgreements) { + const optimizations = agreement.analyzeOptimizations(); + optimizations.forEach(opt => { + suggestions.push({ + type: 'sharing-optimization', + element: opt.element, + message: opt.suggestion, + reason: opt.reason, + expectedImprovement: opt.expectedImprovement, + priority: 'low' + }); + }); + } + + // Sort by priority + const priorityOrder = { high: 0, medium: 1, low: 2 }; + suggestions.sort((a, b) => + priorityOrder[a.priority] - priorityOrder[b.priority] + ); + + return suggestions; + } + + /** + * Get niche construction status + * @returns {Object} + */ + getStatus() { + return { + observations: { + total: this.observations.length, + recent: this.observations.filter(o => + Date.now() - o.timestamp < 3600000 + ).length + }, + patterns: { + total: this.patterns.size, + significant: Array.from(this.patterns.values()) + .filter(p => p.isSignificant()).length + }, + hypotheses: { + total: this.hypotheses.length, + byState: { + proposed: this.hypotheses.filter(h => h.state === 'proposed').length, + testing: this.hypotheses.filter(h => h.state === 'testing').length, + validated: this.hypotheses.filter(h => h.state === 'validated').length, + invalidated: this.hypotheses.filter(h => h.state === 'invalidated').length + } + }, + experiments: { + running: this.experiments.size, + completed: this.completedExperiments.length + }, + integrations: this.integrations.length, + modifications: this.modifications.length, + suggestions: this.getSuggestions().length + }; + } + + /** + * Visualize niche construction engine state + * @returns {string} + */ + visualize() { + const status = this.getStatus(); + + return ` +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ NICHE CONSTRUCTION ENGINE โ”‚ +โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค +โ”‚ โ”‚ +โ”‚ 1. OBSERVATION PHASE โ”‚ +โ”‚ โ€ข Total observations: ${status.observations.total} +โ”‚ โ€ข Recent (1h): ${status.observations.recent} +โ”‚ โ€ข Patterns detected: ${status.patterns.total} +โ”‚ โ€ข Significant patterns: ${status.patterns.significant} +โ”‚ โ”‚ +โ”‚ 2. HYPOTHESIS GENERATION โ”‚ +โ”‚ โ€ข Total hypotheses: ${status.hypotheses.total} +โ”‚ โ€ข Proposed: ${status.hypotheses.byState.proposed} +โ”‚ โ€ข Testing: ${status.hypotheses.byState.testing} +โ”‚ โ€ข Validated: ${status.hypotheses.byState.validated} +โ”‚ โ”‚ +โ”‚ 3. SAFE EXPERIMENTATION โ”‚ +โ”‚ โ€ข Running experiments: ${status.experiments.running} +โ”‚ โ€ข Completed: ${status.experiments.completed} +โ”‚ โ”‚ +โ”‚ 4. INTEGRATION โ”‚ +โ”‚ โ€ข Active integrations: ${status.integrations} +โ”‚ โ”‚ +โ”‚ 5. ENVIRONMENTAL MODIFICATION โ”‚ +โ”‚ โ€ข Modifications applied: ${status.modifications} +โ”‚ โ”‚ +โ”‚ ๐Ÿ’ก PENDING SUGGESTIONS: ${status.suggestions} +โ”‚ โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜`; + } +} + +// Export classes +export { + NicheConstructor, + Observation, + Pattern, + Hypothesis, + Experiment, + KnowledgeSharingAgreement +}; + +export default NicheConstructor;