|
1 | 1 | import { Router } from 'express'; |
2 | 2 | import { |
3 | 3 | isEntityStoreAvailable, listEntities, findEntity, getEntityMemories, getEntityStats, |
| 4 | + _getStoreInstance, |
4 | 5 | } from '../services/stores/interface.js'; |
| 6 | +import { reclassifyEntity } from '../services/entities.js'; |
| 7 | +import { batchUpdateEntityType } from '../services/qdrant.js'; |
| 8 | +import { findMisclassifiedEntities } from '../services/entity-type-heuristics.js'; |
5 | 9 |
|
6 | 10 | export const entitiesRouter = Router(); |
7 | 11 |
|
@@ -41,6 +45,143 @@ entitiesRouter.get('/stats', async (req, res) => { |
41 | 45 | } |
42 | 46 | }); |
43 | 47 |
|
| 48 | +// GET /entities/reclassify/suggestions — Auto-suggest misclassified entities |
| 49 | +entitiesRouter.get('/reclassify/suggestions', async (req, res) => { |
| 50 | + try { |
| 51 | + if (!isEntityStoreAvailable()) { |
| 52 | + return res.status(400).json({ error: 'Entity queries require sqlite or postgres backend.' }); |
| 53 | + } |
| 54 | + |
| 55 | + // Fetch all entities (high limit to scan them all) |
| 56 | + const result = await listEntities({ limit: 5000 }); |
| 57 | + const suggestions = findMisclassifiedEntities(result.results); |
| 58 | + |
| 59 | + res.json({ |
| 60 | + count: suggestions.length, |
| 61 | + suggestions, |
| 62 | + }); |
| 63 | + } catch (err) { |
| 64 | + console.error('[entities:reclassify:suggestions]', err.message); |
| 65 | + res.status(500).json({ error: 'Internal server error' }); |
| 66 | + } |
| 67 | +}); |
| 68 | + |
| 69 | +// POST /entities/reclassify — Reclassify entity types |
| 70 | +entitiesRouter.post('/reclassify', async (req, res) => { |
| 71 | + try { |
| 72 | + if (!isEntityStoreAvailable()) { |
| 73 | + return res.status(400).json({ error: 'Entity queries require sqlite or postgres backend.' }); |
| 74 | + } |
| 75 | + |
| 76 | + const { reclassifications, dry_run } = req.body; |
| 77 | + const isDryRun = dry_run !== false; // default true |
| 78 | + |
| 79 | + if (!Array.isArray(reclassifications) || reclassifications.length === 0) { |
| 80 | + return res.status(400).json({ error: 'reclassifications array is required and must not be empty' }); |
| 81 | + } |
| 82 | + |
| 83 | + const VALID_TYPES = ['client', 'person', 'system', 'service', 'domain', 'technology', 'workflow', 'agent']; |
| 84 | + |
| 85 | + // Validate all entries |
| 86 | + for (const entry of reclassifications) { |
| 87 | + if (!entry.name || typeof entry.name !== 'string') { |
| 88 | + return res.status(400).json({ error: `Each reclassification must have a "name" string` }); |
| 89 | + } |
| 90 | + if (!entry.new_type || !VALID_TYPES.includes(entry.new_type)) { |
| 91 | + return res.status(400).json({ error: `Invalid new_type "${entry.new_type}" for "${entry.name}". Valid types: ${VALID_TYPES.join(', ')}` }); |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + const results = []; |
| 96 | + |
| 97 | + for (const entry of reclassifications) { |
| 98 | + const entity = await findEntity(entry.name); |
| 99 | + if (!entity) { |
| 100 | + results.push({ |
| 101 | + name: entry.name, |
| 102 | + old_type: entry.current_type || 'unknown', |
| 103 | + new_type: entry.new_type, |
| 104 | + memories_affected: 0, |
| 105 | + error: 'Entity not found', |
| 106 | + }); |
| 107 | + continue; |
| 108 | + } |
| 109 | + |
| 110 | + const oldType = entity.entity_type; |
| 111 | + |
| 112 | + if (isDryRun) { |
| 113 | + // Count linked memories for preview |
| 114 | + const store = _getStoreInstance(); |
| 115 | + const linkCount = store?.db |
| 116 | + ? store.db.prepare('SELECT COUNT(*) as count FROM entity_memory_links WHERE entity_id = @id').get({ id: entity.id }) |
| 117 | + : { count: 0 }; |
| 118 | + |
| 119 | + results.push({ |
| 120 | + name: entity.canonical_name, |
| 121 | + old_type: oldType, |
| 122 | + new_type: entry.new_type, |
| 123 | + memories_affected: linkCount?.count || 0, |
| 124 | + }); |
| 125 | + } else { |
| 126 | + // 1. Update structured store |
| 127 | + const storeResult = await reclassifyEntity(entry.name, entry.new_type, { |
| 128 | + findEntity, |
| 129 | + _getStoreInstance, |
| 130 | + }); |
| 131 | + |
| 132 | + // 2. Update Qdrant payloads in chunks |
| 133 | + let qdrantResult = { total_updated: 0, total_scanned: 0 }; |
| 134 | + try { |
| 135 | + qdrantResult = await batchUpdateEntityType(entity.canonical_name, oldType, entry.new_type); |
| 136 | + } catch (err) { |
| 137 | + console.error(`[entities:reclassify] Qdrant update failed for "${entry.name}":`, err.message); |
| 138 | + } |
| 139 | + |
| 140 | + results.push({ |
| 141 | + name: entity.canonical_name, |
| 142 | + old_type: oldType, |
| 143 | + new_type: entry.new_type, |
| 144 | + memories_affected: storeResult.memories_affected, |
| 145 | + qdrant_updated: qdrantResult.total_updated, |
| 146 | + qdrant_scanned: qdrantResult.total_scanned, |
| 147 | + }); |
| 148 | + |
| 149 | + // 3. Log reclassification as an event in the brain (fire-and-forget) |
| 150 | + try { |
| 151 | + const internalUrl = `http://localhost:${process.env.PORT || 8084}/memory`; |
| 152 | + const apiKey = req.headers['x-api-key']; |
| 153 | + fetch(internalUrl, { |
| 154 | + method: 'POST', |
| 155 | + headers: { |
| 156 | + 'Content-Type': 'application/json', |
| 157 | + ...(apiKey ? { 'x-api-key': apiKey } : {}), |
| 158 | + }, |
| 159 | + body: JSON.stringify({ |
| 160 | + type: 'event', |
| 161 | + content: `Entity reclassified: "${entity.canonical_name}" changed from ${oldType} to ${entry.new_type}. ${storeResult.memories_affected} memories linked, ${qdrantResult.total_updated} Qdrant payloads updated.`, |
| 162 | + source_agent: 'system', |
| 163 | + client_id: 'global', |
| 164 | + category: 'episodic', |
| 165 | + importance: 'medium', |
| 166 | + }), |
| 167 | + }).catch(e => console.error('[entities:reclassify:log]', e.message)); |
| 168 | + } catch (e) { |
| 169 | + console.error('[entities:reclassify:log]', e.message); |
| 170 | + } |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + res.json({ |
| 175 | + preview: isDryRun ? results : undefined, |
| 176 | + applied: isDryRun ? false : results, |
| 177 | + dry_run: isDryRun, |
| 178 | + }); |
| 179 | + } catch (err) { |
| 180 | + console.error('[entities:reclassify]', err.message); |
| 181 | + res.status(500).json({ error: 'Internal server error' }); |
| 182 | + } |
| 183 | +}); |
| 184 | + |
44 | 185 | // GET /entities/:name — Single entity by name or alias |
45 | 186 | entitiesRouter.get('/:name', async (req, res) => { |
46 | 187 | try { |
|
0 commit comments