Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(brain): real people — stricter names, owner curation, checked new names, belief links
Salman Qureshi7be61fb6d7ae
diff --git a/src/index.ts b/src/index.tsindex 6b5304b8..8f326e55 100644--- a/src/index.ts+++ b/src/index.ts@@ -58,6 +58,8 @@ import { BotManager } from './bots/bot-manager.js';import { getPluginManager, peekPluginManager, setProviderLookup } from './plugins/manager.js';import { setCallLearning, setChannelHost, setDesktopActivityHook, setVoiceBriefing, setWorkStopper } from './plugins/channel-bridge.js';import { registerPluginsCli } from './cli/plugins-cli.js';+import { PersonVerifier, personCheckPrompt, parsePersonCheck } from './memory/person-verifier.js';+import { setPersonVerifier } from './web/api/brain.js';import { registerDevicesCli } from './cli/devices-cli.js';import { SECOND_BRAIN_UNAVAILABLE_MESSAGE } from './memory/second-brain-db.js';import { isSqliteAvailable } from './utils/sqlite-driver.js';@@ -2577,6 +2579,22 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {logger.warn(`Second brain disabled: ${SECOND_BRAIN_UNAVAILABLE_MESSAGE}`);}+ // "Is it a person?" for names new memories mention: batched, slow, capped.+ // Only the process that owns the runtime runs it (never a second terminal).+ if (userMemory && !daemonOwnsRuntime) {+ const memForChecks = userMemory;+ const verifier = new PersonVerifier(memForChecks, async (items) => {+ const provider = providers.getDefault();+ const { generateText } = await import('ai');+ const result = await generateText({ model: provider.getModelInstance(), prompt: personCheckPrompt(items), maxOutputTokens: 400 });+ const usage = (result as { usage?: { inputTokens?: number; outputTokens?: number } }).usage;+ tokenBudget.recordUsage({ provider: provider.name, model: provider.getModel(), inputTokens: usage?.inputTokens ?? 0, outputTokens: usage?.outputTokens ?? 0, totalTokens: (usage?.inputTokens ?? 0) + (usage?.outputTokens ?? 0), channelType: 'internal' });+ return parsePersonCheck(result.text, items);+ });+ verifier.start();+ setPersonVerifier(verifier);+ }+const channels = new ChannelRegistry(config, { cliOnly: daemonOwnsRuntime });const webChannel = new WebChannel(config.identity.name);channels.register('web', webChannel);diff --git a/src/memory/person-curation.test.ts b/src/memory/person-curation.test.tsnew file mode 100644index 00000000..c0a2f7b7--- /dev/null+++ b/src/memory/person-curation.test.ts@@ -0,0 +1,109 @@+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import { getDefaultConfig } from '../utils/config.js';+import { UserMemoryStore } from './user-memory.js';+import { isBetterSqlite3Available } from './second-brain-db.js';++/**+ * The owner curates people: edits keep the id and survive rebuilds, merges+ * move every link, "not a person" is permanent, and new names (never old+ * ones) are queued for a check.+ */+const tempDirs: string[] = [];+const sqliteAvailable = isBetterSqlite3Available();++function createStore(): UserMemoryStore {+ const dir = mkdtempSync(join(tmpdir(), 'mercury-people-'));+ tempDirs.push(dir);+ const config = getDefaultConfig();+ config.memory.secondBrain = { enabled: true };+ return new UserMemoryStore(config, 'user:owner', join(dir, 'second-brain', 'second-brain.db'));+}++afterEach(() => {+ while (tempDirs.length > 0) {+ try { rmSync(tempDirs.pop()!, { recursive: true, force: true }); } catch { /* ignore */ }+ }+});++function remember(store: UserMemoryStore, summary: string) {+ store.remember([{ type: 'relationship', summary, evidenceKind: 'direct', confidence: 0.9, importance: 0.8, durability: 0.9 }], 'system');+}++const byName = (store: UserMemoryStore, name: string) => store.listPersons(name, 50).find((p) => p.name === name);++describe.skipIf(!sqliteAvailable)('people curation', () => {+ it('stores real names only; junk phrases never become people', () => {+ const store = createStore();+ remember(store, 'My wife Heer loves tea. Married since 2020. During winter She works on the Brain Graph.');+ const names = store.listPersons('', 50).map((p) => p.name);+ expect(names).toContain('Heer');+ for (const junk of ['Married', 'During', 'She', 'Brain Graph']) expect(names).not.toContain(junk);+ });++ it('an edit keeps the id, adds the new name as an alias, and survives a rebuild', () => {+ const store = createStore();+ remember(store, 'My son Zayd started school.');+ const zayd = byName(store, 'Zayd')!;+ const edited = store.updatePerson(zayd.id, { displayName: 'Zayd Qureshi', kind: 'person', meta: { birthday: '2019-05-01' } })!;+ expect(edited.id).toBe(zayd.id);+ expect(edited.verifiedBy).toBe('owner');+ store.rebuildPersonsFromMemory();+ const after = store.getPerson(zayd.id)!;+ expect(after.name).toBe('Zayd Qureshi');+ expect(after.meta).toEqual({ birthday: '2019-05-01' });+ remember(store, 'Zayd Qureshi won a medal.');+ expect(store.getPersonMemories(zayd.id, 10).length).toBe(2);+ });++ it('merging moves memories to one id, and the old name keeps resolving to it', () => {+ const store = createStore();+ remember(store, 'My wife Heer likes hiking.');+ remember(store, 'Heer Salman painted the room.');+ const a = byName(store, 'Heer')!;+ const b = byName(store, 'Heer Salman')!;+ expect(store.mergePersons(b.id, a.id)).toBe(true);+ expect(store.getPerson(b.id)).toBeNull();+ expect(store.getPersonMemories(a.id, 10).length).toBe(2);+ store.rebuildPersonsFromMemory();+ expect(byName(store, 'Heer Salman')).toBeUndefined();+ expect(store.getPersonMemories(a.id, 10).length).toBe(2);+ });++ it('"not a person" removes it and it never comes back', () => {+ const store = createStore();+ remember(store, 'Tesla Motors announced a car.');+ const t = store.listPersons('Tesla', 10)[0];+ if (!t) return; // the rules may already reject it; either way it must stay gone+ expect(store.markNotPerson(t.id)).toBe(true);+ store.rebuildPersonsFromMemory();+ remember(store, 'Tesla Motors shipped again.');+ expect(store.listPersons('Tesla', 10)).toHaveLength(0);+ });++ it('new names are queued for a check; rebuilds of old memories are not', () => {+ const store = createStore();+ remember(store, 'Zayd started school.');+ store.listPersons('', 10); // first use: the backfill indexes what already exists, unchecked+ expect(store.countPersonChecks()).toBe(0);+ remember(store, 'Shehzen visited yesterday.');+ expect(store.countPersonChecks()).toBe(1);+ const [item] = store.pendingPersonChecks(10);+ store.applyPersonCheck(item.person_id, 'person');+ expect(store.countPersonChecks()).toBe(0);+ expect(store.getPerson(item.person_id)?.kind).toBe('person');+ store.rebuildPersonsFromMemory();+ expect(store.countPersonChecks()).toBe(0);+ });++ it('the graph has only real links', () => {+ const store = createStore();+ remember(store, 'My wife Heer and my son Zayd went to the park.');+ const g = store.personGraph(100);+ expect(g.persons.map((p) => p.name).sort()).toEqual(['Heer', 'Zayd']);+ expect(g.memoryPersons.length).toBe(2);+ expect(g.memories.length).toBe(1);+ });+});diff --git a/src/memory/person-verifier.test.ts b/src/memory/person-verifier.test.tsnew file mode 100644index 00000000..c1702e95--- /dev/null+++ b/src/memory/person-verifier.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it } from 'vitest';+import { PersonVerifier, parsePersonCheck, personCheckPrompt, type PersonCheckItem, type PersonVerdict } from './person-verifier.js';+import { isLikelyHumanName } from './user-memory.js';++function host(items: PersonCheckItem[]) {+ const applied: Record<string, PersonVerdict> = {};+ return {+ applied,+ pendingPersonChecks: (limit: number) => items.filter((i) => !(i.person_id in applied)).slice(0, limit),+ countPersonChecks: () => items.filter((i) => !(i.person_id in applied)).length,+ applyPersonCheck: (id: string, v: PersonVerdict) => { applied[id] = v; },+ };+}++describe('person checks', () => {+ it('rejects ordinary words and product names before anything is stored', () => {+ for (const bad of ['Married', 'During', 'She', 'Heer The', 'Heer User', 'Brain Graph', 'System Fixes User', 'Mercury Agent Web', 'Optimus Prime', 'The Architect', 'Battlefield', 'Working']) {+ expect(isLikelyHumanName(bad)).toBe(false);+ }+ for (const good of ['Heer', 'Zayd', 'Shehzen', 'Salman Qureshi']) expect(isLikelyHumanName(good)).toBe(true);+ });++ it('checks a batch in one call and applies each verdict', async () => {+ const h = host([+ { person_id: 'a', name: 'Zayd', context: 'Zayd is my son' },+ { person_id: 'b', name: 'Bruno', context: 'walked Bruno, our dog' },+ { person_id: 'c', name: 'Tesla', context: 'bought Tesla shares' },+ ]);+ let calls = 0;+ const v = new PersonVerifier(h, async (items) => { calls++; return parsePersonCheck('1: person\n2: pet\n3: not_person', items); });+ expect(await v.runOnce()).toBe(3);+ expect(calls).toBe(1);+ expect(h.applied).toEqual({ a: 'person', b: 'pet', c: 'not_person' });+ expect(await v.runOnce()).toBe(0); // queue empty: no call+ expect(calls).toBe(1);+ });++ it('never exceeds the daily cap', async () => {+ const items = Array.from({ length: 10 }, (_, i) => ({ person_id: `p${i}`, name: `Name${i}`, context: '' }));+ const h = host(items);+ let calls = 0;+ const v = new PersonVerifier(h, async () => { calls++; return {}; }, { batch: 2, dailyCap: 3 });+ for (let i = 0; i < 6; i++) await v.runOnce();+ expect(calls).toBe(3);+ expect(v.status().callsToday).toBe(3);+ });++ it('a failed call leaves the names queued and reports the error', async () => {+ const h = host([{ person_id: 'a', name: 'Zayd', context: '' }]);+ const v = new PersonVerifier(h, async () => { throw new Error('rate limited'); });+ expect(await v.runOnce()).toBe(0);+ expect(h.countPersonChecks()).toBe(1);+ expect(v.status().lastError).toBe('rate limited');+ });++ it('prompt numbers the names and the parser tolerates loose formatting', () => {+ const items = [{ id: 'x', name: 'Heer', context: 'my wife Heer' }, { id: 'y', name: 'Rex', context: '' }];+ expect(personCheckPrompt(items)).toContain('1. name: "Heer"');+ expect(parsePersonCheck('1) Person\n2 - not a person\nnoise', items)).toEqual({ x: 'person', y: 'not_person' });+ });+});diff --git a/src/memory/person-verifier.ts b/src/memory/person-verifier.tsnew file mode 100644index 00000000..a7b9a8fc--- /dev/null+++ b/src/memory/person-verifier.ts@@ -0,0 +1,162 @@+/**+ * Is it a person? New names found in memories are checked by a model —+ * new ones only (rebuilds of old memories never queue), in batches, on a+ * slow clock, under a daily cap — so the people list stays real without a+ * call per mention. The owner's own edits always win and are never queued.+ *+ * - waits `intervalMs` (5 min) between runs, longer after a failure;+ * - one call checks up to `batch` (20) names;+ * - at most `dailyCap` (24) calls a day;+ * - does nothing while the queue is empty.+ */++import { logger } from '../utils/logger.js';++export type PersonVerdict = 'person' | 'pet' | 'not_person' | 'unsure';++export interface PersonCheckItem {+ person_id: string;+ name: string;+ context: string | null;+}++export interface PersonVerifierHost {+ pendingPersonChecks(limit: number): PersonCheckItem[];+ countPersonChecks(): number;+ applyPersonCheck(personId: string, verdict: PersonVerdict): void;+}++export interface PersonVerifierStatus {+ enabled: boolean;+ pending: number;+ callsToday: number;+ dailyCap: number;+ lastRunAt: number | null;+ lastError: string | null;+ nextRunAt: number | null;+ checked: number;+}++export interface PersonVerifierOptions {+ intervalMs?: number;+ batch?: number;+ dailyCap?: number;+ now?: () => number;+}++export type PersonClassifier = (items: Array<{ id: string; name: string; context: string }>) => Promise<Record<string, PersonVerdict>>;++export class PersonVerifier {+ private readonly intervalMs: number;+ private readonly batch: number;+ private readonly dailyCap: number;+ private readonly now: () => number;+ private timer: ReturnType<typeof setTimeout> | null = null;+ private running = false;+ private failures = 0;+ private day = '';+ private calls = 0;+ private checked = 0;+ private lastRunAt: number | null = null;+ private lastError: string | null = null;+ private nextRunAt: number | null = null;++ constructor(private readonly host: PersonVerifierHost, private readonly classify: PersonClassifier, opts: PersonVerifierOptions = {}) {+ this.intervalMs = opts.intervalMs ?? 5 * 60_000;+ this.batch = opts.batch ?? 20;+ this.dailyCap = opts.dailyCap ?? 24;+ this.now = opts.now ?? Date.now;+ }++ start(): void {+ this.schedule(60_000);+ }++ stop(): void {+ if (this.timer) clearTimeout(this.timer);+ this.timer = null;+ this.nextRunAt = null;+ }++ status(): PersonVerifierStatus {+ this.rollDay();+ let pending = 0;+ try { pending = this.host.countPersonChecks(); } catch { /* db closed */ }+ return { enabled: this.timer !== null || this.running, pending, callsToday: this.calls, dailyCap: this.dailyCap, lastRunAt: this.lastRunAt, lastError: this.lastError, nextRunAt: this.nextRunAt, checked: this.checked };+ }++ /** One run: returns how many names were checked (0 when idle, capped or failing). */+ async runOnce(): Promise<number> {+ if (this.running) return 0;+ this.rollDay();+ if (this.calls >= this.dailyCap) return 0;+ const items = this.host.pendingPersonChecks(this.batch);+ if (items.length === 0) return 0;+ this.running = true;+ this.calls += 1;+ this.lastRunAt = this.now();+ try {+ const verdicts = await this.classify(items.map((i) => ({ id: i.person_id, name: i.name, context: i.context ?? '' })));+ for (const item of items) this.host.applyPersonCheck(item.person_id, verdicts[item.person_id] ?? 'unsure');+ this.failures = 0;+ this.lastError = null;+ this.checked += items.length;+ return items.length;+ } catch (err) {+ this.failures += 1;+ this.lastError = err instanceof Error ? err.message : String(err);+ logger.warn({ err: this.lastError }, 'Person check failed; will retry later');+ return 0;+ } finally {+ this.running = false;+ }+ }++ private schedule(delay: number): void {+ if (this.timer) clearTimeout(this.timer);+ this.nextRunAt = this.now() + delay;+ this.timer = setTimeout(() => {+ void this.runOnce().finally(() => {+ // Back off after failures: 5 min → 10 → 20 → … → 1 h.+ const next = Math.min(60 * 60_000, this.intervalMs * 2 ** Math.min(this.failures, 4));+ this.schedule(next);+ });+ }, delay);+ this.timer.unref?.();+ }++ private rollDay(): void {+ const today = new Date(this.now()).toISOString().slice(0, 10);+ if (today !== this.day) {+ this.day = today;+ this.calls = 0;+ }+ }+}++/** The prompt and parser for a batch check; kept here so tests cover them. */+export function personCheckPrompt(items: Array<{ id: string; name: string; context: string }>): string {+ const lines = items.map((i, n) => `${n + 1}. name: "${i.name.replace(/"/g, "'")}"\n context: "${i.context.replace(/\s+/g, ' ').replace(/"/g, "'").slice(0, 300)}"`);+ return [+ 'For each name below, decide what it refers to in its context.',+ 'Answer "person" for a real human being (the user, family, friends, colleagues, public figures),',+ '"pet" for an animal someone keeps, "not_person" for anything else (companies, products, places,',+ 'projects, software, fictional or game characters, ordinary words), "unsure" if the context cannot tell.',+ 'Reply with one line per name, exactly: <number>: <person|pet|not_person|unsure>',+ '',+ ...lines,+ ].join('\n');+}++export function parsePersonCheck(text: string, items: Array<{ id: string }>): Record<string, PersonVerdict> {+ const out: Record<string, PersonVerdict> = {};+ for (const line of text.split(/\r?\n/)) {+ const m = /^\s*(\d+)\s*[:.)-]\s*(person|pet|not_person|not a person|unsure)\b/i.exec(line);+ if (!m) continue;+ const item = items[Number(m[1]) - 1];+ if (!item) continue;+ const v = m[2].toLowerCase().replace(/ /g, '_').replace('not_a_person', 'not_person') as PersonVerdict;+ out[item.id] = v;+ }+ return out;+}diff --git a/src/memory/second-brain-db.ts b/src/memory/second-brain-db.tsindex f51a194a..930e395b 100644--- a/src/memory/second-brain-db.ts+++ b/src/memory/second-brain-db.ts@@ -55,6 +55,23 @@ export interface PersonRow {last_seen_at: number;created_at: number;updated_at: number;+ /** 'person' | 'pet' | 'unverified' (never 'not_person': those are not stored). */+ kind?: string;+ /** Who decided `kind`: 'owner' | 'model' | 'rule' | null. */+ verified_by?: string | null;+ /** Contact card: JSON { phone, email, birthday, location, company, notes, links[] }. */+ meta?: string;+ /** 1 = the owner edited this person; rebuilds never overwrite or delete it. */+ owner_edited?: number;+}++export type PersonKind = 'person' | 'pet' | 'unverified';++export interface PersonGraph {+ persons: Array<{ id: string; name: string; kind: string; relationship: string | null; memoryCount: number }>;+ memories: Array<{ id: string; summary: string; type: string; importance: number; updatedAt: number }>;+ memoryPersons: Array<{ memoryId: string; personId: string; role: string }>;+ relationships: Array<{ source: string; target: string; type: string; strength: number }>;}export interface PersonListRow extends PersonRow {@@ -247,6 +264,44 @@ export class SecondBrainDB {// Index for incremental fetch (shareable + updated_at — the cloud pull query).this.db.exec('CREATE INDEX IF NOT EXISTS idx_memories_shareable_updated ON memories(shareable, updated_at)');+ // People: what an entity is, who decided, the contact card, and owner edits.+ const personColumns = this.db.prepare('PRAGMA table_info(persons)').all() as { name: string }[];+ const addPersonColumn = (name: string, ddl: string) => {+ if (!personColumns.some((c) => c.name === name)) this.db.exec(`ALTER TABLE persons ADD COLUMN ${ddl}`);+ };+ addPersonColumn('kind', "kind TEXT NOT NULL DEFAULT 'unverified'");+ addPersonColumn('verified_by', 'verified_by TEXT');+ addPersonColumn('meta', "meta TEXT NOT NULL DEFAULT '{}'");+ addPersonColumn('owner_edited', 'owner_edited INTEGER NOT NULL DEFAULT 0');+ this.db.exec(`+ CREATE TABLE IF NOT EXISTS person_overrides (+ user_key TEXT NOT NULL,+ canonical_name TEXT NOT NULL,+ action TEXT NOT NULL,+ target_person_id TEXT,+ created_at INTEGER NOT NULL,+ PRIMARY KEY (user_key, canonical_name)+ );+ CREATE TABLE IF NOT EXISTS belief_persons (+ belief_id TEXT NOT NULL,+ person_id TEXT NOT NULL,+ role TEXT NOT NULL DEFAULT 'mentioned',+ confidence REAL NOT NULL DEFAULT 0.7,+ created_at INTEGER NOT NULL,+ PRIMARY KEY (belief_id, person_id),+ FOREIGN KEY (person_id) REFERENCES persons(id) ON DELETE CASCADE+ );+ CREATE INDEX IF NOT EXISTS idx_belief_persons_person ON belief_persons(person_id);+ CREATE TABLE IF NOT EXISTS person_checks (+ person_id TEXT PRIMARY KEY,+ user_key TEXT NOT NULL,+ name TEXT NOT NULL,+ context TEXT,+ queued_at INTEGER NOT NULL,+ FOREIGN KEY (person_id) REFERENCES persons(id) ON DELETE CASCADE+ );+ `);+logger.info({ backend: this.db.backend }, 'Second brain database initialized');}@@ -533,11 +588,33 @@ export class SecondBrainDB {confidence?: number;description?: string | null;personId?: string;- }): PersonRow {+ /** Queue a newly created person for a model check (new mentions only, never rebuilds). */+ queueCheck?: { context: string } | null;+ }): PersonRow | null {const now = Date.now();const normalized = this.normalizePersonName(params.name);+ if (!normalized) return null;++ // The owner's decisions win over every extraction, including rebuilds.+ const override = this.db.prepare('SELECT action, target_person_id FROM person_overrides WHERE user_key = ? AND canonical_name = ? LIMIT 1')+ .get(params.userKey, normalized) as { action: string; target_person_id: string | null } | undefined;+ if (override?.action === 'not_person') return null;+const existingStmt = this.db.prepare('SELECT * FROM persons WHERE user_key = ? AND canonical_name = ? LIMIT 1');- const existing = existingStmt.get(params.userKey, normalized) as PersonRow | undefined;+ let existing = existingStmt.get(params.userKey, normalized) as PersonRow | undefined;+ if (!existing && override?.action === 'merge' && override.target_person_id) existing = this.getPersonById(override.target_person_id);+ if (!existing) {+ // A name the owner gave another person (rename, merge) resolves to that person.+ existing = this.db.prepare(`+ SELECT p.* FROM person_aliases a JOIN persons p ON p.id = a.person_id+ WHERE p.user_key = ? AND a.normalized_alias = ? ORDER BY p.owner_edited DESC LIMIT 1+ `).get(params.userKey, normalized) as PersonRow | undefined;+ }++ if (existing && existing.owner_edited === 1) {+ this.db.prepare('UPDATE persons SET last_seen_at = ?, updated_at = ? WHERE id = ?').run(now, now, existing.id);+ return this.getPersonById(existing.id) ?? existing;+ }if (existing) {const confidence = Math.max(existing.confidence, params.confidence ?? existing.confidence);@@ -577,9 +654,181 @@ export class SecondBrainDB {const created = this.getPersonById(id);if (!created) throw new Error('Failed to create person record');+ if (params.queueCheck) {+ this.db.prepare('INSERT OR IGNORE INTO person_checks (person_id, user_key, name, context, queued_at) VALUES (?, ?, ?, ?, ?)')+ .run(id, params.userKey, params.name.trim(), params.queueCheck.context.slice(0, 400), now);+ }return created;}+ // ── People in beliefs (the live brain since the Owner Model) ─────────────++ linkBeliefPerson(beliefId: string, personId: string, role: string, confidence: number): void {+ this.db.prepare(`INSERT INTO belief_persons (belief_id, person_id, role, confidence, created_at) VALUES (?, ?, ?, ?, ?)+ ON CONFLICT(belief_id, person_id) DO UPDATE SET role = excluded.role, confidence = excluded.confidence`).run(beliefId, personId, role, confidence, Date.now());+ }++ clearBeliefPersons(beliefId: string): void {+ this.db.prepare('DELETE FROM belief_persons WHERE belief_id = ?').run(beliefId);+ }++ clearAllBeliefPersons(userKey: string): void {+ this.db.prepare('DELETE FROM belief_persons WHERE person_id IN (SELECT id FROM persons WHERE user_key = ?)').run(userKey);+ }++ /** Live beliefs created after `since` (ms), oldest first, for incremental person indexing. */+ beliefsSince(userKey: string, since: number, limit = 500): Array<{ id: string; statement: string; detail: string | null; kind: string; confidence: number; created_at: number }> {+ return this.db.prepare(`SELECT id, statement, detail, kind, MIN(1, 0.5 + support / 10.0) AS confidence, created_at FROM beliefs+ WHERE owner_key = ? AND created_at > ? AND status IN ('candidate', 'held', 'confirmed', 'contested') ORDER BY created_at ASC LIMIT ?`)+ .all(userKey, since, limit) as Array<{ id: string; statement: string; detail: string | null; kind: string; confidence: number; created_at: number }>;+ }++ // ── Owner curation of people ─────────────────────────────────────────────++ updatePerson(userKey: string, id: string, fields: { displayName?: string; relationship?: string | null; description?: string | null; kind?: PersonKind; meta?: Record<string, unknown> }): PersonRow | null {+ const row = this.getPersonById(id);+ if (!row || row.user_key !== userKey) return null;+ const now = Date.now();+ const meta = fields.meta !== undefined ? JSON.stringify(fields.meta) : row.meta ?? '{}';+ const kind = fields.kind ?? row.kind ?? 'unverified';+ const displayName = fields.displayName?.trim() || row.display_name;+ this.db.prepare(`+ UPDATE persons SET display_name = ?, relationship_to_user = ?, description = ?, kind = ?, verified_by = ?, meta = ?, owner_edited = 1, updated_at = ?+ WHERE id = ?+ `).run(+ displayName,+ fields.relationship !== undefined ? fields.relationship : row.relationship_to_user,+ fields.description !== undefined ? fields.description : row.description,+ kind,+ fields.kind !== undefined ? 'owner' : row.verified_by ?? null,+ meta,+ now,+ id,+ );+ // The id never changes; a new name becomes an alias, so future mentions link here.+ if (fields.displayName && fields.displayName.trim() !== row.display_name) this.addPersonAlias(id, fields.displayName.trim(), 'owner');+ this.db.prepare('DELETE FROM person_checks WHERE person_id = ?').run(id);+ return this.getPersonById(id) ?? null;+ }++ /** "This isn't a person": forget the entity, and never create it again. */+ markNotPerson(userKey: string, id: string): boolean {+ const row = this.getPersonById(id);+ if (!row || row.user_key !== userKey) return false;+ const names = [row.canonical_name, ...(this.db.prepare('SELECT normalized_alias FROM person_aliases WHERE person_id = ?').all(id) as Array<{ normalized_alias: string }>).map((a) => a.normalized_alias)];+ const now = Date.now();+ const put = this.db.prepare(`INSERT INTO person_overrides (user_key, canonical_name, action, target_person_id, created_at) VALUES (?, ?, 'not_person', NULL, ?)+ ON CONFLICT(user_key, canonical_name) DO UPDATE SET action = 'not_person', target_person_id = NULL, created_at = excluded.created_at`);+ for (const n of new Set(names)) put.run(userKey, n, now);+ this.db.prepare('DELETE FROM persons WHERE id = ?').run(id);+ return true;+ }++ /** Merge `fromId` into `intoId`: links, relationships and names move; `intoId` keeps its id. */+ mergePersons(userKey: string, fromId: string, intoId: string): boolean {+ if (fromId === intoId) return false;+ const from = this.getPersonById(fromId);+ const into = this.getPersonById(intoId);+ if (!from || !into || from.user_key !== userKey || into.user_key !== userKey) return false;+ const now = Date.now();+ // The driver runs the function inside BEGIN/COMMIT right away.+ this.db.transaction(() => {+ this.db.prepare(`INSERT INTO memory_persons (memory_id, person_id, role, confidence, created_at, updated_at)+ SELECT memory_id, ?, role, confidence, created_at, ? FROM memory_persons WHERE person_id = ?+ ON CONFLICT(memory_id, person_id) DO NOTHING`).run(intoId, now, fromId);+ this.db.prepare(`INSERT INTO belief_persons (belief_id, person_id, role, confidence, created_at)+ SELECT belief_id, ?, role, confidence, created_at FROM belief_persons WHERE person_id = ?+ ON CONFLICT(belief_id, person_id) DO NOTHING`).run(intoId, fromId);+ this.db.prepare('UPDATE OR IGNORE person_relationships SET source_person_id = ? WHERE source_person_id = ?').run(intoId, fromId);+ this.db.prepare('UPDATE OR IGNORE person_relationships SET target_person_id = ? WHERE target_person_id = ?').run(intoId, fromId);+ this.db.prepare('DELETE FROM person_relationships WHERE source_person_id = target_person_id').run();+ const aliases = [from.display_name, ...(this.db.prepare('SELECT alias FROM person_aliases WHERE person_id = ?').all(fromId) as Array<{ alias: string }>).map((a) => a.alias)];+ for (const a of aliases) this.addPersonAlias(intoId, a, 'owner');+ const put = this.db.prepare(`INSERT INTO person_overrides (user_key, canonical_name, action, target_person_id, created_at) VALUES (?, ?, 'merge', ?, ?)+ ON CONFLICT(user_key, canonical_name) DO UPDATE SET action = 'merge', target_person_id = excluded.target_person_id, created_at = excluded.created_at`);+ put.run(userKey, from.canonical_name, intoId, now);+ this.db.prepare('DELETE FROM persons WHERE id = ?').run(fromId);+ this.db.prepare('UPDATE persons SET owner_edited = 1, updated_at = ? WHERE id = ?').run(now, intoId);+ });+ return true;+ }++ // ── The model check queue (new names only) ────────────────────────────────++ pendingPersonChecks(userKey: string, limit: number): Array<{ person_id: string; name: string; context: string | null }> {+ return this.db.prepare('SELECT person_id, name, context FROM person_checks WHERE user_key = ? ORDER BY queued_at ASC LIMIT ?')+ .all(userKey, Math.max(1, Math.min(limit, 50))) as Array<{ person_id: string; name: string; context: string | null }>;+ }++ /** Owner opt-in: queue existing unreviewed people (not owner-edited, not already decided). */+ queueExistingPersonChecks(userKey: string): number {+ const rows = this.db.prepare(`+ SELECT p.id, p.display_name,+ COALESCE(+ (SELECT b.statement FROM belief_persons bp JOIN beliefs b ON b.id = bp.belief_id WHERE bp.person_id = p.id ORDER BY b.updated_at DESC LIMIT 1),+ (SELECT m.summary FROM memory_persons mp JOIN memories m ON m.id = mp.memory_id WHERE mp.person_id = p.id ORDER BY m.updated_at DESC LIMIT 1),+ ''+ ) AS context+ FROM persons p+ WHERE p.user_key = ? AND p.owner_edited = 0 AND COALESCE(p.verified_by, '') = '' AND p.kind = 'unverified'+ `).all(userKey) as Array<{ id: string; display_name: string; context: string }>;+ const put = this.db.prepare('INSERT OR IGNORE INTO person_checks (person_id, user_key, name, context, queued_at) VALUES (?, ?, ?, ?, ?)');+ const now = Date.now();+ for (const r of rows) put.run(r.id, userKey, r.display_name, (r.context ?? '').slice(0, 400), now);+ return rows.length;+ }++ countPersonChecks(userKey: string): number {+ return (this.db.prepare('SELECT COUNT(*) AS n FROM person_checks WHERE user_key = ?').get(userKey) as { n: number }).n;+ }++ applyPersonCheck(userKey: string, personId: string, verdict: 'person' | 'pet' | 'not_person' | 'unsure'): void {+ this.db.prepare('DELETE FROM person_checks WHERE person_id = ?').run(personId);+ const row = this.getPersonById(personId);+ if (!row || row.user_key !== userKey || row.owner_edited === 1) return;+ if (verdict === 'not_person') {+ // A model's "no" hides it; only the owner's "no" is permanent (markNotPerson).+ this.db.prepare("UPDATE persons SET kind = 'unverified', verified_by = 'model-rejected', updated_at = ? WHERE id = ?").run(Date.now(), personId);+ return;+ }+ if (verdict === 'unsure') return;+ this.db.prepare('UPDATE persons SET kind = ?, verified_by = ?, updated_at = ? WHERE id = ?').run(verdict, 'model', Date.now(), personId);+ }++ // ── The brain graph: real links only ─────────────────────────────────────++ personGraph(userKey: string, maxMemories: number): PersonGraph {+ // Nodes: the live brain (beliefs) and the people in it; edges: who appears+ // in which belief, and person-to-person relationships. Legacy archive+ // links still count toward a person's weight.+ const persons = (this.db.prepare(`+ SELECT p.id, p.display_name AS name, p.kind, p.relationship_to_user AS relationship,+ (SELECT COUNT(*) FROM belief_persons bp JOIN beliefs b ON b.id = bp.belief_id AND b.status IN ('candidate','held','confirmed','contested') WHERE bp.person_id = p.id)+ + (SELECT COUNT(*) FROM memory_persons mp JOIN memories m ON m.id = mp.memory_id AND m.dismissed = 0 WHERE mp.person_id = p.id) AS memoryCount+ FROM persons p+ WHERE p.user_key = ? AND COALESCE(p.verified_by, '') != 'model-rejected'+ ORDER BY memoryCount DESC+ LIMIT 400+ `).all(userKey) as PersonGraph['persons']).filter((p) => p.memoryCount > 0 || p.relationship);+ const memories = (this.db.prepare(`+ SELECT id, statement AS summary, kind AS type, MIN(1, 0.3 + support / 8.0) AS importance, updated_at AS updatedAt FROM beliefs+ WHERE owner_key = ? AND status IN ('candidate', 'held', 'confirmed', 'contested')+ ORDER BY (status = 'confirmed') DESC, (status = 'held') DESC, updated_at DESC+ LIMIT ?+ `).all(userKey, Math.max(10, Math.min(maxMemories, 2000))) as PersonGraph['memories'])+ .map((m) => ({ ...m, summary: m.summary.length > 140 ? `${m.summary.slice(0, 137)}…` : m.summary }));+ const personIds = new Set(persons.map((p) => p.id));+ const memoryIds = new Set(memories.map((m) => m.id));+ const memoryPersons = (this.db.prepare(`+ SELECT bp.belief_id AS memoryId, bp.person_id AS personId, bp.role FROM belief_persons bp+ JOIN persons p ON p.id = bp.person_id WHERE p.user_key = ?+ `).all(userKey) as PersonGraph['memoryPersons']).filter((l) => personIds.has(l.personId) && memoryIds.has(l.memoryId));+ const relationships = (this.db.prepare(`+ SELECT source_person_id AS source, target_person_id AS target, relation_type AS type, strength FROM person_relationships WHERE user_key = ?+ `).all(userKey) as PersonGraph['relationships']).filter((r) => personIds.has(r.source) && personIds.has(r.target));+ return { persons, memories, memoryPersons, relationships };+ }+getPersonById(id: string): PersonRow | undefined {const stmt = this.db.prepare('SELECT * FROM persons WHERE id = ? LIMIT 1');return stmt.get(id) as PersonRow | undefined;@@ -632,7 +881,9 @@ export class SecondBrainDB {const stmt = this.db.prepare(`DELETE FROM personsWHERE user_key = ?+ AND owner_edited = 0AND id NOT IN (SELECT DISTINCT person_id FROM memory_persons)+ AND id NOT IN (SELECT DISTINCT person_id FROM belief_persons)`);stmt.run(userKey);}@@ -694,60 +945,42 @@ export class SecondBrainDB {listPersons(userKey: string, query?: string, limit: number = 100): PersonListRow[] {const cappedLimit = Math.min(Math.max(limit, 1), 300);- if (query && query.trim()) {- const q = `%${query.trim().toLowerCase()}%`;- const stmt = this.db.prepare(`- SELECT- p.*,- COUNT(DISTINCT mp.memory_id) AS memory_count+ // Counts both the legacy archive and live beliefs; owner-edited people+ // stay listed even with nothing linked yet.+ const q = query && query.trim() ? `%${query.trim().toLowerCase()}%` : null;+ const stmt = this.db.prepare(`+ SELECT * FROM (+ SELECT p.*, (SELECT COUNT(*) FROM memory_persons mp JOIN memories m ON m.id = mp.memory_id AND m.dismissed = 0 WHERE mp.person_id = p.id)+ + (SELECT COUNT(*) FROM belief_persons bp JOIN beliefs b ON b.id = bp.belief_id AND b.status IN ('candidate','held','confirmed','contested') WHERE bp.person_id = p.id) AS memory_countFROM persons p- LEFT JOIN memory_persons mp ON mp.person_id = p.id- LEFT JOIN memories m ON m.id = mp.memory_idWHERE p.user_key = ?- AND (LOWER(p.display_name) LIKE ? OR LOWER(p.canonical_name) LIKE ?)- AND (m.id IS NULL OR m.dismissed = 0)- GROUP BY p.id- HAVING COUNT(DISTINCT mp.memory_id) > 0- ORDER BY memory_count DESC, p.updated_at DESC- LIMIT ?- `);- return stmt.all(userKey, q, q, cappedLimit) as PersonListRow[];- }-- const stmt = this.db.prepare(`- SELECT- p.*,- COUNT(DISTINCT mp.memory_id) AS memory_count- FROM persons p- LEFT JOIN memory_persons mp ON mp.person_id = p.id- LEFT JOIN memories m ON m.id = mp.memory_id- WHERE p.user_key = ?- AND (m.id IS NULL OR m.dismissed = 0)- GROUP BY p.id- HAVING COUNT(DISTINCT mp.memory_id) > 0- ORDER BY memory_count DESC, p.updated_at DESC+ ${q ? 'AND (LOWER(p.display_name) LIKE ? OR LOWER(p.canonical_name) LIKE ? OR p.id IN (SELECT person_id FROM person_aliases WHERE normalized_alias LIKE ?))' : ''}+ )+ WHERE memory_count > 0 OR owner_edited = 1+ ORDER BY memory_count DESC, updated_at DESCLIMIT ?`);- return stmt.all(userKey, cappedLimit) as PersonListRow[];+ return (q ? stmt.all(userKey, q, q, q, cappedLimit) : stmt.all(userKey, cappedLimit)) as PersonListRow[];}getPersonWithCount(userKey: string, personId: string): PersonListRow | undefined {const stmt = this.db.prepare(`- SELECT- p.*,- COUNT(DISTINCT mp.memory_id) AS memory_count+ SELECT p.*, (SELECT COUNT(*) FROM memory_persons mp JOIN memories m ON m.id = mp.memory_id AND m.dismissed = 0 WHERE mp.person_id = p.id)+ + (SELECT COUNT(*) FROM belief_persons bp JOIN beliefs b ON b.id = bp.belief_id AND b.status IN ('candidate','held','confirmed','contested') WHERE bp.person_id = p.id) AS memory_countFROM persons p- LEFT JOIN memory_persons mp ON mp.person_id = p.id- LEFT JOIN memories m ON m.id = mp.memory_id- WHERE p.user_key = ?- AND p.id = ?- AND (m.id IS NULL OR m.dismissed = 0)- GROUP BY p.id+ WHERE p.user_key = ? AND p.id = ?LIMIT 1`);return stmt.get(userKey, personId) as PersonListRow | undefined;}+ /** Live beliefs that mention a person, newest first. */+ getBeliefIdsForPerson(personId: string, limit: number = 50): string[] {+ return (this.db.prepare(`SELECT bp.belief_id AS id FROM belief_persons bp JOIN beliefs b ON b.id = bp.belief_id+ WHERE bp.person_id = ? AND b.status IN ('candidate','held','confirmed','contested') ORDER BY b.updated_at DESC LIMIT ?`)+ .all(personId, Math.max(1, Math.min(limit, 200))) as Array<{ id: string }>).map((r) => r.id);+ }+getPersonConnections(userKey: string, personId: string, limit: number = 30): PersonConnectionRow[] {const cappedLimit = Math.min(Math.max(limit, 1), 100);const stmt = this.db.prepare(`diff --git a/src/memory/user-memory.ts b/src/memory/user-memory.tsindex eb304109..a6057676 100644--- a/src/memory/user-memory.ts+++ b/src/memory/user-memory.ts@@ -1,6 +1,6 @@import type { MercuryConfig } from '../utils/config.js';import { getMemoryDir } from '../utils/config.js';-import { SecondBrainDB, type MemoryRow, type PersonListRow } from './second-brain-db.js';+import { SecondBrainDB, type MemoryRow, type PersonListRow, type PersonGraph, type PersonKind } from './second-brain-db.js';import { BeliefStore, type Belief, type BeliefKind } from './beliefs.js';import { looksLikeSecret } from '../learning/text.js';import { join } from 'node:path';@@ -77,13 +77,21 @@ export interface UserPersonRecord {description: string | null;confidence: number;memoryCount: number;+ /** 'person' | 'pet' | 'unverified'. */+ kind: string;+ /** 'owner' | 'model' | 'model-rejected' | null. */+ verifiedBy: string | null;+ /** Contact card: phone, email, birthday, location, company, notes, links. */+ meta: Record<string, unknown>;+ ownerEdited: boolean;firstSeenAt: number;lastSeenAt: number;createdAt: number;updatedAt: number;}-const PERSON_INDEX_VERSION = '7';+// 8: stricter name rules, owner overrides, model checks for new names, beliefs indexed.+const PERSON_INDEX_VERSION = '8';export class UserMemoryStore {private db: SecondBrainDB;@@ -200,7 +208,7 @@ export class UserMemoryStore {}listPersons(query?: string, limit: number = 100): UserPersonRecord[] {- this.ensurePersonsBackfilled();+ this.indexNewBeliefs();const rows = this.db.listPersons(this.userKey, query, limit);return rows.map(row => this.toPersonRecord(row));}@@ -212,17 +220,73 @@ export class UserMemoryStore {return this.toPersonRecord(row);}+ // ── Owner curation of people (stable ids; rebuilds respect every decision) ──++ updatePerson(personId: string, fields: { displayName?: string; relationship?: string | null; description?: string | null; kind?: PersonKind; meta?: Record<string, unknown> }): UserPersonRecord | null {+ if (!this.db.updatePerson(this.userKey, personId, fields)) return null;+ return this.getPerson(personId);+ }++ markNotPerson(personId: string): boolean {+ return this.db.markNotPerson(this.userKey, personId);+ }++ mergePersons(fromId: string, intoId: string): boolean {+ return this.db.mergePersons(this.userKey, fromId, intoId);+ }++ personGraph(maxMemories: number): PersonGraph {+ this.indexNewBeliefs();+ return this.db.personGraph(this.userKey, maxMemories);+ }++ pendingPersonChecks(limit: number) {+ this.indexNewBeliefs();+ return this.db.pendingPersonChecks(this.userKey, limit);+ }++ queueExistingPersonChecks(): number {+ this.indexNewBeliefs();+ return this.db.queueExistingPersonChecks(this.userKey);+ }++ countPersonChecks(): number {+ this.indexNewBeliefs();+ return this.db.countPersonChecks(this.userKey);+ }++ applyPersonCheck(personId: string, verdict: 'person' | 'pet' | 'not_person' | 'unsure'): void {+ this.db.applyPersonCheck(this.userKey, personId, verdict);+ }+getPersonMemories(personId: string, limit: number = 50): UserMemoryRecord[] {- this.ensurePersonsBackfilled();- const rows = this.db.getMemoriesForPerson(this.userKey, personId, limit);- return rows.map(row => this.toRecord(row));+ this.indexNewBeliefs();+ const live = this.db.getBeliefIdsForPerson(personId, limit)+ .map((id) => this.beliefs.get(id))+ .filter((b): b is NonNullable<typeof b> => Boolean(b))+ .map((b) => this.toBeliefRecord(b));+ const legacy = this.db.getMemoriesForPerson(this.userKey, personId, limit).map(row => this.toRecord(row));+ return [...live, ...legacy].slice(0, limit);}+ /** True while persons are rebuilt from old memories: those never queue model checks. */+ private rebuilding = false;+rebuildPersonsFromMemory(): number {this.db.clearUserPersonGraph(this.userKey);const rows = this.db.getRelationshipMemoryRows(this.userKey);- for (const row of rows) {- this.indexPersonsForMemoryRow(row);+ this.db.clearAllBeliefPersons(this.userKey);+ this.rebuilding = true;+ try {+ for (const row of rows) {+ this.indexPersonsForMemoryRow(row);+ }+ // The live brain: every current belief, as of now.+ const cursor = Date.now();+ for (const b of this.db.beliefsSince(this.userKey, 0, 100_000)) this.indexPersonsForBelief(b);+ this.db.setMeta(`${this.userKey}:persons_belief_cursor`, String(cursor));+ } finally {+ this.rebuilding = false;}this.db.deleteOrphanPersons(this.userKey);this.db.setMeta(`${this.userKey}:persons_backfilled`, '1');@@ -440,6 +504,10 @@ export class UserMemoryStore {description: row.description,confidence: row.confidence,memoryCount: row.memory_count,+ kind: row.kind ?? 'unverified',+ verifiedBy: row.verified_by ?? null,+ meta: parseMeta(row.meta),+ ownerEdited: row.owner_edited === 1,firstSeenAt: row.first_seen_at,lastSeenAt: row.last_seen_at,createdAt: row.created_at,@@ -447,6 +515,49 @@ export class UserMemoryStore {};}+ /**+ * People in beliefs created since the last pass. These are NEW mentions, so+ * new people they create are queued for a check. Cheap when nothing is new.+ */+ indexNewBeliefs(): number {+ this.ensurePersonsBackfilled();+ const since = Number(this.db.getMeta(`${this.userKey}:persons_belief_cursor`) ?? '0') || 0;+ const fresh = this.db.beliefsSince(this.userKey, since, 200);+ for (const b of fresh) this.indexPersonsForBelief(b);+ if (fresh.length) this.db.setMeta(`${this.userKey}:persons_belief_cursor`, String(fresh[fresh.length - 1].created_at));+ return fresh.length;+ }++ private indexPersonsForBelief(b: { id: string; statement: string; detail: string | null; kind: string; confidence: number }): void {+ const text = `${b.statement} ${b.detail ?? ''}`.trim();+ if (!text) return;+ this.db.clearBeliefPersons(b.id);+ const queueCheck = this.rebuilding ? null : { context: text };+ const seen = new Set<string>();+ const link = (name: string, relation: string | null, role: string) => {+ const person = this.db.upsertPerson({ userKey: this.userKey, name, relationshipToUser: relation, confidence: b.confidence, queueCheck });+ if (!person || seen.has(person.id)) return;+ seen.add(person.id);+ this.db.addPersonAlias(person.id, name, 'memory');+ this.db.linkBeliefPerson(b.id, person.id, role, b.confidence);+ };+ for (const m of extractUserRelationshipMentions(text)) link(m.name, m.relation, 'relationship');+ // New people come only from beliefs about people; other beliefs link to people already known.+ if (b.kind === 'relationship' || b.kind === 'episode') {+ // A belief about a relationship is about people: a name may open the sentence there+ // ("Shehzen visited"); new names from it are checked by the model anyway.+ for (const name of extractHumanNames(text, b.kind === 'relationship')) link(name, b.kind === 'relationship' ? 'known' : null, 'mention');+ }+ // Known people mentioned by name or alias.+ for (const person of this.db.listPersons(this.userKey, '', 300)) {+ if (seen.has(person.id)) continue;+ if (mentionsPerson(text, person.display_name) || mentionsPerson(text, person.canonical_name)) {+ seen.add(person.id);+ this.db.linkBeliefPerson(b.id, person.id, 'interaction', b.confidence);+ }+ }+ }+private indexPersonsForMemory(memory: UserMemoryRecord): void {const row = this.db.getById(memory.id);if (row) this.indexPersonsForMemoryRow(row);@@ -471,7 +582,9 @@ export class UserMemoryStore {name: mention.name,relationshipToUser: mention.relation,confidence: memory.confidence,+ queueCheck: this.rebuilding ? null : { context: text },});+ if (!person) continue;this.db.addPersonAlias(person.id, mention.name, 'memory');this.db.linkMemoryPerson(memory.id, person.id, 'relationship', memory.confidence);}@@ -484,7 +597,9 @@ export class UserMemoryStore {name,relationshipToUser: 'known',confidence: memory.confidence,+ queueCheck: this.rebuilding ? null : { context: text },});+ if (!person) continue;this.db.addPersonAlias(person.id, name, 'memory');this.db.linkMemoryPerson(memory.id, person.id, 'relationship', memory.confidence);}@@ -500,7 +615,9 @@ export class UserMemoryStore {name,relationshipToUser: 'known',confidence: memory.confidence,+ queueCheck: this.rebuilding ? null : { context: text },});+ if (!person) continue;this.db.addPersonAlias(person.id, name, 'memory');this.db.linkMemoryPerson(memory.id, person.id, 'mention', memory.confidence);}@@ -608,6 +725,27 @@ const NON_PERSON_TERMS = new Set(['November', 'December', 'Mercury', 'Openai', 'Anthropic', 'Kashmir', 'Article', 'Covid',]);+/**+ * Words that are never (part of) a person's name: pronouns, determiners,+ * function words, common verbs and nouns, and software/product vocabulary.+ * Any token from this set rejects the whole candidate ("Brain Graph",+ * "System Fixes User", "Married", "During", "She").+ */+const NON_NAME_TOKENS = new Set([+ // pronouns, determiners, function words+ 'user', 'users', 'i', 'me', 'my', 'mine', 'you', 'your', 'yours', 'he', 'him', 'his', 'she', 'her', 'hers', 'it', 'its', 'we', 'us', 'our', 'they', 'them', 'their',+ 'a', 'an', 'the', 'this', 'that', 'these', 'those', 'there', 'here', 'what', 'which', 'who', 'whom', 'whose', 'when', 'where', 'why', 'how',+ 'and', 'or', 'but', 'if', 'then', 'so', 'because', 'while', 'during', 'after', 'before', 'since', 'until', 'about', 'with', 'without', 'from', 'into', 'onto', 'for', 'of', 'on', 'in', 'at', 'by', 'to', 'as', 'also', 'just', 'only', 'very', 'not', 'no', 'yes', 'all', 'any', 'some', 'each', 'every', 'both', 'more', 'most', 'other', 'another', 'such',+ // common verbs / states that start sentences+ 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'has', 'have', 'had', 'do', 'does', 'did', 'can', 'could', 'will', 'would', 'should', 'may', 'might', 'must',+ 'task', 'tasks', 'node', 'active', 'full', 'three', 'two', 'one', 'four', 'five', 'recent', 'card', 'cards', 'vulnerabilities', 'downloads', 'official', 'account', 'developing', 'email', 'jira', 'creating', 'combinator', 'console', 'status', 'ready', 'completed', 'application', 'current', 'multiple', 'part', 'colab', 'includes', 'fork', 'mentioned', 'manages', 'requested', 'form', 'context', 'assigned', 'temp', 'issue', 'issues', 'next', 'real', 'progress', 'write', 'main', 'sub', 'setting', 'successfully', 'maintainers', 'new', 'old', 'first', 'last', 'daily', 'weekly', 'india', 'pakistan', 'search', 'checker', 'oct', 'nov', 'dec', 'jan', 'feb', 'mar', 'apr', 'jun', 'jul', 'aug', 'sep',+ 'married', 'working', 'works', 'worked', 'building', 'built', 'using', 'used', 'uses', 'wants', 'wanted', 'likes', 'liked', 'prefers', 'preferred', 'asked', 'asks', 'said', 'says', 'told', 'needs', 'needed', 'started', 'finished', 'created', 'updated', 'fixed', 'fixes', 'added', 'removed', 'please', 'thanks', 'thank',+ // roles and generic nouns+ 'assistant', 'agent', 'agents', 'bot', 'bots', 'model', 'models', 'owner', 'admin', 'team', 'company', 'project', 'projects', 'product', 'products', 'customer', 'client', 'friend', 'friends', 'family', 'wife', 'husband', 'partner', 'mother', 'father', 'son', 'daughter', 'brother', 'sister',+ // software and product vocabulary+ 'app', 'apps', 'web', 'website', 'site', 'page', 'interface', 'ui', 'ux', 'api', 'server', 'system', 'systems', 'graph', 'brain', 'memory', 'memories', 'animation', 'dashboard', 'desktop', 'mobile', 'code', 'repo', 'stack', 'cloud', 'plugin', 'plugins', 'skill', 'skills', 'chat', 'session', 'sessions', 'file', 'files', 'folder', 'data', 'database', 'feature', 'features', 'bug', 'bugs', 'fix', 'release', 'version', 'build', 'test', 'tests', 'error', 'errors', 'mode', 'settings', 'config', 'github', 'google', 'youtube', 'whatsapp', 'telegram', 'slack', 'discord', 'twitter', 'linkedin', 'battlefield', 'prime', 'architect',+]);+interface UserRelationMention {name: string;relation: string;@@ -678,13 +816,30 @@ function extractUserRelationshipMentions(text: string): UserRelationMention[] {return [...mentions.values()];}-function extractHumanNames(segment: string): string[] {+function extractHumanNames(segment: string, allowSentenceStart = false): string[] {const found = new Set<string>();const nameRegex = /\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+){0,2})\b/g;+ // Words capitalised somewhere OTHER than the start of a sentence: a+ // sentence-initial "Task" or "Active" is just English, not a name.+ const midSentence = new Set<string>();+ const firstWords = new Set<string>();let match: RegExpExecArray | null;+ while ((match = nameRegex.exec(segment)) !== null) {+ const before = segment.slice(0, match.index);+ const atStart = /(^|[.!?:;\n•\-–—(\[]\s*)$/.test(before);+ const first = match[1].split(' ')[0];+ if (atStart) firstWords.add(first);+ else midSentence.add(first);+ }+ nameRegex.lastIndex = 0;while ((match = nameRegex.exec(segment)) !== null) {const name = match[1].trim();- if (isLikelyHumanName(name)) found.add(name);+ if (!isLikelyHumanName(name)) continue;+ const before = segment.slice(0, match.index);+ const atStart = /(^|[.!?:;\n•\-–—(\[]\s*)$/.test(before);+ const single = !name.includes(' ');+ if (!allowSentenceStart && atStart && single && !midSentence.has(name)) continue;+ found.add(name);}return [...found.values()];}@@ -693,6 +848,7 @@ function isLikelyHumanName(name: string): boolean {if (!name || name.length < 2 || name.length > 48) return false;if (NON_PERSON_TERMS.has(name)) return false;const parts = name.split(' ').filter(Boolean);+ if (parts.some((p) => NON_NAME_TOKENS.has(p.toLowerCase()))) return false;if (parts.length === 1 && parts[0].length < 3) return false;return parts.every(part => /^[A-Z][a-z]+$/.test(part));}@@ -742,3 +898,14 @@ function typeToKinds(type: UserMemoryType): BeliefKind[] {default: return [type];}}++export { isLikelyHumanName };++function parseMeta(raw: string | undefined): Record<string, unknown> {+ try {+ const v = JSON.parse(raw ?? '{}');+ return v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : {};+ } catch {+ return {};+ }+}diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsindex 0c03d08a..7f3f4e25 100644--- a/src/web/api-contract.ts+++ b/src/web/api-contract.ts@@ -36,6 +36,7 @@ export const API_FEATURES: readonly string[] = Object.freeze(['chat.uploads', // attachments on messages + GET /api/chat/uploads/:month/:file'voice', // /api/voice, /api/voice/events, /api/voice/control (Optimus)'usage.history', // GET /api/usage/history?days= — tokens per local day+ 'brain.people', // PATCH/merge persons, person checks, GET /api/brain/graph/v2]);export interface ApiContractInfo {diff --git a/src/web/api/brain.ts b/src/web/api/brain.tsindex 2ea176c1..9b328191 100644--- a/src/web/api/brain.ts+++ b/src/web/api/brain.ts@@ -1,4 +1,5 @@import { Hono } from 'hono';+import type { PersonVerifier } from '../../memory/person-verifier.js';import { loadConfig, getMemoryDir, saveConfig } from '../../utils/config.js';import { isBetterSqlite3Available } from '../../memory/second-brain-db.js';import { UserMemoryStore } from '../../memory/user-memory.js';@@ -14,6 +15,11 @@ export function setUserMemory(mem: UserMemoryStore | null): void {userMemory = mem;}+let personVerifier: PersonVerifier | null = null;+export function setPersonVerifier(v: PersonVerifier | null): void {+ personVerifier = v;+}+function ensureMemory(): UserMemoryStore | null {if (userMemory) return userMemory;@@ -61,6 +67,10 @@ function personToJson(p: any) {traits: p.traits ?? [],confidence: p.confidence,memoryCount: p.memoryCount,+ kind: p.kind ?? 'unverified',+ verifiedBy: p.verifiedBy ?? null,+ meta: p.meta ?? {},+ ownerEdited: p.ownerEdited === true,firstSeenAt: p.firstSeenAt,lastSeenAt: p.lastSeenAt,createdAt: p.createdAt,@@ -205,10 +215,95 @@ brain.get('/api/brain/persons', async (c) => {if (!mem) return c.json({ persons: [], total: 0, available: false, error: SQLITE_DEPENDENCY_ERROR }, 503);const q = c.req.query('q') || '';const limit = Math.min(parseInt(c.req.query('limit') || '100'), 200);- const persons = mem.listPersons(q, limit);+ const kinds = (c.req.query('kind') || '').split(',').map((k) => k.trim()).filter(Boolean);+ const showRejected = c.req.query('rejected') === '1';+ const persons = mem.listPersons(q, limit)+ .filter((p) => showRejected || p.verifiedBy !== 'model-rejected')+ .filter((p) => kinds.length === 0 || kinds.includes(p.kind));return c.json({ persons: persons.map(personToJson), total: persons.length, available: true });});+// ── People: curation, checks (registered before /:id so the paths win) ────++const PERSON_KINDS = ['person', 'pet', 'unverified'] as const;+const META_KEYS = ['phone', 'email', 'birthday', 'location', 'company', 'role', 'notes', 'links', 'avatarColor'] as const;++function cleanMeta(input: unknown): Record<string, unknown> | undefined {+ if (input === undefined) return undefined;+ if (!input || typeof input !== 'object' || Array.isArray(input)) return {};+ const out: Record<string, unknown> = {};+ for (const key of META_KEYS) {+ const v = (input as Record<string, unknown>)[key];+ if (v === undefined || v === null || v === '') continue;+ if (key === 'links') {+ if (Array.isArray(v)) out.links = v.filter((l): l is string => typeof l === 'string').map((l) => l.trim().slice(0, 300)).filter(Boolean).slice(0, 20);+ continue;+ }+ if (typeof v === 'string') out[key] = v.trim().slice(0, key === 'notes' ? 4000 : 200);+ }+ return out;+}++brain.get('/api/brain/persons/checks', (c) => {+ const status = personVerifier?.status();+ const mem = ensureMemory();+ return c.json(status ?? { enabled: false, pending: mem ? mem.countPersonChecks() : 0, callsToday: 0, dailyCap: 0, lastRunAt: null, lastError: null, nextRunAt: null, checked: 0 });+});++/** Owner opt-in: queue the people already in the brain for the same slow, capped check. */+brain.post('/api/brain/persons/checks/queue-existing', (c) => {+ const mem = ensureMemory();+ if (!mem) return c.json({ error: SQLITE_DEPENDENCY_ERROR, available: false }, 503);+ const queued = mem.queueExistingPersonChecks();+ return c.json({ queued, status: personVerifier?.status() ?? null });+});++brain.post('/api/brain/persons/checks/run', async (c) => {+ if (!personVerifier) return c.json({ error: 'Person checks run in the process that owns the runtime' }, 409);+ const checked = await personVerifier.runOnce();+ return c.json({ checked, status: personVerifier.status() });+});++brain.patch('/api/brain/persons/:id', async (c) => {+ const mem = ensureMemory();+ if (!mem) return c.json({ error: SQLITE_DEPENDENCY_ERROR, available: false }, 503);+ const body = await c.req.json<Record<string, unknown>>().catch(() => ({} as Record<string, unknown>));+ const kind = body.kind as string | undefined;+ if (kind !== undefined && kind !== 'not_person' && !(PERSON_KINDS as readonly string[]).includes(kind)) return c.json({ error: 'kind must be person, pet, unverified or not_person' }, 400);+ if (kind === 'not_person') {+ return mem.markNotPerson(c.req.param('id')) ? c.json({ success: true, removed: true }) : c.json({ error: 'Person not found' }, 404);+ }+ const str = (v: unknown, max: number) => (typeof v === 'string' ? v.trim().slice(0, max) : undefined);+ const updated = mem.updatePerson(c.req.param('id'), {+ displayName: str(body.name, 80),+ relationship: body.relationship === null ? null : str(body.relationship, 60),+ description: body.summary === null ? null : str(body.summary, 2000),+ kind: kind as 'person' | 'pet' | 'unverified' | undefined,+ meta: cleanMeta(body.meta),+ });+ if (!updated) return c.json({ error: 'Person not found' }, 404);+ return c.json({ person: personToJson(updated) });+});++brain.post('/api/brain/persons/:id/merge', async (c) => {+ const mem = ensureMemory();+ if (!mem) return c.json({ error: SQLITE_DEPENDENCY_ERROR, available: false }, 503);+ const body = await c.req.json<{ into?: unknown }>().catch(() => ({} as { into?: unknown }));+ if (typeof body.into !== 'string' || !body.into) return c.json({ error: 'into (a person id) is required' }, 400);+ if (!mem.mergePersons(c.req.param('id'), body.into)) return c.json({ error: 'Could not merge (missing person or same person)' }, 404);+ const into = mem.getPerson(body.into);+ return c.json({ person: into ? personToJson(into) : null });+});++/** The brain as a graph of real links: memories, people, who appears where, who relates to whom. */+brain.get('/api/brain/graph/v2', (c) => {+ const mem = ensureMemory();+ if (!mem) return c.json({ available: false, error: SQLITE_DEPENDENCY_ERROR }, 503);+ const parsed = parseInt(c.req.query('memories') || '400', 10);+ const g = mem.personGraph(Number.isFinite(parsed) ? parsed : 400);+ return c.json({ ...g, available: true });+});+brain.get('/api/brain/persons/:id', async (c) => {const mem = ensureMemory();if (!mem) return c.json({ error: SQLITE_DEPENDENCY_ERROR, available: false }, 503);