Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(brain): people need recurrence, a relationship, and a score
Salman Qureshi04f638e97c2b
diff --git a/src/memory/person-curation.test.ts b/src/memory/person-curation.test.tsindex c0a2f7b7..ccb28913 100644--- a/src/memory/person-curation.test.ts+++ b/src/memory/person-curation.test.ts@@ -19,6 +19,7 @@ function createStore(): UserMemoryStore {tempDirs.push(dir);const config = getDefaultConfig();config.memory.secondBrain = { enabled: true };+ config.identity.owner = 'Test Owner';return new UserMemoryStore(config, 'user:owner', join(dir, 'second-brain', 'second-brain.db'));}@@ -83,13 +84,15 @@ describe.skipIf(!sqliteAvailable)('people curation', () => {expect(store.listPersons('Tesla', 10)).toHaveLength(0);});- it('new names are queued for a check; rebuilds of old memories are not', () => {+ it('a name is checked only when it recurs; one-offs and rebuilds cost nothing', () => {const store = createStore();remember(store, 'Zayd started school.');store.listPersons('', 10); // first use: the backfill indexes what already exists, uncheckedexpect(store.countPersonChecks()).toBe(0);remember(store, 'Shehzen visited yesterday.');- expect(store.countPersonChecks()).toBe(1);+ expect(store.countPersonChecks()).toBe(0); // seen once: no tokens spent+ remember(store, 'Shehzen brought biryani for dinner.');+ expect(store.countPersonChecks()).toBe(1); // recurring: worth one checkconst [item] = store.pendingPersonChecks(10);store.applyPersonCheck(item.person_id, 'person');expect(store.countPersonChecks()).toBe(0);@@ -98,12 +101,48 @@ describe.skipIf(!sqliteAvailable)('people curation', () => {expect(store.countPersonChecks()).toBe(0);});- it('the graph has only real links', () => {+ it('one mention makes a shadow; a recurring one makes someone known, with real links only', () => {const store = createStore();remember(store, 'My wife Heer and my son Zayd went to the park.');+ expect(store.personGraph(100).persons).toEqual([]);+ const shadows = store.personGraph(100, { shadows: true });+ expect(shadows.persons.map((p) => `${p.name}:${p.tier}`).sort()).toEqual(['Heer:shadow', 'Zayd:shadow']);++ remember(store, 'Heer and Zayd baked a cake for my birthday.');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);+ expect(g.persons.every((p) => p.tier === 'known')).toBe(true);+ expect(g.memoryPersons.length).toBe(4);+ expect(g.memories.length).toBe(2);+ const heer = store.listPersons('Heer', 5)[0];+ expect(heer.relationshipToUser).toBe('wife');+ expect(store.listPersons('Zayd', 5)[0].relationshipToUser).toBe('son');+ });++ it('the owner is never a person', () => {+ const store = createStore();+ remember(store, 'Test Owner married Heer in 2019. Test and Heer live in Srinagar.');+ remember(store, "Heer is Test's wife.");+ expect(store.listPersons('', 50).map((p) => p.name)).not.toContain('Test');+ expect(store.listPersons('', 50).map((p) => p.name)).not.toContain('Test Owner');+ });++ it('two spellings in one note become one person', () => {+ const store = createStore();+ remember(store, "Zaid is the user's friend from college.");+ remember(store, "Zayd is the user's friend who loves cricket.");+ expect(store.listPersons('', 50).filter((p) => /Za[iy]d/.test(p.name))).toHaveLength(2);+ remember(store, 'Zaid (also Zayd) dislikes long meetings.');+ const left = store.listPersons('', 50).filter((p) => /Za[iy]d/.test(p.name));+ expect(left).toHaveLength(1);+ expect(left[0].memoryCount).toBe(3);+ });++ it('a one-to-one relation stays with its first holder unless the owner moves it', () => {+ const store = createStore();+ remember(store, "Heer is the user's wife.");+ remember(store, "Sara is the user's wife.");+ expect(store.listPersons('Heer', 5)[0].relationshipToUser).toBe('wife');+ expect(store.listPersons('Sara', 5)[0].relationshipToUser).toBe('known');});});diff --git a/src/memory/person-extract.test.ts b/src/memory/person-extract.test.tsnew file mode 100644index 00000000..ce5797d7--- /dev/null+++ b/src/memory/person-extract.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest';+import { extractAliases, extractOwnerRelations, extractPersonLinks, isOwnerName, ownerNameSet, stripAliasNotes } from './person-extract.js';++const owner = ownerNameSet('Salman');+// Stand-in for the store's name finder: capitalised words that are not common English.+const names = (s: string) => (s.match(/\b[A-Z][a-z]+\b/g) ?? []).filter((n) => !['User', 'The', 'My', 'MTech', 'Married'].includes(n));+const isName = (n: string) => /^[A-Z][a-z]+$/.test(n);+const rel = (t: string, social = true) => extractOwnerRelations(t, owner, names, { social }).map((r) => `${r.name}:${r.relation}`).sort();++describe('people from real memory phrasing', () => {+ it('knows the owner is not a person', () => {+ expect(isOwnerName('Salman', owner)).toBe(true);+ expect(isOwnerName('user', owner)).toBe(true);+ expect(isOwnerName('Heer', owner)).toBe(false);+ expect(rel('Salman is the user interacting with the assistant.')).toEqual([]);+ });++ it('reads a relationship to the owner in every common form', () => {+ expect(rel("User's wife is Heer")).toEqual(['Heer:wife']);+ expect(rel('Heer is my wife.')).toEqual(['Heer:wife']);+ expect(rel("Heer is the user's wife, married since 2019.")).toEqual(['Heer:wife']);+ expect(rel("Heer is Salman's wife, married since 2019")).toEqual(['Heer:wife']);+ expect(rel("User's partner Heer has been with them through major life events since 2019.")).toEqual(['Heer:partner']);+ expect(rel("Zayd and Shehzen are Salman's MTech friends")).toEqual(['Shehzen:friend', 'Zayd:friend']);+ expect(rel("Shehzen is the user's friend")).toEqual(['Shehzen:friend']);+ expect(rel("Zaid (Zayd) is user's MTech friend who hates Shehzen, another MTech friend")).toEqual(['Zaid:friend']);+ expect(rel('Zaid (Zayd) dislikes Shehzen, a friend of Salman from MTech days')).toEqual(['Shehzen:friend']);+ expect(rel("Shazain is a colleague/co-worker in user's office")).toEqual(['Shazain:colleague']);+ });++ it('reads marriage as a spouse', () => {+ expect(rel('Salman married Heer on October 9, 2025.')).toEqual(['Heer:spouse']);+ expect(rel('User is married to someone named Heer.')).toEqual(['Heer:spouse']);+ expect(rel('Married to Heer since 2019, with major life events together.')).toEqual(['Heer:spouse']);+ });++ it('keeps son and daughter apart instead of lumping them as family', () => {+ expect(rel('My son Ayaan started school')).toEqual(['Ayaan:son']);+ expect(rel('Zoya is my daughter')).toEqual(['Zoya:daughter']);+ });++ it('needs "my/user\'s" outside relationship beliefs', () => {+ expect(rel('Castor is a client tool for casting video', false)).toEqual([]);+ });++ it('finds aliases and reads past them', () => {+ expect(extractAliases('Zaid (Zayd) dislikes Shehzen')).toEqual([['Zaid', 'Zayd']]);+ expect(extractAliases('Shehzen (also spelled Shezan) is a friend')).toEqual([['Shehzen', 'Shezan']]);+ expect(extractAliases('Zaid (also Zayd) is close to the user')).toEqual([['Zaid', 'Zayd']]);+ expect(stripAliasNotes('Zaid (Zayd) is user\'s friend')).toBe("Zaid is user's friend");+ });++ it('finds relationships between two people, never with the owner', () => {+ expect(extractPersonLinks('Zaid (Zayd) dislikes Shehzen, a friend of Salman', owner, isName)).toEqual([{ a: 'Zaid', b: 'Shehzen', type: 'dislikes' }]);+ expect(extractPersonLinks("Zaid is user's MTech friend who hates Shehzen", owner, isName)).toEqual([]);+ expect(extractPersonLinks('Ali is Sara\'s brother', owner, isName)).toEqual([{ a: 'Ali', b: 'Sara', type: 'brother' }]);+ expect(extractPersonLinks('Salman dislikes Mondays', owner, isName)).toEqual([]);+ });+});diff --git a/src/memory/person-extract.ts b/src/memory/person-extract.tsnew file mode 100644index 00000000..36442a6c--- /dev/null+++ b/src/memory/person-extract.ts@@ -0,0 +1,158 @@+/**+ * Reading people out of what Mercury learned, the way memories are actually+ * phrased ("User's wife is Heer", "Zayd and Shehzen are Salman's MTech+ * friends", "Zaid (also Zayd) dislikes Shehzen", "Salman married Heer").+ *+ * Pure functions; the store decides what to keep (person-standing.ts).+ * The owner is never a person here: their own names refer to "you".+ */++import { normalizeRelationship, relationWords } from './person-standing.js';++const NAME = '[A-Z][a-z]+(?:\\s+[A-Z][a-z]+){0,3}';+const NAME_LIST = `${NAME}(?:\\s*(?:,\\s*(?:and\\s+)?|\\s+and\\s+|\\s*&\\s*)${NAME})*`;+/** Up to two describing words before the role: "MTech friend", "best friend", "older brother". */+const MOD = '(?:[A-Za-z][A-Za-z-]*\\s+){0,2}?';++function escape(s: string): string {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++/** "wife" → "[Ww]ife": roles match at either case, names still need a capital. */+function caseless(word: string): string {+ const e = escape(word);+ const first = word[0];+ return /[a-z]/i.test(first) ? `[${first.toLowerCase()}${first.toUpperCase()}]${e.slice(1)}` : e;+}++const ROLE = relationWords().map(caseless).join('|');++/** Every way the owner is named: "Salman Qureshi" → {"salman qureshi", "salman"}. */+export function ownerNameSet(owner: string | null | undefined): Set<string> {+ const out = new Set<string>(['user', 'the user']);+ const full = (owner ?? '').trim().toLowerCase().replace(/\s+/g, ' ');+ if (full) {+ out.add(full);+ out.add(full.split(' ')[0]);+ }+ return out;+}++/** The owner by any of their names, including longer forms ("Salman Qureshi" when the owner is "Salman"). */+export function isOwnerName(name: string, owner: Set<string>): boolean {+ const n = name.trim().toLowerCase().replace(/\s+/g, ' ');+ if (owner.has(n)) return true;+ return owner.has(n.split(' ')[0]);+}++function ownerAlternation(owner: Set<string>): string {+ const names = [...owner].filter((n) => n !== 'user' && n !== 'the user').sort((a, b) => b.length - a.length);+ return names.map((n) => n.split(' ').map((w) => caseless(w)).join('\\s+')).join('|');+}++/** "my", "our", "user's", "the user's", "Salman's". */+function subject(owner: Set<string>): string {+ const alts = ownerAlternation(owner);+ return `(?:[Mm]y|[Oo]ur|(?:[Tt]he\\s+)?[Uu]ser(?:'s|s'|’s)${alts ? `|(?:${alts})(?:'s|’s)` : ''})`;+}++/** Aliases written in the text: "Zaid (Zayd)", "Shehzen (also spelled Shezan)", "X, aka Y". */+export function extractAliases(text: string): Array<[string, string]> {+ const out: Array<[string, string]> = [];+ const patterns = [+ new RegExp(`(${NAME})\\s*\\(\\s*(?:(?:also\\s+(?:spelled|known\\s+as|called)\\s+)|also\\s+|aka\\s+|or\\s+)?(${NAME})\\s*\\)`, 'g'),+ new RegExp(`(${NAME}),?\\s+(?:also\\s+spelled|also\\s+known\\s+as|aka)\\s+(${NAME})`, 'g'),+ ];+ for (const re of patterns) {+ let m: RegExpExecArray | null;+ while ((m = re.exec(text)) !== null) if (m[1] !== m[2]) out.push([m[1], m[2]]);+ }+ return out;+}++/** Drop alias parentheticals so "Zaid (Zayd) is user's friend" reads as "Zaid is user's friend". */+export function stripAliasNotes(text: string): string {+ return text.replace(new RegExp(`\\s*\\(\\s*(?:(?:also\\s+(?:spelled|known\\s+as|called)\\s+)|also\\s+|aka\\s+|or\\s+)?${NAME}\\s*\\)`, 'g'), '');+}++export interface RelationMention { name: string; relation: string }++/**+ * People with a stated relationship to the owner. `social` allows the+ * looser "Shazain is a colleague" form (no "user's") inside beliefs that+ * are already about relationships.+ */+export function extractOwnerRelations(+ raw: string,+ owner: Set<string>,+ names: (segment: string) => string[],+ opts: { social?: boolean } = {},+): RelationMention[] {+ const text = stripAliasNotes(raw.replace(/[\r\n]+/g, ' '));+ const SUBJ = subject(owner);+ const ownerAlts = ownerAlternation(owner);+ const found = new Map<string, RelationMention>();+ const add = (segment: string, relation: string) => {+ const rel = normalizeRelationship(relation);+ if (!rel) return;+ for (const n of names(segment)) {+ if (isOwnerName(n, owner)) continue;+ const key = n.toLowerCase();+ if (!found.has(key)) found.set(key, { name: n, relation: rel });+ }+ };+ let m: RegExpExecArray | null;++ // "my wife Heer", "User's wife is Heer", "User's partner Heer has…", "Salman's friends Zayd and Shehzen"+ const roleFirst = new RegExp(`${SUBJ}\\s+${MOD}(${ROLE})\\s*(?:is|are|was|named|called|,|:)?\\s+(${NAME_LIST})`, 'g');+ while ((m = roleFirst.exec(text)) !== null) add(m[2], m[1]);++ // "Heer is my wife", "Zayd and Shehzen are Salman's MTech friends", "Shehzen is the user's friend"+ const nameFirst = new RegExp(`(${NAME_LIST})\\s+(?:is|are|was|were)\\s+(?:(?:the|a|an|one\\s+of)\\s+)?(${SUBJ}\\s+)?${MOD}(${ROLE})\\b`, 'g');+ while ((m = nameFirst.exec(text)) !== null) {+ if (m[2] || opts.social) add(m[1], m[3]);+ }++ // "Shehzen, a friend of Salman", "Zara, the sister of the user"+ const appositive = new RegExp(`(${NAME}),\\s+(?:a|an|the)\\s+${MOD}(${ROLE})\\s+of\\s+(?:the\\s+)?(?:[Uu]ser|mine|me${ownerAlts ? `|${ownerAlts}` : ''})\\b`, 'g');+ while ((m = appositive.exec(text)) !== null) add(m[1], m[2]);++ // Marriage: "Salman married Heer", "User is married to someone named Heer", "Married to Heer since 2019".+ const married = new RegExp(`(?:\\b(?:[Uu]ser|I${ownerAlts ? `|${ownerAlts}` : ''})\\s+(?:is\\s+|was\\s+|got\\s+)?|^\\s*)[Mm]arried\\s+(?:to\\s+)?(?:someone\\s+named\\s+)?(${NAME})`, 'g');+ while ((m = married.exec(text)) !== null) add(m[1], 'spouse');++ return [...found.values()];+}++export interface PersonLink { a: string; b: string; type: string }++const LINK_VERBS: Array<[RegExp, string]> = [+ [/^(?:dislikes|hates|can't stand)$/i, 'dislikes'],+ [/^(?:likes|loves|admires)$/i, 'likes'],+ [/^knows$/i, 'knows'],+ [/^reports\s+to$/i, 'reports to'],+ [/^works\s+with$/i, 'works with'],+ [/^is\s+jealous\s+of$/i, 'jealous of'],+ [/^is\s+married\s+to$/i, 'spouse'],+ [/^is\s+dating$/i, 'partner'],+ [/^is\s+friends\s+with$/i, 'friend'],+];++/** Relationships between two people (never the owner): "Zaid dislikes Shehzen", "Ali is Sara's brother". */+export function extractPersonLinks(raw: string, owner: Set<string>, isName: (n: string) => boolean): PersonLink[] {+ const text = stripAliasNotes(raw.replace(/[\r\n]+/g, ' '));+ const out: PersonLink[] = [];+ const ok = (n: string) => isName(n) && !isOwnerName(n, owner);+ let m: RegExpExecArray | null;+ const verbs = new RegExp(`(${NAME})\\s+(?:also\\s+|really\\s+)?(dislikes|hates|can't stand|likes|loves|admires|knows|reports\\s+to|works\\s+with|is\\s+jealous\\s+of|is\\s+married\\s+to|is\\s+dating|is\\s+friends\\s+with)\\s+(?:the\\s+)?(${NAME})`, 'g');+ while ((m = verbs.exec(text)) !== null) {+ const type = LINK_VERBS.find(([re]) => re.test(m![2].replace(/\s+/g, ' ')))?.[1];+ if (type && ok(m[1]) && ok(m[3]) && m[1] !== m[3]) out.push({ a: m[1], b: m[3], type });+ }+ const possessive = new RegExp(`(${NAME})\\s+is\\s+(${NAME})(?:'s|’s)\\s+${MOD}(${ROLE})\\b`, 'g');+ while ((m = possessive.exec(text)) !== null) {+ const rel = normalizeRelationship(m[3]);+ if (rel && ok(m[1]) && ok(m[2]) && m[1] !== m[2]) out.push({ a: m[1], b: m[2], type: rel });+ }+ return out;+}diff --git a/src/memory/person-standing.test.ts b/src/memory/person-standing.test.tsnew file mode 100644index 00000000..23ed5c9b--- /dev/null+++ b/src/memory/person-standing.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest';+import { capKnown, cardinalityOf, exclusiveGroup, normalizeRelationship, standingOf, type PersonEvidence } from './person-standing.js';++const base: PersonEvidence = { mentions: 0, socialMentions: 0, distinctDays: 0, relationship: null, personLinks: 0, kind: 'unverified', verifiedBy: null, ownerEdited: false };+const s = (e: Partial<PersonEvidence>) => standingOf({ ...base, ...e });++describe('person standing', () => {+ it('a single mention is never known', () => {+ expect(s({ mentions: 1, socialMentions: 1, relationship: 'wife' }).tier).toBe('shadow');+ expect(s({ mentions: 1 }).tier).toBe('faint');+ });++ it('recurrence plus a relationship makes someone known', () => {+ const st = s({ mentions: 3, socialMentions: 2, relationship: 'wife', distinctDays: 2 });+ expect(st.tier).toBe('known');+ expect(st.reasons).toContain('your wife');+ });++ it('frequent mentions without any relationship stay a shadow (a city, a product)', () => {+ const st = s({ mentions: 12, socialMentions: 3, distinctDays: 5 });+ expect(st.score).toBeGreaterThanOrEqual(55);+ expect(st.tier).toBe('shadow');+ expect(st.reasons).toContain('no relationship yet');+ });++ it('a link to another person counts as a tie', () => {+ expect(s({ mentions: 4, socialMentions: 2, personLinks: 1 }).tier).toBe('known');+ });++ it('owner decisions win; model rejections lose', () => {+ expect(s({ ownerEdited: true }).score).toBe(100);+ expect(s({ mentions: 9, relationship: 'friend', verifiedBy: 'model-rejected' }).score).toBe(0);+ });++ it('caps the known list, weakest first, never the owner-confirmed', () => {+ const people = Array.from({ length: 5 }, (_, i) => ({ id: `p${i}`, ownerEdited: i === 0, standing: { score: 60 + i, tier: 'known' as const, reasons: [] } }));+ people[0].standing = { score: 100, tier: 'known', reasons: [] };+ capKnown(people, 3);+ expect(people.filter((p) => p.standing.tier === 'known').map((p) => p.id).sort()).toEqual(['p0', 'p3', 'p4']);+ });+});++describe('relationships and cardinality', () => {+ it('normalises words and keeps specific family roles', () => {+ expect(normalizeRelationship('Mom')).toBe('mother');+ expect(normalizeRelationship('co-workers')).toBe('colleague');+ expect(normalizeRelationship('sons')).toBe('son');+ });++ it('knows one-to-one from one-to-many', () => {+ expect(cardinalityOf('wife')).toBe('one');+ expect(cardinalityOf('mother')).toBe('one');+ expect(cardinalityOf('friend')).toBe('many');+ expect(cardinalityOf('son')).toBe('many');+ expect(exclusiveGroup('husband')).toBe('spouse');+ expect(exclusiveGroup('partner')).toBe('spouse');+ expect(exclusiveGroup('friend')).toBeNull();+ });+});diff --git a/src/memory/person-standing.ts b/src/memory/person-standing.tsnew file mode 100644index 00000000..bced7349--- /dev/null+++ b/src/memory/person-standing.ts@@ -0,0 +1,200 @@+/**+ * Who counts as a person in the Second Brain, and how sure Mercury is.+ *+ * A name seen once is not a person yet. Standing is a 0-100 score built+ * from evidence: how often the name recurs, whether it appears in social+ * memories (relationships, episodes) or only in work/project notes,+ * whether it has a relationship to the owner or to someone else, and+ * whether the owner or the model confirmed it. The score sets a tier:+ *+ * known shown everywhere (graph, People). Needs a solid score AND at+ * least one tie: a relationship to you, a relationship to+ * another person, or a model-confirmed person or pet.+ * shadow kept, but dimmed and out of the way until more evidence+ * arrives or you confirm them.+ * faint one stray mention; listed only under "All".+ *+ * The number of known people is capped (KNOWN_CAP); past it, the lowest+ * scores fall back to shadow. Owner decisions always win.+ */++export type PersonTier = 'known' | 'shadow' | 'faint';++export interface PersonEvidence {+ /** Distinct memories and beliefs that mention the person. */+ mentions: number;+ /** Of those, how many are social (relationship / episode). */+ socialMentions: number;+ /** Distinct local days the mentions span. */+ distinctDays: number;+ /** Relationship to the owner, if any ("wife", "friend", "known" = none). */+ relationship: string | null;+ /** Relationships to other people. */+ personLinks: number;+ kind: string | null;+ verifiedBy: string | null;+ ownerEdited: boolean;+}++export interface PersonStanding {+ score: number;+ tier: PersonTier;+ /** Plain reasons, for the People screen ("4 mentions", "your wife"). */+ reasons: string[];+}++/** Most people keep about 150 stable relationships (Dunbar); past that the brain shows the strongest. */+export const KNOWN_CAP = 150;+export const KNOWN_MIN_SCORE = 55;+export const SHADOW_MIN_SCORE = 25;++export function standingOf(e: PersonEvidence): PersonStanding {+ const reasons: string[] = [];+ if (e.verifiedBy === 'model-rejected') return { score: 0, tier: 'faint', reasons: ['the model judged this is not a person'] };+ if (e.ownerEdited || e.verifiedBy === 'owner') {+ return { score: 100, tier: 'known', reasons: ['confirmed by you'] };+ }++ let score = 0;+ // Recurrence: the main signal. One mention is weak; repeated mentions add up, with diminishing returns.+ score += e.mentions <= 0 ? 0 : e.mentions === 1 ? 15 : e.mentions === 2 ? 32 : e.mentions === 3 ? 42 : e.mentions < 8 ? 50 : 56;+ if (e.mentions > 0) reasons.push(`${e.mentions} mention${e.mentions === 1 ? '' : 's'}`);+ if (e.socialMentions >= 2) { score += 18; reasons.push('in your relationships and moments'); }+ else if (e.socialMentions === 1) score += 8;+ const rel = specificRelationship(e.relationship);+ if (rel) { score += 25; reasons.push(`your ${rel}`); }+ if (e.personLinks > 0) { score += 10; reasons.push(`connected to ${e.personLinks} other${e.personLinks === 1 ? '' : 's'}`); }+ if (e.distinctDays >= 2) score += 5;+ if (e.verifiedBy === 'model' && (e.kind === 'person' || e.kind === 'pet')) { score += 15; reasons.push('checked by the model'); }+ score = Math.max(0, Math.min(99, Math.round(score)));++ // Known needs a real tie: a relationship to you, to someone else, or a confirmed person/pet.+ // Being mentioned often (a city, a product) is not enough on its own.+ const tied = !!rel || e.personLinks > 0 || (e.verifiedBy === 'model' && (e.kind === 'person' || e.kind === 'pet'));+ if (score >= KNOWN_MIN_SCORE && tied) return { score, tier: 'known', reasons };+ if (score >= SHADOW_MIN_SCORE) {+ if (!tied) reasons.push('no relationship yet');+ return { score, tier: 'shadow', reasons };+ }+ return { score, tier: 'faint', reasons: reasons.length ? reasons : ['seen once'] };+}++/** Apply the cap: past KNOWN_CAP known people, the weakest become shadows. Owner-confirmed people never move. */+export function capKnown<T extends { standing: PersonStanding; ownerEdited: boolean }>(people: T[], cap = KNOWN_CAP): T[] {+ const known = people.filter((p) => p.standing.tier === 'known' && !p.ownerEdited).sort((a, b) => b.standing.score - a.standing.score);+ const owner = people.filter((p) => p.standing.tier === 'known' && p.ownerEdited).length;+ const room = Math.max(0, cap - owner);+ for (const p of known.slice(room)) p.standing = { ...p.standing, tier: 'shadow', reasons: [...p.standing.reasons, 'past the limit of people shown'] };+ return people;+}++// ── Relationships and their cardinality ─────────────────────────────────++export type Cardinality = 'one' | 'many';++interface RelationSpec {+ /** Canonical label. */+ label: string;+ /** "one": you have at most one at a time (spouse, mother). "many": any number (friends, children). */+ cardinality: Cardinality;+ /** One-to-one relations in the same group exclude each other (wife / husband / spouse / partner). */+ group?: string;+}++const RELATIONS: Record<string, RelationSpec> = {+ wife: { label: 'wife', cardinality: 'one', group: 'spouse' },+ husband: { label: 'husband', cardinality: 'one', group: 'spouse' },+ spouse: { label: 'spouse', cardinality: 'one', group: 'spouse' },+ partner: { label: 'partner', cardinality: 'one', group: 'spouse' },+ fiance: { label: 'fiancé', cardinality: 'one', group: 'spouse' },+ fiancee: { label: 'fiancée', cardinality: 'one', group: 'spouse' },+ girlfriend: { label: 'girlfriend', cardinality: 'one', group: 'spouse' },+ boyfriend: { label: 'boyfriend', cardinality: 'one', group: 'spouse' },+ mother: { label: 'mother', cardinality: 'one', group: 'mother' },+ father: { label: 'father', cardinality: 'one', group: 'father' },+ son: { label: 'son', cardinality: 'many' },+ daughter: { label: 'daughter', cardinality: 'many' },+ child: { label: 'child', cardinality: 'many' },+ brother: { label: 'brother', cardinality: 'many' },+ sister: { label: 'sister', cardinality: 'many' },+ sibling: { label: 'sibling', cardinality: 'many' },+ cousin: { label: 'cousin', cardinality: 'many' },+ uncle: { label: 'uncle', cardinality: 'many' },+ aunt: { label: 'aunt', cardinality: 'many' },+ grandmother: { label: 'grandmother', cardinality: 'many' },+ grandfather: { label: 'grandfather', cardinality: 'many' },+ family: { label: 'family', cardinality: 'many' },+ friend: { label: 'friend', cardinality: 'many' },+ colleague: { label: 'colleague', cardinality: 'many' },+ cofounder: { label: 'co-founder', cardinality: 'many' },+ manager: { label: 'manager', cardinality: 'one', group: 'manager' },+ boss: { label: 'boss', cardinality: 'one', group: 'manager' },+ mentor: { label: 'mentor', cardinality: 'many' },+ mentee: { label: 'mentee', cardinality: 'many' },+ client: { label: 'client', cardinality: 'many' },+ neighbour: { label: 'neighbour', cardinality: 'many' },+ pet: { label: 'pet', cardinality: 'many' },+};++const ALIASES: Record<string, string> = {+ wives: 'wife', husbands: 'husband', mom: 'mother', mum: 'mother', mothers: 'mother', moms: 'mother', ammi: 'mother',+ dad: 'father', fathers: 'father', dads: 'father', abbu: 'father', papa: 'father',+ sons: 'son', daughters: 'daughter', children: 'child', kid: 'child', kids: 'child',+ brothers: 'brother', sisters: 'sister', siblings: 'sibling', cousins: 'cousin', uncles: 'uncle', aunts: 'aunt', aunty: 'aunt', auntie: 'aunt',+ grandma: 'grandmother', granny: 'grandmother', grandpa: 'grandfather',+ families: 'family', friends: 'friend', 'best friend': 'friend', bestie: 'friend',+ colleagues: 'colleague', coworker: 'colleague', coworkers: 'colleague', 'co-worker': 'colleague', 'co-workers': 'colleague',+ teammate: 'colleague', teammates: 'colleague', 'team member': 'colleague', developer: 'colleague', developers: 'colleague', cto: 'colleague', ceo: 'colleague',+ 'co-founder': 'cofounder', cofounders: 'cofounder', 'co-founders': 'cofounder',+ partners: 'partner', lover: 'partner', 'fiancé': 'fiance', 'fiancée': 'fiancee', neighbor: 'neighbour', neighbours: 'neighbour', neighbors: 'neighbour',+ clients: 'client', mentors: 'mentor', mentees: 'mentee', managers: 'manager',+};++/** "Mom" → "mother", "co-workers" → "colleague"; unknown words pass through lower-cased. */+export function normalizeRelationship(raw: string | null | undefined): string | null {+ if (!raw) return null;+ const k = raw.trim().toLowerCase().replace(/\s+/g, ' ');+ if (!k) return null;+ const key = ALIASES[k] ?? k;+ return RELATIONS[key]?.label ?? k;+}++/** The relation words the extractor looks for, longest first. */+export function relationWords(): string[] {+ return [...new Set([...Object.keys(RELATIONS), ...Object.keys(ALIASES)])].sort((a, b) => b.length - a.length);+}++export function relationSpec(relationship: string | null | undefined): RelationSpec | null {+ const n = normalizeRelationship(relationship);+ if (!n) return null;+ const key = Object.keys(RELATIONS).find((k) => RELATIONS[k].label === n);+ return key ? RELATIONS[key] : null;+}++export function cardinalityOf(relationship: string | null | undefined): Cardinality {+ return relationSpec(relationship)?.cardinality ?? 'many';+}++/** The exclusive group of a one-to-one relation ("spouse" for wife/husband/partner), or null. */+export function exclusiveGroup(relationship: string | null | undefined): string | null {+ const s = relationSpec(relationship);+ return s && s.cardinality === 'one' ? s.group ?? s.label : null;+}++/** A relationship worth showing, or null for none / the placeholder "known". */+export function specificRelationship(relationship: string | null | undefined): string | null {+ const n = normalizeRelationship(relationship);+ return n && n !== 'known' ? n : null;+}++/** For the edit form: every relation with its cardinality. */+export function relationCatalog(): Array<{ label: string; cardinality: Cardinality }> {+ const seen = new Set<string>();+ const out: Array<{ label: string; cardinality: Cardinality }> = [];+ for (const spec of Object.values(RELATIONS)) {+ if (seen.has(spec.label)) continue;+ seen.add(spec.label);+ out.push({ label: spec.label, cardinality: spec.cardinality });+ }+ return out;+}diff --git a/src/memory/second-brain-db.ts b/src/memory/second-brain-db.tsindex 930e395b..aa1864d5 100644--- a/src/memory/second-brain-db.ts+++ b/src/memory/second-brain-db.ts@@ -2,6 +2,7 @@ import { existsSync, mkdirSync } from 'node:fs';import { dirname } from 'node:path';import { logger } from '../utils/logger.js';import { isSqliteAvailable, openSqlite, type SqliteDatabase } from '../utils/sqlite-driver.js';+import { exclusiveGroup, normalizeRelationship } from './person-standing.js';/*** True when any SQLite engine is available (better-sqlite3, bun:sqlite or@@ -588,7 +589,11 @@ export class SecondBrainDB {confidence?: number;description?: string | null;personId?: string;- /** Queue a newly created person for a model check (new mentions only, never rebuilds). */+ /**+ * Context for a model check. A check is queued only when an unreviewed+ * name RECURS (its second sighting), never on first sight and never in+ * rebuilds: one-off names cost no tokens.+ */queueCheck?: { context: string } | null;}): PersonRow | null {const now = Date.now();@@ -618,7 +623,12 @@ export class SecondBrainDB {if (existing) {const confidence = Math.max(existing.confidence, params.confidence ?? existing.confidence);- const relationshipToUser = params.relationshipToUser ?? existing.relationship_to_user;+ // A plain mention ("known") never erases a real relationship ("wife").+ const incoming = this.allowedRelationship(params.userKey, existing.id, params.relationshipToUser);+ // A specific relationship already stored wins over a vaguer one ("wife" over "spouse").+ const current = existing.relationship_to_user;+ const currentSpecific = !!current && !['known', 'spouse', 'family'].includes(current);+ const relationshipToUser = incoming && incoming !== 'known' && !currentSpecific ? incoming : current ?? incoming;const description = params.description ?? existing.description;this.db.prepare(`UPDATE persons@@ -628,11 +638,16 @@ export class SecondBrainDB {const updated = this.getPersonById(existing.id);if (!updated) throw new Error('Failed to update person record');+ if (params.queueCheck && !updated.verified_by && (updated.kind ?? 'unverified') === 'unverified') {+ this.db.prepare('INSERT OR IGNORE INTO person_checks (person_id, user_key, name, context, queued_at) VALUES (?, ?, ?, ?, ?)')+ .run(updated.id, params.userKey, updated.display_name, params.queueCheck.context.slice(0, 400), now);+ }return updated;}const id = params.personId || `per_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;const confidence = params.confidence ?? 0.7;+ params = { ...params, relationshipToUser: this.allowedRelationship(params.userKey, id, params.relationshipToUser) ?? (params.relationshipToUser ? 'known' : null) };this.db.prepare(`INSERT INTO persons (id, user_key, canonical_name, display_name, relationship_to_user,@@ -654,13 +669,80 @@ 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;}+ /**+ * Cardinality: a one-to-one relation (wife, mother, manager…) belongs to one+ * person at a time. An extracted claim never takes it from someone who+ * already holds it; only the owner can move it (see moveExclusiveRelationship).+ * Returns the relationship to store, or null to keep what is there.+ */+ private allowedRelationship(userKey: string, personId: string, relationship: string | null | undefined): string | null {+ const rel = normalizeRelationship(relationship);+ if (!rel) return null;+ const group = exclusiveGroup(rel);+ if (!group) return rel;+ const holder = this.exclusiveHolder(userKey, group, personId);+ return holder ? null : rel;+ }++ /** Who holds a one-to-one relation group (spouse, mother…), other than `exceptId`. */+ exclusiveHolder(userKey: string, group: string, exceptId?: string): PersonRow | undefined {+ const rows = this.db.prepare(`SELECT * FROM persons WHERE user_key = ? AND relationship_to_user IS NOT NULL AND relationship_to_user != 'known' AND id != ?`)+ .all(userKey, exceptId ?? '') as PersonRow[];+ return rows.find((r) => exclusiveGroup(r.relationship_to_user) === group);+ }++ /** Owner moves a one-to-one relation: the previous holder becomes "known". */+ releaseExclusiveRelationship(userKey: string, group: string, exceptId: string): PersonRow | undefined {+ const holder = this.exclusiveHolder(userKey, group, exceptId);+ if (holder) this.db.prepare(`UPDATE persons SET relationship_to_user = 'known', updated_at = ? WHERE id = ?`).run(Date.now(), holder.id);+ return holder;+ }++ /** Find a person by name or alias without creating one. */+ resolvePersonId(userKey: string, name: string): string | null {+ const normalized = this.normalizePersonName(name);+ if (!normalized) return null;+ const direct = this.db.prepare('SELECT id FROM persons WHERE user_key = ? AND canonical_name = ? LIMIT 1').get(userKey, normalized) as { id: string } | undefined;+ if (direct) return direct.id;+ const alias = this.db.prepare('SELECT p.id FROM person_aliases a JOIN persons p ON p.id = a.person_id WHERE p.user_key = ? AND a.normalized_alias = ? LIMIT 1').get(userKey, normalized) as { id: string } | undefined;+ return alias?.id ?? null;+ }++ /**+ * The evidence behind each person, for standing (person-standing.ts):+ * mentions in live beliefs and the archive, how many are social, the days+ * they span, and links to other people. Grouped queries, one pass.+ */+ personEvidence(userKey: string): Array<{ id: string; relationship: string | null; kind: string | null; verified_by: string | null; owner_edited: number; mentions: number; social: number; days: number; plinks: number }> {+ return this.db.prepare(`+ WITH links AS (+ SELECT bp.person_id AS pid, b.kind AS kind, b.created_at AS ts FROM belief_persons bp+ JOIN beliefs b ON b.id = bp.belief_id AND b.status IN ('candidate','held','confirmed','contested')+ UNION ALL+ SELECT mp.person_id, m.type, m.created_at FROM memory_persons mp+ JOIN memories m ON m.id = mp.memory_id AND m.dismissed = 0+ ),+ agg AS (+ SELECT pid, COUNT(*) AS mentions, SUM(CASE WHEN kind IN ('relationship','episode') THEN 1 ELSE 0 END) AS social,+ COUNT(DISTINCT date(ts / 1000, 'unixepoch', 'localtime')) AS days+ FROM links GROUP BY pid+ ),+ rel AS (+ SELECT pid, COUNT(*) AS n FROM (+ SELECT source_person_id AS pid FROM person_relationships WHERE user_key = ?+ UNION ALL SELECT target_person_id FROM person_relationships WHERE user_key = ?+ ) GROUP BY pid+ )+ SELECT p.id, p.relationship_to_user AS relationship, p.kind, p.verified_by, p.owner_edited,+ COALESCE(agg.mentions, 0) AS mentions, COALESCE(agg.social, 0) AS social, COALESCE(agg.days, 0) AS days, COALESCE(rel.n, 0) AS plinks+ FROM persons p LEFT JOIN agg ON agg.pid = p.id LEFT JOIN rel ON rel.pid = p.id+ WHERE p.user_key = ?+ `).all(userKey, userKey, userKey) as Array<{ id: string; relationship: string | null; kind: string | null; verified_by: string | null; owner_edited: number; mentions: number; social: number; days: number; plinks: number }>;+ }+// ── People in beliefs (the live brain since the Owner Model) ─────────────linkBeliefPerson(beliefId: string, personId: string, role: string, confidence: number): void {@@ -697,7 +779,7 @@ export class SecondBrainDB {WHERE id = ?`).run(displayName,- fields.relationship !== undefined ? fields.relationship : row.relationship_to_user,+ fields.relationship !== undefined ? normalizeRelationship(fields.relationship) : row.relationship_to_user,fields.description !== undefined ? fields.description : row.description,kind,fields.kind !== undefined ? 'owner' : row.verified_by ?? null,@@ -725,7 +807,8 @@ export class SecondBrainDB {}/** Merge `fromId` into `intoId`: links, relationships and names move; `intoId` keeps its id. */- mergePersons(userKey: string, fromId: string, intoId: string): boolean {+ mergePersons(userKey: string, fromId: string, intoId: string, opts: { byOwner?: boolean } = {}): boolean {+ const byOwner = opts.byOwner ?? true;if (fromId === intoId) return false;const from = this.getPersonById(fromId);const into = this.getPersonById(intoId);@@ -743,12 +826,12 @@ export class SecondBrainDB {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');+ for (const a of aliases) this.addPersonAlias(intoId, a, byOwner ? 'owner' : 'memory');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);+ if (byOwner) this.db.prepare('UPDATE persons SET owner_edited = 1, updated_at = ? WHERE id = ?').run(now, intoId);});return true;}diff --git a/src/memory/user-memory.ts b/src/memory/user-memory.tsindex ac3eafd0..2f453f49 100644--- a/src/memory/user-memory.ts+++ b/src/memory/user-memory.ts@@ -6,6 +6,8 @@ import { looksLikeSecret } from '../learning/text.js';import { join } from 'node:path';import { copyFileSync, existsSync } from 'node:fs';import { logger } from '../utils/logger.js';+import { capKnown, standingOf, type PersonStanding, type PersonTier } from './person-standing.js';+import { extractAliases, extractOwnerRelations, extractPersonLinks, isOwnerName, ownerNameSet } from './person-extract.js';export type UserMemoryType =| 'identity'@@ -84,6 +86,8 @@ export interface UserPersonRecord {/** Contact card: phone, email, birthday, location, company, notes, links. */meta: Record<string, unknown>;ownerEdited: boolean;+ /** How sure Mercury is that this is someone in your life, and why (person-standing.ts). */+ standing?: PersonStanding;firstSeenAt: number;lastSeenAt: number;createdAt: number;@@ -91,7 +95,8 @@ export interface UserPersonRecord {}// 8: stricter name rules, owner overrides, model checks for new names, beliefs indexed.-const PERSON_INDEX_VERSION = '9';+// 10: owner is never a person, real relationship phrasing, aliases merged, person-to-person links, standing.+const PERSON_INDEX_VERSION = '10';export class UserMemoryStore {private db: SecondBrainDB;@@ -103,8 +108,12 @@ export class UserMemoryStore {/** What Mercury believes about this owner, with evidence (ADR-026). Shares the database. */readonly beliefs: BeliefStore;+ /** The owner's own names: never a person, always "you". */+ private ownerNames: Set<string>;+constructor(config: MercuryConfig, userKey: string = 'user:owner', dbPath?: string) {this.userKey = userKey;+ this.ownerNames = ownerNameSet(config.identity?.owner);this.consolidateThrottleMs = 5 * 60 * 1000;this.shareLearning = config.memory.collaborativeKnowledge?.shareLearning ?? false;const resolvedDbPath = dbPath ?? join(getMemoryDir(), 'second-brain', 'second-brain.db');@@ -207,17 +216,50 @@ export class UserMemoryStore {return this.beliefs.list({ kinds, limit: 500 }).map((b) => this.toBeliefRecord(b));}- listPersons(query?: string, limit: number = 100): UserPersonRecord[] {+ /**+ * People, each with its standing. `tier` narrows to known / shadow /+ * faint; omitted, everyone is returned (strongest first).+ */+ listPersons(query?: string, limit: number = 100, tier?: PersonTier): UserPersonRecord[] {this.indexNewBeliefs();- const rows = this.db.listPersons(this.userKey, query, limit);- return rows.map(row => this.toPersonRecord(row));+ const standings = this.standings();+ const rows = this.db.listPersons(this.userKey, query, 300);+ return rows+ .map((row) => ({ ...this.toPersonRecord(row), standing: standings.get(row.id) }))+ .filter((p) => !tier || p.standing?.tier === tier)+ .sort((a, b) => (b.standing?.score ?? 0) - (a.standing?.score ?? 0) || b.memoryCount - a.memoryCount)+ .slice(0, Math.max(1, Math.min(limit, 300)));}getPerson(personId: string): UserPersonRecord | null {this.ensurePersonsBackfilled();const row = this.db.getPersonWithCount(this.userKey, personId);if (!row) return null;- return this.toPersonRecord(row);+ return { ...this.toPersonRecord(row), standing: this.standings().get(personId) };+ }++ /** Standing for every person, with the known-people cap applied. */+ standings(): Map<string, PersonStanding> {+ const people = this.db.personEvidence(this.userKey).map((e) => ({+ id: e.id,+ ownerEdited: e.owner_edited === 1,+ standing: standingOf({+ mentions: e.mentions, socialMentions: e.social, distinctDays: e.days, relationship: e.relationship,+ personLinks: e.plinks, kind: e.kind, verifiedBy: e.verified_by, ownerEdited: e.owner_edited === 1,+ }),+ }));+ capKnown(people);+ return new Map(people.map((p) => [p.id, p.standing]));+ }++ /** The one-to-one relation holder (spouse, mother…) other than `exceptId`, for conflicts on edit. */+ exclusiveHolder(group: string, exceptId: string): UserPersonRecord | null {+ const row = this.db.exclusiveHolder(this.userKey, group, exceptId);+ return row ? this.getPerson(row.id) : null;+ }++ releaseExclusiveRelationship(group: string, exceptId: string): void {+ this.db.releaseExclusiveRelationship(this.userKey, group, exceptId);}// ── Owner curation of people (stable ids; rebuilds respect every decision) ──@@ -235,9 +277,24 @@ export class UserMemoryStore {return this.db.mergePersons(this.userKey, fromId, intoId);}- personGraph(maxMemories: number): PersonGraph {+ /**+ * The graph: known people (and shadows when asked), the memories, and the+ * real links between them. Each person carries its tier and score.+ */+ personGraph(maxMemories: number, opts: { shadows?: boolean } = {}): Omit<PersonGraph, 'persons'> & { persons: Array<PersonGraph['persons'][number] & { tier: PersonTier; score: number }> } {this.indexNewBeliefs();- return this.db.personGraph(this.userKey, maxMemories);+ const g = this.db.personGraph(this.userKey, maxMemories);+ const standings = this.standings();+ const persons = g.persons+ .map((p) => ({ ...p, tier: standings.get(p.id)?.tier ?? 'faint' as PersonTier, score: standings.get(p.id)?.score ?? 0 }))+ .filter((p) => p.tier === 'known' || (opts.shadows && p.tier === 'shadow'));+ const ids = new Set(persons.map((p) => p.id));+ return {+ persons,+ memories: g.memories,+ memoryPersons: g.memoryPersons.filter((l) => ids.has(l.personId)),+ relationships: g.relationships.filter((r) => ids.has(r.source) && ids.has(r.target)),+ };}pendingPersonChecks(limit: number) {@@ -534,14 +591,18 @@ export class UserMemoryStore {this.db.clearBeliefPersons(b.id);const queueCheck = this.rebuilding ? null : { context: text };const seen = new Set<string>();+ const social = b.kind === 'relationship' || b.kind === 'episode';+ // "Zaid (Zayd)": one person with two spellings, merged before anyone is linked.+ for (const [name, alias] of extractAliases(text)) this.absorbAlias(name, alias);const link = (name: string, relation: string | null, role: string) => {+ if (isOwnerName(name, this.ownerNames)) return;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');+ for (const m of extractOwnerRelations(text, this.ownerNames, (seg) => extractHumanNames(seg, true), { social })) 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@@ -556,6 +617,38 @@ export class UserMemoryStore {this.db.linkBeliefPerson(b.id, person.id, 'interaction', b.confidence);}}+ // Between people: "Zaid dislikes Shehzen", "Ali is Sara's brother".+ for (const l of extractPersonLinks(text, this.ownerNames, isLikelyHumanName)) {+ const a = this.db.resolvePersonId(this.userKey, l.a);+ const c = this.db.resolvePersonId(this.userKey, l.b);+ if (a && c && a !== c) this.db.upsertPersonRelationship({ userKey: this.userKey, sourcePersonId: a, targetPersonId: c, relationType: l.type, strength: b.confidence, evidenceMemoryId: null });+ // (evidence_memory_id references the legacy archive; beliefs are cleared by a full rebuild instead.)+ }+ }++ /**+ * Two spellings of one person ("Zaid (Zayd)"). The alias is recorded so+ * future mentions resolve; if both already exist as separate people, the+ * one with less evidence folds into the other. Not an owner decision: the+ * owner can still split or rename.+ */+ private absorbAlias(name: string, alias: string): void {+ if (isOwnerName(name, this.ownerNames) || isOwnerName(alias, this.ownerNames)) return;+ if (!isLikelyHumanName(name) || !isLikelyHumanName(alias)) return;+ const a = this.db.resolvePersonId(this.userKey, name);+ const b = this.db.resolvePersonId(this.userKey, alias);+ if (a && b && a !== b) {+ const rowA = this.db.getPersonById(a);+ const rowB = this.db.getPersonById(b);+ if (!rowA || !rowB || (rowA.owner_edited === 1 && rowB.owner_edited === 1)) return;+ const ev = new Map(this.db.personEvidence(this.userKey).map((e) => [e.id, e.mentions]));+ // Keep the owner-edited one, else the one with more evidence.+ const keepA = rowA.owner_edited === 1 || (rowB.owner_edited !== 1 && (ev.get(a) ?? 0) >= (ev.get(b) ?? 0));+ this.db.mergePersons(this.userKey, keepA ? b : a, keepA ? a : b, { byOwner: false });+ return;+ }+ if (a && !b) this.db.addPersonAlias(a, alias, 'memory');+ else if (b && !a) this.db.addPersonAlias(b, name, 'memory');}private indexPersonsForMemory(memory: UserMemoryRecord): void {@@ -574,9 +667,10 @@ export class UserMemoryStore {this.db.clearRelationshipsByMemory(memory.id);if (memory.type === 'relationship') {- const relationMentions = extractUserRelationshipMentions(text);+ const relationMentions = extractOwnerRelations(text, this.ownerNames, (seg) => extractHumanNames(seg, true), { social: true });if (relationMentions.length > 0) {for (const mention of relationMentions) {+ if (isOwnerName(mention.name, this.ownerNames)) continue;const person = this.db.upsertPerson({userKey: this.userKey,name: mention.name,@@ -592,6 +686,7 @@ export class UserMemoryStore {// Fallback: extract any capitalized names from relationship memoriesconst names = extractHumanNames(text);for (const name of names) {+ if (isOwnerName(name, this.ownerNames)) continue;const person = this.db.upsertPerson({userKey: this.userKey,name,@@ -610,6 +705,7 @@ export class UserMemoryStore {// For identity/project/episode: extract names and create/link personsconst names = extractHumanNames(text);for (const name of names) {+ if (isOwnerName(name, this.ownerNames)) continue;const person = this.db.upsertPerson({userKey: this.userKey,name,@@ -663,59 +759,6 @@ export class UserMemoryStore {}}-const USER_RELATION_ROLE_MAP: Record<string, string> = {- wife: 'wife',- wives: 'wife',- husband: 'husband',- husbands: 'husband',- mother: 'mother',- mothers: 'mother',- mom: 'mother',- moms: 'mother',- father: 'father',- fathers: 'father',- dad: 'father',- dads: 'father',- brother: 'family',- brothers: 'family',- sister: 'family',- sisters: 'family',- son: 'family',- sons: 'family',- daughter: 'family',- daughters: 'family',- family: 'family',- families: 'family',- cousin: 'family',- cousins: 'family',- friend: 'friend',- friends: 'friend',- colleague: 'colleague',- colleagues: 'colleague',- coworker: 'colleague',- coworkers: 'colleague',- teammate: 'colleague',- teammates: 'colleague',- partner: 'partner',- partners: 'partner',- developer: 'colleague',- developers: 'colleague',- 'co-founder': 'partner',- cofounder: 'partner',- cofounders: 'partner',- boss: 'colleague',- manager: 'colleague',- mentor: 'colleague',- mentee: 'colleague',- cto: 'colleague',- ceo: 'colleague',- lover: 'partner',- girlfriend: 'partner',- boyfriend: 'partner',- fiancee: 'partner',- fiance: 'partner',- spouse: 'partner',-};const NON_PERSON_TERMS = new Set(['User', 'Users',@@ -738,6 +781,8 @@ const NON_NAME_TOKENS = new Set(['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',+ // verbs and fillers that open a sentence in notes ("Recalled …", "Posted …")+ 'despite', 'invited', 'recalled', 'makes', 'made', 'posted', 'stated', 'noted', 'corrected', 'studied', 'collaborates', 'operates', 'derived', 'asked', 'said', 'says', 'wants', 'prefers', 'uses', 'used', 'likes', 'loves', 'built', 'building', 'created', 'fixed', 'added', 'shared', 'sent', 'replied', 'reply', 'confirmed', 'decided', 'started', 'finished', 'moved', 'plans', 'planned', 'profile', 'founders', 'fleet', 'phase', 'multi', 'governance', 'cycle', 'crisis', 'sites', 'reels', 'traffic', 'spec', 'impact', 'home', 'path','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', 'sept', 'mercury', 'optimus','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@@ -746,76 +791,6 @@ const NON_NAME_TOKENS = new Set(['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;-}--function extractUserRelationshipMentions(text: string): UserRelationMention[] {- const mentions = new Map<string, UserRelationMention>();- const rolePattern = Object.keys(USER_RELATION_ROLE_MAP)- .sort((a, b) => b.length - a.length)- .map(r => r.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))- .join('|');- const normalizedText = text.replace(/[\r\n]+/g, ' ').trim();-- const patterns = [- new RegExp(`\\bmy\\s+(${rolePattern})\\s+([A-Z][a-z]+(?:\\s+[A-Z][a-z]+){0,2})\\b`, 'gi'),- new RegExp(`\\b([A-Z][a-z]+(?:\\s+[A-Z][a-z]+){0,2})\\s+is\\s+my\\s+(${rolePattern})\\b`, 'gi'),- new RegExp(`\\b([A-Z][a-z]+(?:\\s+[A-Z][a-z]+){0,2})\\s*,\\s*my\\s+(${rolePattern})\\b`, 'gi'),- new RegExp(`\\bmy\\s+(${rolePattern})\\s*,\\s*([A-Z][a-z]+(?:\\s+[A-Z][a-z]+){0,2})\\b`, 'gi'),- ];-- for (const pattern of patterns) {- let match: RegExpExecArray | null;- while ((match = pattern.exec(normalizedText)) !== null) {- const first = match[1]?.trim();- const second = match[2]?.trim();- if (!first || !second) continue;-- const firstIsRole = USER_RELATION_ROLE_MAP[first.toLowerCase()];- const role = firstIsRole ? first.toLowerCase() : second.toLowerCase();- const name = firstIsRole ? second : first;- const relation = USER_RELATION_ROLE_MAP[role];- if (!relation || !isLikelyHumanName(name)) continue;-- const key = name.toLowerCase();- mentions.set(key, { name, relation });- }- }-- const groupedPatterns = [- new RegExp(`\\bmy\\s+(${rolePattern})\\s+(?:is|are|named|called)\\s+([^.!?;]+)`, 'gi'),- new RegExp(`\\b(?:our|user(?:'s)?|users?)\\s+(${rolePattern})\\s+(?:is|are|named|called|include|includes)\\s+([^.!?;]+)`, 'gi'),- new RegExp(`\\b(${rolePattern})\\s+(?:is|are|named|called|include|includes)\\s+([^.!?;]+)`, 'gi'),- new RegExp(`\\b(?:i|we)\\s+have\\s+(${rolePattern})\\s+([^.!?;]+)`, 'gi'),- new RegExp(`\\b([^.!?;]+?)\\s+(?:is|are)\\s+my\\s+(${rolePattern})\\b`, 'gi'),- new RegExp(`\\b([^.!?;]+?)\\s+(?:is|are)\\s+(?:our|user(?:'s)?)\\s+(${rolePattern})\\b`, 'gi'),- ];-- for (const pattern of groupedPatterns) {- let match: RegExpExecArray | null;- while ((match = pattern.exec(normalizedText)) !== null) {- const first = match[1]?.trim();- const second = match[2]?.trim();- if (!first || !second) continue;-- const firstRole = USER_RELATION_ROLE_MAP[first.toLowerCase()];- const roleToken = firstRole ? first.toLowerCase() : second.toLowerCase();- const namesSegment = firstRole ? second : first;- const relation = USER_RELATION_ROLE_MAP[roleToken];- if (!relation) continue;-- for (const name of extractHumanNames(namesSegment)) {- const key = name.toLowerCase();- mentions.set(key, { name, relation });- }- }- }-- return [...mentions.values()];-}-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;diff --git a/src/web/api/brain.ts b/src/web/api/brain.tsindex 9b328191..8404eff3 100644--- a/src/web/api/brain.ts+++ b/src/web/api/brain.ts@@ -3,6 +3,7 @@ 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';+import { cardinalityOf, exclusiveGroup, KNOWN_CAP, relationCatalog } from '../../memory/person-standing.js';import type { Belief, BeliefKind, BeliefStatus, BeliefStore, Evidence } from '../../memory/beliefs.js';import { join } from 'node:path';@@ -71,6 +72,9 @@ function personToJson(p: any) {verifiedBy: p.verifiedBy ?? null,meta: p.meta ?? {},ownerEdited: p.ownerEdited === true,+ /** 0-100 and known / shadow / faint, with the reasons (person-standing.ts). */+ standing: p.standing ?? null,+ cardinality: p.relationshipToUser ? cardinalityOf(p.relationshipToUser) : null,firstSeenAt: p.firstSeenAt,lastSeenAt: p.lastSeenAt,createdAt: p.createdAt,@@ -217,7 +221,9 @@ brain.get('/api/brain/persons', async (c) => {const limit = Math.min(parseInt(c.req.query('limit') || '100'), 200);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)+ const tierParam = c.req.query('tier');+ const tier = tierParam === 'known' || tierParam === 'shadow' || tierParam === 'faint' ? tierParam : undefined;+ const persons = mem.listPersons(q, limit, tier).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 });@@ -244,6 +250,9 @@ function cleanMeta(input: unknown): Record<string, unknown> | undefined {return out;}+/** Relationship words with their cardinality, for the edit form. */+brain.get('/api/brain/relations', (c) => c.json({ relations: relationCatalog(), knownCap: KNOWN_CAP }));+brain.get('/api/brain/persons/checks', (c) => {const status = personVerifier?.status();const mem = ensureMemory();@@ -274,9 +283,20 @@ brain.patch('/api/brain/persons/:id', async (c) => {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);+ // One-to-one relations (wife, mother, manager…) belong to one person: say who has it,+ // and move it only when the owner confirms (force).+ const relationship = body.relationship === null ? null : str(body.relationship, 60);+ const group = relationship ? exclusiveGroup(relationship) : null;+ if (group) {+ const holder = mem.exclusiveHolder(group, c.req.param('id'));+ if (holder && body.force !== true) {+ return c.json({ error: `${holder.name} is already your ${holder.relationshipToUser}.`, conflict: { id: holder.id, name: holder.name, relationship: holder.relationshipToUser } }, 409);+ }+ if (holder) mem.releaseExclusiveRelationship(group, c.req.param('id'));+ }const updated = mem.updatePerson(c.req.param('id'), {displayName: str(body.name, 80),- relationship: body.relationship === null ? null : str(body.relationship, 60),+ relationship,description: body.summary === null ? null : str(body.summary, 2000),kind: kind as 'person' | 'pet' | 'unverified' | undefined,meta: cleanMeta(body.meta),@@ -300,7 +320,7 @@ 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);+ const g = mem.personGraph(Number.isFinite(parsed) ? parsed : 400, { shadows: c.req.query('shadows') === '1' });return c.json({ ...g, available: true });});