The optimization objective
K-means alternates between two operations: assign each point to its nearest centroid, then replace each centroid with the mean of its assigned points. Each operation cannot increase the within-cluster sum of squared Euclidean distances, so the process converges to a local solution.
inertia = sum ||memory - assigned centroid||^2
embednormalizeclusterroutererank
Why normalize?
Embedding magnitude may reflect factors other than semantic direction. L2 normalization places vectors on a unit sphere, making Euclidean distance closely related to cosine similarity.
Choose K
Too few clusters merge distinct contexts. Too many fragment one topic into brittle micro-groups. Evaluate retrieval quality, stability, and operational cost rather than trusting one elbow plot.
Handle outliers
K-means must assign every point. A distant or corrupted memory can pull a centroid away from its useful neighborhood. Robust preprocessing or density methods can isolate noise.
Do not stop at routing
A centroid is a coarse index. After routing, compare the query with individual memories, apply recency and permission filters, then rerank the survivors.