Repository navigation
Description
Summary
Automatically assign facts to topic clusters during import/extraction and compute cohesion scores for each cluster. The graph explorer should display color-coded communities with a cluster sidebar, replacing the current ad-hoc subject grouping with meaningful, pre-computed topic neighborhoods.
Parent epic: #204
Background
Cortex's current /api/cluster endpoint groups facts by subject frequency — it picks the N most common subjects and returns their facts. This is a proximity heuristic, not real clustering. Facts about "ORB strategy" and "options scanner" end up in separate groups even though they're semantically the same topic cluster (trading).
GitNexus pre-computes functional communities at index time using code structure. For a knowledge graph, we can do the same using co-occurrence patterns and semantic similarity between subjects.
Implementation Plan
1. Cluster detection at import time (internal/extract/cluster.go)
Algorithm: Connected Components + Merge by Co-occurrence
1. Build subject co-occurrence graph:
- For each memory, collect all extracted fact subjects
- Create edge between subjects that appear in the same memory
- Edge weight = number of memories they co-occur in
2. Find connected components (subjects linked by co-occurrence chains)
3. Merge small components:
- Components with <3 subjects get merged into nearest neighbor
- Nearest = highest edge weight to any existing cluster
4. Name each cluster:
- Primary name = most frequent subject in the cluster
- Aliases = other high-frequency subjects
5. Score cohesion:
- cohesion = (actual internal edges) / (possible internal edges)
- Range: 0.0 (no internal connections) to 1.0 (fully connected)
- Also compute: avg confidence of facts in cluster, total fact count
Trigger: Runs after extract.ExtractFacts() during any import operation. Also available as standalone: cortex cluster --rebuild.
2. Storage schema
Add two tables:
CREATE TABLE IF NOT EXISTS clusters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
aliases TEXT DEFAULT , -- JSON array of alternative names
cohesion REAL DEFAULT 0.0, -- 0.0–1.0
fact_count INTEGER DEFAULT 0,
avg_confidence REAL DEFAULT 0.0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS fact_clusters (
fact_id INTEGER NOT NULL,
cluster_id INTEGER NOT NULL,
relevance REAL DEFAULT 1.0, -- how strongly this fact belongs (0.0–1.0)
PRIMARY KEY (fact_id, cluster_id),
FOREIGN KEY (fact_id) REFERENCES facts(id) ON DELETE CASCADE,
FOREIGN KEY (cluster_id) REFERENCES clusters(id) ON DELETE CASCADE
);
CREATE INDEX idx_fact_clusters_cluster ON fact_clusters(cluster_id);Migration: Add schema migration in internal/store/migrations.go. Existing DBs get the tables on first run.
3. Cluster API endpoints
GET /api/clusters
Returns all clusters with stats:
{
"clusters": [
{
"id": 1,
"name": "trading",
"aliases": ["orb", "options", "alpaca", "public.com"],
"cohesion": 0.78,
"fact_count": 156,
"avg_confidence": 0.82,
"color": "#a855f7",
"top_subjects": ["trading", "orb strategy", "options scanner", "alpaca", "public.com"]
},
{
"id": 2,
"name": "spear",
"aliases": ["hha", "paypal", "rustdesk"],
"cohesion": 0.65,
"fact_count": 89,
"avg_confidence": 0.76,
"color": "#3b82f6",
"top_subjects": ["spear", "hha exchange", "paypal", "rustdesk fleet"]
}
],
"unclustered_count": 42,
"total_facts": 28000
}GET /api/clusters/:id
Returns full cluster detail with all member facts.
4. Graph UI — Cluster mode
Cluster sidebar panel:
- List all clusters with name, cohesion badge (0.78 = green, 0.45 = yellow), fact count
- Click a cluster → graph zooms to show only that cluster's facts
- Cluster color legend in stats bar
Graph canvas changes:
- Nodes colored by cluster membership (consistent palette across sessions)
- Unclustered nodes rendered in gray
- Optional: force-layout group gravity — nodes in same cluster attract each other
- Cohesion score displayed as a label on the cluster centroid
Cluster explorer mode (new view):
- Overview: all clusters as large circles, sized by fact count, colored by cohesion
- Click to drill into a cluster's internal graph
- Shows inter-cluster edges (subjects that bridge two clusters)
5. CLI command
cortex cluster # List all clusters with stats
cortex cluster --rebuild # Force rebuild all clusters
cortex cluster --name "trading" # Show details for one cluster
cortex cluster --export json # Export cluster data6. Integration with import pipeline
In internal/extract/extractor.go, after ExtractFacts():
// After extraction, update cluster assignments for new facts
if len(newFacts) > 0 {
cluster.UpdateClusters(ctx, store, newFacts)
}UpdateClusters should be incremental — assign new facts to existing clusters when possible, only trigger full rebuild when cluster structure might have changed significantly (>10% new subjects).
Testing
| Test | Description |
|---|---|
TestClusterDetection |
Facts about related subjects form a single cluster |
TestClusterCohesionScore |
Fully connected subjects score ~1.0, sparse score <0.5 |
TestClusterNaming |
Cluster named after most frequent subject |
TestClusterMergeSmall |
Clusters with <3 subjects merge into nearest |
TestClusterIncremental |
New facts assigned to existing clusters correctly |
TestClusterRebuild |
Full rebuild produces same clusters as incremental |
TestClusterAPI |
/api/clusters returns valid response |
TestClusterAPIDetail |
/api/clusters/:id returns member facts |
TestClusterMigration |
New tables created on existing DB without data loss |
Acceptance Criteria
-
cortex clusterlists detected topic communities with cohesion scores - Facts auto-assigned to clusters during import
- Graph explorer shows color-coded clusters
- Cluster sidebar with drill-down works
-
/api/clustersand/api/clusters/:idreturn valid data - Schema migration runs cleanly on existing DBs
-
cortex cluster --rebuildcan regenerate from scratch - 9+ new tests passing
- Existing import pipeline unaffected in performance (<5% overhead)
Files to Create/Modify
| File | Change |
|---|---|
internal/extract/cluster.go |
New — cluster detection, cohesion scoring, naming |
internal/extract/cluster_test.go |
New — tests |
internal/store/migrations.go |
Add clusters and fact_clusters tables |
internal/store/cluster_store.go |
New — CRUD for cluster tables |
internal/graph/server.go |
Register /api/clusters and /api/clusters/:id |
internal/graph/visualizer.html |
Cluster mode UI, color palette, cluster sidebar |
internal/extract/extractor.go |
Wire UpdateClusters() after fact extraction |
cmd/cluster.go |
New — cortex cluster CLI command |
cmd/root.go |
Register cluster subcommand |
Estimated Effort
Large — new schema, new algorithm, new API endpoints, new UI mode. Core clustering algorithm is the critical path; everything else is plumbing.
Activity
feat(graph): topic clustering with cohesion scores (#207)