agentic-flow 3.1.0 → 3.3.0
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/.agents/skills/agentic-flow-ecosystem/SKILL.md +51 -0
- package/.claude/skills/agentic-flow-ecosystem/skill.md +59 -0
- package/.claude/skills/agentic-flow-quickstart/skill.md +6 -6
- package/.claude/skills/hooks-automation/skill.md +11 -11
- package/.claude/skills/memory-patterns/skill.md +7 -7
- package/.claude/skills/sparc-methodology/skill.md +13 -13
- package/.claude/skills/swarm-coordination/skill.md +5 -5
- package/.claude/skills/worker-benchmarks/skill.md +5 -5
- package/.claude/skills/worker-integration/skill.md +5 -5
- package/CHANGELOG.md +50 -0
- package/README.md +82 -67
- package/dist/.tsbuildinfo +1 -1
- package/dist/cli/commands/init.d.ts.map +1 -1
- package/dist/cli/commands/init.js +9 -0
- package/dist/cli/commands/init.js.map +1 -1
- package/dist/config/claudeFlow.d.ts +1 -1
- package/dist/core/agentdb-fast.d.ts +21 -11
- package/dist/core/agentdb-fast.d.ts.map +1 -1
- package/dist/core/agentdb-fast.js +39 -14
- package/dist/core/agentdb-fast.js.map +1 -1
- package/dist/integrations/agent-booster.d.ts +35 -0
- package/dist/integrations/agent-booster.d.ts.map +1 -0
- package/dist/integrations/agent-booster.js +45 -0
- package/dist/integrations/agent-booster.js.map +1 -0
- package/dist/integrations/index.d.ts +15 -0
- package/dist/integrations/index.d.ts.map +1 -0
- package/dist/integrations/index.js +11 -0
- package/dist/integrations/index.js.map +1 -0
- package/dist/integrations/onnx-wasm-embedder.d.ts +59 -0
- package/dist/integrations/onnx-wasm-embedder.d.ts.map +1 -0
- package/dist/integrations/onnx-wasm-embedder.js +145 -0
- package/dist/integrations/onnx-wasm-embedder.js.map +1 -0
- package/dist/integrations/optional.d.ts +32 -0
- package/dist/integrations/optional.d.ts.map +1 -0
- package/dist/integrations/optional.js +83 -0
- package/dist/integrations/optional.js.map +1 -0
- package/dist/integrations/prompt-injection.d.ts +52 -0
- package/dist/integrations/prompt-injection.d.ts.map +1 -0
- package/dist/integrations/prompt-injection.js +126 -0
- package/dist/integrations/prompt-injection.js.map +1 -0
- package/dist/integrations/sublinear.d.ts +99 -0
- package/dist/integrations/sublinear.d.ts.map +1 -0
- package/dist/integrations/sublinear.js +303 -0
- package/dist/integrations/sublinear.js.map +1 -0
- package/dist/integrations/task-partition.d.ts +40 -0
- package/dist/integrations/task-partition.d.ts.map +1 -0
- package/dist/integrations/task-partition.js +173 -0
- package/dist/integrations/task-partition.js.map +1 -0
- package/dist/intelligence/RuVectorIntelligence.d.ts.map +1 -1
- package/dist/intelligence/RuVectorIntelligence.js +4 -3
- package/dist/intelligence/RuVectorIntelligence.js.map +1 -1
- package/dist/mcp/mcp-policy.d.ts.map +1 -1
- package/dist/mcp/mcp-policy.js +2 -0
- package/dist/mcp/mcp-policy.js.map +1 -1
- package/dist/mcp/standalone-stdio.js +12 -26
- package/dist/mcp/standalone-stdio.js.map +1 -1
- package/dist/mcp/tools/ecosystem-tools.d.ts +49 -0
- package/dist/mcp/tools/ecosystem-tools.d.ts.map +1 -0
- package/dist/mcp/tools/ecosystem-tools.js +148 -0
- package/dist/mcp/tools/ecosystem-tools.js.map +1 -0
- package/dist/optimizations/configuration-tuning.d.ts +1 -1
- package/dist/routing/SemanticRouter.d.ts +25 -9
- package/dist/routing/SemanticRouter.d.ts.map +1 -1
- package/dist/routing/SemanticRouter.js +63 -12
- package/dist/routing/SemanticRouter.js.map +1 -1
- package/dist/services/sona-loader.d.ts +15 -1
- package/dist/services/sona-loader.d.ts.map +1 -1
- package/dist/services/sona-loader.js +54 -2
- package/dist/services/sona-loader.js.map +1 -1
- package/dist/utils/input-validator.d.ts +10 -2
- package/dist/utils/input-validator.d.ts.map +1 -1
- package/dist/utils/input-validator.js +30 -2
- package/dist/utils/input-validator.js.map +1 -1
- package/dist/utils/model-cache.d.ts.map +1 -1
- package/dist/utils/model-cache.js +6 -25
- package/dist/utils/model-cache.js.map +1 -1
- package/dist/wasm/onnx-embeddings-wasm.d.ts.map +1 -1
- package/dist/wasm/onnx-embeddings-wasm.js +21 -10
- package/dist/wasm/onnx-embeddings-wasm.js.map +1 -1
- package/docs/integrations/FASTMCP_CLI_INTEGRATION.md +1 -1
- package/package.json +13 -8
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Split a task-dependency graph into two groups with the least coupling.
|
|
3
|
+
*
|
|
4
|
+
* A global minimum cut over the (undirected, weighted) dependency graph finds
|
|
5
|
+
* the split that severs the fewest/lightest dependencies — the natural seam for
|
|
6
|
+
* handing work to two agent teams so they block on each other least.
|
|
7
|
+
*
|
|
8
|
+
* Engine: `@ruvector/mincut-wasm` (optionalDependency) when installed; a
|
|
9
|
+
* built-in Stoer-Wagner implementation otherwise (O(n^3), capped at
|
|
10
|
+
* BUILTIN_MAX_TASKS). Both are exact, so they agree on the cut weight.
|
|
11
|
+
*
|
|
12
|
+
* A global min cut can be lopsided (one loosely-attached task vs the rest):
|
|
13
|
+
* that is the correct answer to "where is the weakest seam", not a balance
|
|
14
|
+
* guarantee. Tasks with no dependencies have nothing to cut and are reported
|
|
15
|
+
* in `isolated` rather than forced into a side.
|
|
16
|
+
*/
|
|
17
|
+
import { importOptional } from './optional.js';
|
|
18
|
+
export const BUILTIN_MAX_TASKS = 400;
|
|
19
|
+
function normalize(tasks, deps) {
|
|
20
|
+
const ids = new Map();
|
|
21
|
+
const names = [];
|
|
22
|
+
const add = (t) => {
|
|
23
|
+
if (!ids.has(t)) {
|
|
24
|
+
ids.set(t, names.length);
|
|
25
|
+
names.push(t);
|
|
26
|
+
}
|
|
27
|
+
return ids.get(t);
|
|
28
|
+
};
|
|
29
|
+
for (const t of tasks)
|
|
30
|
+
add(String(t));
|
|
31
|
+
const weights = new Map();
|
|
32
|
+
for (const d of deps) {
|
|
33
|
+
const w = d.weight ?? 1;
|
|
34
|
+
if (!Number.isFinite(w) || w < 0)
|
|
35
|
+
throw new Error(`invalid dependency weight ${w} (${d.from} -> ${d.to})`);
|
|
36
|
+
const a = add(String(d.from));
|
|
37
|
+
const b = add(String(d.to));
|
|
38
|
+
if (a === b || w === 0)
|
|
39
|
+
continue;
|
|
40
|
+
const key = a < b ? `${a},${b}` : `${b},${a}`;
|
|
41
|
+
weights.set(key, (weights.get(key) ?? 0) + w);
|
|
42
|
+
}
|
|
43
|
+
const edges = [];
|
|
44
|
+
for (const [key, w] of weights) {
|
|
45
|
+
const [a, b] = key.split(',').map(Number);
|
|
46
|
+
edges.push([a, b, w]);
|
|
47
|
+
}
|
|
48
|
+
return { names, edges };
|
|
49
|
+
}
|
|
50
|
+
/** Exact global min cut (Stoer-Wagner) over vertices that appear in `edges`. */
|
|
51
|
+
function stoerWagner(n, edges) {
|
|
52
|
+
const W = Array.from({ length: n }, () => new Array(n).fill(0));
|
|
53
|
+
for (const [a, b, w] of edges) {
|
|
54
|
+
W[a][b] += w;
|
|
55
|
+
W[b][a] += w;
|
|
56
|
+
}
|
|
57
|
+
const members = Array.from({ length: n }, (_, i) => [i]);
|
|
58
|
+
let active = Array.from({ length: n }, (_, i) => i);
|
|
59
|
+
let best = Infinity;
|
|
60
|
+
let bestSide = [];
|
|
61
|
+
while (active.length > 1) {
|
|
62
|
+
const added = new Set();
|
|
63
|
+
const conn = new Map(active.map((v) => [v, 0]));
|
|
64
|
+
let prev = -1;
|
|
65
|
+
let last = -1;
|
|
66
|
+
for (let step = 0; step < active.length; step++) {
|
|
67
|
+
let pick = -1;
|
|
68
|
+
for (const v of active) {
|
|
69
|
+
if (!added.has(v) && (pick === -1 || conn.get(v) > conn.get(pick)))
|
|
70
|
+
pick = v;
|
|
71
|
+
}
|
|
72
|
+
added.add(pick);
|
|
73
|
+
prev = last;
|
|
74
|
+
last = pick;
|
|
75
|
+
if (step === active.length - 1) {
|
|
76
|
+
const cutOfPhase = conn.get(pick);
|
|
77
|
+
if (cutOfPhase < best) {
|
|
78
|
+
best = cutOfPhase;
|
|
79
|
+
bestSide = [...members[pick]];
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
for (const v of active)
|
|
83
|
+
if (!added.has(v))
|
|
84
|
+
conn.set(v, conn.get(v) + W[pick][v]);
|
|
85
|
+
}
|
|
86
|
+
// merge `last` into `prev`
|
|
87
|
+
for (const v of active) {
|
|
88
|
+
W[prev][v] += W[last][v];
|
|
89
|
+
W[v][prev] = W[prev][v];
|
|
90
|
+
}
|
|
91
|
+
members[prev].push(...members[last]);
|
|
92
|
+
active = active.filter((v) => v !== last);
|
|
93
|
+
}
|
|
94
|
+
return { cut: best === Infinity ? 0 : best, side: new Set(bestSide) };
|
|
95
|
+
}
|
|
96
|
+
function components(n, edges) {
|
|
97
|
+
const parent = Array.from({ length: n }, (_, i) => i);
|
|
98
|
+
const find = (x) => (parent[x] === x ? x : (parent[x] = find(parent[x])));
|
|
99
|
+
for (const [a, b] of edges)
|
|
100
|
+
parent[find(a)] = find(b);
|
|
101
|
+
const groups = new Map();
|
|
102
|
+
for (let i = 0; i < n; i++) {
|
|
103
|
+
const r = find(i);
|
|
104
|
+
if (!groups.has(r))
|
|
105
|
+
groups.set(r, []);
|
|
106
|
+
groups.get(r).push(i);
|
|
107
|
+
}
|
|
108
|
+
return [...groups.values()];
|
|
109
|
+
}
|
|
110
|
+
export async function partitionTaskGraph(tasks, dependencies, options = {}) {
|
|
111
|
+
const { names, edges } = normalize(tasks, dependencies);
|
|
112
|
+
const touched = new Set();
|
|
113
|
+
for (const [a, b] of edges) {
|
|
114
|
+
touched.add(a);
|
|
115
|
+
touched.add(b);
|
|
116
|
+
}
|
|
117
|
+
const isolated = names.filter((_, i) => !touched.has(i));
|
|
118
|
+
const toEdges = (list) => list.map((e) => ({ from: names[e.u], to: names[e.v], weight: e.weight }));
|
|
119
|
+
if (touched.size < 2) {
|
|
120
|
+
return { groups: [names.filter((_, i) => touched.has(i)), []], isolated, cutWeight: 0, cutEdges: [], engine: 'builtin' };
|
|
121
|
+
}
|
|
122
|
+
if (options.engine !== 'builtin') {
|
|
123
|
+
const mod = await importOptional('@ruvector/mincut-wasm');
|
|
124
|
+
if (mod?.WasmMinCut) {
|
|
125
|
+
const g = mod.WasmMinCut.fromEdges(edges);
|
|
126
|
+
try {
|
|
127
|
+
const p = g.partition();
|
|
128
|
+
return {
|
|
129
|
+
groups: [p.s.map((i) => names[i]), p.t.map((i) => names[i])],
|
|
130
|
+
isolated,
|
|
131
|
+
cutWeight: g.minCutValue(),
|
|
132
|
+
cutEdges: toEdges(g.cutEdges()),
|
|
133
|
+
engine: 'mincut-wasm',
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
g.free?.();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
// Built-in: disconnected graphs cut at weight 0 between components.
|
|
142
|
+
const comps = components(names.length, edges).filter((c) => c.some((v) => touched.has(v)));
|
|
143
|
+
let side;
|
|
144
|
+
let cut;
|
|
145
|
+
if (comps.length > 1) {
|
|
146
|
+
side = new Set(comps[0]);
|
|
147
|
+
cut = 0;
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
if (touched.size > BUILTIN_MAX_TASKS) {
|
|
151
|
+
throw new Error(`built-in min cut is limited to ${BUILTIN_MAX_TASKS} connected tasks; install @ruvector/mincut-wasm for larger graphs`);
|
|
152
|
+
}
|
|
153
|
+
// Re-index the touched vertices densely for Stoer-Wagner.
|
|
154
|
+
const order = [...touched];
|
|
155
|
+
const local = new Map(order.map((v, i) => [v, i]));
|
|
156
|
+
const r = stoerWagner(order.length, edges.map(([a, b, w]) => [local.get(a), local.get(b), w]));
|
|
157
|
+
side = new Set([...r.side].map((i) => order[i]));
|
|
158
|
+
cut = r.cut;
|
|
159
|
+
}
|
|
160
|
+
const s = [...touched].filter((v) => side.has(v));
|
|
161
|
+
const t = [...touched].filter((v) => !side.has(v));
|
|
162
|
+
const crossing = edges
|
|
163
|
+
.filter(([a, b]) => side.has(a) !== side.has(b))
|
|
164
|
+
.map(([u, v, weight]) => ({ u, v, weight }));
|
|
165
|
+
return {
|
|
166
|
+
groups: [s.map((i) => names[i]), t.map((i) => names[i])],
|
|
167
|
+
isolated,
|
|
168
|
+
cutWeight: cut,
|
|
169
|
+
cutEdges: toEdges(crossing),
|
|
170
|
+
engine: 'builtin',
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
//# sourceMappingURL=task-partition.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"task-partition.js","sourceRoot":"","sources":["../../src/integrations/task-partition.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAmB/C,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAarC,SAAS,SAAS,CAAC,KAAe,EAAE,IAAsB;IACxD,MAAM,GAAG,GAAG,IAAI,GAAG,EAAkB,CAAC;IACtC,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,EAAE;QACxB,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;YAChB,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;YACzB,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAChB,CAAC;QACD,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,CAAE,CAAC;IACrB,CAAC,CAAC;IACF,KAAK,MAAM,CAAC,IAAI,KAAK;QAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IACtC,MAAM,OAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC1C,KAAK,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;QACrB,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC;QACxB,IAAI,CAAC,MAAM,CAAC,QAAQ,C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AAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;SAC/C,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC;IAC/C,OAAO;QACL,MAAM,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QACxD,QAAQ;QACR,SAAS,EAAE,GAAG;QACd,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC;QAC3B,MAAM,EAAE,SAAS;KAClB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Split a task-dependency graph into two groups with the least coupling.\n *\n * A global minimum cut over the (undirected, weighted) dependency graph finds\n * the split that severs the fewest/lightest dependencies — the natural seam for\n * handing work to two agent teams so they block on each other least.\n *\n * Engine: `@ruvector/mincut-wasm` (optionalDependency) when installed; a\n * built-in Stoer-Wagner implementation otherwise (O(n^3), capped at\n * BUILTIN_MAX_TASKS). Both are exact, so they agree on the cut weight.\n *\n * A global min cut can be lopsided (one loosely-attached task vs the rest):\n * that is the correct answer to \"where is the weakest seam\", not a balance\n * guarantee. Tasks with no dependencies have nothing to cut and are reported\n * in `isolated` rather than forced into a side.\n */\n\nimport { importOptional } from './optional.js';\n\nexport interface TaskDependency {\n from: string;\n to: string;\n /** Coupling strength, default 1. Must be finite and >= 0. */\n weight?: number;\n}\n\nexport interface TaskPartition {\n groups: [string[], string[]];\n /** Tasks that have no dependencies at all. */\n isolated: string[];\n /** Sum of weights of the dependencies crossing between the groups. */\n cutWeight: number;\n cutEdges: Array<{ from: string; to: string; weight: number }>;\n engine: 'mincut-wasm' | 'builtin';\n}\n\nexport const BUILTIN_MAX_TASKS = 400;\n\ninterface MinCutModule {\n WasmMinCut: {\n fromEdges(edges: Array<[number, number, number]>): {\n minCutValue(): number;\n partition(): { s: number[]; t: number[] };\n cutEdges(): Array<{ u: number; v: number; weight: number }>;\n free?(): void;\n };\n };\n}\n\nfunction normalize(tasks: string[], deps: TaskDependency[]) {\n const ids = new Map<string, number>();\n const names: string[] = [];\n const add = (t: string) => {\n if (!ids.has(t)) {\n ids.set(t, names.length);\n names.push(t);\n }\n return ids.get(t)!;\n };\n for (const t of tasks) add(String(t));\n const weights = new Map<string, number>();\n for (const d of deps) {\n const w = d.weight ?? 1;\n if (!Number.isFinite(w) || w < 0) throw new Error(`invalid dependency weight ${w} (${d.from} -> ${d.to})`);\n const a = add(String(d.from));\n const b = add(String(d.to));\n if (a === b || w === 0) continue;\n const key = a < b ? `${a},${b}` : `${b},${a}`;\n weights.set(key, (weights.get(key) ?? 0) + w);\n }\n const edges: Array<[number, number, number]> = [];\n for (const [key, w] of weights) {\n const [a, b] = key.split(',').map(Number);\n edges.push([a, b, w]);\n }\n return { names, edges };\n}\n\n/** Exact global min cut (Stoer-Wagner) over vertices that appear in `edges`. */\nfunction stoerWagner(n: number, edges: Array<[number, number, number]>): { cut: number; side: Set<number> } {\n const W: number[][] = Array.from({ length: n }, () => new Array(n).fill(0));\n for (const [a, b, w] of edges) {\n W[a][b] += w;\n W[b][a] += w;\n }\n const members: number[][] = Array.from({ length: n }, (_, i) => [i]);\n let active = Array.from({ length: n }, (_, i) => i);\n let best = Infinity;\n let bestSide: number[] = [];\n while (active.length > 1) {\n const added = new Set<number>();\n const conn = new Map<number, number>(active.map((v) => [v, 0]));\n let prev = -1;\n let last = -1;\n for (let step = 0; step < active.length; step++) {\n let pick = -1;\n for (const v of active) {\n if (!added.has(v) && (pick === -1 || conn.get(v)! > conn.get(pick)!)) pick = v;\n }\n added.add(pick);\n prev = last;\n last = pick;\n if (step === active.length - 1) {\n const cutOfPhase = conn.get(pick)!;\n if (cutOfPhase < best) {\n best = cutOfPhase;\n bestSide = [...members[pick]];\n }\n }\n for (const v of active) if (!added.has(v)) conn.set(v, conn.get(v)! + W[pick][v]);\n }\n // merge `last` into `prev`\n for (const v of active) {\n W[prev][v] += W[last][v];\n W[v][prev] = W[prev][v];\n }\n members[prev].push(...members[last]);\n active = active.filter((v) => v !== last);\n }\n return { cut: best === Infinity ? 0 : best, side: new Set(bestSide) };\n}\n\nfunction components(n: number, edges: Array<[number, number, number]>): number[][] {\n const parent = Array.from({ length: n }, (_, i) => i);\n const find = (x: number): number => (parent[x] === x ? x : (parent[x] = find(parent[x])));\n for (const [a, b] of edges) parent[find(a)] = find(b);\n const groups = new Map<number, number[]>();\n for (let i = 0; i < n; i++) {\n const r = find(i);\n if (!groups.has(r)) groups.set(r, []);\n groups.get(r)!.push(i);\n }\n return [...groups.values()];\n}\n\nexport async function partitionTaskGraph(\n tasks: string[],\n dependencies: TaskDependency[],\n options: { engine?: 'auto' | 'builtin' } = {},\n): Promise<TaskPartition> {\n const { names, edges } = normalize(tasks, dependencies);\n const touched = new Set<number>();\n for (const [a, b] of edges) {\n touched.add(a);\n touched.add(b);\n }\n const isolated = names.filter((_, i) => !touched.has(i));\n const toEdges = (list: Array<{ u: number; v: number; weight: number }>) =>\n list.map((e) => ({ from: names[e.u], to: names[e.v], weight: e.weight }));\n\n if (touched.size < 2) {\n return { groups: [names.filter((_, i) => touched.has(i)), []], isolated, cutWeight: 0, cutEdges: [], engine: 'builtin' };\n }\n\n if (options.engine !== 'builtin') {\n const mod = await importOptional<MinCutModule>('@ruvector/mincut-wasm');\n if (mod?.WasmMinCut) {\n const g = mod.WasmMinCut.fromEdges(edges);\n try {\n const p = g.partition();\n return {\n groups: [p.s.map((i) => names[i]), p.t.map((i) => names[i])],\n isolated,\n cutWeight: g.minCutValue(),\n cutEdges: toEdges(g.cutEdges()),\n engine: 'mincut-wasm',\n };\n } finally {\n g.free?.();\n }\n }\n }\n\n // Built-in: disconnected graphs cut at weight 0 between components.\n const comps = components(names.length, edges).filter((c) => c.some((v) => touched.has(v)));\n let side: Set<number>;\n let cut: number;\n if (comps.length > 1) {\n side = new Set(comps[0]);\n cut = 0;\n } else {\n if (touched.size > BUILTIN_MAX_TASKS) {\n throw new Error(\n `built-in min cut is limited to ${BUILTIN_MAX_TASKS} connected tasks; install @ruvector/mincut-wasm for larger graphs`,\n );\n }\n // Re-index the touched vertices densely for Stoer-Wagner.\n const order = [...touched];\n const local = new Map(order.map((v, i) => [v, i]));\n const r = stoerWagner(order.length, edges.map(([a, b, w]) => [local.get(a)!, local.get(b)!, w] as [number, number, number]));\n side = new Set([...r.side].map((i) => order[i]));\n cut = r.cut;\n }\n const s = [...touched].filter((v) => side.has(v));\n const t = [...touched].filter((v) => !side.has(v));\n const crossing = edges\n .filter(([a, b]) => side.has(a) !== side.has(b))\n .map(([u, v, weight]) => ({ u, v, weight }));\n return {\n groups: [s.map((i) => names[i]), t.map((i) => names[i])],\n isolated,\n cutWeight: cut,\n cutEdges: toEdges(crossing),\n engine: 'builtin',\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RuVectorIntelligence.d.ts","sourceRoot":"","sources":["../../src/intelligence/RuVectorIntelligence.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAIH,QAAA,IAAI,aAAa,SAAQ,CAAC;AAe1B,QAAA,IAAI,kBAAkB,SAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"RuVectorIntelligence.d.ts","sourceRoot":"","sources":["../../src/intelligence/RuVectorIntelligence.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAIH,QAAA,IAAI,aAAa,SAAQ,CAAC;AAe1B,QAAA,IAAI,kBAAkB,SAAQ,CAAC;AAwC/B,OAAO,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AA4B;;;;;CAK7B,CAAC"}
|
|
@@ -47,10 +47,10 @@ let poincareDistance = null;
|
|
|
47
47
|
let projectToPoincareBall = null;
|
|
48
48
|
let AttentionType = null;
|
|
49
49
|
let attentionAvailable = false;
|
|
50
|
-
// Try to load @ruvector/sona
|
|
50
|
+
// Try to load @ruvector/sona (through the loader, whose engines validate
|
|
51
|
+
// LoRA input lengths instead of letting a native panic abort the process)
|
|
51
52
|
try {
|
|
52
|
-
|
|
53
|
-
SonaEngine = sonaModule.SonaEngine;
|
|
53
|
+
SonaEngine = requireSonaEngine();
|
|
54
54
|
sonaAvailable = true;
|
|
55
55
|
}
|
|
56
56
|
catch {
|
|
@@ -81,6 +81,7 @@ catch {
|
|
|
81
81
|
console.warn('[RuVectorIntelligence] @ruvector/attention not available - attention features disabled');
|
|
82
82
|
}
|
|
83
83
|
// Import from ruvector core (for HNSW)
|
|
84
|
+
import { requireSonaEngine } from '../services/sona-loader.js';
|
|
84
85
|
import ruvector from 'ruvector';
|
|
85
86
|
// Export availability flags
|
|
86
87
|
export { sonaAvailable, attentionAvailable };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RuVectorIntelligence.js","sourceRoot":"","sources":["../../src/intelligence/RuVectorIntelligence.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,oFAAoF;AACpF,IAAI,UAAU,GAAQ,IAAI,CAAC;AAC3B,IAAI,aAAa,GAAG,KAAK,CAAC;AAE1B,IAAI,kBAAkB,GAAQ,IAAI,CAAC;AACnC,IAAI,cAAc,GAAQ,IAAI,CAAC;AAC/B,IAAI,mBAAmB,GAAQ,IAAI,CAAC;AACpC,IAAI,YAAY,GAAQ,IAAI,CAAC;AAC7B,IAAI,kBAAkB,GAAQ,IAAI,CAAC;AACnC,IAAI,kBAAkB,GAAQ,IAAI,CAAC;AACnC,IAAI,aAAa,GAAQ,IAAI,CAAC;AAC9B,IAAI,qBAAqB,GAAQ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AAE,GAAG;QACrB,UAAU,EAAE;YACV,aAAa,EAAE,CAAC;YAChB,YAAY,EAAE,EAAE;YAChB,kBAAkB,EAAE,KAAK;SAC1B;KACF;IAED,kDAAkD;IAClD,YAAY,EAAE;QACZ,aAAa,EAAE,YAAqB;QACpC,SAAS,EAAE,GAAG;QACd,kBAAkB,EAAE,IAAI;KACzB;IAED,4BAA4B;IAC5B,KAAK,EAAE;QACL,aAAa,EAAE,OAAgB;QAC/B,kBAAkB,EAAE,IAAI;KACzB;CACF,CAAC","sourcesContent":["/**\n * RuVector Unified Intelligence Layer\n *\n * Integrates the FULL power of RuVector ecosystem:\n *\n * @ruvector/sona - Self-Learning:\n * - Micro-LoRA: Ultra-fast rank-1/2 adaptations (~0.1ms)\n * - Base-LoRA: Deeper pattern adaptations\n * - EWC++: Elastic Weight Consolidation (catastrophic forgetting prevention)\n * - ReasoningBank: Pattern storage/retrieval via findPatterns\n * - Trajectory tracking: Learn from execution paths\n *\n * @ruvector/attention - Advanced Attention:\n * - MultiHeadAttention: Standard transformer attention\n * - FlashAttention: Memory-efficient O(n) attention\n * - HyperbolicAttention: Poincaré ball geometry for hierarchies\n * - MoEAttention: Mixture of Experts routing\n * - GraphRoPeAttention: Graph + Rotary Position Embeddings\n * - EdgeFeaturedAttention: Edge-aware graph attention\n * - DualSpaceAttention: Euclidean + Hyperbolic hybrid\n *\n * @ruvector/core - Vector Database:\n * - HNSW indexing: 150x faster than brute force\n * - Real vector similarity search\n * - Cosine/Euclidean/Dot product distance\n *\n * Performance:\n * - Micro-LoRA adaptation: ~0.1ms\n * - FlashAttention: O(n) complexity vs O(n²)\n * - HNSW search: O(log n) vs O(n)\n * - Background learning: Non-blocking\n */\n\n// Optional imports - graceful fallback on Windows/platforms without native binaries\nlet SonaEngine: any = null;\nlet sonaAvailable = false;\n\nlet MultiHeadAttention: any = null;\nlet FlashAttention: any = null;\nlet HyperbolicAttention: any = null;\nlet MoEAttention: any = null;\nlet GraphRoPeAttention: any = null;\nlet DualSpaceAttention: any = null;\nlet AdamOptimizer: any = null;\nlet computeAttentionAsync: any = null;\nlet computeFlashAttentionAsync: any = null;\nlet computeHyperbolicAttentionAsync: any = null;\nlet poincareDistance: any = null;\nlet projectToPoincareBall: any = null;\nlet AttentionType: any = null;\nlet attentionAvailable = false;\n\n// Try to load @ruvector/sona\ntry {\n const sonaModule = await import('@ruvector/sona');\n SonaEngine = sonaModule.SonaEngine;\n sonaAvailable = true;\n} catch {\n console.warn('[RuVectorIntelligence] @ruvector/sona not available - self-learning disabled');\n}\n\n// Try to load @ruvector/attention\ntry {\n // @ruvector/attention is CommonJS; from 0.1.32 its typings expose it as\n // `default` under ESM interop, while older builds surface named exports.\n const attentionMod: any = await import('@ruvector/attention');\n const attentionModule = attentionMod.default ?? attentionMod;\n MultiHeadAttention = attentionModule.MultiHeadAttention;\n FlashAttention = attentionModule.FlashAttention;\n HyperbolicAttention = attentionModule.HyperbolicAttention;\n MoEAttention = attentionModule.MoEAttention;\n GraphRoPeAttention = attentionModule.GraphRoPeAttention;\n DualSpaceAttention = attentionModule.DualSpaceAttention;\n AdamOptimizer = attentionModule.AdamOptimizer;\n computeAttentionAsync = attentionModule.computeAttentionAsync;\n computeFlashAttentionAsync = attentionModule.computeFlashAttentionAsync;\n computeHyperbolicAttentionAsync = attentionModule.computeHyperbolicAttentionAsync;\n poincareDistance = attentionModule.poincareDistance;\n projectToPoincareBall = attentionModule.projectToPoincareBall;\n AttentionType = attentionModule.AttentionType;\n attentionAvailable = true;\n} catch {\n console.warn('[RuVectorIntelligence] @ruvector/attention not available - attention features disabled');\n}\n\n// Import from ruvector core (for HNSW)\nimport ruvector from 'ruvector';\n\n// Export availability flags\nexport { sonaAvailable, attentionAvailable };\n\n// Local type definitions (replaces imports from optional packages)\nexport interface JsSonaConfig {\n embeddingDim?: number;\n hiddenDim?: number;\n microLoraRank?: number;\n baseLoraRank?: number;\n ewcLambda?: number;\n microLoraLr?: number;\n baseLoraLr?: number;\n patternClusters?: number;\n [key: string]: any; // Allow additional properties\n}\n\nexport interface JsLearnedPattern {\n id: string;\n pattern: number[];\n confidence: number;\n timestamp: number;\n}\n\nexport interface MoEConfig {\n numExperts?: number;\n topK?: number;\n routerDim?: number;\n dim?: number;\n}\n\n/**\n * Intelligence Layer Configuration\n */\nexport interface RuVectorIntelligenceConfig {\n /** Embedding dimension (default: 384 for all-MiniLM-L6-v2) */\n embeddingDim?: number;\n\n /** Hidden dimension for SONA (default: 256) */\n hiddenDim?: number;\n\n /** Enable SONA self-learning (default: true) */\n enableSona?: boolean;\n\n /** SONA configuration */\n sonaConfig?: Partial<JsSonaConfig>;\n\n /** Attention type for agent routing (default: 'moe') */\n attentionType?: 'multi_head' | 'flash' | 'hyperbolic' | 'moe' | 'graph' | 'dual';\n\n /** Number of attention heads (default: 8) */\n numHeads?: number;\n\n /** Number of MoE experts (default: 4) */\n numExperts?: number;\n\n /** Top-K experts to use (default: 2) */\n topK?: number;\n\n /** Hyperbolic curvature for hierarchical structures (default: 1.0) */\n curvature?: number;\n\n /** Enable HNSW vector index (default: true) */\n enableHnsw?: boolean;\n\n /** HNSW M parameter - connections per node (default: 16) */\n hnswM?: number;\n\n /** HNSW ef_construction (default: 200) */\n hnswEfConstruction?: number;\n\n /** Enable trajectory tracking (default: true) */\n enableTrajectories?: boolean;\n\n /** Quality threshold for learning (default: 0.5) */\n qualityThreshold?: number;\n\n /** Background learning interval in ms (default: 60000 = 1 min) */\n backgroundIntervalMs?: number;\n\n /** Maximum trajectories to keep in memory (default: 1000, LRU eviction) */\n maxTrajectories?: number;\n\n /** Trajectory TTL in ms (default: 1800000 = 30 min) */\n trajectoryTTLMs?: number;\n\n /** Maximum agent embeddings to cache (default: 500, LRU eviction) */\n maxAgentEmbeddings?: number;\n}\n\n/**\n * Trajectory for learning\n */\nexport interface Trajectory {\n id: number;\n query: string;\n embedding: number[];\n steps: TrajectoryStep[];\n route?: string;\n contexts: string[];\n startTime: number;\n}\n\nexport interface TrajectoryStep {\n action: string;\n activations: number[];\n attentionWeights: number[];\n reward: number;\n timestamp: number;\n}\n\n/**\n * Agent routing result\n */\nexport interface AgentRoutingResult {\n agentId: string;\n confidence: number;\n attentionWeights: Float32Array;\n expertWeights?: number[];\n latencyMs: number;\n usedHnsw: boolean;\n usedSona: boolean;\n}\n\n/**\n * Learning outcome\n */\nexport interface LearningOutcome {\n trajectoryId: number;\n success: boolean;\n quality: number;\n patternsLearned: number;\n adaptations: {\n microLora: boolean;\n baseLora: boolean;\n ewc: boolean;\n };\n}\n\n/**\n * RuVector Unified Intelligence Layer\n *\n * Combines SONA self-learning, advanced attention mechanisms,\n * and HNSW vector search for intelligent agent orchestration.\n */\n/**\n * Result wrapper for operations that can fail\n */\nexport interface OperationResult<T> {\n success: boolean;\n value?: T;\n error?: string;\n}\n\nexport class RuVectorIntelligence {\n private config: Required<RuVectorIntelligenceConfig>;\n private initialized = false;\n private initPromise: Promise<void> | null = null;\n\n // SONA Engine for self-learning\n private sona: any = null;\n\n // Attention mechanisms\n private multiHeadAttention: any = null;\n private flashAttention: any = null;\n private hyperbolicAttention: any = null;\n private moeAttention: any = null;\n private graphAttention: any = null;\n private dualSpaceAttention: any = null;\n\n // Training (simplified - removed unused scheduler/loss)\n private optimizer: any = null;\n\n // HNSW index for vector search\n private hnswIndex: any = null;\n\n // Active trajectories with LRU tracking\n private trajectories: Map<number, Trajectory> = new Map();\n private trajectoryAccessOrder: number[] = []; // For LRU eviction\n private nextTrajectoryId = 0;\n\n // Agent embeddings with LRU tracking\n private agentEmbeddings: Map<string, Float32Array> = new Map();\n private agentAccessOrder: string[] = []; // For LRU eviction\n\n // Background learning timer\n private learningTimer: NodeJS.Timeout | null = null;\n\n // Cleanup timer for stale trajectories\n private cleanupTimer: NodeJS.Timeout | null = null;\n\n // Statistics\n private stats = {\n totalRoutings: 0,\n totalTrajectories: 0,\n totalLearningCycles: 0,\n avgRoutingLatencyMs: 0,\n patternsLearned: 0,\n hnswQueries: 0,\n sonaAdaptations: 0,\n evictedTrajectories: 0,\n evictedAgents: 0,\n };\n\n constructor(config?: RuVectorIntelligenceConfig) {\n this.config = {\n embeddingDim: config?.embeddingDim ?? 384,\n hiddenDim: config?.hiddenDim ?? 256,\n enableSona: config?.enableSona ?? true,\n sonaConfig: config?.sonaConfig ?? {},\n attentionType: config?.attentionType ?? 'moe',\n numHeads: config?.numHeads ?? 8,\n numExperts: config?.numExperts ?? 4,\n topK: config?.topK ?? 2,\n curvature: config?.curvature ?? 1.0,\n enableHnsw: config?.enableHnsw ?? true,\n hnswM: config?.hnswM ?? 16,\n hnswEfConstruction: config?.hnswEfConstruction ?? 200,\n enableTrajectories: config?.enableTrajectories ?? true,\n qualityThreshold: config?.qualityThreshold ?? 0.5,\n backgroundIntervalMs: config?.backgroundIntervalMs ?? 60000,\n // Memory limits with LRU eviction\n maxTrajectories: config?.maxTrajectories ?? 1000,\n trajectoryTTLMs: config?.trajectoryTTLMs ?? 1800000, // 30 min\n maxAgentEmbeddings: config?.maxAgentEmbeddings ?? 500,\n };\n\n // Initialize asynchronously to avoid race conditions\n this.initPromise = this.initializeAsync();\n }\n\n /**\n * Wait for initialization to complete\n */\n async waitForInit(): Promise<void> {\n if (this.initPromise) {\n await this.initPromise;\n }\n }\n\n /**\n * Initialize all components (async to avoid race conditions)\n */\n private async initializeAsync(): Promise<void> {\n if (this.initialized) return;\n\n const dim = this.config.embeddingDim;\n\n // Initialize SONA Engine\n if (this.config.enableSona) {\n try {\n // Ensure all values are explicitly defined (no undefined values)\n const sonaConfig: JsSonaConfig = {\n hiddenDim: this.config.hiddenDim ?? 256,\n embeddingDim: dim ?? 384,\n microLoraRank: 1, // Ultra-fast rank-1\n baseLoraRank: 8,\n microLoraLr: 0.001,\n baseLoraLr: 0.0001,\n ewcLambda: 1000.0, // EWC++ regularization\n patternClusters: 50,\n trajectoryCapacity: 10000,\n qualityThreshold: this.config.qualityThreshold ?? 0.5, // Ensure defined\n enableSimd: true,\n // Only spread defined values from sonaConfig\n ...(this.config.sonaConfig && Object.fromEntries(\n Object.entries(this.config.sonaConfig).filter(([, v]) => v !== undefined)\n )),\n };\n\n this.sona = SonaEngine.withConfig(sonaConfig);\n } catch (err) {\n console.warn('[RuVectorIntelligence] SONA init failed, using fallback:', err);\n this.sona = null;\n }\n }\n\n // Initialize attention mechanisms based on type\n try {\n switch (this.config.attentionType) {\n case 'multi_head':\n this.multiHeadAttention = new MultiHeadAttention(dim, this.config.numHeads ?? 8);\n break;\n\n case 'flash':\n this.flashAttention = new FlashAttention(dim);\n break;\n\n case 'hyperbolic':\n this.hyperbolicAttention = new HyperbolicAttention(dim, this.config.curvature ?? 1.0);\n break;\n\n case 'moe':\n const moeConfig: MoEConfig = {\n dim,\n numExperts: this.config.numExperts ?? 4,\n topK: this.config.topK ?? 2,\n };\n this.moeAttention = new MoEAttention(moeConfig);\n break;\n\n case 'graph':\n this.graphAttention = new GraphRoPeAttention(dim, 10000);\n break;\n\n case 'dual':\n this.dualSpaceAttention = new DualSpaceAttention(\n dim,\n this.config.curvature ?? 1.0,\n 0.5, // Euclidean weight\n 0.5 // Hyperbolic weight\n );\n break;\n }\n } catch (err) {\n console.warn('[RuVectorIntelligence] Attention init failed, using fallback:', err);\n }\n\n // Initialize training components (simplified - only optimizer needed)\n try {\n // AdamOptimizer requires: learning_rate, beta1, beta2, epsilon\n this.optimizer = new AdamOptimizer(0.001, 0.9, 0.999, 1e-8);\n } catch (err) {\n console.warn('[RuVectorIntelligence] Optimizer init failed:', err);\n }\n\n // Initialize HNSW index\n if (this.config.enableHnsw) {\n try {\n this.initializeHnsw();\n } catch (err) {\n console.warn('[RuVectorIntelligence] HNSW init failed:', err);\n }\n }\n\n // Start background learning\n if (this.config.enableSona) {\n this.startBackgroundLearning();\n }\n\n // Start cleanup timer for stale trajectories\n this.startCleanupTimer();\n\n this.initialized = true;\n }\n\n /**\n * Start cleanup timer for stale trajectories\n */\n private startCleanupTimer(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n\n // Run cleanup every 5 minutes\n this.cleanupTimer = setInterval(() => {\n this.cleanupStaleTrajectories();\n }, 300000);\n }\n\n /**\n * Clean up trajectories older than TTL\n */\n private cleanupStaleTrajectories(): void {\n const now = Date.now();\n const ttl = this.config.trajectoryTTLMs;\n\n for (const [id, trajectory] of this.trajectories) {\n if (now - trajectory.startTime > ttl) {\n this.trajectories.delete(id);\n this.trajectoryAccessOrder = this.trajectoryAccessOrder.filter(t => t !== id);\n this.stats.evictedTrajectories++;\n }\n }\n }\n\n /**\n * LRU eviction for trajectories when limit exceeded\n */\n private evictOldestTrajectory(): void {\n if (this.trajectoryAccessOrder.length === 0) return;\n\n const oldestId = this.trajectoryAccessOrder.shift()!;\n this.trajectories.delete(oldestId);\n this.stats.evictedTrajectories++;\n }\n\n /**\n * LRU eviction for agent embeddings when limit exceeded\n */\n private evictOldestAgent(): void {\n if (this.agentAccessOrder.length === 0) return;\n\n const oldestId = this.agentAccessOrder.shift()!;\n this.agentEmbeddings.delete(oldestId);\n this.stats.evictedAgents++;\n }\n\n /**\n * Update LRU access order for trajectory\n */\n private touchTrajectory(id: number): void {\n const idx = this.trajectoryAccessOrder.indexOf(id);\n if (idx !== -1) {\n this.trajectoryAccessOrder.splice(idx, 1);\n }\n this.trajectoryAccessOrder.push(id);\n }\n\n /**\n * Update LRU access order for agent\n */\n private touchAgent(id: string): void {\n const idx = this.agentAccessOrder.indexOf(id);\n if (idx !== -1) {\n this.agentAccessOrder.splice(idx, 1);\n }\n this.agentAccessOrder.push(id);\n }\n\n /**\n * Initialize HNSW index for fast vector search\n */\n private initializeHnsw(): void {\n try {\n // Use ruvector core HNSW\n this.hnswIndex = new ruvector.HnswIndex({\n dim: this.config.embeddingDim,\n m: this.config.hnswM,\n efConstruction: this.config.hnswEfConstruction,\n distance: 'cosine',\n });\n } catch (error) {\n console.warn('HNSW initialization failed, falling back to brute force:', error);\n this.hnswIndex = null;\n }\n }\n\n /**\n * Register an agent with its embedding\n *\n * @param agentId - Unique agent identifier\n * @param embedding - Agent's semantic embedding\n * @param metadata - Optional metadata\n * @returns Operation result indicating success/failure\n */\n async registerAgent(\n agentId: string,\n embedding: number[] | Float32Array,\n metadata?: Record<string, any>\n ): Promise<OperationResult<void>> {\n await this.waitForInit();\n\n try {\n const embeddingArray = embedding instanceof Float32Array\n ? embedding\n : new Float32Array(embedding);\n\n // LRU eviction if at capacity\n while (this.agentEmbeddings.size >= this.config.maxAgentEmbeddings) {\n this.evictOldestAgent();\n }\n\n // Store in cache and update LRU order\n this.agentEmbeddings.set(agentId, embeddingArray);\n this.touchAgent(agentId);\n\n // Add to HNSW index\n if (this.hnswIndex) {\n try {\n await this.hnswIndex.add(agentId, embeddingArray);\n } catch (error) {\n console.warn(`Failed to add agent ${agentId} to HNSW:`, error);\n }\n }\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Route a task to the best agent using full intelligence stack\n *\n * Uses:\n * - HNSW for fast candidate retrieval\n * - Attention mechanism for ranking\n * - SONA for adaptive learning\n *\n * @param taskEmbedding - Task's semantic embedding\n * @param candidates - Optional candidate agent IDs\n * @param topK - Number of results\n */\n async routeTask(\n taskEmbedding: number[] | Float32Array,\n candidates?: string[],\n topK: number = 5\n ): Promise<AgentRoutingResult[]> {\n const startTime = performance.now();\n const query = taskEmbedding instanceof Float32Array\n ? taskEmbedding\n : new Float32Array(taskEmbedding);\n\n let results: AgentRoutingResult[] = [];\n let usedHnsw = false;\n let usedSona = false;\n\n // Step 1: Get candidates via HNSW (150x faster than brute force)\n let candidateAgents: Array<{ id: string; embedding: Float32Array; score: number }> = [];\n\n if (this.hnswIndex && this.agentEmbeddings.size > 10) {\n try {\n const hnswResults = await this.hnswIndex.search(query, Math.min(topK * 2, 20));\n candidateAgents = hnswResults.map((r: any) => ({\n id: r.id,\n embedding: this.agentEmbeddings.get(r.id)!,\n score: r.score,\n }));\n usedHnsw = true;\n this.stats.hnswQueries++;\n } catch (error) {\n // Fallback to all agents\n }\n }\n\n // Fallback: use provided candidates or all agents\n if (candidateAgents.length === 0) {\n const agentIds = candidates || Array.from(this.agentEmbeddings.keys());\n candidateAgents = agentIds\n .filter(id => this.agentEmbeddings.has(id))\n .map(id => ({\n id,\n embedding: this.agentEmbeddings.get(id)!,\n score: 0,\n }));\n }\n\n if (candidateAgents.length === 0) {\n return [];\n }\n\n // Step 2: Apply SONA Micro-LoRA transformation (~0.1ms)\n let transformedQuery = query;\n if (this.sona) {\n try {\n const loraResult = this.sona.applyMicroLora(Array.from(query));\n transformedQuery = new Float32Array(loraResult);\n usedSona = true;\n this.stats.sonaAdaptations++;\n } catch (error) {\n // Use original query\n }\n }\n\n // Step 3: Compute attention scores\n const keys = candidateAgents.map(c => c.embedding);\n const values = candidateAgents.map(c => c.embedding);\n\n let attentionOutput: Float32Array;\n let expertWeights: number[] | undefined;\n\n switch (this.config.attentionType) {\n case 'moe':\n if (this.moeAttention) {\n attentionOutput = this.moeAttention.compute(transformedQuery, keys, values);\n // MoE provides expert routing weights\n expertWeights = Array.from(attentionOutput.slice(0, this.config.numExperts));\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n case 'flash':\n if (this.flashAttention) {\n attentionOutput = this.flashAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n case 'hyperbolic':\n if (this.hyperbolicAttention) {\n attentionOutput = this.hyperbolicAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n case 'dual':\n if (this.dualSpaceAttention) {\n attentionOutput = this.dualSpaceAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n default:\n if (this.multiHeadAttention) {\n attentionOutput = this.multiHeadAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n }\n\n // Step 4: Compute similarity scores for ranking\n const scores = candidateAgents.map((agent, i) => {\n // Combine HNSW score with attention-weighted score\n const attentionScore = this.cosineSimilarity(\n attentionOutput,\n agent.embedding\n );\n const hnswScore = agent.score || 0;\n\n // Weighted combination\n const finalScore = usedHnsw\n ? 0.3 * hnswScore + 0.7 * attentionScore\n : attentionScore;\n\n return {\n agentId: agent.id,\n confidence: finalScore,\n attentionWeights: attentionOutput,\n expertWeights,\n latencyMs: 0,\n usedHnsw,\n usedSona,\n };\n });\n\n // Sort by confidence\n results = scores\n .sort((a, b) => b.confidence - a.confidence)\n .slice(0, topK);\n\n // Update latency\n const latencyMs = performance.now() - startTime;\n results.forEach(r => (r.latencyMs = latencyMs));\n\n // Update stats\n this.stats.totalRoutings++;\n this.stats.avgRoutingLatencyMs =\n (this.stats.avgRoutingLatencyMs * (this.stats.totalRoutings - 1) + latencyMs) /\n this.stats.totalRoutings;\n\n return results;\n }\n\n /**\n * Fallback attention using dot product\n */\n private computeFallbackAttention(\n query: Float32Array,\n keys: Float32Array[],\n values: Float32Array[]\n ): Float32Array {\n const dim = query.length;\n const result = new Float32Array(dim);\n let totalWeight = 0;\n\n for (let i = 0; i < keys.length; i++) {\n const similarity = this.cosineSimilarity(query, keys[i]);\n const weight = Math.exp(similarity * 10); // Temperature scaling\n totalWeight += weight;\n\n for (let j = 0; j < dim; j++) {\n result[j] += weight * values[i][j];\n }\n }\n\n // Normalize\n if (totalWeight > 0) {\n for (let j = 0; j < dim; j++) {\n result[j] /= totalWeight;\n }\n }\n\n return result;\n }\n\n /**\n * Cosine similarity between two vectors\n */\n private cosineSimilarity(a: Float32Array, b: Float32Array): number {\n let dot = 0;\n let normA = 0;\n let normB = 0;\n\n for (let i = 0; i < a.length; i++) {\n dot += a[i] * b[i];\n normA += a[i] * a[i];\n normB += b[i] * b[i];\n }\n\n const norm = Math.sqrt(normA) * Math.sqrt(normB);\n return norm > 0 ? dot / norm : 0;\n }\n\n // ==========================================================================\n // Trajectory Learning (SONA)\n // ==========================================================================\n\n /**\n * Begin a new trajectory for learning\n *\n * @param query - The task query\n * @param embedding - Query embedding\n * @returns Operation result with trajectory ID\n */\n beginTrajectory(query: string, embedding: number[]): OperationResult<number> {\n if (!this.config.enableTrajectories) {\n return {\n success: false,\n error: 'Trajectories are disabled in config',\n };\n }\n\n if (!this.sona) {\n return {\n success: false,\n error: 'SONA engine not initialized',\n };\n }\n\n try {\n // LRU eviction if at capacity\n while (this.trajectories.size >= this.config.maxTrajectories) {\n this.evictOldestTrajectory();\n }\n\n const trajectoryId = this.nextTrajectoryId++;\n\n // Start SONA trajectory\n const sonaId = this.sona.beginTrajectory(embedding);\n\n // Store local trajectory\n this.trajectories.set(trajectoryId, {\n id: sonaId,\n query,\n embedding,\n steps: [],\n contexts: [],\n startTime: Date.now(),\n });\n\n // Update LRU order\n this.touchTrajectory(trajectoryId);\n\n this.stats.totalTrajectories++;\n return { success: true, value: trajectoryId };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Add a step to trajectory\n *\n * @param trajectoryId - Trajectory ID from beginTrajectory\n * @param action - Action taken (e.g., agent selected)\n * @param reward - Reward for this step (0-1)\n * @param activations - Optional activations\n * @param attentionWeights - Optional attention weights\n */\n addTrajectoryStep(\n trajectoryId: number,\n action: string,\n reward: number,\n activations?: number[],\n attentionWeights?: number[]\n ): void {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return;\n }\n\n const step: TrajectoryStep = {\n action,\n activations: activations || new Array(this.config.hiddenDim).fill(0),\n attentionWeights: attentionWeights || new Array(this.config.numHeads).fill(0),\n reward,\n timestamp: Date.now(),\n };\n\n trajectory.steps.push(step);\n\n // Add to SONA\n this.sona.addTrajectoryStep(\n trajectory.id,\n step.activations,\n step.attentionWeights,\n reward\n );\n }\n\n /**\n * Set the route (agent selected) for trajectory\n */\n setTrajectoryRoute(trajectoryId: number, route: string): void {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return;\n }\n\n trajectory.route = route;\n this.sona.setTrajectoryRoute(trajectory.id, route);\n }\n\n /**\n * Add context to trajectory\n */\n addTrajectoryContext(trajectoryId: number, contextId: string): void {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return;\n }\n\n trajectory.contexts.push(contextId);\n this.sona.addTrajectoryContext(trajectory.id, contextId);\n }\n\n /**\n * End trajectory and submit for learning\n *\n * @param trajectoryId - Trajectory ID\n * @param success - Whether the task succeeded\n * @param quality - Quality score (0-1)\n * @returns Learning outcome\n */\n endTrajectory(\n trajectoryId: number,\n success: boolean,\n quality: number\n ): LearningOutcome {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return {\n trajectoryId,\n success,\n quality,\n patternsLearned: 0,\n adaptations: { microLora: false, baseLora: false, ewc: false },\n };\n }\n\n // End SONA trajectory\n this.sona.endTrajectory(trajectory.id, quality);\n\n // Cleanup\n this.trajectories.delete(trajectoryId);\n\n return {\n trajectoryId,\n success,\n quality,\n patternsLearned: quality >= this.config.qualityThreshold ? 1 : 0,\n adaptations: {\n microLora: true, // Micro-LoRA always adapts\n baseLora: quality >= 0.7, // Base-LoRA for high quality\n ewc: quality >= 0.8, // EWC++ for very high quality\n },\n };\n }\n\n // ==========================================================================\n // Pattern Retrieval (ReasoningBank)\n // ==========================================================================\n\n /**\n * Find similar learned patterns\n *\n * Uses SONA's ReasoningBank for pattern retrieval\n *\n * @param embedding - Query embedding\n * @param k - Number of patterns to return\n */\n findPatterns(embedding: number[], k: number = 5): JsLearnedPattern[] {\n if (!this.sona) {\n return [];\n }\n\n return this.sona.findPatterns(embedding, k);\n }\n\n /**\n * Force a learning cycle\n */\n forceLearning(): string {\n if (!this.sona) {\n return 'SONA not enabled';\n }\n\n const result = this.sona.forceLearn();\n this.stats.totalLearningCycles++;\n return result;\n }\n\n // ==========================================================================\n // Background Learning\n // ==========================================================================\n\n /**\n * Start background learning timer\n */\n private startBackgroundLearning(): void {\n if (this.learningTimer) {\n clearInterval(this.learningTimer);\n }\n\n this.learningTimer = setInterval(() => {\n if (this.sona) {\n const result = this.sona.tick();\n if (result) {\n this.stats.totalLearningCycles++;\n this.stats.patternsLearned = this.getPatternsCount();\n }\n }\n }, this.config.backgroundIntervalMs);\n }\n\n /**\n * Get patterns count from SONA stats\n */\n private getPatternsCount(): number {\n if (!this.sona) return 0;\n\n try {\n const stats = JSON.parse(this.sona.getStats());\n return stats.patterns_count || 0;\n } catch {\n return 0;\n }\n }\n\n // ==========================================================================\n // Async Attention (for large batches)\n // ==========================================================================\n\n /**\n * Compute attention asynchronously\n *\n * Useful for large batches or when non-blocking is required\n */\n async computeAttentionAsync(\n query: Float32Array,\n keys: Float32Array[],\n values: Float32Array[],\n type?: 'flash' | 'hyperbolic' | 'standard'\n ): Promise<Float32Array> {\n switch (type) {\n case 'flash':\n return computeFlashAttentionAsync(query, keys, values);\n\n case 'hyperbolic':\n return computeHyperbolicAttentionAsync(\n query,\n keys,\n values,\n this.config.curvature\n );\n\n default:\n return computeAttentionAsync(query, keys, values, AttentionType.MultiHead);\n }\n }\n\n // ==========================================================================\n // Hyperbolic Operations (for hierarchical structures)\n // ==========================================================================\n\n /**\n * Compute Poincaré distance between two embeddings\n *\n * Useful for hierarchical agent structures\n */\n poincareDistance(a: Float32Array, b: Float32Array): number {\n return poincareDistance(a, b, this.config.curvature);\n }\n\n /**\n * Project embedding to Poincaré ball\n */\n projectToPoincare(embedding: Float32Array): Float32Array {\n return projectToPoincareBall(embedding, this.config.curvature);\n }\n\n // ==========================================================================\n // Statistics & Status\n // ==========================================================================\n\n /**\n * Get intelligence layer statistics\n */\n getStats(): typeof this.stats & { sonaStats?: any } {\n let sonaStats: any = null;\n\n if (this.sona) {\n try {\n sonaStats = JSON.parse(this.sona.getStats());\n } catch {}\n }\n\n return {\n ...this.stats,\n sonaStats,\n };\n }\n\n /**\n * Enable/disable the intelligence layer\n */\n setEnabled(enabled: boolean): void {\n if (this.sona) {\n this.sona.setEnabled(enabled);\n }\n }\n\n /**\n * Check if enabled\n */\n isEnabled(): boolean {\n return this.sona?.isEnabled() ?? false;\n }\n\n /**\n * Cleanup resources\n */\n dispose(): void {\n if (this.learningTimer) {\n clearInterval(this.learningTimer);\n this.learningTimer = null;\n }\n\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n\n // Flush SONA\n if (this.sona) {\n this.sona.flush();\n }\n\n // Clear caches and LRU tracking\n this.trajectories.clear();\n this.trajectoryAccessOrder = [];\n this.agentEmbeddings.clear();\n this.agentAccessOrder = [];\n }\n}\n\n/**\n * Create a default intelligence layer\n */\nexport function createIntelligenceLayer(\n config?: RuVectorIntelligenceConfig\n): RuVectorIntelligence {\n return new RuVectorIntelligence(config);\n}\n\n/**\n * Presets for common configurations\n */\nexport const IntelligencePresets = {\n /** Fast routing with MoE and minimal learning */\n fast: {\n attentionType: 'moe' as const,\n numExperts: 4,\n topK: 2,\n enableTrajectories: false,\n backgroundIntervalMs: 300000, // 5 min\n },\n\n /** Balanced performance and learning */\n balanced: {\n attentionType: 'moe' as const,\n numExperts: 4,\n topK: 2,\n enableTrajectories: true,\n backgroundIntervalMs: 60000, // 1 min\n qualityThreshold: 0.5,\n },\n\n /** Maximum learning for development */\n learning: {\n attentionType: 'dual' as const,\n enableTrajectories: true,\n backgroundIntervalMs: 30000, // 30 sec\n qualityThreshold: 0.3,\n sonaConfig: {\n microLoraRank: 2,\n baseLoraRank: 16,\n trajectoryCapacity: 50000,\n },\n },\n\n /** Hierarchical structures (Poincaré geometry) */\n hierarchical: {\n attentionType: 'hyperbolic' as const,\n curvature: 1.0,\n enableTrajectories: true,\n },\n\n /** Graph-based reasoning */\n graph: {\n attentionType: 'graph' as const,\n enableTrajectories: true,\n },\n};\n"]}
|
|
1
|
+
{"version":3,"file":"RuVectorIntelligence.js","sourceRoot":"","sources":["../../src/intellig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aAAa,EAAE,KAAc;QAC7B,UAAU,EAAE,CAAC;QACb,IAAI,EAAE,CAAC;QACP,kBAAkB,EAAE,KAAK;QACzB,oBAAoB,EAAE,MAAM,EAAE,QAAQ;KACvC;IAED,wCAAwC;IACxC,QAAQ,EAAE;QACR,aAAa,EAAE,KAAc;QAC7B,UAAU,EAAE,CAAC;QACb,IAAI,EAAE,CAAC;QACP,kBAAkB,EAAE,IAAI;QACxB,oBAAoB,EAAE,KAAK,EAAE,QAAQ;QACrC,gBAAgB,EAAE,GAAG;KACtB;IAED,uCAAuC;IACvC,QAAQ,EAAE;QACR,aAAa,EAAE,MAAe;QAC9B,kBAAkB,EAAE,IAAI;QACxB,oBAAoB,EAAE,KAAK,EAAE,SAAS;QACtC,gBAAgB,EAAE,GAAG;QACrB,UAAU,EAAE;YACV,aAAa,EAAE,CAAC;YAChB,YAAY,EAAE,EAAE;YAChB,kBAAkB,EAAE,KAAK;SAC1B;KACF;IAED,kDAAkD;IAClD,YAAY,EAAE;QACZ,aAAa,EAAE,YAAqB;QACpC,SAAS,EAAE,GAAG;QACd,kBAAkB,EAAE,IAAI;KACzB;IAED,4BAA4B;IAC5B,KAAK,EAAE;QACL,aAAa,EAAE,OAAgB;QAC/B,kBAAkB,EAAE,IAAI;KACzB;CACF,CAAC","sourcesContent":["/**\n * RuVector Unified Intelligence Layer\n *\n * Integrates the FULL power of RuVector ecosystem:\n *\n * @ruvector/sona - Self-Learning:\n * - Micro-LoRA: Ultra-fast rank-1/2 adaptations (~0.1ms)\n * - Base-LoRA: Deeper pattern adaptations\n * - EWC++: Elastic Weight Consolidation (catastrophic forgetting prevention)\n * - ReasoningBank: Pattern storage/retrieval via findPatterns\n * - Trajectory tracking: Learn from execution paths\n *\n * @ruvector/attention - Advanced Attention:\n * - MultiHeadAttention: Standard transformer attention\n * - FlashAttention: Memory-efficient O(n) attention\n * - HyperbolicAttention: Poincaré ball geometry for hierarchies\n * - MoEAttention: Mixture of Experts routing\n * - GraphRoPeAttention: Graph + Rotary Position Embeddings\n * - EdgeFeaturedAttention: Edge-aware graph attention\n * - DualSpaceAttention: Euclidean + Hyperbolic hybrid\n *\n * @ruvector/core - Vector Database:\n * - HNSW indexing: 150x faster than brute force\n * - Real vector similarity search\n * - Cosine/Euclidean/Dot product distance\n *\n * Performance:\n * - Micro-LoRA adaptation: ~0.1ms\n * - FlashAttention: O(n) complexity vs O(n²)\n * - HNSW search: O(log n) vs O(n)\n * - Background learning: Non-blocking\n */\n\n// Optional imports - graceful fallback on Windows/platforms without native binaries\nlet SonaEngine: any = null;\nlet sonaAvailable = false;\n\nlet MultiHeadAttention: any = null;\nlet FlashAttention: any = null;\nlet HyperbolicAttention: any = null;\nlet MoEAttention: any = null;\nlet GraphRoPeAttention: any = null;\nlet DualSpaceAttention: any = null;\nlet AdamOptimizer: any = null;\nlet computeAttentionAsync: any = null;\nlet computeFlashAttentionAsync: any = null;\nlet computeHyperbolicAttentionAsync: any = null;\nlet poincareDistance: any = null;\nlet projectToPoincareBall: any = null;\nlet AttentionType: any = null;\nlet attentionAvailable = false;\n\n// Try to load @ruvector/sona (through the loader, whose engines validate\n// LoRA input lengths instead of letting a native panic abort the process)\ntry {\n SonaEngine = requireSonaEngine();\n sonaAvailable = true;\n} catch {\n console.warn('[RuVectorIntelligence] @ruvector/sona not available - self-learning disabled');\n}\n\n// Try to load @ruvector/attention\ntry {\n // @ruvector/attention is CommonJS; from 0.1.32 its typings expose it as\n // `default` under ESM interop, while older builds surface named exports.\n const attentionMod: any = await import('@ruvector/attention');\n const attentionModule = attentionMod.default ?? attentionMod;\n MultiHeadAttention = attentionModule.MultiHeadAttention;\n FlashAttention = attentionModule.FlashAttention;\n HyperbolicAttention = attentionModule.HyperbolicAttention;\n MoEAttention = attentionModule.MoEAttention;\n GraphRoPeAttention = attentionModule.GraphRoPeAttention;\n DualSpaceAttention = attentionModule.DualSpaceAttention;\n AdamOptimizer = attentionModule.AdamOptimizer;\n computeAttentionAsync = attentionModule.computeAttentionAsync;\n computeFlashAttentionAsync = attentionModule.computeFlashAttentionAsync;\n computeHyperbolicAttentionAsync = attentionModule.computeHyperbolicAttentionAsync;\n poincareDistance = attentionModule.poincareDistance;\n projectToPoincareBall = attentionModule.projectToPoincareBall;\n AttentionType = attentionModule.AttentionType;\n attentionAvailable = true;\n} catch {\n console.warn('[RuVectorIntelligence] @ruvector/attention not available - attention features disabled');\n}\n\n// Import from ruvector core (for HNSW)\nimport { requireSonaEngine } from '../services/sona-loader.js';\nimport ruvector from 'ruvector';\n\n// Export availability flags\nexport { sonaAvailable, attentionAvailable };\n\n// Local type definitions (replaces imports from optional packages)\nexport interface JsSonaConfig {\n embeddingDim?: number;\n hiddenDim?: number;\n microLoraRank?: number;\n baseLoraRank?: number;\n ewcLambda?: number;\n microLoraLr?: number;\n baseLoraLr?: number;\n patternClusters?: number;\n [key: string]: any; // Allow additional properties\n}\n\nexport interface JsLearnedPattern {\n id: string;\n pattern: number[];\n confidence: number;\n timestamp: number;\n}\n\nexport interface MoEConfig {\n numExperts?: number;\n topK?: number;\n routerDim?: number;\n dim?: number;\n}\n\n/**\n * Intelligence Layer Configuration\n */\nexport interface RuVectorIntelligenceConfig {\n /** Embedding dimension (default: 384 for all-MiniLM-L6-v2) */\n embeddingDim?: number;\n\n /** Hidden dimension for SONA (default: 256) */\n hiddenDim?: number;\n\n /** Enable SONA self-learning (default: true) */\n enableSona?: boolean;\n\n /** SONA configuration */\n sonaConfig?: Partial<JsSonaConfig>;\n\n /** Attention type for agent routing (default: 'moe') */\n attentionType?: 'multi_head' | 'flash' | 'hyperbolic' | 'moe' | 'graph' | 'dual';\n\n /** Number of attention heads (default: 8) */\n numHeads?: number;\n\n /** Number of MoE experts (default: 4) */\n numExperts?: number;\n\n /** Top-K experts to use (default: 2) */\n topK?: number;\n\n /** Hyperbolic curvature for hierarchical structures (default: 1.0) */\n curvature?: number;\n\n /** Enable HNSW vector index (default: true) */\n enableHnsw?: boolean;\n\n /** HNSW M parameter - connections per node (default: 16) */\n hnswM?: number;\n\n /** HNSW ef_construction (default: 200) */\n hnswEfConstruction?: number;\n\n /** Enable trajectory tracking (default: true) */\n enableTrajectories?: boolean;\n\n /** Quality threshold for learning (default: 0.5) */\n qualityThreshold?: number;\n\n /** Background learning interval in ms (default: 60000 = 1 min) */\n backgroundIntervalMs?: number;\n\n /** Maximum trajectories to keep in memory (default: 1000, LRU eviction) */\n maxTrajectories?: number;\n\n /** Trajectory TTL in ms (default: 1800000 = 30 min) */\n trajectoryTTLMs?: number;\n\n /** Maximum agent embeddings to cache (default: 500, LRU eviction) */\n maxAgentEmbeddings?: number;\n}\n\n/**\n * Trajectory for learning\n */\nexport interface Trajectory {\n id: number;\n query: string;\n embedding: number[];\n steps: TrajectoryStep[];\n route?: string;\n contexts: string[];\n startTime: number;\n}\n\nexport interface TrajectoryStep {\n action: string;\n activations: number[];\n attentionWeights: number[];\n reward: number;\n timestamp: number;\n}\n\n/**\n * Agent routing result\n */\nexport interface AgentRoutingResult {\n agentId: string;\n confidence: number;\n attentionWeights: Float32Array;\n expertWeights?: number[];\n latencyMs: number;\n usedHnsw: boolean;\n usedSona: boolean;\n}\n\n/**\n * Learning outcome\n */\nexport interface LearningOutcome {\n trajectoryId: number;\n success: boolean;\n quality: number;\n patternsLearned: number;\n adaptations: {\n microLora: boolean;\n baseLora: boolean;\n ewc: boolean;\n };\n}\n\n/**\n * RuVector Unified Intelligence Layer\n *\n * Combines SONA self-learning, advanced attention mechanisms,\n * and HNSW vector search for intelligent agent orchestration.\n */\n/**\n * Result wrapper for operations that can fail\n */\nexport interface OperationResult<T> {\n success: boolean;\n value?: T;\n error?: string;\n}\n\nexport class RuVectorIntelligence {\n private config: Required<RuVectorIntelligenceConfig>;\n private initialized = false;\n private initPromise: Promise<void> | null = null;\n\n // SONA Engine for self-learning\n private sona: any = null;\n\n // Attention mechanisms\n private multiHeadAttention: any = null;\n private flashAttention: any = null;\n private hyperbolicAttention: any = null;\n private moeAttention: any = null;\n private graphAttention: any = null;\n private dualSpaceAttention: any = null;\n\n // Training (simplified - removed unused scheduler/loss)\n private optimizer: any = null;\n\n // HNSW index for vector search\n private hnswIndex: any = null;\n\n // Active trajectories with LRU tracking\n private trajectories: Map<number, Trajectory> = new Map();\n private trajectoryAccessOrder: number[] = []; // For LRU eviction\n private nextTrajectoryId = 0;\n\n // Agent embeddings with LRU tracking\n private agentEmbeddings: Map<string, Float32Array> = new Map();\n private agentAccessOrder: string[] = []; // For LRU eviction\n\n // Background learning timer\n private learningTimer: NodeJS.Timeout | null = null;\n\n // Cleanup timer for stale trajectories\n private cleanupTimer: NodeJS.Timeout | null = null;\n\n // Statistics\n private stats = {\n totalRoutings: 0,\n totalTrajectories: 0,\n totalLearningCycles: 0,\n avgRoutingLatencyMs: 0,\n patternsLearned: 0,\n hnswQueries: 0,\n sonaAdaptations: 0,\n evictedTrajectories: 0,\n evictedAgents: 0,\n };\n\n constructor(config?: RuVectorIntelligenceConfig) {\n this.config = {\n embeddingDim: config?.embeddingDim ?? 384,\n hiddenDim: config?.hiddenDim ?? 256,\n enableSona: config?.enableSona ?? true,\n sonaConfig: config?.sonaConfig ?? {},\n attentionType: config?.attentionType ?? 'moe',\n numHeads: config?.numHeads ?? 8,\n numExperts: config?.numExperts ?? 4,\n topK: config?.topK ?? 2,\n curvature: config?.curvature ?? 1.0,\n enableHnsw: config?.enableHnsw ?? true,\n hnswM: config?.hnswM ?? 16,\n hnswEfConstruction: config?.hnswEfConstruction ?? 200,\n enableTrajectories: config?.enableTrajectories ?? true,\n qualityThreshold: config?.qualityThreshold ?? 0.5,\n backgroundIntervalMs: config?.backgroundIntervalMs ?? 60000,\n // Memory limits with LRU eviction\n maxTrajectories: config?.maxTrajectories ?? 1000,\n trajectoryTTLMs: config?.trajectoryTTLMs ?? 1800000, // 30 min\n maxAgentEmbeddings: config?.maxAgentEmbeddings ?? 500,\n };\n\n // Initialize asynchronously to avoid race conditions\n this.initPromise = this.initializeAsync();\n }\n\n /**\n * Wait for initialization to complete\n */\n async waitForInit(): Promise<void> {\n if (this.initPromise) {\n await this.initPromise;\n }\n }\n\n /**\n * Initialize all components (async to avoid race conditions)\n */\n private async initializeAsync(): Promise<void> {\n if (this.initialized) return;\n\n const dim = this.config.embeddingDim;\n\n // Initialize SONA Engine\n if (this.config.enableSona) {\n try {\n // Ensure all values are explicitly defined (no undefined values)\n const sonaConfig: JsSonaConfig = {\n hiddenDim: this.config.hiddenDim ?? 256,\n embeddingDim: dim ?? 384,\n microLoraRank: 1, // Ultra-fast rank-1\n baseLoraRank: 8,\n microLoraLr: 0.001,\n baseLoraLr: 0.0001,\n ewcLambda: 1000.0, // EWC++ regularization\n patternClusters: 50,\n trajectoryCapacity: 10000,\n qualityThreshold: this.config.qualityThreshold ?? 0.5, // Ensure defined\n enableSimd: true,\n // Only spread defined values from sonaConfig\n ...(this.config.sonaConfig && Object.fromEntries(\n Object.entries(this.config.sonaConfig).filter(([, v]) => v !== undefined)\n )),\n };\n\n this.sona = SonaEngine.withConfig(sonaConfig);\n } catch (err) {\n console.warn('[RuVectorIntelligence] SONA init failed, using fallback:', err);\n this.sona = null;\n }\n }\n\n // Initialize attention mechanisms based on type\n try {\n switch (this.config.attentionType) {\n case 'multi_head':\n this.multiHeadAttention = new MultiHeadAttention(dim, this.config.numHeads ?? 8);\n break;\n\n case 'flash':\n this.flashAttention = new FlashAttention(dim);\n break;\n\n case 'hyperbolic':\n this.hyperbolicAttention = new HyperbolicAttention(dim, this.config.curvature ?? 1.0);\n break;\n\n case 'moe':\n const moeConfig: MoEConfig = {\n dim,\n numExperts: this.config.numExperts ?? 4,\n topK: this.config.topK ?? 2,\n };\n this.moeAttention = new MoEAttention(moeConfig);\n break;\n\n case 'graph':\n this.graphAttention = new GraphRoPeAttention(dim, 10000);\n break;\n\n case 'dual':\n this.dualSpaceAttention = new DualSpaceAttention(\n dim,\n this.config.curvature ?? 1.0,\n 0.5, // Euclidean weight\n 0.5 // Hyperbolic weight\n );\n break;\n }\n } catch (err) {\n console.warn('[RuVectorIntelligence] Attention init failed, using fallback:', err);\n }\n\n // Initialize training components (simplified - only optimizer needed)\n try {\n // AdamOptimizer requires: learning_rate, beta1, beta2, epsilon\n this.optimizer = new AdamOptimizer(0.001, 0.9, 0.999, 1e-8);\n } catch (err) {\n console.warn('[RuVectorIntelligence] Optimizer init failed:', err);\n }\n\n // Initialize HNSW index\n if (this.config.enableHnsw) {\n try {\n this.initializeHnsw();\n } catch (err) {\n console.warn('[RuVectorIntelligence] HNSW init failed:', err);\n }\n }\n\n // Start background learning\n if (this.config.enableSona) {\n this.startBackgroundLearning();\n }\n\n // Start cleanup timer for stale trajectories\n this.startCleanupTimer();\n\n this.initialized = true;\n }\n\n /**\n * Start cleanup timer for stale trajectories\n */\n private startCleanupTimer(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n\n // Run cleanup every 5 minutes\n this.cleanupTimer = setInterval(() => {\n this.cleanupStaleTrajectories();\n }, 300000);\n }\n\n /**\n * Clean up trajectories older than TTL\n */\n private cleanupStaleTrajectories(): void {\n const now = Date.now();\n const ttl = this.config.trajectoryTTLMs;\n\n for (const [id, trajectory] of this.trajectories) {\n if (now - trajectory.startTime > ttl) {\n this.trajectories.delete(id);\n this.trajectoryAccessOrder = this.trajectoryAccessOrder.filter(t => t !== id);\n this.stats.evictedTrajectories++;\n }\n }\n }\n\n /**\n * LRU eviction for trajectories when limit exceeded\n */\n private evictOldestTrajectory(): void {\n if (this.trajectoryAccessOrder.length === 0) return;\n\n const oldestId = this.trajectoryAccessOrder.shift()!;\n this.trajectories.delete(oldestId);\n this.stats.evictedTrajectories++;\n }\n\n /**\n * LRU eviction for agent embeddings when limit exceeded\n */\n private evictOldestAgent(): void {\n if (this.agentAccessOrder.length === 0) return;\n\n const oldestId = this.agentAccessOrder.shift()!;\n this.agentEmbeddings.delete(oldestId);\n this.stats.evictedAgents++;\n }\n\n /**\n * Update LRU access order for trajectory\n */\n private touchTrajectory(id: number): void {\n const idx = this.trajectoryAccessOrder.indexOf(id);\n if (idx !== -1) {\n this.trajectoryAccessOrder.splice(idx, 1);\n }\n this.trajectoryAccessOrder.push(id);\n }\n\n /**\n * Update LRU access order for agent\n */\n private touchAgent(id: string): void {\n const idx = this.agentAccessOrder.indexOf(id);\n if (idx !== -1) {\n this.agentAccessOrder.splice(idx, 1);\n }\n this.agentAccessOrder.push(id);\n }\n\n /**\n * Initialize HNSW index for fast vector search\n */\n private initializeHnsw(): void {\n try {\n // Use ruvector core HNSW\n this.hnswIndex = new ruvector.HnswIndex({\n dim: this.config.embeddingDim,\n m: this.config.hnswM,\n efConstruction: this.config.hnswEfConstruction,\n distance: 'cosine',\n });\n } catch (error) {\n console.warn('HNSW initialization failed, falling back to brute force:', error);\n this.hnswIndex = null;\n }\n }\n\n /**\n * Register an agent with its embedding\n *\n * @param agentId - Unique agent identifier\n * @param embedding - Agent's semantic embedding\n * @param metadata - Optional metadata\n * @returns Operation result indicating success/failure\n */\n async registerAgent(\n agentId: string,\n embedding: number[] | Float32Array,\n metadata?: Record<string, any>\n ): Promise<OperationResult<void>> {\n await this.waitForInit();\n\n try {\n const embeddingArray = embedding instanceof Float32Array\n ? embedding\n : new Float32Array(embedding);\n\n // LRU eviction if at capacity\n while (this.agentEmbeddings.size >= this.config.maxAgentEmbeddings) {\n this.evictOldestAgent();\n }\n\n // Store in cache and update LRU order\n this.agentEmbeddings.set(agentId, embeddingArray);\n this.touchAgent(agentId);\n\n // Add to HNSW index\n if (this.hnswIndex) {\n try {\n await this.hnswIndex.add(agentId, embeddingArray);\n } catch (error) {\n console.warn(`Failed to add agent ${agentId} to HNSW:`, error);\n }\n }\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Route a task to the best agent using full intelligence stack\n *\n * Uses:\n * - HNSW for fast candidate retrieval\n * - Attention mechanism for ranking\n * - SONA for adaptive learning\n *\n * @param taskEmbedding - Task's semantic embedding\n * @param candidates - Optional candidate agent IDs\n * @param topK - Number of results\n */\n async routeTask(\n taskEmbedding: number[] | Float32Array,\n candidates?: string[],\n topK: number = 5\n ): Promise<AgentRoutingResult[]> {\n const startTime = performance.now();\n const query = taskEmbedding instanceof Float32Array\n ? taskEmbedding\n : new Float32Array(taskEmbedding);\n\n let results: AgentRoutingResult[] = [];\n let usedHnsw = false;\n let usedSona = false;\n\n // Step 1: Get candidates via HNSW (150x faster than brute force)\n let candidateAgents: Array<{ id: string; embedding: Float32Array; score: number }> = [];\n\n if (this.hnswIndex && this.agentEmbeddings.size > 10) {\n try {\n const hnswResults = await this.hnswIndex.search(query, Math.min(topK * 2, 20));\n candidateAgents = hnswResults.map((r: any) => ({\n id: r.id,\n embedding: this.agentEmbeddings.get(r.id)!,\n score: r.score,\n }));\n usedHnsw = true;\n this.stats.hnswQueries++;\n } catch (error) {\n // Fallback to all agents\n }\n }\n\n // Fallback: use provided candidates or all agents\n if (candidateAgents.length === 0) {\n const agentIds = candidates || Array.from(this.agentEmbeddings.keys());\n candidateAgents = agentIds\n .filter(id => this.agentEmbeddings.has(id))\n .map(id => ({\n id,\n embedding: this.agentEmbeddings.get(id)!,\n score: 0,\n }));\n }\n\n if (candidateAgents.length === 0) {\n return [];\n }\n\n // Step 2: Apply SONA Micro-LoRA transformation (~0.1ms)\n let transformedQuery = query;\n if (this.sona) {\n try {\n const loraResult = this.sona.applyMicroLora(Array.from(query));\n transformedQuery = new Float32Array(loraResult);\n usedSona = true;\n this.stats.sonaAdaptations++;\n } catch (error) {\n // Use original query\n }\n }\n\n // Step 3: Compute attention scores\n const keys = candidateAgents.map(c => c.embedding);\n const values = candidateAgents.map(c => c.embedding);\n\n let attentionOutput: Float32Array;\n let expertWeights: number[] | undefined;\n\n switch (this.config.attentionType) {\n case 'moe':\n if (this.moeAttention) {\n attentionOutput = this.moeAttention.compute(transformedQuery, keys, values);\n // MoE provides expert routing weights\n expertWeights = Array.from(attentionOutput.slice(0, this.config.numExperts));\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n case 'flash':\n if (this.flashAttention) {\n attentionOutput = this.flashAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n case 'hyperbolic':\n if (this.hyperbolicAttention) {\n attentionOutput = this.hyperbolicAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n case 'dual':\n if (this.dualSpaceAttention) {\n attentionOutput = this.dualSpaceAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n break;\n\n default:\n if (this.multiHeadAttention) {\n attentionOutput = this.multiHeadAttention.compute(transformedQuery, keys, values);\n } else {\n attentionOutput = this.computeFallbackAttention(transformedQuery, keys, values);\n }\n }\n\n // Step 4: Compute similarity scores for ranking\n const scores = candidateAgents.map((agent, i) => {\n // Combine HNSW score with attention-weighted score\n const attentionScore = this.cosineSimilarity(\n attentionOutput,\n agent.embedding\n );\n const hnswScore = agent.score || 0;\n\n // Weighted combination\n const finalScore = usedHnsw\n ? 0.3 * hnswScore + 0.7 * attentionScore\n : attentionScore;\n\n return {\n agentId: agent.id,\n confidence: finalScore,\n attentionWeights: attentionOutput,\n expertWeights,\n latencyMs: 0,\n usedHnsw,\n usedSona,\n };\n });\n\n // Sort by confidence\n results = scores\n .sort((a, b) => b.confidence - a.confidence)\n .slice(0, topK);\n\n // Update latency\n const latencyMs = performance.now() - startTime;\n results.forEach(r => (r.latencyMs = latencyMs));\n\n // Update stats\n this.stats.totalRoutings++;\n this.stats.avgRoutingLatencyMs =\n (this.stats.avgRoutingLatencyMs * (this.stats.totalRoutings - 1) + latencyMs) /\n this.stats.totalRoutings;\n\n return results;\n }\n\n /**\n * Fallback attention using dot product\n */\n private computeFallbackAttention(\n query: Float32Array,\n keys: Float32Array[],\n values: Float32Array[]\n ): Float32Array {\n const dim = query.length;\n const result = new Float32Array(dim);\n let totalWeight = 0;\n\n for (let i = 0; i < keys.length; i++) {\n const similarity = this.cosineSimilarity(query, keys[i]);\n const weight = Math.exp(similarity * 10); // Temperature scaling\n totalWeight += weight;\n\n for (let j = 0; j < dim; j++) {\n result[j] += weight * values[i][j];\n }\n }\n\n // Normalize\n if (totalWeight > 0) {\n for (let j = 0; j < dim; j++) {\n result[j] /= totalWeight;\n }\n }\n\n return result;\n }\n\n /**\n * Cosine similarity between two vectors\n */\n private cosineSimilarity(a: Float32Array, b: Float32Array): number {\n let dot = 0;\n let normA = 0;\n let normB = 0;\n\n for (let i = 0; i < a.length; i++) {\n dot += a[i] * b[i];\n normA += a[i] * a[i];\n normB += b[i] * b[i];\n }\n\n const norm = Math.sqrt(normA) * Math.sqrt(normB);\n return norm > 0 ? dot / norm : 0;\n }\n\n // ==========================================================================\n // Trajectory Learning (SONA)\n // ==========================================================================\n\n /**\n * Begin a new trajectory for learning\n *\n * @param query - The task query\n * @param embedding - Query embedding\n * @returns Operation result with trajectory ID\n */\n beginTrajectory(query: string, embedding: number[]): OperationResult<number> {\n if (!this.config.enableTrajectories) {\n return {\n success: false,\n error: 'Trajectories are disabled in config',\n };\n }\n\n if (!this.sona) {\n return {\n success: false,\n error: 'SONA engine not initialized',\n };\n }\n\n try {\n // LRU eviction if at capacity\n while (this.trajectories.size >= this.config.maxTrajectories) {\n this.evictOldestTrajectory();\n }\n\n const trajectoryId = this.nextTrajectoryId++;\n\n // Start SONA trajectory\n const sonaId = this.sona.beginTrajectory(embedding);\n\n // Store local trajectory\n this.trajectories.set(trajectoryId, {\n id: sonaId,\n query,\n embedding,\n steps: [],\n contexts: [],\n startTime: Date.now(),\n });\n\n // Update LRU order\n this.touchTrajectory(trajectoryId);\n\n this.stats.totalTrajectories++;\n return { success: true, value: trajectoryId };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Add a step to trajectory\n *\n * @param trajectoryId - Trajectory ID from beginTrajectory\n * @param action - Action taken (e.g., agent selected)\n * @param reward - Reward for this step (0-1)\n * @param activations - Optional activations\n * @param attentionWeights - Optional attention weights\n */\n addTrajectoryStep(\n trajectoryId: number,\n action: string,\n reward: number,\n activations?: number[],\n attentionWeights?: number[]\n ): void {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return;\n }\n\n const step: TrajectoryStep = {\n action,\n activations: activations || new Array(this.config.hiddenDim).fill(0),\n attentionWeights: attentionWeights || new Array(this.config.numHeads).fill(0),\n reward,\n timestamp: Date.now(),\n };\n\n trajectory.steps.push(step);\n\n // Add to SONA\n this.sona.addTrajectoryStep(\n trajectory.id,\n step.activations,\n step.attentionWeights,\n reward\n );\n }\n\n /**\n * Set the route (agent selected) for trajectory\n */\n setTrajectoryRoute(trajectoryId: number, route: string): void {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return;\n }\n\n trajectory.route = route;\n this.sona.setTrajectoryRoute(trajectory.id, route);\n }\n\n /**\n * Add context to trajectory\n */\n addTrajectoryContext(trajectoryId: number, contextId: string): void {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return;\n }\n\n trajectory.contexts.push(contextId);\n this.sona.addTrajectoryContext(trajectory.id, contextId);\n }\n\n /**\n * End trajectory and submit for learning\n *\n * @param trajectoryId - Trajectory ID\n * @param success - Whether the task succeeded\n * @param quality - Quality score (0-1)\n * @returns Learning outcome\n */\n endTrajectory(\n trajectoryId: number,\n success: boolean,\n quality: number\n ): LearningOutcome {\n const trajectory = this.trajectories.get(trajectoryId);\n if (!trajectory || !this.sona) {\n return {\n trajectoryId,\n success,\n quality,\n patternsLearned: 0,\n adaptations: { microLora: false, baseLora: false, ewc: false },\n };\n }\n\n // End SONA trajectory\n this.sona.endTrajectory(trajectory.id, quality);\n\n // Cleanup\n this.trajectories.delete(trajectoryId);\n\n return {\n trajectoryId,\n success,\n quality,\n patternsLearned: quality >= this.config.qualityThreshold ? 1 : 0,\n adaptations: {\n microLora: true, // Micro-LoRA always adapts\n baseLora: quality >= 0.7, // Base-LoRA for high quality\n ewc: quality >= 0.8, // EWC++ for very high quality\n },\n };\n }\n\n // ==========================================================================\n // Pattern Retrieval (ReasoningBank)\n // ==========================================================================\n\n /**\n * Find similar learned patterns\n *\n * Uses SONA's ReasoningBank for pattern retrieval\n *\n * @param embedding - Query embedding\n * @param k - Number of patterns to return\n */\n findPatterns(embedding: number[], k: number = 5): JsLearnedPattern[] {\n if (!this.sona) {\n return [];\n }\n\n return this.sona.findPatterns(embedding, k);\n }\n\n /**\n * Force a learning cycle\n */\n forceLearning(): string {\n if (!this.sona) {\n return 'SONA not enabled';\n }\n\n const result = this.sona.forceLearn();\n this.stats.totalLearningCycles++;\n return result;\n }\n\n // ==========================================================================\n // Background Learning\n // ==========================================================================\n\n /**\n * Start background learning timer\n */\n private startBackgroundLearning(): void {\n if (this.learningTimer) {\n clearInterval(this.learningTimer);\n }\n\n this.learningTimer = setInterval(() => {\n if (this.sona) {\n const result = this.sona.tick();\n if (result) {\n this.stats.totalLearningCycles++;\n this.stats.patternsLearned = this.getPatternsCount();\n }\n }\n }, this.config.backgroundIntervalMs);\n }\n\n /**\n * Get patterns count from SONA stats\n */\n private getPatternsCount(): number {\n if (!this.sona) return 0;\n\n try {\n const stats = JSON.parse(this.sona.getStats());\n return stats.patterns_count || 0;\n } catch {\n return 0;\n }\n }\n\n // ==========================================================================\n // Async Attention (for large batches)\n // ==========================================================================\n\n /**\n * Compute attention asynchronously\n *\n * Useful for large batches or when non-blocking is required\n */\n async computeAttentionAsync(\n query: Float32Array,\n keys: Float32Array[],\n values: Float32Array[],\n type?: 'flash' | 'hyperbolic' | 'standard'\n ): Promise<Float32Array> {\n switch (type) {\n case 'flash':\n return computeFlashAttentionAsync(query, keys, values);\n\n case 'hyperbolic':\n return computeHyperbolicAttentionAsync(\n query,\n keys,\n values,\n this.config.curvature\n );\n\n default:\n return computeAttentionAsync(query, keys, values, AttentionType.MultiHead);\n }\n }\n\n // ==========================================================================\n // Hyperbolic Operations (for hierarchical structures)\n // ==========================================================================\n\n /**\n * Compute Poincaré distance between two embeddings\n *\n * Useful for hierarchical agent structures\n */\n poincareDistance(a: Float32Array, b: Float32Array): number {\n return poincareDistance(a, b, this.config.curvature);\n }\n\n /**\n * Project embedding to Poincaré ball\n */\n projectToPoincare(embedding: Float32Array): Float32Array {\n return projectToPoincareBall(embedding, this.config.curvature);\n }\n\n // ==========================================================================\n // Statistics & Status\n // ==========================================================================\n\n /**\n * Get intelligence layer statistics\n */\n getStats(): typeof this.stats & { sonaStats?: any } {\n let sonaStats: any = null;\n\n if (this.sona) {\n try {\n sonaStats = JSON.parse(this.sona.getStats());\n } catch {}\n }\n\n return {\n ...this.stats,\n sonaStats,\n };\n }\n\n /**\n * Enable/disable the intelligence layer\n */\n setEnabled(enabled: boolean): void {\n if (this.sona) {\n this.sona.setEnabled(enabled);\n }\n }\n\n /**\n * Check if enabled\n */\n isEnabled(): boolean {\n return this.sona?.isEnabled() ?? false;\n }\n\n /**\n * Cleanup resources\n */\n dispose(): void {\n if (this.learningTimer) {\n clearInterval(this.learningTimer);\n this.learningTimer = null;\n }\n\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n\n // Flush SONA\n if (this.sona) {\n this.sona.flush();\n }\n\n // Clear caches and LRU tracking\n this.trajectories.clear();\n this.trajectoryAccessOrder = [];\n this.agentEmbeddings.clear();\n this.agentAccessOrder = [];\n }\n}\n\n/**\n * Create a default intelligence layer\n */\nexport function createIntelligenceLayer(\n config?: RuVectorIntelligenceConfig\n): RuVectorIntelligence {\n return new RuVectorIntelligence(config);\n}\n\n/**\n * Presets for common configurations\n */\nexport const IntelligencePresets = {\n /** Fast routing with MoE and minimal learning */\n fast: {\n attentionType: 'moe' as const,\n numExperts: 4,\n topK: 2,\n enableTrajectories: false,\n backgroundIntervalMs: 300000, // 5 min\n },\n\n /** Balanced performance and learning */\n balanced: {\n attentionType: 'moe' as const,\n numExperts: 4,\n topK: 2,\n enableTrajectories: true,\n backgroundIntervalMs: 60000, // 1 min\n qualityThreshold: 0.5,\n },\n\n /** Maximum learning for development */\n learning: {\n attentionType: 'dual' as const,\n enableTrajectories: true,\n backgroundIntervalMs: 30000, // 30 sec\n qualityThreshold: 0.3,\n sonaConfig: {\n microLoraRank: 2,\n baseLoraRank: 16,\n trajectoryCapacity: 50000,\n },\n },\n\n /** Hierarchical structures (Poincaré geometry) */\n hierarchical: {\n attentionType: 'hyperbolic' as const,\n curvature: 1.0,\n enableTrajectories: true,\n },\n\n /** Graph-based reasoning */\n graph: {\n attentionType: 'graph' as const,\n enableTrajectories: true,\n },\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-policy.d.ts","sourceRoot":"","sources":["../../src/mcp/mcp-policy.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,UAAU,GAAG,UAAU,GAAG,WAAW,GAAG,UAAU,GAAG,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"mcp-policy.d.ts","sourceRoot":"","sources":["../../src/mcp/mcp-policy.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,UAAU,GAAG,UAAU,GAAG,WAAW,GAAG,UAAU,GAAG,OAAO,CAAC;AAazE,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,UAAU,CAMrE;AAED,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE;IAAE,OAAO,EAAE,UAAU,CAAC;IAAC,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAAE,GAC/D,OAAO,CAQT;AAED,wBAAgB,gBAAgB,CAAC,CAAC,SAAS;IAAE,OAAO,EAAE,CAAC,IAAI,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,KAAK,OAAO,CAAA;CAAE,EACzF,MAAM,EAAE,CAAC,EACT,OAAO,EAAE;IAAE,OAAO,EAAE,UAAU,CAAC;IAAC,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAAE,GAC/D,CAAC,CAOH"}
|
package/dist/mcp/mcp-policy.js
CHANGED
|
@@ -3,6 +3,8 @@ const READONLY = [
|
|
|
3
3
|
/^agentdb_(stats|pattern_search|pattern_stats)$/,
|
|
4
4
|
/^harness_(capabilities|manifest|verify)$/,
|
|
5
5
|
/_(stats|get_profile|list_profiles|benchmark)$/,
|
|
6
|
+
// Ecosystem tools: pure computations over their arguments, no side effects.
|
|
7
|
+
/^(ecosystem_status|swarm_partition_tasks|sublinear_solve|sublinear_pagerank|prompt_injection_scan)$/,
|
|
6
8
|
];
|
|
7
9
|
const RETRIEVAL = [...READONLY, /search$/, /context$/];
|
|
8
10
|
const LEARNING = [...RETRIEVAL, /^agentic_flow_agent$/, /^agentdb_pattern_store$/, /^sona_/];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-policy.js","sourceRoot":"","sources":["../../src/mcp/mcp-policy.ts"],"names":[],"mappings":"AAEA,MAAM,QAAQ,GAAG;IACf,0DAA0D;IAC1D,gDAAgD;IAChD,0CAA0C;IAC1C,+CAA+C;
|
|
1
|
+
{"version":3,"file":"mcp-policy.js","sourceRoot":"","sources":["../../src/mcp/mcp-policy.ts"],"names":[],"mappings":"AAEA,MAAM,QAAQ,GAAG;IACf,0DAA0D;IAC1D,gDAAgD;IAChD,0CAA0C;IAC1C,+CAA+C;IAC/C,4EAA4E;IAC5E,qGAAqG;CACtG,CAAC;AACF,MAAM,SAAS,GAAG,CAAC,GAAG,QAAQ,EAAE,SAAS,EAAE,UAAU,CAAC,CAAC;AACvD,MAAM,QAAQ,GAAG,CAAC,GAAG,SAAS,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,QAAQ,CAAC,CAAC;AAE7F,MAAM,UAAU,eAAe,CAAC,KAAyB;IACvD,MAAM,OAAO,GAAG,KAAK,IAAI,UAAU,CAAC;IACpC,IAAI,CAAC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Y = [\n /^agentic_flow_(list|list_all|agent_info|check_conflicts)/,\n /^agentdb_(stats|pattern_search|pattern_stats)$/,\n /^harness_(capabilities|manifest|verify)$/,\n /_(stats|get_profile|list_profiles|benchmark)$/,\n // Ecosystem tools: pure computations over their arguments, no side effects.\n /^(ecosystem_status|swarm_partition_tasks|sublinear_solve|sublinear_pagerank|prompt_injection_scan)$/,\n];\nconst RETRIEVAL = [...READONLY, /search$/, /context$/];\nconst LEARNING = [...RETRIEVAL, /^agentic_flow_agent$/, /^agentdb_pattern_store$/, /^sona_/];\n\nexport function parseMcpProfile(value: string | undefined): McpProfile {\n const profile = value ?? 'readonly';\n if (!['readonly', 'retrieval', 'learning', 'admin'].includes(profile)) {\n throw new Error(`invalid MCP profile: ${profile}`);\n }\n return profile as McpProfile;\n}\n\nexport function isMcpToolAllowed(\n name: string,\n options: { profile: McpProfile; allowDarwinExecution?: boolean },\n): boolean {\n if (name === 'harness_repair') {\n return options.profile === 'admin' && options.allowDarwinExecution === true;\n }\n if (options.profile === 'admin') return true;\n const rules = options.profile === 'learning' ? LEARNING :\n options.profile === 'retrieval' ? RETRIEVAL : READONLY;\n return rules.some((rule) => rule.test(name));\n}\n\nexport function installMcpPolicy<T extends { addTool: (tool: { name: string }) => unknown }>(\n server: T,\n options: { profile: McpProfile; allowDarwinExecution?: boolean },\n): T {\n const addTool = server.addTool.bind(server);\n server.addTool = ((tool: { name: string }) => {\n if (isMcpToolAllowed(tool.name, options)) return addTool(tool);\n return undefined;\n }) as T['addTool'];\n return server;\n}\n"]}
|