agentic-flow 2.0.2 → 2.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/agents/test-neural.md +14 -0
- package/.claude/settings.json +9 -133
- package/README.md +622 -1862
- package/dist/.tsbuildinfo +1 -1
- package/dist/billing/mcp/tools.js +0 -1
- package/dist/billing/mcp/tools.js.map +1 -1
- package/dist/cli/commands/hooks.d.ts.map +1 -1
- package/dist/cli/commands/hooks.js +4 -79
- package/dist/cli/commands/hooks.js.map +1 -1
- package/dist/cli-proxy.js +1 -89
- package/dist/cli-proxy.js.map +1 -1
- package/dist/core/agentdb-fast.js +3 -3
- package/dist/core/agentdb-fast.js.map +1 -1
- package/dist/core/agentdb-wrapper-enhanced.d.ts.map +1 -1
- package/dist/core/agentdb-wrapper-enhanced.js +4 -20
- package/dist/core/agentdb-wrapper-enhanced.js.map +1 -1
- package/dist/core/agentdb-wrapper.d.ts +2 -3
- package/dist/core/agentdb-wrapper.d.ts.map +1 -1
- package/dist/core/agentdb-wrapper.js +1 -15
- package/dist/core/agentdb-wrapper.js.map +1 -1
- package/dist/core/attention-native.d.ts +0 -4
- package/dist/core/attention-native.d.ts.map +1 -1
- package/dist/core/attention-native.js +2 -14
- package/dist/core/attention-native.js.map +1 -1
- package/dist/federation/SecurityManager.d.ts +2 -11
- package/dist/federation/SecurityManager.d.ts.map +1 -1
- package/dist/federation/SecurityManager.js +17 -50
- package/dist/federation/SecurityManager.js.map +1 -1
- package/dist/federation/integrations/supabase-adapter-debug.js +3 -3
- package/dist/federation/integrations/supabase-adapter-debug.js.map +1 -1
- package/dist/hooks/swarm-learning-optimizer.js +5 -5
- package/dist/hooks/swarm-learning-optimizer.js.map +1 -1
- package/dist/intelligence/IntelligenceStore.d.ts +26 -35
- package/dist/intelligence/IntelligenceStore.d.ts.map +1 -1
- package/dist/intelligence/IntelligenceStore.js +123 -308
- package/dist/intelligence/IntelligenceStore.js.map +1 -1
- package/dist/intelligence/RuVectorIntelligence.d.ts +1 -26
- package/dist/intelligence/RuVectorIntelligence.d.ts.map +1 -1
- package/dist/intelligence/RuVectorIntelligence.js +10 -49
- package/dist/intelligence/RuVectorIntelligence.js.map +1 -1
- package/dist/intelligence/agent-booster-enhanced.d.ts +0 -1
- package/dist/intelligence/agent-booster-enhanced.d.ts.map +1 -1
- package/dist/intelligence/agent-booster-enhanced.js +3 -24
- package/dist/intelligence/agent-booster-enhanced.js.map +1 -1
- package/dist/intelligence/index.d.ts +3 -29
- package/dist/intelligence/index.d.ts.map +1 -1
- package/dist/intelligence/index.js +3 -13
- package/dist/intelligence/index.js.map +1 -1
- package/dist/mcp/claudeFlowSdkServer.d.ts.map +1 -1
- package/dist/mcp/claudeFlowSdkServer.js +3 -9
- package/dist/mcp/claudeFlowSdkServer.js.map +1 -1
- package/dist/mcp/fastmcp/tools/hooks/intelligence-bridge.js +5 -5
- package/dist/mcp/fastmcp/tools/hooks/intelligence-bridge.js.map +1 -1
- package/dist/mcp/fastmcp/tools/swarm/init.d.ts.map +1 -1
- package/dist/mcp/fastmcp/tools/swarm/init.js +7 -36
- package/dist/mcp/fastmcp/tools/swarm/init.js.map +1 -1
- package/dist/mcp/fastmcp/tools/swarm/spawn.d.ts.map +1 -1
- package/dist/mcp/fastmcp/tools/swarm/spawn.js +8 -47
- package/dist/mcp/fastmcp/tools/swarm/spawn.js.map +1 -1
- package/dist/mcp/tools/agent-booster-tools.d.ts +1 -1
- package/dist/mcp/tools/agent-booster-tools.d.ts.map +1 -1
- package/dist/mcp/tools/agent-booster-tools.js +4 -10
- package/dist/mcp/tools/agent-booster-tools.js.map +1 -1
- package/dist/mcp/tools/sona-tools.d.ts.map +1 -1
- package/dist/mcp/tools/sona-tools.js +0 -6
- package/dist/mcp/tools/sona-tools.js.map +1 -1
- package/dist/optimizations/agent-booster-migration.d.ts.map +1 -1
- package/dist/optimizations/agent-booster-migration.js +2 -5
- package/dist/optimizations/agent-booster-migration.js.map +1 -1
- package/dist/proxy/anthropic-to-openrouter.js.map +1 -1
- package/dist/proxy/anthropic-to-requesty.js.map +1 -1
- package/dist/proxy/quic-proxy.d.ts +1 -0
- package/dist/proxy/quic-proxy.d.ts.map +1 -1
- package/dist/proxy/quic-proxy.js +2 -2
- package/dist/proxy/quic-proxy.js.map +1 -1
- package/dist/reasoningbank/AdvancedMemory.js +1 -1
- package/dist/reasoningbank/AdvancedMemory.js.map +1 -1
- package/dist/reasoningbank/HybridBackend.d.ts.map +1 -1
- package/dist/reasoningbank/HybridBackend.js +5 -2
- package/dist/reasoningbank/HybridBackend.js.map +1 -1
- package/dist/reasoningbank/backend-selector.d.ts +1 -11
- package/dist/reasoningbank/backend-selector.d.ts.map +1 -1
- package/dist/reasoningbank/backend-selector.js +5 -45
- package/dist/reasoningbank/backend-selector.js.map +1 -1
- package/dist/reasoningbank/core/consolidate.d.ts.map +1 -1
- package/dist/reasoningbank/core/consolidate.js +45 -113
- package/dist/reasoningbank/core/consolidate.js.map +1 -1
- package/dist/reasoningbank/index-new.d.ts +6 -1
- package/dist/reasoningbank/index-new.d.ts.map +1 -1
- package/dist/reasoningbank/index-new.js +6 -1
- package/dist/reasoningbank/index-new.js.map +1 -1
- package/dist/reasoningbank/index.d.ts +6 -2
- package/dist/reasoningbank/index.d.ts.map +1 -1
- package/dist/reasoningbank/index.js +6 -2
- package/dist/reasoningbank/index.js.map +1 -1
- package/dist/reasoningbank/utils/embeddings.d.ts +0 -1
- package/dist/reasoningbank/utils/embeddings.d.ts.map +1 -1
- package/dist/reasoningbank/utils/embeddings.js +26 -53
- package/dist/reasoningbank/utils/embeddings.js.map +1 -1
- package/dist/router/index.d.ts +17 -0
- package/dist/router/index.d.ts.map +1 -0
- package/dist/router/index.js +19 -0
- package/dist/router/index.js.map +1 -0
- package/dist/router/providers/onnx-local-optimized.d.ts +0 -2
- package/dist/router/providers/onnx-local-optimized.d.ts.map +1 -1
- package/dist/router/providers/onnx-local-optimized.js +0 -10
- package/dist/router/providers/onnx-local-optimized.js.map +1 -1
- package/dist/router/providers/onnx-local.d.ts +0 -1
- package/dist/router/providers/onnx-local.d.ts.map +1 -1
- package/dist/router/providers/onnx-local.js +5 -22
- package/dist/router/providers/onnx-local.js.map +1 -1
- package/dist/services/embedding-service.js.map +1 -1
- package/dist/services/sona-agent-training.d.ts +0 -1
- package/dist/services/sona-agent-training.d.ts.map +1 -1
- package/dist/services/sona-agent-training.js.map +1 -1
- package/dist/services/sona-agentdb-integration.d.ts.map +1 -1
- package/dist/services/sona-agentdb-integration.js +6 -9
- package/dist/services/sona-agentdb-integration.js.map +1 -1
- package/dist/services/sona-service.d.ts.map +1 -1
- package/dist/services/sona-service.js +5 -6
- package/dist/services/sona-service.js.map +1 -1
- package/dist/utils/cli.d.ts +1 -1
- package/dist/utils/cli.d.ts.map +1 -1
- package/dist/utils/cli.js +0 -21
- package/dist/utils/cli.js.map +1 -1
- package/package.json +7 -19
- package/scripts/postinstall.js +4 -45
- package/wasm/reasoningbank/reasoningbank_wasm_bg.js +2 -2
- package/wasm/reasoningbank/reasoningbank_wasm_bg.wasm +0 -0
- package/.claude/agents/.claude-flow/metrics/agent-metrics.json +0 -1
- package/.claude/agents/.claude-flow/metrics/performance.json +0 -87
- package/.claude/agents/.claude-flow/metrics/task-metrics.json +0 -10
- package/.claude/skills/.claude-flow/metrics/agent-metrics.json +0 -1
- package/.claude/skills/.claude-flow/metrics/performance.json +0 -87
- package/.claude/skills/.claude-flow/metrics/task-metrics.json +0 -10
- package/.claude/skills/agentic-flow-quickstart/skill.md +0 -69
- package/.claude/skills/hooks-automation/skill.md +0 -155
- package/.claude/skills/memory-patterns/skill.md +0 -110
- package/.claude/skills/skill-builder/.claude-flow/metrics/agent-metrics.json +0 -1
- package/.claude/skills/skill-builder/.claude-flow/metrics/performance.json +0 -87
- package/.claude/skills/skill-builder/.claude-flow/metrics/task-metrics.json +0 -10
- package/.claude/skills/sparc-methodology/skill.md +0 -137
- package/.claude/skills/swarm-coordination/skill.md +0 -94
- package/.claude/skills/worker-benchmarks/skill.md +0 -135
- package/.claude/skills/worker-integration/skill.md +0 -154
- package/.claude/statusline.mjs +0 -109
- package/.claude/statusline.sh +0 -71
- package/dist/agentdb/benchmarks/comprehensive-benchmark.js +0 -664
- package/dist/agentdb/benchmarks/frontier-benchmark.js +0 -419
- package/dist/agentdb/benchmarks/reflexion-benchmark.js +0 -370
- package/dist/agentdb/cli/agentdb-cli.js +0 -717
- package/dist/agentdb/controllers/CausalMemoryGraph.js +0 -322
- package/dist/agentdb/controllers/CausalRecall.js +0 -281
- package/dist/agentdb/controllers/EmbeddingService.d.ts +0 -37
- package/dist/agentdb/controllers/EmbeddingService.d.ts.map +0 -1
- package/dist/agentdb/controllers/EmbeddingService.js +0 -119
- package/dist/agentdb/controllers/EmbeddingService.js.map +0 -1
- package/dist/agentdb/controllers/ExplainableRecall.js +0 -387
- package/dist/agentdb/controllers/NightlyLearner.js +0 -382
- package/dist/agentdb/controllers/ReflexionMemory.js +0 -239
- package/dist/agentdb/controllers/SkillLibrary.js +0 -276
- package/dist/agentdb/controllers/frontier-index.js +0 -9
- package/dist/agentdb/controllers/index.js +0 -8
- package/dist/agentdb/optimizations/BatchOperations.js +0 -198
- package/dist/agentdb/optimizations/QueryOptimizer.js +0 -225
- package/dist/agentdb/optimizations/index.js +0 -7
- package/dist/agentdb/tests/frontier-features.test.js +0 -665
- package/dist/benchmarks/embeddings-benchmark.d.ts +0 -38
- package/dist/benchmarks/embeddings-benchmark.d.ts.map +0 -1
- package/dist/benchmarks/embeddings-benchmark.js +0 -282
- package/dist/benchmarks/embeddings-benchmark.js.map +0 -1
- package/dist/cli/commands/embeddings.d.ts +0 -12
- package/dist/cli/commands/embeddings.d.ts.map +0 -1
- package/dist/cli/commands/embeddings.js +0 -386
- package/dist/cli/commands/embeddings.js.map +0 -1
- package/dist/cli/commands/init.d.ts +0 -8
- package/dist/cli/commands/init.d.ts.map +0 -1
- package/dist/cli/commands/init.js +0 -514
- package/dist/cli/commands/init.js.map +0 -1
- package/dist/cli/commands/workers.d.ts +0 -9
- package/dist/cli/commands/workers.d.ts.map +0 -1
- package/dist/cli/commands/workers.js +0 -991
- package/dist/cli/commands/workers.js.map +0 -1
- package/dist/cli/skills-manager.js +0 -1297
- package/dist/cli/update-message.js +0 -175
- package/dist/embeddings/index.d.ts +0 -17
- package/dist/embeddings/index.d.ts.map +0 -1
- package/dist/embeddings/index.js +0 -17
- package/dist/embeddings/index.js.map +0 -1
- package/dist/embeddings/neural-substrate.d.ts +0 -206
- package/dist/embeddings/neural-substrate.d.ts.map +0 -1
- package/dist/embeddings/neural-substrate.js +0 -629
- package/dist/embeddings/neural-substrate.js.map +0 -1
- package/dist/embeddings/optimized-embedder.d.ts +0 -103
- package/dist/embeddings/optimized-embedder.d.ts.map +0 -1
- package/dist/embeddings/optimized-embedder.js +0 -730
- package/dist/embeddings/optimized-embedder.js.map +0 -1
- package/dist/examples/embedding-geometry.d.ts +0 -105
- package/dist/examples/embedding-geometry.d.ts.map +0 -1
- package/dist/examples/embedding-geometry.js +0 -528
- package/dist/examples/embedding-geometry.js.map +0 -1
- package/dist/memory/SharedMemoryPool.d.ts +0 -129
- package/dist/memory/SharedMemoryPool.d.ts.map +0 -1
- package/dist/memory/SharedMemoryPool.js +0 -243
- package/dist/memory/SharedMemoryPool.js.map +0 -1
- package/dist/memory/index.d.ts +0 -8
- package/dist/memory/index.d.ts.map +0 -1
- package/dist/memory/index.js +0 -7
- package/dist/memory/index.js.map +0 -1
- package/dist/proxy/http3-proxy-old.js +0 -331
- package/dist/proxy/proxy/anthropic-to-gemini.js +0 -439
- package/dist/proxy/utils/logger.js +0 -59
- package/dist/reasoningbank/agentdb-adapter.js +0 -125
- package/dist/reasoningbank/core/database.js +0 -250
- package/dist/reasoningbank/core/memory-engine.js +0 -335
- package/dist/swarm/ipfs-swarm.d.ts +0 -265
- package/dist/swarm/ipfs-swarm.d.ts.map +0 -1
- package/dist/swarm/ipfs-swarm.js +0 -508
- package/dist/swarm/ipfs-swarm.js.map +0 -1
- package/dist/swarm/p2p-free-swarm.d.ts +0 -344
- package/dist/swarm/p2p-free-swarm.d.ts.map +0 -1
- package/dist/swarm/p2p-free-swarm.js +0 -603
- package/dist/swarm/p2p-free-swarm.js.map +0 -1
- package/dist/swarm/real-p2p-swarm.d.ts +0 -183
- package/dist/swarm/real-p2p-swarm.d.ts.map +0 -1
- package/dist/swarm/real-p2p-swarm.js +0 -469
- package/dist/swarm/real-p2p-swarm.js.map +0 -1
- package/dist/utils/adaptive-pool-sizing.js +0 -414
- package/dist/utils/agentdbCommands.js +0 -175
- package/dist/utils/circular-rate-limiter.js +0 -391
- package/dist/utils/dynamic-compression.js +0 -298
- package/dist/utils/http2-multiplexing.js +0 -319
- package/dist/utils/index.d.ts +0 -6
- package/dist/utils/index.d.ts.map +0 -1
- package/dist/utils/index.js +0 -6
- package/dist/utils/index.js.map +0 -1
- package/dist/utils/lazy-auth.js +0 -311
- package/dist/utils/model-cache.d.ts +0 -61
- package/dist/utils/model-cache.d.ts.map +0 -1
- package/dist/utils/model-cache.js +0 -176
- package/dist/utils/model-cache.js.map +0 -1
- package/dist/utils/server-push.js +0 -251
- package/dist/utils/suppress-warnings.d.ts +0 -19
- package/dist/utils/suppress-warnings.d.ts.map +0 -1
- package/dist/utils/suppress-warnings.js +0 -59
- package/dist/utils/suppress-warnings.js.map +0 -1
- package/dist/utils/zero-copy-buffer.js +0 -286
- package/dist/workers/consolidated-phases.d.ts +0 -40
- package/dist/workers/consolidated-phases.d.ts.map +0 -1
- package/dist/workers/consolidated-phases.js +0 -497
- package/dist/workers/consolidated-phases.js.map +0 -1
- package/dist/workers/custom-worker-config.d.ts +0 -133
- package/dist/workers/custom-worker-config.d.ts.map +0 -1
- package/dist/workers/custom-worker-config.js +0 -215
- package/dist/workers/custom-worker-config.js.map +0 -1
- package/dist/workers/custom-worker-factory.d.ts +0 -89
- package/dist/workers/custom-worker-factory.d.ts.map +0 -1
- package/dist/workers/custom-worker-factory.js +0 -404
- package/dist/workers/custom-worker-factory.js.map +0 -1
- package/dist/workers/dispatch-service.d.ts +0 -123
- package/dist/workers/dispatch-service.d.ts.map +0 -1
- package/dist/workers/dispatch-service.js +0 -1024
- package/dist/workers/dispatch-service.js.map +0 -1
- package/dist/workers/hooks-integration.d.ts +0 -79
- package/dist/workers/hooks-integration.d.ts.map +0 -1
- package/dist/workers/hooks-integration.js +0 -286
- package/dist/workers/hooks-integration.js.map +0 -1
- package/dist/workers/index.d.ts +0 -42
- package/dist/workers/index.d.ts.map +0 -1
- package/dist/workers/index.js +0 -52
- package/dist/workers/index.js.map +0 -1
- package/dist/workers/mcp-tools.d.ts +0 -56
- package/dist/workers/mcp-tools.d.ts.map +0 -1
- package/dist/workers/mcp-tools.js +0 -359
- package/dist/workers/mcp-tools.js.map +0 -1
- package/dist/workers/phase-executors.d.ts +0 -22
- package/dist/workers/phase-executors.d.ts.map +0 -1
- package/dist/workers/phase-executors.js +0 -445
- package/dist/workers/phase-executors.js.map +0 -1
- package/dist/workers/resource-governor.d.ts +0 -75
- package/dist/workers/resource-governor.d.ts.map +0 -1
- package/dist/workers/resource-governor.js +0 -187
- package/dist/workers/resource-governor.js.map +0 -1
- package/dist/workers/ruvector-integration.d.ts +0 -163
- package/dist/workers/ruvector-integration.d.ts.map +0 -1
- package/dist/workers/ruvector-integration.js +0 -543
- package/dist/workers/ruvector-integration.js.map +0 -1
- package/dist/workers/ruvector-native-integration.d.ts +0 -91
- package/dist/workers/ruvector-native-integration.d.ts.map +0 -1
- package/dist/workers/ruvector-native-integration.js +0 -254
- package/dist/workers/ruvector-native-integration.js.map +0 -1
- package/dist/workers/trigger-detector.d.ts +0 -68
- package/dist/workers/trigger-detector.d.ts.map +0 -1
- package/dist/workers/trigger-detector.js +0 -281
- package/dist/workers/trigger-detector.js.map +0 -1
- package/dist/workers/types.d.ts +0 -145
- package/dist/workers/types.d.ts.map +0 -1
- package/dist/workers/types.js +0 -6
- package/dist/workers/types.js.map +0 -1
- package/dist/workers/worker-agent-integration.d.ts +0 -140
- package/dist/workers/worker-agent-integration.d.ts.map +0 -1
- package/dist/workers/worker-agent-integration.js +0 -471
- package/dist/workers/worker-agent-integration.js.map +0 -1
- package/dist/workers/worker-benchmarks.d.ts +0 -88
- package/dist/workers/worker-benchmarks.d.ts.map +0 -1
- package/dist/workers/worker-benchmarks.js +0 -452
- package/dist/workers/worker-benchmarks.js.map +0 -1
- package/dist/workers/worker-registry.d.ts +0 -85
- package/dist/workers/worker-registry.d.ts.map +0 -1
- package/dist/workers/worker-registry.js +0 -547
- package/dist/workers/worker-registry.js.map +0 -1
- package/docs/.claude-flow/metrics/agent-metrics.json +0 -1
- package/docs/.claude-flow/metrics/performance.json +0 -87
- package/docs/.claude-flow/metrics/task-metrics.json +0 -10
- package/docs/embeddings/EMBEDDING_GEOMETRY.md +0 -935
- /package/.claude/agents/analysis/{analyze-code-quality.md → code-review/analyze-code-quality.md} +0 -0
- /package/.claude/agents/architecture/{arch-system-design.md → system-design/arch-system-design.md} +0 -0
- /package/.claude/agents/data/{data-ml-model.md → ml/data-ml-model.md} +0 -0
- /package/.claude/agents/development/{dev-backend-api.md → backend/dev-backend-api.md} +0 -0
- /package/.claude/agents/devops/{ops-cicd-github.md → ci-cd/ops-cicd-github.md} +0 -0
- /package/.claude/agents/documentation/{docs-api-openapi.md → api-docs/docs-api-openapi.md} +0 -0
- /package/.claude/agents/specialized/{spec-mobile-react-native.md → mobile/spec-mobile-react-native.md} +0 -0
- /package/.claude/agents/testing/{tdd-london-swarm.md → unit/tdd-london-swarm.md} +0 -0
- /package/.claude/agents/testing/{production-validator.md → validation/production-validator.md} +0 -0
|
@@ -1,629 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Neural Embedding Substrate Integration
|
|
3
|
-
*
|
|
4
|
-
* Wraps ruvector's NeuralSubstrate for agentic-flow agents
|
|
5
|
-
* treating embeddings as a synthetic nervous system.
|
|
6
|
-
*
|
|
7
|
-
* Based on ruvector@0.1.85 neural-embeddings.ts
|
|
8
|
-
*/
|
|
9
|
-
import { getOptimizedEmbedder, cosineSimilarity, euclideanDistance } from './optimized-embedder.js';
|
|
10
|
-
// ============================================================================
|
|
11
|
-
// Security Constants
|
|
12
|
-
// ============================================================================
|
|
13
|
-
const MAX_TEXT_LENGTH = 10000; // Maximum input text length
|
|
14
|
-
const MAX_MEMORIES = 10000; // Maximum memories in MemoryPhysics
|
|
15
|
-
const MAX_AGENTS = 1000; // Maximum agents in swarm
|
|
16
|
-
const MAX_BASELINE_SAMPLES = 1000; // Maximum calibration samples
|
|
17
|
-
const MAX_HISTORY_SIZE = 100; // Maximum drift history
|
|
18
|
-
const VALID_ID_PATTERN = /^[a-zA-Z0-9_-]{1,256}$/;
|
|
19
|
-
// ============================================================================
|
|
20
|
-
// Security Validation Functions
|
|
21
|
-
// ============================================================================
|
|
22
|
-
/**
|
|
23
|
-
* Validate text input length
|
|
24
|
-
*/
|
|
25
|
-
function validateTextInput(text, context) {
|
|
26
|
-
if (!text || typeof text !== 'string') {
|
|
27
|
-
throw new Error(`${context}: Input must be a non-empty string`);
|
|
28
|
-
}
|
|
29
|
-
if (text.length > MAX_TEXT_LENGTH) {
|
|
30
|
-
throw new Error(`${context}: Text exceeds maximum length of ${MAX_TEXT_LENGTH} characters`);
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Validate ID format
|
|
35
|
-
*/
|
|
36
|
-
function validateId(id, context) {
|
|
37
|
-
if (!id || typeof id !== 'string') {
|
|
38
|
-
throw new Error(`${context}: ID must be a non-empty string`);
|
|
39
|
-
}
|
|
40
|
-
if (!VALID_ID_PATTERN.test(id)) {
|
|
41
|
-
throw new Error(`${context}: Invalid ID format. Use 1-256 alphanumeric characters, underscores, or hyphens`);
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* Validate array is not null and has expected dimension
|
|
46
|
-
*/
|
|
47
|
-
function validateEmbedding(arr, context) {
|
|
48
|
-
if (!arr) {
|
|
49
|
-
throw new Error(`${context}: Not initialized. Call the appropriate setup method first.`);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Semantic Drift Detector
|
|
54
|
-
* Monitors semantic movement and triggers reflexes
|
|
55
|
-
* Optimized with pre-allocated buffers (80-95% less GC pressure)
|
|
56
|
-
*/
|
|
57
|
-
export class SemanticDriftDetector {
|
|
58
|
-
driftThreshold;
|
|
59
|
-
escalationThreshold;
|
|
60
|
-
historySize;
|
|
61
|
-
embedder = getOptimizedEmbedder();
|
|
62
|
-
baseline = null;
|
|
63
|
-
history = [];
|
|
64
|
-
velocity = null;
|
|
65
|
-
acceleration = null;
|
|
66
|
-
dimension = 0;
|
|
67
|
-
// Pre-allocated buffer for velocity calculation (reused each detect call)
|
|
68
|
-
tempVelocityBuffer = null;
|
|
69
|
-
constructor(driftThreshold = 0.15, escalationThreshold = 0.30, historySize = 20) {
|
|
70
|
-
this.driftThreshold = driftThreshold;
|
|
71
|
-
this.escalationThreshold = escalationThreshold;
|
|
72
|
-
this.historySize = historySize;
|
|
73
|
-
}
|
|
74
|
-
async init() {
|
|
75
|
-
await this.embedder.init();
|
|
76
|
-
}
|
|
77
|
-
async setBaseline(context) {
|
|
78
|
-
validateTextInput(context, 'SemanticDriftDetector.setBaseline');
|
|
79
|
-
this.baseline = await this.embedder.embed(context);
|
|
80
|
-
this.dimension = this.baseline.length;
|
|
81
|
-
this.history = [{ embedding: this.baseline, timestamp: Date.now() }];
|
|
82
|
-
// Pre-allocate buffers once (reused for all subsequent detect calls)
|
|
83
|
-
if (!this.velocity || this.velocity.length !== this.dimension) {
|
|
84
|
-
this.velocity = new Float32Array(this.dimension);
|
|
85
|
-
this.acceleration = new Float32Array(this.dimension);
|
|
86
|
-
this.tempVelocityBuffer = new Float32Array(this.dimension);
|
|
87
|
-
}
|
|
88
|
-
else {
|
|
89
|
-
// Zero out existing buffers
|
|
90
|
-
this.velocity.fill(0);
|
|
91
|
-
this.acceleration.fill(0);
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
async detect(input) {
|
|
95
|
-
validateTextInput(input, 'SemanticDriftDetector.detect');
|
|
96
|
-
validateEmbedding(this.baseline, 'SemanticDriftDetector.detect');
|
|
97
|
-
const current = await this.embedder.embed(input);
|
|
98
|
-
const distance = 1 - cosineSimilarity(this.baseline, current);
|
|
99
|
-
// Calculate velocity using pre-allocated buffer (no new allocation!)
|
|
100
|
-
const prev = this.history[this.history.length - 1]?.embedding || this.baseline;
|
|
101
|
-
const newVelocity = this.tempVelocityBuffer;
|
|
102
|
-
const dim = this.dimension;
|
|
103
|
-
// 8x unrolled velocity calculation
|
|
104
|
-
const unrolledLen = dim - (dim % 8);
|
|
105
|
-
let i = 0;
|
|
106
|
-
for (; i < unrolledLen; i += 8) {
|
|
107
|
-
newVelocity[i] = current[i] - prev[i];
|
|
108
|
-
newVelocity[i + 1] = current[i + 1] - prev[i + 1];
|
|
109
|
-
newVelocity[i + 2] = current[i + 2] - prev[i + 2];
|
|
110
|
-
newVelocity[i + 3] = current[i + 3] - prev[i + 3];
|
|
111
|
-
newVelocity[i + 4] = current[i + 4] - prev[i + 4];
|
|
112
|
-
newVelocity[i + 5] = current[i + 5] - prev[i + 5];
|
|
113
|
-
newVelocity[i + 6] = current[i + 6] - prev[i + 6];
|
|
114
|
-
newVelocity[i + 7] = current[i + 7] - prev[i + 7];
|
|
115
|
-
}
|
|
116
|
-
for (; i < dim; i++) {
|
|
117
|
-
newVelocity[i] = current[i] - prev[i];
|
|
118
|
-
}
|
|
119
|
-
// Calculate acceleration and update velocity in-place
|
|
120
|
-
let velocityMagSq = 0;
|
|
121
|
-
let accelerationMagSq = 0;
|
|
122
|
-
for (i = 0; i < dim; i++) {
|
|
123
|
-
const oldVel = this.velocity[i];
|
|
124
|
-
const newVel = newVelocity[i];
|
|
125
|
-
this.acceleration[i] = newVel - oldVel;
|
|
126
|
-
this.velocity[i] = newVel;
|
|
127
|
-
velocityMagSq += newVel * newVel;
|
|
128
|
-
accelerationMagSq += this.acceleration[i] * this.acceleration[i];
|
|
129
|
-
}
|
|
130
|
-
const velocityMag = Math.sqrt(velocityMagSq);
|
|
131
|
-
const accelerationMag = Math.sqrt(accelerationMagSq);
|
|
132
|
-
// Update history
|
|
133
|
-
this.history.push({ embedding: current, timestamp: Date.now() });
|
|
134
|
-
if (this.history.length > this.historySize)
|
|
135
|
-
this.history.shift();
|
|
136
|
-
// Determine trend
|
|
137
|
-
let trend = 'stable';
|
|
138
|
-
if (accelerationMag > 0.01)
|
|
139
|
-
trend = 'accelerating';
|
|
140
|
-
else if (velocityMag > 0.05)
|
|
141
|
-
trend = 'drifting';
|
|
142
|
-
else if (distance < this.driftThreshold * 0.5 && velocityMag < 0.02)
|
|
143
|
-
trend = 'recovering';
|
|
144
|
-
return {
|
|
145
|
-
distance,
|
|
146
|
-
velocity: velocityMag,
|
|
147
|
-
acceleration: accelerationMag,
|
|
148
|
-
trend,
|
|
149
|
-
shouldEscalate: distance > this.driftThreshold,
|
|
150
|
-
shouldTriggerReasoning: distance > this.escalationThreshold
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
getStats() {
|
|
154
|
-
if (!this.baseline || this.history.length < 2) {
|
|
155
|
-
return { avgDrift: 0, maxDrift: 0, driftEvents: 0 };
|
|
156
|
-
}
|
|
157
|
-
const drifts = this.history.map(h => 1 - cosineSimilarity(this.baseline, h.embedding));
|
|
158
|
-
const avgDrift = drifts.reduce((a, b) => a + b, 0) / drifts.length;
|
|
159
|
-
const maxDrift = Math.max(...drifts);
|
|
160
|
-
const driftEvents = drifts.filter(d => d > this.driftThreshold).length;
|
|
161
|
-
return { avgDrift, maxDrift, driftEvents };
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
/**
|
|
165
|
-
* Memory Physics
|
|
166
|
-
* Hippocampal-like dynamics: decay, interference, consolidation
|
|
167
|
-
*/
|
|
168
|
-
export class MemoryPhysics {
|
|
169
|
-
decayRate;
|
|
170
|
-
interferenceRadius;
|
|
171
|
-
forgettingThreshold;
|
|
172
|
-
embedder = getOptimizedEmbedder();
|
|
173
|
-
memories = new Map();
|
|
174
|
-
lastConsolidation = Date.now();
|
|
175
|
-
constructor(decayRate = 0.01, interferenceRadius = 0.3, forgettingThreshold = 0.1) {
|
|
176
|
-
this.decayRate = decayRate;
|
|
177
|
-
this.interferenceRadius = interferenceRadius;
|
|
178
|
-
this.forgettingThreshold = forgettingThreshold;
|
|
179
|
-
}
|
|
180
|
-
async init() {
|
|
181
|
-
await this.embedder.init();
|
|
182
|
-
}
|
|
183
|
-
async store(id, content) {
|
|
184
|
-
validateId(id, 'MemoryPhysics.store');
|
|
185
|
-
validateTextInput(content, 'MemoryPhysics.store');
|
|
186
|
-
// Security: Enforce memory limit
|
|
187
|
-
if (this.memories.size >= MAX_MEMORIES && !this.memories.has(id)) {
|
|
188
|
-
throw new Error(`Memory capacity exceeded (max: ${MAX_MEMORIES}). Call consolidate() to free space.`);
|
|
189
|
-
}
|
|
190
|
-
const embedding = await this.embedder.embed(content);
|
|
191
|
-
const interference = [];
|
|
192
|
-
// Check interference with existing memories
|
|
193
|
-
for (const [memId, mem] of this.memories) {
|
|
194
|
-
const distance = euclideanDistance(embedding, mem.embedding);
|
|
195
|
-
if (distance < this.interferenceRadius) {
|
|
196
|
-
const strength = (this.interferenceRadius - distance) / this.interferenceRadius;
|
|
197
|
-
mem.strength *= (1 - strength * 0.5);
|
|
198
|
-
interference.push(memId);
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
this.memories.set(id, {
|
|
202
|
-
id,
|
|
203
|
-
embedding,
|
|
204
|
-
content,
|
|
205
|
-
strength: 1.0,
|
|
206
|
-
timestamp: Date.now(),
|
|
207
|
-
accessCount: 0,
|
|
208
|
-
associations: interference
|
|
209
|
-
});
|
|
210
|
-
return { stored: true, interference };
|
|
211
|
-
}
|
|
212
|
-
async recall(query, topK = 5) {
|
|
213
|
-
validateTextInput(query, 'MemoryPhysics.recall');
|
|
214
|
-
const queryEmb = await this.embedder.embed(query);
|
|
215
|
-
this.applyDecay();
|
|
216
|
-
const results = [];
|
|
217
|
-
for (const mem of this.memories.values()) {
|
|
218
|
-
if (mem.strength < this.forgettingThreshold)
|
|
219
|
-
continue;
|
|
220
|
-
const relevance = cosineSimilarity(queryEmb, mem.embedding);
|
|
221
|
-
mem.accessCount++;
|
|
222
|
-
mem.strength = Math.min(1.0, mem.strength * 1.1); // Retrieval strengthens
|
|
223
|
-
results.push({ ...mem, relevance });
|
|
224
|
-
}
|
|
225
|
-
return results
|
|
226
|
-
.sort((a, b) => (b.relevance * b.strength) - (a.relevance * a.strength))
|
|
227
|
-
.slice(0, topK);
|
|
228
|
-
}
|
|
229
|
-
applyDecay() {
|
|
230
|
-
const now = Date.now();
|
|
231
|
-
for (const mem of this.memories.values()) {
|
|
232
|
-
const hours = (now - mem.timestamp) / 3600000;
|
|
233
|
-
mem.strength *= Math.exp(-this.decayRate * hours);
|
|
234
|
-
mem.timestamp = now;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
consolidate() {
|
|
238
|
-
const clusters = [];
|
|
239
|
-
const used = new Set();
|
|
240
|
-
let merged = 0;
|
|
241
|
-
let forgotten = 0;
|
|
242
|
-
// Remove forgotten memories
|
|
243
|
-
for (const [id, mem] of this.memories) {
|
|
244
|
-
if (mem.strength < this.forgettingThreshold) {
|
|
245
|
-
this.memories.delete(id);
|
|
246
|
-
forgotten++;
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
// Cluster similar memories
|
|
250
|
-
for (const mem of this.memories.values()) {
|
|
251
|
-
if (used.has(mem.id))
|
|
252
|
-
continue;
|
|
253
|
-
const cluster = [mem];
|
|
254
|
-
for (const other of this.memories.values()) {
|
|
255
|
-
if (used.has(other.id) || mem.id === other.id)
|
|
256
|
-
continue;
|
|
257
|
-
const sim = cosineSimilarity(mem.embedding, other.embedding);
|
|
258
|
-
if (sim > 0.9) {
|
|
259
|
-
cluster.push(other);
|
|
260
|
-
used.add(other.id);
|
|
261
|
-
merged++;
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
if (cluster.length > 1) {
|
|
265
|
-
// Merge: keep strongest, combine strength
|
|
266
|
-
const strongest = cluster.reduce((a, b) => a.strength > b.strength ? a : b);
|
|
267
|
-
strongest.strength = Math.min(1.0, cluster.reduce((s, m) => s + m.strength, 0));
|
|
268
|
-
strongest.associations = [...new Set(cluster.flatMap(c => c.associations))];
|
|
269
|
-
for (const c of cluster) {
|
|
270
|
-
if (c.id !== strongest.id)
|
|
271
|
-
this.memories.delete(c.id);
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
clusters.push(cluster);
|
|
275
|
-
}
|
|
276
|
-
this.lastConsolidation = Date.now();
|
|
277
|
-
return { merged, forgotten, remaining: this.memories.size };
|
|
278
|
-
}
|
|
279
|
-
getStats() {
|
|
280
|
-
const active = [...this.memories.values()].filter(m => m.strength > this.forgettingThreshold);
|
|
281
|
-
const avgStrength = active.length > 0
|
|
282
|
-
? active.reduce((s, m) => s + m.strength, 0) / active.length
|
|
283
|
-
: 0;
|
|
284
|
-
return {
|
|
285
|
-
total: this.memories.size,
|
|
286
|
-
active: active.length,
|
|
287
|
-
avgStrength
|
|
288
|
-
};
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
/**
|
|
292
|
-
* Embedding State Machine
|
|
293
|
-
* Agent state through geometry: position, velocity, attention
|
|
294
|
-
*/
|
|
295
|
-
export class EmbeddingStateMachine {
|
|
296
|
-
dimension;
|
|
297
|
-
embedder = getOptimizedEmbedder();
|
|
298
|
-
agents = new Map();
|
|
299
|
-
stateRegions = new Map();
|
|
300
|
-
constructor(dimension = 384) {
|
|
301
|
-
this.dimension = dimension;
|
|
302
|
-
}
|
|
303
|
-
async init() {
|
|
304
|
-
await this.embedder.init();
|
|
305
|
-
// Initialize default state regions
|
|
306
|
-
const regions = {
|
|
307
|
-
exploring: 'exploring options, gathering information, uncertain, searching',
|
|
308
|
-
executing: 'executing task, confident, taking action, progressing',
|
|
309
|
-
waiting: 'waiting for input, paused, blocked, need information',
|
|
310
|
-
error: 'error state, confused, failed, need help, recovery'
|
|
311
|
-
};
|
|
312
|
-
for (const [name, desc] of Object.entries(regions)) {
|
|
313
|
-
this.stateRegions.set(name, await this.embedder.embed(desc));
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
async registerAgent(id, initialRole) {
|
|
317
|
-
validateId(id, 'EmbeddingStateMachine.registerAgent');
|
|
318
|
-
validateTextInput(initialRole, 'EmbeddingStateMachine.registerAgent');
|
|
319
|
-
// Security: Enforce agent limit
|
|
320
|
-
if (this.agents.size >= MAX_AGENTS && !this.agents.has(id)) {
|
|
321
|
-
throw new Error(`Agent capacity exceeded (max: ${MAX_AGENTS})`);
|
|
322
|
-
}
|
|
323
|
-
const position = await this.embedder.embed(initialRole);
|
|
324
|
-
const state = {
|
|
325
|
-
id,
|
|
326
|
-
position,
|
|
327
|
-
velocity: new Float32Array(this.dimension).fill(0),
|
|
328
|
-
attention: new Float32Array(this.dimension).fill(1),
|
|
329
|
-
energy: 1.0,
|
|
330
|
-
lastUpdate: Date.now()
|
|
331
|
-
};
|
|
332
|
-
this.agents.set(id, state);
|
|
333
|
-
return state;
|
|
334
|
-
}
|
|
335
|
-
async updateState(agentId, observation) {
|
|
336
|
-
validateId(agentId, 'EmbeddingStateMachine.updateState');
|
|
337
|
-
validateTextInput(observation, 'EmbeddingStateMachine.updateState');
|
|
338
|
-
const agent = this.agents.get(agentId);
|
|
339
|
-
if (!agent)
|
|
340
|
-
throw new Error('Agent not found or access denied');
|
|
341
|
-
const obsEmb = await this.embedder.embed(observation);
|
|
342
|
-
// Update velocity and position
|
|
343
|
-
const learningRate = 0.3;
|
|
344
|
-
const momentumRate = 0.7;
|
|
345
|
-
for (let i = 0; i < this.dimension; i++) {
|
|
346
|
-
const gradient = obsEmb[i] - agent.position[i];
|
|
347
|
-
agent.velocity[i] = momentumRate * agent.velocity[i] + learningRate * gradient;
|
|
348
|
-
agent.position[i] += agent.velocity[i];
|
|
349
|
-
}
|
|
350
|
-
// Normalize position
|
|
351
|
-
const norm = Math.sqrt(agent.position.reduce((s, v) => s + v * v, 0));
|
|
352
|
-
for (let i = 0; i < this.dimension; i++) {
|
|
353
|
-
agent.position[i] /= norm;
|
|
354
|
-
}
|
|
355
|
-
// Update attention based on velocity magnitude
|
|
356
|
-
const velocityMag = Math.sqrt(agent.velocity.reduce((s, v) => s + v * v, 0));
|
|
357
|
-
for (let i = 0; i < this.dimension; i++) {
|
|
358
|
-
agent.attention[i] = 1 + velocityMag * Math.abs(agent.velocity[i]);
|
|
359
|
-
}
|
|
360
|
-
// Energy decay with movement
|
|
361
|
-
agent.energy = Math.max(0.1, agent.energy - velocityMag * 0.1);
|
|
362
|
-
agent.lastUpdate = Date.now();
|
|
363
|
-
// Find nearest state region
|
|
364
|
-
let nearestRegion = 'unknown';
|
|
365
|
-
let regionProximity = -1;
|
|
366
|
-
for (const [name, region] of this.stateRegions) {
|
|
367
|
-
const sim = cosineSimilarity(agent.position, region);
|
|
368
|
-
if (sim > regionProximity) {
|
|
369
|
-
regionProximity = sim;
|
|
370
|
-
nearestRegion = name;
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
return { newState: agent, nearestRegion, regionProximity };
|
|
374
|
-
}
|
|
375
|
-
getAgent(id) {
|
|
376
|
-
return this.agents.get(id);
|
|
377
|
-
}
|
|
378
|
-
getAllAgents() {
|
|
379
|
-
return [...this.agents.values()];
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
/**
|
|
383
|
-
* Swarm Coordinator
|
|
384
|
-
* Multi-agent coordination through shared embedding space
|
|
385
|
-
*/
|
|
386
|
-
export class SwarmCoordinator {
|
|
387
|
-
embedder = getOptimizedEmbedder();
|
|
388
|
-
stateMachine;
|
|
389
|
-
constructor(dimension = 384) {
|
|
390
|
-
this.stateMachine = new EmbeddingStateMachine(dimension);
|
|
391
|
-
}
|
|
392
|
-
async init() {
|
|
393
|
-
await this.embedder.init();
|
|
394
|
-
await this.stateMachine.init();
|
|
395
|
-
}
|
|
396
|
-
async addAgent(id, role) {
|
|
397
|
-
validateId(id, 'SwarmCoordinator.addAgent');
|
|
398
|
-
validateTextInput(role, 'SwarmCoordinator.addAgent');
|
|
399
|
-
return this.stateMachine.registerAgent(id, role);
|
|
400
|
-
}
|
|
401
|
-
async coordinate(task) {
|
|
402
|
-
const taskEmb = await this.embedder.embed(task);
|
|
403
|
-
const agents = this.stateMachine.getAllAgents();
|
|
404
|
-
const results = [];
|
|
405
|
-
for (const agent of agents) {
|
|
406
|
-
const taskAlignment = cosineSimilarity(agent.position, taskEmb);
|
|
407
|
-
// Find best collaborator
|
|
408
|
-
let bestCollaborator = null;
|
|
409
|
-
let bestScore = -1;
|
|
410
|
-
for (const other of agents) {
|
|
411
|
-
if (other.id === agent.id)
|
|
412
|
-
continue;
|
|
413
|
-
const otherAlignment = cosineSimilarity(other.position, taskEmb);
|
|
414
|
-
const complementarity = 1 - cosineSimilarity(agent.position, other.position);
|
|
415
|
-
const score = otherAlignment * 0.6 + complementarity * 0.4;
|
|
416
|
-
if (score > bestScore) {
|
|
417
|
-
bestScore = score;
|
|
418
|
-
bestCollaborator = other.id;
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
results.push({
|
|
422
|
-
agentId: agent.id,
|
|
423
|
-
taskAlignment,
|
|
424
|
-
bestCollaborator,
|
|
425
|
-
collaborationScore: bestScore
|
|
426
|
-
});
|
|
427
|
-
}
|
|
428
|
-
return results.sort((a, b) => b.taskAlignment - a.taskAlignment);
|
|
429
|
-
}
|
|
430
|
-
specialize() {
|
|
431
|
-
const agents = this.stateMachine.getAllAgents();
|
|
432
|
-
const repulsionStrength = 0.05;
|
|
433
|
-
for (let i = 0; i < agents.length; i++) {
|
|
434
|
-
for (let j = i + 1; j < agents.length; j++) {
|
|
435
|
-
const sim = cosineSimilarity(agents[i].position, agents[j].position);
|
|
436
|
-
if (sim > 0.8) {
|
|
437
|
-
// Repel similar agents
|
|
438
|
-
for (let k = 0; k < agents[i].position.length; k++) {
|
|
439
|
-
const repulsion = repulsionStrength * (agents[j].position[k] - agents[i].position[k]);
|
|
440
|
-
agents[i].position[k] -= repulsion;
|
|
441
|
-
agents[j].position[k] += repulsion;
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
// Normalize all
|
|
447
|
-
for (const agent of agents) {
|
|
448
|
-
const norm = Math.sqrt(agent.position.reduce((s, v) => s + v * v, 0));
|
|
449
|
-
for (let k = 0; k < agent.position.length; k++) {
|
|
450
|
-
agent.position[k] /= norm;
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
getStatus() {
|
|
455
|
-
const agents = this.stateMachine.getAllAgents();
|
|
456
|
-
if (agents.length === 0)
|
|
457
|
-
return { agentCount: 0, avgEnergy: 0, coherence: 0 };
|
|
458
|
-
const avgEnergy = agents.reduce((s, a) => s + a.energy, 0) / agents.length;
|
|
459
|
-
// Coherence = average pairwise similarity
|
|
460
|
-
let coherence = 0;
|
|
461
|
-
let pairs = 0;
|
|
462
|
-
for (let i = 0; i < agents.length; i++) {
|
|
463
|
-
for (let j = i + 1; j < agents.length; j++) {
|
|
464
|
-
coherence += cosineSimilarity(agents[i].position, agents[j].position);
|
|
465
|
-
pairs++;
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
coherence = pairs > 0 ? coherence / pairs : 1;
|
|
469
|
-
return { agentCount: agents.length, avgEnergy, coherence };
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
/**
|
|
473
|
-
* Coherence Monitor
|
|
474
|
-
* Safety and alignment detection
|
|
475
|
-
*/
|
|
476
|
-
export class CoherenceMonitor {
|
|
477
|
-
embedder = getOptimizedEmbedder();
|
|
478
|
-
baseline = [];
|
|
479
|
-
centroid = null;
|
|
480
|
-
avgDistance = 0;
|
|
481
|
-
async init() {
|
|
482
|
-
await this.embedder.init();
|
|
483
|
-
}
|
|
484
|
-
async calibrate(goodOutputs) {
|
|
485
|
-
// Security: Validate input array
|
|
486
|
-
if (!Array.isArray(goodOutputs)) {
|
|
487
|
-
throw new Error('CoherenceMonitor.calibrate: goodOutputs must be an array');
|
|
488
|
-
}
|
|
489
|
-
if (goodOutputs.length === 0) {
|
|
490
|
-
throw new Error('CoherenceMonitor.calibrate: At least one sample is required');
|
|
491
|
-
}
|
|
492
|
-
if (goodOutputs.length > MAX_BASELINE_SAMPLES) {
|
|
493
|
-
throw new Error(`CoherenceMonitor.calibrate: Sample count exceeds maximum of ${MAX_BASELINE_SAMPLES}`);
|
|
494
|
-
}
|
|
495
|
-
// Validate each sample
|
|
496
|
-
for (const output of goodOutputs) {
|
|
497
|
-
validateTextInput(output, 'CoherenceMonitor.calibrate');
|
|
498
|
-
}
|
|
499
|
-
this.baseline = await this.embedder.embedBatch(goodOutputs);
|
|
500
|
-
const dim = this.baseline[0].length;
|
|
501
|
-
// Calculate centroid
|
|
502
|
-
this.centroid = new Float32Array(dim).fill(0);
|
|
503
|
-
for (const emb of this.baseline) {
|
|
504
|
-
for (let i = 0; i < dim; i++) {
|
|
505
|
-
this.centroid[i] += emb[i];
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
for (let i = 0; i < dim; i++) {
|
|
509
|
-
this.centroid[i] /= this.baseline.length;
|
|
510
|
-
}
|
|
511
|
-
// Average distance from centroid
|
|
512
|
-
this.avgDistance = this.baseline.reduce((s, b) => s + euclideanDistance(b, this.centroid), 0) / this.baseline.length;
|
|
513
|
-
return { calibrated: true, sampleCount: this.baseline.length };
|
|
514
|
-
}
|
|
515
|
-
async check(output) {
|
|
516
|
-
validateTextInput(output, 'CoherenceMonitor.check');
|
|
517
|
-
validateEmbedding(this.centroid, 'CoherenceMonitor.check (call calibrate() first)');
|
|
518
|
-
const outputEmb = await this.embedder.embed(output);
|
|
519
|
-
const warnings = [];
|
|
520
|
-
// Anomaly score
|
|
521
|
-
const distance = euclideanDistance(outputEmb, this.centroid);
|
|
522
|
-
const anomalyScore = distance / this.avgDistance;
|
|
523
|
-
// Nearest neighbor
|
|
524
|
-
let maxSim = -1;
|
|
525
|
-
for (const b of this.baseline) {
|
|
526
|
-
const sim = cosineSimilarity(outputEmb, b);
|
|
527
|
-
if (sim > maxSim)
|
|
528
|
-
maxSim = sim;
|
|
529
|
-
}
|
|
530
|
-
const stabilityScore = maxSim;
|
|
531
|
-
// Drift direction
|
|
532
|
-
const driftDirection = new Float32Array(outputEmb.length);
|
|
533
|
-
for (let i = 0; i < outputEmb.length; i++) {
|
|
534
|
-
driftDirection[i] = outputEmb[i] - this.centroid[i];
|
|
535
|
-
}
|
|
536
|
-
// Warnings
|
|
537
|
-
if (anomalyScore > 2.0) {
|
|
538
|
-
warnings.push('CRITICAL: Output significantly outside baseline');
|
|
539
|
-
}
|
|
540
|
-
else if (anomalyScore > 1.5) {
|
|
541
|
-
warnings.push('WARNING: Output drifting from baseline');
|
|
542
|
-
}
|
|
543
|
-
if (stabilityScore < 0.5) {
|
|
544
|
-
warnings.push('WARNING: Low similarity to all baseline examples');
|
|
545
|
-
}
|
|
546
|
-
return {
|
|
547
|
-
isCoherent: anomalyScore < 1.5 && stabilityScore > 0.5,
|
|
548
|
-
anomalyScore,
|
|
549
|
-
stabilityScore,
|
|
550
|
-
driftDirection,
|
|
551
|
-
warnings
|
|
552
|
-
};
|
|
553
|
-
}
|
|
554
|
-
}
|
|
555
|
-
/**
|
|
556
|
-
* Neural Substrate
|
|
557
|
-
* Unified nervous system combining all components
|
|
558
|
-
*/
|
|
559
|
-
export class NeuralSubstrate {
|
|
560
|
-
drift;
|
|
561
|
-
memory;
|
|
562
|
-
states;
|
|
563
|
-
swarm;
|
|
564
|
-
coherence;
|
|
565
|
-
startTime = Date.now();
|
|
566
|
-
constructor(config = {}) {
|
|
567
|
-
const { dimension = 384, driftThreshold = 0.15, decayRate = 0.01 } = config;
|
|
568
|
-
this.drift = new SemanticDriftDetector(driftThreshold);
|
|
569
|
-
this.memory = new MemoryPhysics(decayRate);
|
|
570
|
-
this.states = new EmbeddingStateMachine(dimension);
|
|
571
|
-
this.swarm = new SwarmCoordinator(dimension);
|
|
572
|
-
this.coherence = new CoherenceMonitor();
|
|
573
|
-
}
|
|
574
|
-
async init() {
|
|
575
|
-
await Promise.all([
|
|
576
|
-
this.drift.init(),
|
|
577
|
-
this.memory.init(),
|
|
578
|
-
this.states.init(),
|
|
579
|
-
this.swarm.init(),
|
|
580
|
-
this.coherence.init()
|
|
581
|
-
]);
|
|
582
|
-
}
|
|
583
|
-
async process(input, context) {
|
|
584
|
-
const result = {};
|
|
585
|
-
// Always check drift
|
|
586
|
-
result.drift = await this.drift.detect(input);
|
|
587
|
-
// Update agent state if specified
|
|
588
|
-
if (context?.agentId) {
|
|
589
|
-
const { nearestRegion, regionProximity } = await this.states.updateState(context.agentId, input);
|
|
590
|
-
result.state = { nearestRegion, regionProximity };
|
|
591
|
-
}
|
|
592
|
-
// Store in memory if specified
|
|
593
|
-
if (context?.memoryId) {
|
|
594
|
-
const { stored } = await this.memory.store(context.memoryId, input);
|
|
595
|
-
result.stored = stored;
|
|
596
|
-
}
|
|
597
|
-
// Check coherence if requested
|
|
598
|
-
if (context?.checkCoherence) {
|
|
599
|
-
result.coherence = await this.coherence.check(input);
|
|
600
|
-
}
|
|
601
|
-
return result;
|
|
602
|
-
}
|
|
603
|
-
consolidate() {
|
|
604
|
-
return { memory: this.memory.consolidate() };
|
|
605
|
-
}
|
|
606
|
-
health() {
|
|
607
|
-
const memStats = this.memory.getStats();
|
|
608
|
-
const driftStats = this.drift.getStats();
|
|
609
|
-
const swarmStatus = this.swarm.getStatus();
|
|
610
|
-
return {
|
|
611
|
-
memoryCount: memStats.total,
|
|
612
|
-
activeAgents: swarmStatus.agentCount,
|
|
613
|
-
avgDrift: driftStats.avgDrift,
|
|
614
|
-
avgCoherence: swarmStatus.coherence,
|
|
615
|
-
lastConsolidation: 0, // Would need to track this
|
|
616
|
-
uptime: Date.now() - this.startTime
|
|
617
|
-
};
|
|
618
|
-
}
|
|
619
|
-
}
|
|
620
|
-
// Export singleton factory
|
|
621
|
-
let substrate = null;
|
|
622
|
-
export async function getNeuralSubstrate(config) {
|
|
623
|
-
if (!substrate) {
|
|
624
|
-
substrate = new NeuralSubstrate(config);
|
|
625
|
-
await substrate.init();
|
|
626
|
-
}
|
|
627
|
-
return substrate;
|
|
628
|
-
}
|
|
629
|
-
//# sourceMappingURL=neural-substrate.js.map
|