Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(brain): no cap on a person's memories; people limit is a hidden soft cap
Salman Qureshi7e28c6efa6c2
diff --git a/apps/desktop/src/api/brain.ts b/apps/desktop/src/api/brain.tsindex 9b848e22..b87376dc 100644--- a/apps/desktop/src/api/brain.ts+++ b/apps/desktop/src/api/brain.ts@@ -105,7 +105,9 @@ export const brain = {return http.get<{ persons: BrainPerson[] }>(`/api/brain/persons?${qs}`);},person: (id: string) => http.get<{ person: BrainPerson }>(`/api/brain/persons/${encodeURIComponent(id)}`),- personMemories: (id: string) => http.get<{ memories: BrainMemory[] }>(`/api/brain/persons/${encodeURIComponent(id)}/memories?limit=60`),+ /** Paged; `total` is everything that mentions them (no upper bound). */+ personMemories: (id: string, offset = 0, limit = 50) =>+ http.get<{ memories: BrainMemory[]; total?: number }>(`/api/brain/persons/${encodeURIComponent(id)}/memories?limit=${limit}&offset=${offset}`),/** A one-to-one relation someone else holds fails with 409 ("Heer is already your wife."); `force` moves it. */updatePerson: (id: string, patch: { name?: string; relationship?: string | null; summary?: string | null; kind?: string; meta?: PersonMeta; force?: boolean }) =>http.patch<{ person?: BrainPerson; removed?: boolean }>(`/api/brain/persons/${encodeURIComponent(id)}`, patch),@@ -117,5 +119,5 @@ export const brain = {queueExisting: () => http.post<{ queued: number; status: CheckStatus | null }>("/api/brain/persons/checks/queue-existing"),graph: (memories = 300, shadows = false) => http.get<BrainGraphData>(`/api/brain/graph/v2?memories=${memories}${shadows ? "&shadows=1" : ""}`),- relations: () => http.get<{ relations: Array<{ label: string; cardinality: "one" | "many" }>; knownCap: number }>("/api/brain/relations"),+ relations: () => http.get<{ relations: Array<{ label: string; cardinality: "one" | "many" }> }>("/api/brain/relations"),};diff --git a/apps/desktop/src/views/brain/BrainView.tsx b/apps/desktop/src/views/brain/BrainView.tsxindex 65d7c4c9..96a858d2 100644--- a/apps/desktop/src/views/brain/BrainView.tsx+++ b/apps/desktop/src/views/brain/BrainView.tsx@@ -27,7 +27,7 @@ export function BrainView() {useEffect(() => { try { sessionStorage.setItem(TAB_KEY, tab); } catch { /* ignore */ } }, [tab]);useEffect(() => { if (visible) setOpened((o) => (o[tab] ? o : { ...o, [tab]: true })); }, [visible, tab]);- const loadPeople = useCallback(() => { void brain.persons({ limit: 300 }).then((r) => setPeople(r.persons)).catch(() => {}); }, []);+ const loadPeople = useCallback(() => { void brain.persons({ limit: 2000 }).then((r) => setPeople(r.persons)).catch(() => {}); }, []);useEffect(() => { if (visible && selected && selected.kind !== "memory" && people.length === 0) loadPeople(); }, [visible, selected, people.length, loadPeople]);return (diff --git a/apps/desktop/src/views/brain/People.tsx b/apps/desktop/src/views/brain/People.tsxindex c7c3498d..6297de5e 100644--- a/apps/desktop/src/views/brain/People.tsx+++ b/apps/desktop/src/views/brain/People.tsx@@ -25,7 +25,7 @@ export function People({ initialId }: { initialId?: string | null }) {const load = useCallback(async () => {setError(null);- try { setPeople((await brain.persons({ limit: 300 })).persons); } catch (e) { setError(e instanceof Error ? e.message : String(e)); }+ try { setPeople((await brain.persons({ limit: 2000 })).persons); } catch (e) { setError(e instanceof Error ? e.message : String(e)); }}, []);useEffect(() => { void load(); }, [load]);useEffect(() => { if (initialId) setSelected(initialId); }, [initialId]);diff --git a/apps/desktop/src/views/brain/PersonCard.tsx b/apps/desktop/src/views/brain/PersonCard.tsxindex d67da9fa..951efc14 100644--- a/apps/desktop/src/views/brain/PersonCard.tsx+++ b/apps/desktop/src/views/brain/PersonCard.tsx@@ -17,6 +17,8 @@ import { cx } from "~/lib/cx";export function PersonCard({ id, onClose, onChanged, allPeople }: { id: string; onClose?: () => void; onChanged: () => void; allPeople: BrainPerson[] }) {const [person, setPerson] = useState<BrainPerson | null>(null);const [memories, setMemories] = useState<BrainMemory[] | null>(null);+ const [total, setTotal] = useState(0);+ const [more, setMore] = useState(false);const [editing, setEditing] = useState(false);const [error, setError] = useState<string | null>(null);@@ -26,11 +28,26 @@ export function PersonCard({ id, onClose, onChanged, allPeople }: { id: string;const [p, m] = await Promise.all([brain.person(id), brain.personMemories(id)]);setPerson(p.person);setMemories(m.memories);+ setTotal(m.total ?? m.memories.length);} catch (e) {setError(e instanceof Error ? e.message : String(e));}}- useEffect(() => { setPerson(null); setMemories(null); setEditing(false); void load(); }, [id]);+ useEffect(() => { setPerson(null); setMemories(null); setTotal(0); setEditing(false); void load(); }, [id]);++ async function loadMore() {+ if (!memories) return;+ setMore(true);+ try {+ const m = await brain.personMemories(id, memories.length);+ setMemories([...memories, ...m.memories]);+ setTotal(m.total ?? total);+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ } finally {+ setMore(false);+ }+ }if (error) return <div className="p-5 text-sm text-red">{error}</div>;if (!person) return <div className="p-5 text-ink3"><Spinner size={16} /></div>;@@ -71,16 +88,19 @@ export function PersonCard({ id, onClose, onChanged, allPeople }: { id: string;)}<div>- <div className="mb-2 text-2xs font-medium uppercase tracking-wider text-ink4">Memories with {person.name.split(" ")[0]}</div>+ <div className="mb-2 text-2xs font-medium uppercase tracking-wider text-ink4">Memories with {person.name.split(" ")[0]}{total > 0 && <span className="ml-1.5 normal-case tracking-normal">· {total}</span>}</div>{memories === null && <Spinner size={14} className="text-ink3" />}{memories && memories.length === 0 && <p className="text-sm text-ink4">None yet.</p>}<div className="flex flex-col gap-1.5">- {memories?.slice(0, 30).map((m) => (+ {memories?.map((m) => (<div key={m.id} className="rounded-lg border border-line bg-surface px-3 py-2 text-sm text-ink2"><span className="mr-2 font-mono text-2xs uppercase text-ink4">{m.type}</span>{m.summary}</div>))}</div>+ {memories && memories.length < total && (+ <Button className="mt-2" size="sm" variant="ghost" loading={more} onClick={() => void loadMore()}>Show more ({total - memories.length})</Button>+ )}</div></div>);diff --git a/src/memory/person-curation.test.ts b/src/memory/person-curation.test.tsindex ccb28913..22a180aa 100644--- a/src/memory/person-curation.test.ts+++ b/src/memory/person-curation.test.ts@@ -59,6 +59,20 @@ describe.skipIf(!sqliteAvailable)('people curation', () => {expect(store.getPersonMemories(zayd.id, 10).length).toBe(2);});+ it('a person\'s memories page with no upper bound', () => {+ const store = createStore();+ // Unrelated words per memory so none of them merge as duplicates.+ let seed = 7;+ const word = () => Array.from({ length: 7 }, () => String.fromCharCode(97 + ((seed = (seed * 48271) % 2147483647) % 26))).join('');+ for (let i = 0; i < 130; i++) remember(store, `My wife Heer ${word()} ${word()} ${word()} ${word()} ${word()} ${word()}.`);+ const heer = byName(store, 'Heer')!;+ const first = store.personMemoryPage(heer.id, 50, 0);+ expect(first.total).toBe(130);+ const seen = new Set(first.records.map((r) => r.id));+ for (let offset = 50; offset < 130; offset += 50) for (const r of store.personMemoryPage(heer.id, 50, offset).records) seen.add(r.id);+ expect(seen.size).toBe(130);+ });+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.');diff --git a/src/memory/person-standing.test.ts b/src/memory/person-standing.test.tsindex 23ed5c9b..ca143151 100644--- a/src/memory/person-standing.test.ts+++ b/src/memory/person-standing.test.ts@@ -32,11 +32,16 @@ describe('person standing', () => {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: [] };+ it('soft-caps the known list: strong ties stay, weak ones fade, owner-confirmed never move', () => {+ const scores = [100, 90, 60, 58, 72];+ const people = scores.map((score, i) => ({ id: `p${i}`, ownerEdited: i === 0, standing: { score, tier: 'known' as const, reasons: [] as string[] } }));capKnown(people, 3);- expect(people.filter((p) => p.standing.tier === 'known').map((p) => p.id).sort()).toEqual(['p0', 'p3', 'p4']);+ // Room for two besides the owner (p1 90, p4 72); past it the bar is 70, so p2 (60) and p3 (58) fade.+ expect(people.filter((p) => p.standing.tier === 'known').map((p) => p.id).sort()).toEqual(['p0', 'p1', 'p4']);+ const strong = Array.from({ length: 6 }, (_, i) => ({ id: `s${i}`, ownerEdited: false, standing: { score: 95, tier: 'known' as const, reasons: [] as string[] } }));+ capKnown(strong, 3);+ expect(strong.every((p) => p.standing.tier === 'known')).toBe(true);+ expect(people.flatMap((p) => p.standing.reasons).join(' ')).not.toMatch(/limit|cap/);});});diff --git a/src/memory/person-standing.ts b/src/memory/person-standing.tsindex bced7349..ad669362 100644--- a/src/memory/person-standing.ts+++ b/src/memory/person-standing.ts@@ -14,8 +14,10 @@* 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.+ * The known list has a soft cap (KNOWN_CAP, about Dunbar's number). It is+ * internal and never shown: past it the bar to stay known rises with each+ * extra person, so a big social life still fits while weak names fade to+ * shadow. Owner decisions always win.*/export type PersonTier = 'known' | 'shadow' | 'faint';@@ -43,7 +45,7 @@ export interface PersonStanding {reasons: string[];}-/** Most people keep about 150 stable relationships (Dunbar); past that the brain shows the strongest. */+/** Most people keep about 150 stable relationships (Dunbar). A soft cap, internal only. */export const KNOWN_CAP = 150;export const KNOWN_MIN_SCORE = 55;export const SHADOW_MIN_SCORE = 25;@@ -79,12 +81,22 @@ export function standingOf(e: PersonEvidence): PersonStanding {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[] {+/**+ * The soft cap. Up to `cap` known people, nothing changes. Past it, each+ * extra place needs a higher score (+1 per `step` people beyond the cap, on+ * top of a margin), so the list keeps growing for strong ties and stops+ * growing for weak ones. Owner-confirmed people never move. Nothing here is+ * worded for the user: someone past the bar simply needs more evidence.+ */+export function capKnown<T extends { standing: PersonStanding; ownerEdited: boolean }>(people: T[], cap = KNOWN_CAP, step = 10): 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'] };+ known.forEach((p, i) => {+ if (i < room) return;+ const bar = KNOWN_MIN_SCORE + 15 + Math.floor((i - room) / step);+ if (p.standing.score < bar) p.standing = { ...p.standing, tier: 'shadow', reasons: [...p.standing.reasons, 'needs more evidence'] };+ });return people;}diff --git a/src/memory/second-brain-db.ts b/src/memory/second-brain-db.tsindex aa1864d5..c687de21 100644--- a/src/memory/second-brain-db.ts+++ b/src/memory/second-brain-db.ts@@ -1027,7 +1027,7 @@ export class SecondBrainDB {}listPersons(userKey: string, query?: string, limit: number = 100): PersonListRow[] {- const cappedLimit = Math.min(Math.max(limit, 1), 300);+ const cappedLimit = Math.min(Math.max(limit, 1), 5000);// 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;@@ -1058,10 +1058,19 @@ export class SecondBrainDB {}/** Live beliefs that mention a person, newest first. */- getBeliefIdsForPerson(personId: string, limit: number = 50): string[] {+ getBeliefIdsForPerson(personId: string, limit: number = 50, offset = 0): 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);+ WHERE bp.person_id = ? AND b.status IN ('candidate','held','confirmed','contested') ORDER BY b.updated_at DESC LIMIT ? OFFSET ?`)+ .all(personId, Math.max(1, limit), Math.max(0, offset)) as Array<{ id: string }>).map((r) => r.id);+ }++ /** How many live beliefs and legacy memories mention a person (for paging). */+ countPersonMemories(userKey: string, personId: string): { beliefs: number; memories: number } {+ const beliefs = (this.db.prepare(`SELECT COUNT(*) AS n 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')`).get(personId) as { n: number }).n;+ const memories = (this.db.prepare(`SELECT COUNT(*) AS n FROM memory_persons mp JOIN memories m ON m.id = mp.memory_id+ WHERE mp.person_id = ? AND m.user_key = ? AND m.dismissed = 0`).get(personId, userKey) as { n: number }).n;+ return { beliefs, memories };}getPersonConnections(userKey: string, personId: string, limit: number = 30): PersonConnectionRow[] {@@ -1081,17 +1090,16 @@ export class SecondBrainDB {return stmt.all(userKey, personId, cappedLimit) as PersonConnectionRow[];}- getMemoriesForPerson(userKey: string, personId: string, limit: number = 50): MemoryRow[] {- const cappedLimit = Math.min(Math.max(limit, 1), 200);+ getMemoriesForPerson(userKey: string, personId: string, limit: number = 50, offset = 0): MemoryRow[] {const stmt = this.db.prepare(`SELECT m.*FROM memory_persons mpJOIN memories m ON m.id = mp.memory_idWHERE mp.person_id = ? AND m.user_key = ? AND m.dismissed = 0ORDER BY m.updated_at DESC- LIMIT ?+ LIMIT ? OFFSET ?`);- return stmt.all(personId, userKey, cappedLimit) as MemoryRow[];+ return stmt.all(personId, userKey, Math.max(1, limit), Math.max(0, offset)) as MemoryRow[];}getRelationshipMemoryRows(userKey: string): MemoryRow[] {diff --git a/src/memory/user-memory.ts b/src/memory/user-memory.tsindex 2f453f49..7de1ae92 100644--- a/src/memory/user-memory.ts+++ b/src/memory/user-memory.ts@@ -223,12 +223,12 @@ export class UserMemoryStore {listPersons(query?: string, limit: number = 100, tier?: PersonTier): UserPersonRecord[] {this.indexNewBeliefs();const standings = this.standings();- const rows = this.db.listPersons(this.userKey, query, 300);+ const rows = this.db.listPersons(this.userKey, query, 5000);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)));+ .slice(0, Math.max(1, limit));}getPerson(personId: string): UserPersonRecord | null {@@ -316,16 +316,30 @@ export class UserMemoryStore {this.db.applyPersonCheck(this.userKey, personId, verdict);}- getPersonMemories(personId: string, limit: number = 50): UserMemoryRecord[] {+ /** Everything about a person, live beliefs first then the legacy archive, one page at a time. No upper bound. */+ getPersonMemories(personId: string, limit: number = 50, offset = 0): UserMemoryRecord[] {+ return this.personMemoryPage(personId, limit, offset).records;+ }++ personMemoryPage(personId: string, limit: number = 50, offset = 0): { records: UserMemoryRecord[]; total: number } {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);+ const counts = this.db.countPersonMemories(this.userKey, personId);+ const take = Math.max(1, limit);+ const from = Math.max(0, offset);+ const live = from < counts.beliefs+ ? this.db.getBeliefIdsForPerson(personId, take, from)+ .map((id) => this.beliefs.get(id))+ .filter((b): b is NonNullable<typeof b> => Boolean(b))+ .map((b) => this.toBeliefRecord(b))+ : [];+ const rest = take - live.length;+ const legacy = rest > 0+ ? this.db.getMemoriesForPerson(this.userKey, personId, rest, Math.max(0, from - counts.beliefs)).map(row => this.toRecord(row))+ : [];+ return { records: [...live, ...legacy], total: counts.beliefs + counts.memories };}+/** True while persons are rebuilt from old memories: those never queue model checks. */private rebuilding = false;@@ -610,7 +624,7 @@ export class UserMemoryStore {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)) {+ for (const person of this.db.listPersons(this.userKey, '', 5000)) {if (seen.has(person.id)) continue;if (mentionsPerson(text, person.display_name) || mentionsPerson(text, person.canonical_name)) {seen.add(person.id);diff --git a/src/web/api/brain.ts b/src/web/api/brain.tsindex 8404eff3..3820a503 100644--- a/src/web/api/brain.ts+++ b/src/web/api/brain.ts@@ -3,7 +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 { cardinalityOf, exclusiveGroup, relationCatalog } from '../../memory/person-standing.js';import type { Belief, BeliefKind, BeliefStatus, BeliefStore, Evidence } from '../../memory/beliefs.js';import { join } from 'node:path';@@ -218,7 +218,7 @@ brain.get('/api/brain/persons', async (c) => {const mem = ensureMemory();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 limit = Math.min(Math.max(parseInt(c.req.query('limit') || '100', 10) || 100, 1), 5000);const kinds = (c.req.query('kind') || '').split(',').map((k) => k.trim()).filter(Boolean);const showRejected = c.req.query('rejected') === '1';const tierParam = c.req.query('tier');@@ -251,7 +251,7 @@ function cleanMeta(input: unknown): Record<string, unknown> | undefined {}/** 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/relations', (c) => c.json({ relations: relationCatalog() }));brain.get('/api/brain/persons/checks', (c) => {const status = personVerifier?.status();@@ -337,9 +337,11 @@ brain.get('/api/brain/persons/:id/memories', async (c) => {const mem = ensureMemory();if (!mem) return c.json({ memories: [], total: 0, available: false, error: SQLITE_DEPENDENCY_ERROR }, 503);const id = c.req.param('id');- const limit = Math.min(parseInt(c.req.query('limit') || '50'), 100);- const memories = mem.getPersonMemories(id, limit);- return c.json({ memories: memories.map(memToJson), total: memories.length, available: true });+ // Paged, not capped: a person can have any number of memories.+ const limit = Math.min(Math.max(parseInt(c.req.query('limit') || '50', 10) || 50, 1), 500);+ const offset = Math.max(parseInt(c.req.query('offset') || '0', 10) || 0, 0);+ const page = mem.personMemoryPage(id, limit, offset);+ return c.json({ memories: page.records.map(memToJson), total: page.total, limit, offset, available: true });});brain.get('/api/brain/graph', async (c) => {