Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(desktop): Second Brain panel with graph, memories and people
Salman Qureshi41c195e31662
diff --git a/apps/desktop/package-lock.json b/apps/desktop/package-lock.jsonindex 882d773b..6de14fbd 100644--- a/apps/desktop/package-lock.json+++ b/apps/desktop/package-lock.json@@ -27,6 +27,7 @@"@tauri-apps/plugin-updater": "^2.14.0","@tauri-apps/plugin-window-state": "^2.5.0","clsx": "^2.1.1",+ "force-graph": "^1.52.0","lucide-react": "^0.511.0","react": "^18.3.1","react-dom": "^18.3.1",@@ -2338,6 +2339,12 @@"@tauri-apps/api": "^2.12.0"}},+ "node_modules/@tweenjs/tween.js": {+ "version": "25.0.0",+ "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-25.0.0.tgz",+ "integrity": "sha512-XKLA6syeBUaPzx4j3qwMqzzq+V4uo72BnlbOjmuljLrRqdsd3qnzvZZoxvMHZ23ndsRS4aufU6JOZYpCbU6T1A==",+ "license": "MIT"+ },"node_modules/@types/babel__core": {"version": "7.20.5","resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",@@ -2623,6 +2630,15 @@"url": "https://opencollective.com/vitest"}},+ "node_modules/accessor-fn": {+ "version": "1.5.3",+ "resolved": "https://registry.npmjs.org/accessor-fn/-/accessor-fn-1.5.3.tgz",+ "integrity": "sha512-rkAofCwe/FvYFUlMB0v0gWmhqtfAtV1IUkdPbfhTUyYniu5LrC0A0UJkTH0Jv3S8SvwkmfuAlY+mQIJATdocMA==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/any-promise": {"version": "1.3.0","resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz",@@ -2733,6 +2749,16 @@"node": ">=6.0.0"}},+ "node_modules/bezier-js": {+ "version": "6.1.4",+ "resolved": "https://registry.npmjs.org/bezier-js/-/bezier-js-6.1.4.tgz",+ "integrity": "sha512-PA0FW9ZpcHbojUCMu28z9Vg/fNkwTj5YhusSAjHHDfHDGLxJ6YUKrAN2vk1fP2MMOxVw4Oko16FMlRGVBGqLKg==",+ "license": "MIT",+ "funding": {+ "type": "individual",+ "url": "https://github.com/Pomax/bezierjs/blob/master/FUNDING.md"+ }+ },"node_modules/binary-extensions": {"version": "2.3.0","resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",@@ -2834,6 +2860,18 @@],"license": "CC-BY-4.0"},+ "node_modules/canvas-color-tracker": {+ "version": "1.3.2",+ "resolved": "https://registry.npmjs.org/canvas-color-tracker/-/canvas-color-tracker-1.3.2.tgz",+ "integrity": "sha512-ryQkDX26yJ3CXzb3hxUVNlg1NKE4REc5crLBq661Nxzr8TNd236SaEf2ffYLXyI5tSABSeguHLqcVq4vf9L3Zg==",+ "license": "MIT",+ "dependencies": {+ "tinycolor2": "^1.6.0"+ },+ "engines": {+ "node": ">=12"+ }+ },"node_modules/ccount": {"version": "2.0.1","resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",@@ -3004,6 +3042,222 @@"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==","license": "MIT"},+ "node_modules/d3-array": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",+ "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",+ "license": "ISC",+ "dependencies": {+ "internmap": "1 - 2"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-binarytree": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/d3-binarytree/-/d3-binarytree-1.0.2.tgz",+ "integrity": "sha512-cElUNH+sHu95L04m92pG73t2MEJXKu+GeKUN1TJkFsu93E5W8E9Sc3kHEGJKgenGvj19m6upSn2EunvMgMD2Yw==",+ "license": "MIT"+ },+ "node_modules/d3-color": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-dispatch": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",+ "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-drag": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",+ "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-selection": "3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-ease": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-force-3d": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/d3-force-3d/-/d3-force-3d-3.0.6.tgz",+ "integrity": "sha512-4tsKHUPLOVkyfEffZo1v6sFHvGFwAIIjt/W8IThbp08DYAsXZck+2pSHEG5W1+gQgEvFLdZkYvmJAbRM2EzMnA==",+ "license": "MIT",+ "dependencies": {+ "d3-binarytree": "1",+ "d3-dispatch": "1 - 3",+ "d3-octree": "1",+ "d3-quadtree": "1 - 3",+ "d3-timer": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-format": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz",+ "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-interpolate": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-octree": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/d3-octree/-/d3-octree-1.1.0.tgz",+ "integrity": "sha512-F8gPlqpP+HwRPMO/8uOu5wjH110+6q4cgJvgJT6vlpy3BEaDIKlTZrgHKZSp/i1InRpVfh4puY/kvL6MxK930A==",+ "license": "MIT"+ },+ "node_modules/d3-quadtree": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz",+ "integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-scale": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",+ "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "2.10.0 - 3",+ "d3-format": "1 - 3",+ "d3-interpolate": "1.2.0 - 3",+ "d3-time": "2.1.1 - 3",+ "d3-time-format": "2 - 4"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-scale-chromatic": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",+ "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3",+ "d3-interpolate": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-selection": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",+ "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-time": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",+ "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "2 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-time-format": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",+ "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",+ "license": "ISC",+ "dependencies": {+ "d3-time": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-timer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-transition": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",+ "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3",+ "d3-dispatch": "1 - 3",+ "d3-ease": "1 - 3",+ "d3-interpolate": "1 - 3",+ "d3-timer": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ },+ "peerDependencies": {+ "d3-selection": "2 - 3"+ }+ },+ "node_modules/d3-zoom": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",+ "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-drag": "2 - 3",+ "d3-interpolate": "1 - 3",+ "d3-selection": "2 - 3",+ "d3-transition": "2 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },"node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -3260,6 +3514,46 @@"node": ">=8"}},+ "node_modules/float-tooltip": {+ "version": "1.7.5",+ "resolved": "https://registry.npmjs.org/float-tooltip/-/float-tooltip-1.7.5.tgz",+ "integrity": "sha512-/kXzuDnnBqyyWyhDMH7+PfP8J/oXiAavGzcRxASOMRHFuReDtofizLLJsf7nnDLAfEaMW4pVWaXrAjtnglpEkg==",+ "license": "MIT",+ "dependencies": {+ "d3-selection": "2 - 3",+ "kapsule": "^1.16",+ "preact": "10"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/force-graph": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/force-graph/-/force-graph-1.52.0.tgz",+ "integrity": "sha512-0fpxrZzW6qwm9zM7wgh54d7GbxQfQSDV71I0apo+75PVYQPpPHGVPQFLsE9WAu+hOS4VdLd53g0Hua/bxDJKSg==",+ "license": "MIT",+ "dependencies": {+ "@tweenjs/tween.js": "18 - 25",+ "accessor-fn": "1",+ "bezier-js": "3 - 6",+ "canvas-color-tracker": "^1.3",+ "d3-array": "1 - 3",+ "d3-drag": "2 - 3",+ "d3-force-3d": "2 - 3",+ "d3-scale": "1 - 4",+ "d3-scale-chromatic": "1 - 3",+ "d3-selection": "2 - 3",+ "d3-zoom": "2 - 3",+ "float-tooltip": "^1.7",+ "index-array-by": "1",+ "kapsule": "^1.16",+ "lodash-es": "4"+ },+ "engines": {+ "node": ">=12"+ }+ },"node_modules/fraction.js": {"version": "5.3.4","resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz",@@ -3427,12 +3721,30 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/index-array-by": {+ "version": "1.4.2",+ "resolved": "https://registry.npmjs.org/index-array-by/-/index-array-by-1.4.2.tgz",+ "integrity": "sha512-SP23P27OUKzXWEC/TOyWlwLviofQkCSCKONnc62eItjp69yCZZPqDQtr3Pw5gJDnPeUMqExmKydNZaJO0FU9pw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/inline-style-parser": {"version": "0.2.7","resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz","integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==","license": "MIT"},+ "node_modules/internmap": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",+ "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/is-alphabetical": {"version": "2.0.1","resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",@@ -3593,6 +3905,18 @@"node": ">=6"}},+ "node_modules/kapsule": {+ "version": "1.16.3",+ "resolved": "https://registry.npmjs.org/kapsule/-/kapsule-1.16.3.tgz",+ "integrity": "sha512-4+5mNNf4vZDSwPhKprKwz3330iisPrb08JyMgbsdFrimBCKNHecua/WBwvVg3n7vwx0C1ARjfhwIpbrbd9n5wg==",+ "license": "MIT",+ "dependencies": {+ "lodash-es": "4"+ },+ "engines": {+ "node": ">=12"+ }+ },"node_modules/lilconfig": {"version": "3.1.4","resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.4.tgz",@@ -3613,6 +3937,12 @@"dev": true,"license": "MIT"},+ "node_modules/lodash-es": {+ "version": "4.18.1",+ "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz",+ "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==",+ "license": "MIT"+ },"node_modules/longest-streak": {"version": "3.1.0","resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",@@ -4897,6 +5227,24 @@"dev": true,"license": "MIT"},+ "node_modules/preact": {+ "version": "10.29.8",+ "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.8.tgz",+ "integrity": "sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/preact"+ },+ "peerDependencies": {+ "preact-render-to-string": ">=5"+ },+ "peerDependenciesMeta": {+ "preact-render-to-string": {+ "optional": true+ }+ }+ },"node_modules/property-information": {"version": "7.2.0","resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz",@@ -5507,6 +5855,12 @@"dev": true,"license": "MIT"},+ "node_modules/tinycolor2": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/tinycolor2/-/tinycolor2-1.6.0.tgz",+ "integrity": "sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==",+ "license": "MIT"+ },"node_modules/tinyexec": {"version": "0.3.2","resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 9f6f07a9..9540220a 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -34,6 +34,7 @@"@tauri-apps/plugin-updater": "^2.14.0","@tauri-apps/plugin-window-state": "^2.5.0","clsx": "^2.1.1",+ "force-graph": "^1.52.0","lucide-react": "^0.511.0","react": "^18.3.1","react-dom": "^18.3.1",diff --git a/apps/desktop/src/api/brain.ts b/apps/desktop/src/api/brain.tsnew file mode 100644index 00000000..388b85ca--- /dev/null+++ b/apps/desktop/src/api/brain.ts@@ -0,0 +1,106 @@+/* The second brain's endpoints (beliefs, people, graph, checks). */++import { http } from "./client";++export interface BrainMemory {+ id: string;+ type: string;+ summary: string;+ detail: string | null;+ scope?: string;+ evidenceKind?: string;+ source?: string;+ confidence: number;+ importance: number;+ evidenceCount?: number;+ dismissed?: boolean;+ createdAt: number;+ updatedAt: number;+ lastSeenAt?: number;+}++export interface PersonMeta {+ phone?: string;+ email?: string;+ birthday?: string;+ location?: string;+ company?: string;+ role?: string;+ notes?: string;+ links?: string[];+}++export interface BrainPerson {+ id: string;+ name: string;+ canonicalName: string;+ relationship?: string;+ summary?: string;+ confidence: number;+ memoryCount: number;+ kind: "person" | "pet" | "unverified";+ verifiedBy: "owner" | "model" | "model-rejected" | null;+ meta: PersonMeta;+ ownerEdited: boolean;+ firstSeenAt: number;+ lastSeenAt: number;+ connections?: Array<{ id: string; name?: string; display_name?: string; relation_type?: string; strength?: number }>;+}++export interface BrainGraphData {+ 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 }>;+ available: boolean;+}++export interface CheckStatus {+ enabled: boolean;+ pending: number;+ callsToday: number;+ dailyCap: number;+ lastRunAt: number | null;+ lastError: string | null;+ nextRunAt: number | null;+ checked: number;+}++export const MEMORY_TYPES = ["identity", "preference", "goal", "project", "habit", "decision", "constraint", "relationship", "episode", "reflection"] as const;++export const brain = {+ status: () => http.get<{ available: boolean; total?: number }>("/api/brain/status"),+ memories: (opts: { limit?: number; offset?: number; type?: string; q?: string } = {}) => {+ const qs = new URLSearchParams();+ if (opts.limit) qs.set("limit", String(opts.limit));+ if (opts.offset) qs.set("offset", String(opts.offset));+ if (opts.type) qs.set("type", opts.type);+ if (opts.q) qs.set("q", opts.q);+ return http.get<{ memories: BrainMemory[]; total: number }>(`/api/brain/memory?${qs}`);+ },+ search: (q: string, limit = 40) => http.get<{ memories: BrainMemory[] }>(`/api/brain/memory/search?q=${encodeURIComponent(q)}&limit=${limit}`),+ memory: (id: string) => http.get<BrainMemory>(`/api/brain/memory/${encodeURIComponent(id)}`),+ updateMemory: (id: string, patch: Partial<Pick<BrainMemory, "summary" | "detail" | "importance" | "confidence">>) => http.put<{ success: boolean }>(`/api/brain/memory/${encodeURIComponent(id)}`, patch),+ deleteMemory: (id: string) => http.delete<{ success: boolean }>(`/api/brain/memory/${encodeURIComponent(id)}`),+ addMemory: (body: { type: string; summary: string; detail?: string }) => http.post<BrainMemory>("/api/brain/memory", body),++ persons: (opts: { q?: string; kind?: string; limit?: number } = {}) => {+ const qs = new URLSearchParams();+ if (opts.q) qs.set("q", opts.q);+ if (opts.kind) qs.set("kind", opts.kind);+ qs.set("limit", String(opts.limit ?? 200));+ 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`),+ updatePerson: (id: string, patch: { name?: string; relationship?: string | null; summary?: string | null; kind?: string; meta?: PersonMeta }) =>+ http.patch<{ person?: BrainPerson; removed?: boolean }>(`/api/brain/persons/${encodeURIComponent(id)}`, patch),+ mergePerson: (id: string, into: string) => http.post<{ person: BrainPerson | null }>(`/api/brain/persons/${encodeURIComponent(id)}/merge`, { into }),+ notAPerson: (id: string) => http.patch<{ removed?: boolean }>(`/api/brain/persons/${encodeURIComponent(id)}`, { kind: "not_person" }),++ checks: () => http.get<CheckStatus>("/api/brain/persons/checks"),+ runCheck: () => http.post<{ checked: number; status: CheckStatus }>("/api/brain/persons/checks/run"),+ queueExisting: () => http.post<{ queued: number; status: CheckStatus | null }>("/api/brain/persons/checks/queue-existing"),++ graph: (memories = 300) => http.get<BrainGraphData>(`/api/brain/graph/v2?memories=${memories}`),+};diff --git a/apps/desktop/src/app/store.ts b/apps/desktop/src/app/store.tsindex 1a64fe06..9361b4b7 100644--- a/apps/desktop/src/app/store.ts+++ b/apps/desktop/src/app/store.ts@@ -7,7 +7,7 @@import { create } from "zustand";import type { BotStatus, ChatThread, PendingPrompt } from "~/api/types";-export type View = "chat" | "code" | "bots" | "plugins" | "skills" | "settings";+export type View = "chat" | "code" | "bots" | "brain" | "plugins" | "skills" | "settings";/** What the agent is doing right now; drives the StateOrb everywhere. */export type AgentState = "idle" | "thinking" | "streaming" | "working" | "needs-you" | "offline";diff --git a/apps/desktop/src/components/ErrorBoundary.tsx b/apps/desktop/src/components/ErrorBoundary.tsxnew file mode 100644index 00000000..30fae6e7--- /dev/null+++ b/apps/desktop/src/components/ErrorBoundary.tsx@@ -0,0 +1,40 @@+import { Component, type ErrorInfo, type ReactNode } from "react";+import { RotateCcw } from "lucide-react";++/**+ * Crash recovery for a part of the window: one broken view (a graph that+ * runs out of memory, a malformed record) shows a calm card with Try again+ * instead of blanking the app. `resetKey` changing also resets it.+ */+export class ErrorBoundary extends Component<{ children: ReactNode; label: string; resetKey?: unknown; fallback?: (retry: () => void, error: Error) => ReactNode }, { error: Error | null }> {+ state: { error: Error | null } = { error: null };++ static getDerivedStateFromError(error: Error) {+ return { error };+ }++ componentDidCatch(error: Error, info: ErrorInfo) {+ console.error(`[${this.props.label}] crashed`, error, info.componentStack);+ }++ componentDidUpdate(prev: { resetKey?: unknown }) {+ if (this.state.error && prev.resetKey !== this.props.resetKey) this.setState({ error: null });+ }++ retry = () => this.setState({ error: null });++ render() {+ const { error } = this.state;+ if (!error) return this.props.children;+ if (this.props.fallback) return this.props.fallback(this.retry, error);+ return (+ <div className="flex h-full items-center justify-center p-8">+ <div className="max-w-[420px] rounded-xl border border-line bg-surface p-5 text-center">+ <div className="text-base font-medium text-ink">{this.props.label} stopped working</div>+ <p className="mt-1 text-sm text-ink3">The rest of Mercury is fine. {error.message ? `(${error.message.slice(0, 160)})` : ""}</p>+ <button onClick={this.retry} className="mt-4 inline-flex h-9 items-center gap-2 rounded-md bg-accent px-3 text-sm font-medium text-on-accent"><RotateCcw size={14} /> Try again</button>+ </div>+ </div>+ );+ }+}diff --git a/apps/desktop/src/layout/Rail.tsx b/apps/desktop/src/layout/Rail.tsxindex ebea0e2f..d42d4639 100644--- a/apps/desktop/src/layout/Rail.tsx+++ b/apps/desktop/src/layout/Rail.tsx@@ -1,4 +1,4 @@-import { Bot, Code2, MessageSquare, Puzzle, Settings, Sparkles } from "lucide-react";+import { Bot, Brain, Code2, MessageSquare, Puzzle, Settings, Sparkles } from "lucide-react";import { useEffect } from "react";import { cx } from "~/lib/cx";import { useRuntimeState, useUi, type View } from "~/app/store";@@ -10,8 +10,9 @@ const ITEMS: Array<{ view: View; label: string; icon: typeof MessageSquare; key:{ view: "chat", label: "Chat", icon: MessageSquare, key: "1" },{ view: "code", label: "Code", icon: Code2, key: "2" },{ view: "bots", label: "Bots", icon: Bot, key: "3" },- { view: "plugins", label: "Plugins", icon: Puzzle, key: "4" },- { view: "skills", label: "Skills", icon: Sparkles, key: "5" },+ { view: "brain", label: "Brain", icon: Brain, key: "4" },+ { view: "plugins", label: "Plugins", icon: Puzzle, key: "5" },+ { view: "skills", label: "Skills", icon: Sparkles, key: "6" },];/**diff --git a/apps/desktop/src/layout/Workspace.tsx b/apps/desktop/src/layout/Workspace.tsxindex 7c46ed3f..a5a2010c 100644--- a/apps/desktop/src/layout/Workspace.tsx+++ b/apps/desktop/src/layout/Workspace.tsx@@ -16,6 +16,8 @@ import { BotsView } from "~/views/bots/BotsView";import { PluginsView } from "~/views/plugins/PluginsView";import { SkillsView } from "~/views/skills/SkillsView";import { SettingsView } from "~/views/settings/SettingsView";+import { BrainView } from "~/views/brain/BrainView";+import { ErrorBoundary } from "~/components/ErrorBoundary";registerBuiltinStatusItems();@@ -44,12 +46,14 @@ export function Workspace({ connection, health, onSwitchConnection }: { connecti<div className="flex min-h-0 flex-1"><Rail connectionName={connection.name} /><main className="relative flex min-w-0 flex-1 flex-col">- <Pane active={view === "chat"}><ChatView /></Pane>- <Pane active={view === "code"}><CodeView /></Pane>- <Pane active={view === "bots"}><BotsView /></Pane>- <Pane active={view === "plugins"}><PluginsView /></Pane>- <Pane active={view === "skills"}><SkillsView /></Pane>- <Pane active={view === "settings"}><SettingsView connection={connection} health={health} onSwitchConnection={onSwitchConnection} /></Pane>+ {/* Each view behind its own crash boundary: one broken view never blanks the window. */}+ <Pane active={view === "chat"}><ErrorBoundary label="Chat"><ChatView /></ErrorBoundary></Pane>+ <Pane active={view === "code"}><ErrorBoundary label="Mercury Code"><CodeView /></ErrorBoundary></Pane>+ <Pane active={view === "bots"}><ErrorBoundary label="Bots"><BotsView /></ErrorBoundary></Pane>+ <Pane active={view === "brain"}><ErrorBoundary label="Brain"><BrainView /></ErrorBoundary></Pane>+ <Pane active={view === "plugins"}><ErrorBoundary label="Plugins"><PluginsView /></ErrorBoundary></Pane>+ <Pane active={view === "skills"}><ErrorBoundary label="Skills"><SkillsView /></ErrorBoundary></Pane>+ <Pane active={view === "settings"}><ErrorBoundary label="Settings"><SettingsView connection={connection} health={health} onSwitchConnection={onSwitchConnection} /></ErrorBoundary></Pane></main></div><StatusBar />diff --git a/apps/desktop/src/views/brain/BrainGraph.tsx b/apps/desktop/src/views/brain/BrainGraph.tsxnew file mode 100644index 00000000..53239a33--- /dev/null+++ b/apps/desktop/src/views/brain/BrainGraph.tsx@@ -0,0 +1,277 @@+import { Maximize2, RefreshCw } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import type ForceGraph from "force-graph";+import type { LinkObject, NodeObject } from "force-graph";+import { brain, type BrainGraphData } from "~/api/brain";+import { Button } from "~/components/ui/Button";+import { Segmented, Spinner } from "~/components/ui/bits";+import { useTheme } from "~/app/theme";+import { cx } from "~/lib/cx";++/**+ * The brain as a living graph (Obsidian-style): you at the centre, the people+ * in your life, and what Mercury knows, joined only by real links (who+ * appears in which memory, who relates to whom). d3-force physics: drag a+ * node and its neighbours follow with springy, fluid motion; let go and it+ * settles. Canvas rendering; the library and the data load only when the+ * graph is opened; animation pauses while it is hidden; positions are kept+ * for the session so reopening doesn't re-settle from scratch.+ */++export interface GraphNode extends NodeObject {+ id: string;+ kind: "you" | "person" | "pet" | "memory";+ label: string;+ type?: string;+ weight: number;+ relationship?: string | null;+}++interface GraphLink extends LinkObject<GraphNode> {+ kind: "about" | "relation" | "you";+}++const POSITIONS_KEY = "mercury.brain.graph.positions.v1";+const TYPE_COLORS: Record<string, string> = {+ fact: "#7E8FA3", preference: "#C9A227", trait: "#9B7BD8", situation: "#5AA9C8", relationship: "#E07BA8",+ goal: "#3FB37F", project: "#8B7CF6", episode: "#6C8EF0", identity: "#2BB5C9", habit: "#E8894A", decision: "#4C8FD6", constraint: "#E06B6B", reflection: "#3BA99C",+};++export function BrainGraph({ visible, onSelect, selectedId }: { visible: boolean; onSelect: (node: { id: string; kind: GraphNode["kind"] } | null) => void; selectedId: string | null }) {+ const host = useRef<HTMLDivElement>(null);+ const graph = useRef<ForceGraph<GraphNode, GraphLink> | null>(null);+ const [data, setData] = useState<BrainGraphData | null>(null);+ const [limit, setLimit] = useState(300);+ const [show, setShow] = useState<"all" | "people" | "memories">("all");+ const [error, setError] = useState<string | null>(null);+ const [loading, setLoading] = useState(false);+ const hover = useRef<GraphNode | null>(null);+ const neighbours = useRef<Set<string>>(new Set());+ const resolved = useTheme((s) => s.resolved);+ const selectedRef = useRef<string | null>(selectedId);+ selectedRef.current = selectedId;++ const load = useCallback(async (n: number) => {+ setLoading(true);+ setError(null);+ try { setData(await brain.graph(n)); } catch (e) { setError(e instanceof Error ? e.message : String(e)); }+ setLoading(false);+ }, []);++ // Lazy: nothing is fetched until the graph is first shown.+ useEffect(() => { if (visible && !data && !loading) void load(limit); }, [visible, data, loading, limit, load]);++ const graphData = useMemo(() => (data ? toGraph(data, show) : null), [data, show]);++ // Create the engine once, lazily (dynamic import keeps it out of the main bundle).+ useEffect(() => {+ if (!visible || !graphData || graph.current || !host.current) return;+ let disposed = false;+ void import("force-graph").then(({ default: ForceGraphCtor }) => {+ if (disposed || !host.current) return;+ const el = host.current;+ const g = new ForceGraphCtor<GraphNode, GraphLink>(el)+ .width(el.clientWidth)+ .height(el.clientHeight)+ .backgroundColor("rgba(0,0,0,0)")+ .nodeId("id")+ .nodeRelSize(4)+ .d3VelocityDecay(0.28) // low friction: fluid, springy motion+ .d3AlphaDecay(0.018)+ .cooldownTime(12_000)+ .warmupTicks(30)+ .linkColor((l) => linkColor(l, hover.current))+ .linkWidth((l) => (hover.current && (endId(l.source) === hover.current.id || endId(l.target) === hover.current.id) ? 1.6 : 0.6))+ .nodeCanvasObject((node, ctx, scale) => drawNode(node, ctx, scale, hover.current, neighbours.current, selectedRef.current))+ .nodePointerAreaPaint((node, color, ctx) => { ctx.fillStyle = color; ctx.beginPath(); ctx.arc(node.x ?? 0, node.y ?? 0, radius(node) + 3, 0, 2 * Math.PI); ctx.fill(); })+ .onNodeHover((node) => {+ hover.current = node ?? null;+ neighbours.current = node ? neighbourIds(g.graphData(), node.id) : new Set();+ el.style.cursor = node ? "pointer" : "grab";+ })+ .onNodeClick((node) => {+ onSelect({ id: node.id, kind: node.kind });+ g.centerAt(node.x, node.y, 500);+ })+ .onBackgroundClick(() => onSelect(null))+ .onNodeDragEnd((node) => {+ // Release it back into the flow (fluid) rather than pinning it.+ node.fx = undefined;+ node.fy = undefined;+ savePositions(g.graphData().nodes);+ })+ .onEngineStop(() => savePositions(g.graphData().nodes));+ const charge = g.d3Force("charge");+ charge?.strength?.((n: GraphNode) => (n.kind === "memory" ? -18 : n.kind === "you" ? -400 : -120));+ const link = g.d3Force("link");+ link?.distance?.((l: GraphLink) => (l.kind === "you" ? 90 : l.kind === "relation" ? 60 : 34));+ graph.current = g;+ g.graphData(withPositions(graphData));+ setTimeout(() => g.zoomToFit(600, 60), 900);+ }).catch((e) => setError(e instanceof Error ? e.message : String(e)));+ return () => { disposed = true; };+ }, [visible, graphData, onSelect]);++ // New data or filter: swap the data in, keeping positions.+ useEffect(() => {+ if (graph.current && graphData) graph.current.graphData(withPositions(graphData, graph.current.graphData().nodes));+ }, [graphData]);++ // Pause when hidden: no frames, no CPU.+ useEffect(() => {+ const g = graph.current;+ if (!g) return;+ if (visible) g.resumeAnimation();+ else g.pauseAnimation();+ }, [visible]);++ useEffect(() => {+ const el = host.current;+ if (!el) return;+ const ro = new ResizeObserver(() => { graph.current?.width(el.clientWidth).height(el.clientHeight); });+ ro.observe(el);+ return () => ro.disconnect();+ }, []);++ useEffect(() => () => { graph.current?._destructor(); graph.current = null; }, []);+ useEffect(() => { graph.current?.nodeCanvasObject(graph.current.nodeCanvasObject()); }, [resolved, selectedId]);++ const counts = data ? { people: data.persons.length, memories: data.memories.length, links: data.memoryPersons.length + data.relationships.length } : null;++ return (+ <div className="relative h-full w-full overflow-hidden">+ <div ref={host} className="absolute inset-0" style={{ cursor: "grab" }} />+ <div className="pointer-events-none absolute left-4 top-3 flex items-center gap-2">+ <div className="pointer-events-auto"><Segmented value={show} onChange={setShow} options={[{ value: "all", label: "Everything" }, { value: "people", label: "People" }, { value: "memories", label: "Memories" }]} /></div>+ {counts && <span className="rounded-md bg-surface/80 px-2 py-1 text-xs text-ink3 backdrop-blur">{counts.people} people · {counts.memories} memories · {counts.links} links</span>}+ </div>+ <div className="absolute right-4 top-3 flex items-center gap-1.5">+ {data && data.memories.length >= limit && limit < 2000 && (+ <Button size="sm" variant="outline" onClick={() => { const next = Math.min(2000, limit * 2); setLimit(next); void load(next); }}>Load more</Button>+ )}+ <Button size="sm" variant="ghost" icon onClick={() => graph.current?.zoomToFit(500, 60)} aria-label="Fit to view"><Maximize2 size={14} /></Button>+ <Button size="sm" variant="ghost" icon onClick={() => void load(limit)} loading={loading} aria-label="Reload"><RefreshCw size={14} /></Button>+ </div>+ {!data && !error && <div className="absolute inset-0 flex items-center justify-center text-ink3"><Spinner size={20} /></div>}+ {error && <div className="absolute inset-0 flex items-center justify-center p-8 text-center text-sm text-ink3">Couldn't load the brain: {error}</div>}+ {data && data.memories.length === 0 && data.persons.length === 0 && <div className="absolute inset-0 flex items-center justify-center text-sm text-ink3">Nothing in the brain yet.</div>}+ <Legend />+ </div>+ );++ function linkColor(l: GraphLink, h: GraphNode | null): string {+ const dark = resolved === "dark";+ const lit = h && (endId(l.source) === h.id || endId(l.target) === h.id);+ if (lit) return dark ? "rgba(52,225,161,0.85)" : "rgba(26,158,110,0.85)";+ if (l.kind === "relation") return dark ? "rgba(224,123,168,0.5)" : "rgba(200,90,140,0.45)";+ return dark ? "rgba(230,234,237,0.12)" : "rgba(22,24,26,0.12)";+ }++ function drawNode(n: GraphNode, ctx: CanvasRenderingContext2D, scale: number, h: GraphNode | null, near: Set<string>, selected: string | null) {+ const dark = resolved === "dark";+ const r = radius(n);+ const dim = h && h.id !== n.id && !near.has(n.id);+ ctx.globalAlpha = dim ? 0.25 : 1;+ ctx.beginPath();+ ctx.arc(n.x ?? 0, n.y ?? 0, r, 0, 2 * Math.PI);+ ctx.fillStyle = n.kind === "you" ? (dark ? "#34E1A1" : "#1A9E6E") : n.kind === "person" ? (dark ? "#7FD8E8" : "#0E7C8C") : n.kind === "pet" ? "#F5C451" : TYPE_COLORS[n.type ?? ""] ?? "#8A97A3";+ ctx.fill();+ if (selected === n.id) {+ ctx.lineWidth = 2 / scale;+ ctx.strokeStyle = dark ? "#fff" : "#000";+ ctx.stroke();+ }+ // Names for people always; memory labels only when zoomed in or hovered.+ const showLabel = n.kind !== "memory" || scale > 2.2 || h?.id === n.id;+ if (showLabel) {+ const size = Math.max(10 / scale, n.kind === "memory" ? 3 : 4);+ ctx.font = `${n.kind === "memory" ? 400 : 600} ${size}px "Geist Variable", system-ui, sans-serif`;+ ctx.textAlign = "center";+ ctx.textBaseline = "top";+ ctx.fillStyle = dark ? "rgba(230,234,237,0.92)" : "rgba(22,24,26,0.9)";+ const text = n.kind === "memory" ? truncate(n.label, 48) : n.label;+ ctx.fillText(text, n.x ?? 0, (n.y ?? 0) + r + 1.5);+ }+ ctx.globalAlpha = 1;+ }+}++function toGraph(d: BrainGraphData, show: "all" | "people" | "memories"): { nodes: GraphNode[]; links: GraphLink[] } {+ const nodes: GraphNode[] = [{ id: "you", kind: "you", label: "You", weight: 10 }];+ const links: GraphLink[] = [];+ const people = show !== "memories";+ const mems = show !== "people";+ if (people) {+ for (const p of d.persons) {+ nodes.push({ id: p.id, kind: p.kind === "pet" ? "pet" : "person", label: p.name, weight: p.memoryCount, relationship: p.relationship });+ if (p.relationship && p.relationship !== "known") links.push({ source: "you", target: p.id, kind: "you" });+ }+ for (const r of d.relationships) links.push({ source: r.source, target: r.target, kind: "relation" });+ }+ if (mems) {+ for (const m of d.memories) nodes.push({ id: m.id, kind: "memory", label: m.summary, type: m.type, weight: m.importance });+ if (people) for (const l of d.memoryPersons) links.push({ source: l.memoryId, target: l.personId, kind: "about" });+ // Memories with no person are about you.+ const linked = new Set(people ? d.memoryPersons.map((l) => l.memoryId) : []);+ for (const m of d.memories) if (!linked.has(m.id)) links.push({ source: "you", target: m.id, kind: "you" });+ }+ return { nodes, links };+}++function radius(n: GraphNode): number {+ if (n.kind === "you") return 9;+ if (n.kind === "memory") return 2.2 + Math.min(2.5, n.weight * 2.5);+ return 3.5 + Math.min(6, Math.sqrt(n.weight) * 1.1);+}++function endId(e: string | number | GraphNode | undefined): string {+ return typeof e === "object" && e ? String(e.id) : String(e ?? "");+}++function neighbourIds(data: { links: GraphLink[] }, id: string): Set<string> {+ const out = new Set<string>();+ for (const l of data.links) {+ const s = endId(l.source);+ const t = endId(l.target);+ if (s === id) out.add(t);+ if (t === id) out.add(s);+ }+ return out;+}++function truncate(s: string, n: number): string {+ return s.length > n ? `${s.slice(0, n - 1)}…` : s;+}++function savePositions(nodes: GraphNode[]): void {+ try {+ const out: Record<string, [number, number]> = {};+ for (const n of nodes) if (n.x !== undefined && n.y !== undefined) out[n.id] = [Math.round(n.x), Math.round(n.y)];+ sessionStorage.setItem(POSITIONS_KEY, JSON.stringify(out));+ } catch { /* storage full or blocked: positions are a convenience */ }+}++function withPositions(g: { nodes: GraphNode[]; links: GraphLink[] }, live?: GraphNode[]): { nodes: GraphNode[]; links: GraphLink[] } {+ let saved: Record<string, [number, number]> = {};+ try { saved = JSON.parse(sessionStorage.getItem(POSITIONS_KEY) ?? "{}"); } catch { saved = {}; }+ const current = new Map((live ?? []).map((n) => [n.id, n]));+ return {+ nodes: g.nodes.map((n) => {+ const c = current.get(n.id);+ if (c?.x !== undefined) return { ...n, x: c.x, y: c.y };+ const p = saved[n.id];+ return p ? { ...n, x: p[0], y: p[1] } : n;+ }),+ links: g.links.map((l) => ({ ...l, source: endId(l.source), target: endId(l.target) })),+ };+}++function Legend() {+ const items: Array<[string, string]> = [["You", "bg-accent"], ["Person", "bg-cyan"], ["Pet", "bg-amber"], ["Memory", "bg-ink3"]];+ return (+ <div className="pointer-events-none absolute bottom-3 left-4 flex items-center gap-3 rounded-md bg-surface/80 px-2.5 py-1.5 text-xs text-ink3 backdrop-blur">+ {items.map(([label, cls]) => <span key={label} className="flex items-center gap-1.5"><span className={cx("block h-2.5 w-2.5 rounded-full", cls)} />{label}</span>)}+ <span className="text-ink4">· drag to move · scroll to zoom · click for details</span>+ </div>+ );+}diff --git a/apps/desktop/src/views/brain/BrainView.tsx b/apps/desktop/src/views/brain/BrainView.tsxnew file mode 100644index 00000000..f75eeb5e--- /dev/null+++ b/apps/desktop/src/views/brain/BrainView.tsx@@ -0,0 +1,99 @@+import { useCallback, useEffect, useState } from "react";+import { brain, type BrainMemory, type BrainPerson } from "~/api/brain";+import { useUi } from "~/app/store";+import { ErrorBoundary } from "~/components/ErrorBoundary";+import { Badge, Segmented, Spinner } from "~/components/ui/bits";+import { PageHeader } from "~/components/ui/kit";+import { BrainGraph, type GraphNode } from "./BrainGraph";+import { Memories } from "./Memories";+import { People } from "./People";+import { PersonCard } from "./PersonCard";++type Tab = "graph" | "memories" | "people";+const TAB_KEY = "mercury.brain.tab";++/**+ * The second brain: a living graph, the memories, and the people. Each tab+ * loads its data only when first opened; the graph pauses while hidden;+ * each part is behind its own crash boundary.+ */+export function BrainView() {+ const view = useUi((s) => s.view);+ const [tab, setTab] = useState<Tab>(() => { try { return (sessionStorage.getItem(TAB_KEY) as Tab) || "graph"; } catch { return "graph"; } });+ const [opened, setOpened] = useState<Record<Tab, boolean>>({ graph: false, memories: false, people: false });+ const [selected, setSelected] = useState<{ id: string; kind: GraphNode["kind"] } | null>(null);+ const [people, setPeople] = useState<BrainPerson[]>([]);+ const visible = view === "brain";++ 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(() => {}); }, []);+ useEffect(() => { if (visible && selected && selected.kind !== "memory" && people.length === 0) loadPeople(); }, [visible, selected, people.length, loadPeople]);++ return (+ <div className="flex h-full min-h-0 flex-col">+ <PageHeader title="Brain">+ <Segmented size="md" value={tab} onChange={setTab} options={[{ value: "graph", label: "Graph" }, { value: "memories", label: "Memories" }, { value: "people", label: "People" }]} />+ </PageHeader>+ <div className="relative min-h-0 flex-1">+ <div className={tab === "graph" ? "absolute inset-0 flex" : "hidden"}>+ <div className="relative min-w-0 flex-1">+ {opened.graph && (+ <ErrorBoundary label="The graph" resetKey={tab}>+ <BrainGraph visible={visible && tab === "graph"} selectedId={selected?.id ?? null} onSelect={setSelected} />+ </ErrorBoundary>+ )}+ </div>+ {selected && selected.kind !== "you" && (+ <aside className="w-[380px] shrink-0 overflow-y-auto border-l border-line bg-soft">+ <ErrorBoundary label="Details" resetKey={selected.id}>+ {selected.kind === "memory"+ ? <MemoryDetail id={selected.id} onClose={() => setSelected(null)} onOpenList={() => setTab("memories")} />+ : <PersonCard id={selected.id} allPeople={people} onClose={() => setSelected(null)} onChanged={loadPeople} />}+ </ErrorBoundary>+ </aside>+ )}+ </div>+ <div className={tab === "memories" ? "absolute inset-0" : "hidden"}>+ {opened.memories && <ErrorBoundary label="Memories"><Memories focusId={selected?.kind === "memory" ? selected.id : null} /></ErrorBoundary>}+ </div>+ <div className={tab === "people" ? "absolute inset-0" : "hidden"}>+ {opened.people && <ErrorBoundary label="People"><People initialId={selected && selected.kind !== "memory" && selected.kind !== "you" ? selected.id : null} /></ErrorBoundary>}+ </div>+ </div>+ </div>+ );+}++/** A memory's details, fetched when its node is clicked. */+function MemoryDetail({ id, onClose, onOpenList }: { id: string; onClose: () => void; onOpenList: () => void }) {+ const [m, setM] = useState<BrainMemory | null>(null);+ const [error, setError] = useState<string | null>(null);+ useEffect(() => {+ let live = true;+ setM(null);+ brain.memory(id).then((r) => { if (live) setM(r); }).catch((e) => { if (live) setError(e instanceof Error ? e.message : String(e)); });+ return () => { live = false; };+ }, [id]);+ if (error) return <div className="p-5 text-sm text-red">{error}</div>;+ if (!m) return <div className="p-5 text-ink3"><Spinner size={16} /></div>;+ return (+ <div className="flex flex-col gap-3 p-5">+ <div className="flex items-center gap-2 text-xs text-ink4">+ <Badge>{m.type}</Badge>+ {m.evidenceKind === "owner" && <Badge tone="accent">you said</Badge>}+ <span className="flex-1" />+ <button onClick={onClose} className="rounded-md px-1 text-ink4 hover:text-ink" aria-label="Close">✕</button>+ </div>+ <p className="text-lg leading-relaxed text-ink" data-selectable>{m.summary}</p>+ {m.detail && <p className="text-sm leading-relaxed text-ink2" data-selectable>{m.detail}</p>}+ <dl className="grid grid-cols-2 gap-x-3 gap-y-1.5 rounded-xl border border-line bg-surface p-3 text-sm">+ <dt className="text-ink4">Confidence</dt><dd className="text-ink">{Math.round(m.confidence * 100)}%</dd>+ {m.evidenceCount !== undefined && <><dt className="text-ink4">Evidence</dt><dd className="text-ink">{m.evidenceCount}</dd></>}+ <dt className="text-ink4">First learned</dt><dd className="text-ink">{new Date(m.createdAt).toLocaleDateString()}</dd>+ <dt className="text-ink4">Last updated</dt><dd className="text-ink">{new Date(m.updatedAt).toLocaleDateString()}</dd>+ </dl>+ <button onClick={onOpenList} className="w-fit text-sm text-accent hover:underline">Edit in Memories →</button>+ </div>+ );+}diff --git a/apps/desktop/src/views/brain/Memories.tsx b/apps/desktop/src/views/brain/Memories.tsxnew file mode 100644index 00000000..e8099d63--- /dev/null+++ b/apps/desktop/src/views/brain/Memories.tsx@@ -0,0 +1,138 @@+import { Plus } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import { brain, MEMORY_TYPES, type BrainMemory } from "~/api/brain";+import { Button } from "~/components/ui/Button";+import { Badge, Empty, Spinner } from "~/components/ui/bits";+import { ConfirmButton, SearchField } from "~/components/ui/kit";+import { Menu, MenuItem } from "~/components/ui/Menu";+import { cx } from "~/lib/cx";++const PAGE = 40;++/**+ * Everything Mercury believes about you, newest first, a page at a time+ * (the next page loads as you scroll). Search runs on the runtime's full+ * text index. Each memory can be edited in place or forgotten.+ */+export function Memories({ focusId }: { focusId?: string | null }) {+ const [items, setItems] = useState<BrainMemory[]>([]);+ const [total, setTotal] = useState(0);+ const [loading, setLoading] = useState(false);+ const [q, setQ] = useState("");+ const [adding, setAdding] = useState(false);+ const sentinel = useRef<HTMLDivElement>(null);+ const searching = q.trim().length > 1;++ const loadPage = useCallback(async (offset: number) => {+ setLoading(true);+ try {+ const r = await brain.memories({ limit: PAGE, offset });+ setItems((cur) => (offset === 0 ? r.memories : [...cur, ...r.memories.filter((m) => !cur.some((c) => c.id === m.id))]));+ setTotal(r.total);+ } catch { /* keep what we have */ }+ setLoading(false);+ }, []);++ useEffect(() => {+ if (!searching) { void loadPage(0); return; }+ const t = setTimeout(() => {+ setLoading(true);+ void brain.search(q.trim(), 60).then((r) => { setItems(r.memories); setTotal(r.memories.length); }).finally(() => setLoading(false));+ }, 250);+ return () => clearTimeout(t);+ }, [q, searching, loadPage]);++ useEffect(() => {+ const el = sentinel.current;+ if (!el || searching) return;+ const io = new IntersectionObserver((e) => { if (e.some((x) => x.isIntersecting) && !loading && items.length < total) void loadPage(items.length); }, { rootMargin: "300px" });+ io.observe(el);+ return () => io.disconnect();+ }, [items.length, total, loading, searching, loadPage]);++ return (+ <div className="flex h-full min-h-0 flex-col">+ <div className="flex shrink-0 items-center gap-3 px-6 pb-3 pt-4">+ <SearchField value={q} onChange={setQ} placeholder="Search everything Mercury knows" className="w-[360px]" />+ <span className="text-sm text-ink3">{searching ? `${items.length} found` : `${items.length} of ${total}`}</span>+ <span className="flex-1" />+ <Button size="sm" variant="outline" onClick={() => setAdding((a) => !a)}><Plus size={14} /> Add a memory</Button>+ </div>+ {adding && <AddMemory onDone={(m) => { setAdding(false); if (m) setItems((cur) => [m, ...cur]); }} />}+ <div className="min-h-0 flex-1 overflow-y-auto px-6 pb-6">+ {items.length === 0 && !loading && <Empty title={searching ? "Nothing matches" : "Nothing remembered yet"} />}+ <div className="flex flex-col gap-2">+ {items.map((m) => <MemoryRow key={m.id} m={m} focused={focusId === m.id} onRemoved={() => setItems((cur) => cur.filter((x) => x.id !== m.id))} onSaved={(u) => setItems((cur) => cur.map((x) => (x.id === u.id ? u : x)))} />)}+ </div>+ <div ref={sentinel} className="h-8">{loading && <Spinner size={14} className="text-ink3" />}</div>+ </div>+ </div>+ );+}++function MemoryRow({ m, focused, onRemoved, onSaved }: { m: BrainMemory; focused: boolean; onRemoved: () => void; onSaved: (m: BrainMemory) => void }) {+ const [editing, setEditing] = useState(false);+ const [summary, setSummary] = useState(m.summary);+ const [detail, setDetail] = useState(m.detail ?? "");+ const [busy, setBusy] = useState(false);+ const ref = useRef<HTMLDivElement>(null);+ useEffect(() => { if (focused) ref.current?.scrollIntoView({ block: "center", behavior: "smooth" }); }, [focused]);++ async function save() {+ setBusy(true);+ try {+ await brain.updateMemory(m.id, { summary: summary.trim(), detail: detail.trim() || null });+ onSaved({ ...m, summary: summary.trim(), detail: detail.trim() || null, updatedAt: Date.now() });+ setEditing(false);+ } finally {+ setBusy(false);+ }+ }++ return (+ <div ref={ref} className={cx("group rounded-xl border bg-surface px-4 py-3", focused ? "border-accent/60" : "border-line")}>+ <div className="flex items-center gap-2 text-xs text-ink4">+ <Badge>{m.type}</Badge>+ {m.evidenceKind === "owner" && <Badge tone="accent">you said</Badge>}+ <span>{new Date(m.updatedAt).toLocaleDateString([], { month: "short", day: "numeric", year: "numeric" })}</span>+ <span>· confidence {Math.round(m.confidence * 100)}%</span>+ <span className="flex-1" />+ {!editing && (+ <span className="flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">+ <Button size="sm" variant="ghost" onClick={() => setEditing(true)}>Edit</Button>+ <ConfirmButton size="sm" confirmLabel="Forget?" onConfirm={() => void brain.deleteMemory(m.id).then(onRemoved)}>Forget</ConfirmButton>+ </span>+ )}+ </div>+ {editing ? (+ <div className="mt-2 flex flex-col gap-2">+ <textarea value={summary} onChange={(e) => setSummary(e.target.value)} rows={2} className="w-full rounded-md border border-line bg-bg px-3 py-2 text-base text-ink focus:border-accent/60" aria-label="Memory" />+ <textarea value={detail} onChange={(e) => setDetail(e.target.value)} rows={2} placeholder="Detail (optional)" className="w-full rounded-md border border-line bg-bg px-3 py-2 text-sm text-ink2 focus:border-accent/60" aria-label="Detail" />+ <div className="flex justify-end gap-2"><Button size="sm" variant="ghost" onClick={() => setEditing(false)}>Cancel</Button><Button size="sm" variant="primary" loading={busy} disabled={!summary.trim()} onClick={() => void save()}>Save</Button></div>+ </div>+ ) : (+ <>+ <p className="mt-1.5 text-base leading-relaxed text-ink" data-selectable>{m.summary}</p>+ {m.detail && <p className="mt-1 text-sm text-ink3" data-selectable>{m.detail}</p>}+ </>+ )}+ </div>+ );+}++function AddMemory({ onDone }: { onDone: (m: BrainMemory | null) => void }) {+ const [type, setType] = useState<string>("preference");+ const [summary, setSummary] = useState("");+ const [busy, setBusy] = useState(false);+ return (+ <div className="mx-6 mb-3 flex items-center gap-2 rounded-xl border border-line bg-surface p-3">+ <Menu trigger={<button className="h-9 rounded-md border border-line px-3 text-sm capitalize text-ink">{type}</button>}>+ {MEMORY_TYPES.map((t) => <MenuItem key={t} selected={t === type} onSelect={() => setType(t)}>{t}</MenuItem>)}+ </Menu>+ <input value={summary} onChange={(e) => setSummary(e.target.value)} placeholder="Something Mercury should know…" className="h-9 flex-1 rounded-md border border-line bg-bg px-3 text-sm text-ink focus:border-accent/60" autoFocus+ onKeyDown={(e) => { if (e.key === "Enter" && summary.trim()) { setBusy(true); void brain.addMemory({ type, summary: summary.trim() }).then((m) => onDone(m)).finally(() => setBusy(false)); } }} />+ <Button size="md" variant="primary" loading={busy} disabled={!summary.trim()} onClick={() => { setBusy(true); void brain.addMemory({ type, summary: summary.trim() }).then((m) => onDone(m)).finally(() => setBusy(false)); }}>Remember</Button>+ <Button size="md" variant="ghost" onClick={() => onDone(null)}>Cancel</Button>+ </div>+ );+}diff --git a/apps/desktop/src/views/brain/People.tsx b/apps/desktop/src/views/brain/People.tsxnew file mode 100644index 00000000..232db755--- /dev/null+++ b/apps/desktop/src/views/brain/People.tsx@@ -0,0 +1,108 @@+import { RefreshCw, Sparkles } from "lucide-react";+import { useCallback, useEffect, useMemo, useState } from "react";+import { brain, type BrainPerson, type CheckStatus } from "~/api/brain";+import { Button } from "~/components/ui/Button";+import { Empty, Segmented, Spinner } from "~/components/ui/bits";+import { SearchField } from "~/components/ui/kit";+import { cx } from "~/lib/cx";+import { Initials, PersonCard, VerifiedBadge } from "./PersonCard";++type Filter = "people" | "pets" | "unreviewed" | "all";++/**+ * People: contact cards for everyone in the brain, search, filters, and the+ * card on the right. "Unreviewed" are names Mercury found but nobody has+ * confirmed; the checks panel shows the slow, capped model check.+ */+export function People({ initialId }: { initialId?: string | null }) {+ const [people, setPeople] = useState<BrainPerson[] | null>(null);+ const [q, setQ] = useState("");+ const [filter, setFilter] = useState<Filter>("people");+ const [selected, setSelected] = useState<string | null>(initialId ?? null);+ const [error, setError] = useState<string | null>(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)); }+ }, []);+ useEffect(() => { void load(); }, [load]);+ useEffect(() => { if (initialId) setSelected(initialId); }, [initialId]);++ const shown = useMemo(() => {+ const query = q.trim().toLowerCase();+ return (people ?? [])+ .filter((p) => filter === "all" || (filter === "pets" ? p.kind === "pet" : filter === "unreviewed" ? p.kind === "unverified" : p.kind === "person" || (p.kind === "unverified" && !!p.relationship && p.relationship !== "known")))+ .filter((p) => !query || p.name.toLowerCase().includes(query) || (p.relationship ?? "").toLowerCase().includes(query) || JSON.stringify(p.meta ?? {}).toLowerCase().includes(query));+ }, [people, q, filter]);++ const counts = useMemo(() => ({+ people: (people ?? []).filter((p) => p.kind === "person" || (p.kind === "unverified" && !!p.relationship && p.relationship !== "known")).length,+ pets: (people ?? []).filter((p) => p.kind === "pet").length,+ unreviewed: (people ?? []).filter((p) => p.kind === "unverified").length,+ }), [people]);++ if (error) return <Empty title="Couldn't load people" body={error} />;+ if (!people) return <div className="flex h-40 items-center justify-center text-ink3"><Spinner size={18} /></div>;++ return (+ <div className="flex h-full min-h-0">+ <div className="flex min-w-0 flex-1 flex-col">+ <div className="flex shrink-0 flex-wrap items-center gap-3 px-6 pb-3 pt-4">+ <Segmented size="md" value={filter} onChange={setFilter} options={[+ { value: "people", label: `People · ${counts.people}` },+ { value: "pets", label: `Pets · ${counts.pets}` },+ { value: "unreviewed", label: `Unreviewed · ${counts.unreviewed}` },+ { value: "all", label: "All" },+ ]} />+ <SearchField value={q} onChange={setQ} placeholder="Search names, relationships, details" className="ml-auto w-[300px]" />+ </div>+ {filter === "unreviewed" && <ChecksPanel onChanged={load} />}+ <div className="min-h-0 flex-1 overflow-y-auto px-6 pb-6">+ {shown.length === 0 ? <Empty title={q ? "No one matches" : filter === "unreviewed" ? "Nothing to review" : "No one here yet"} /> : (+ <div className="grid grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-3">+ {shown.map((p) => (+ <button key={p.id} onClick={() => setSelected(p.id)}+ className={cx("flex items-center gap-3 rounded-xl border bg-surface p-3 text-left transition-colors hover:border-line-strong", selected === p.id ? "border-accent/60" : "border-line")}>+ <Initials name={p.name} kind={p.kind} size={40} />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-base font-medium text-ink">{p.name}</span>+ <span className="block truncate text-xs capitalize text-ink3">{p.relationship && p.relationship !== "known" ? p.relationship : `${p.memoryCount} memor${p.memoryCount === 1 ? "y" : "ies"}`}</span>+ <span className="mt-1 block"><VerifiedBadge p={p} /></span>+ </span>+ </button>+ ))}+ </div>+ )}+ </div>+ </div>+ {selected && (+ <aside className="w-[400px] shrink-0 overflow-y-auto border-l border-line bg-soft">+ <PersonCard id={selected} allPeople={people} onClose={() => setSelected(null)} onChanged={() => void load()} />+ </aside>+ )}+ </div>+ );+}++/** Dev-visible: what the "is it a person?" check is doing, with manual controls. */+function ChecksPanel({ onChanged }: { onChanged: () => void }) {+ const [s, setS] = useState<CheckStatus | null>(null);+ const [busy, setBusy] = useState<string | null>(null);+ const [note, setNote] = useState<string | null>(null);+ const load = useCallback(async () => { try { setS(await brain.checks()); } catch { setS(null); } }, []);+ useEffect(() => { void load(); const t = setInterval(() => void load(), 15_000); return () => clearInterval(t); }, [load]);+ if (!s) return null;+ return (+ <div className="mx-6 mb-3 flex flex-wrap items-center gap-3 rounded-xl border border-line bg-surface px-4 py-3 text-sm">+ <Sparkles size={15} className="text-cyan" />+ <span className="text-ink2">Model check: <span className="text-ink">{s.pending}</span> waiting · {s.callsToday}/{s.dailyCap} calls today · {s.checked} checked this run{s.lastRunAt ? ` · last ${new Date(s.lastRunAt).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}` : ""}</span>+ {s.lastError && <span className="text-xs text-amber">last error: {s.lastError}</span>}+ {note && <span className="text-xs text-ink3">{note}</span>}+ <span className="flex-1" />+ <Button size="sm" variant="outline" loading={busy === "queue"} onClick={() => { setBusy("queue"); void brain.queueExisting().then((r) => { setNote(`${r.queued} queued`); void load(); }).finally(() => setBusy(null)); }}>Check existing people</Button>+ <Button size="sm" variant="ghost" loading={busy === "run"} disabled={!s.enabled || s.pending === 0 || s.callsToday >= s.dailyCap} onClick={() => { setBusy("run"); void brain.runCheck().then((r) => { setNote(`${r.checked} checked`); void load(); onChanged(); }).catch((e) => setNote(String(e instanceof Error ? e.message : e))).finally(() => setBusy(null)); }}>+ <RefreshCw size={13} /> Run a batch now+ </Button>+ </div>+ );+}diff --git a/apps/desktop/src/views/brain/PersonCard.tsx b/apps/desktop/src/views/brain/PersonCard.tsxnew file mode 100644index 00000000..9b9aa226--- /dev/null+++ b/apps/desktop/src/views/brain/PersonCard.tsx@@ -0,0 +1,208 @@+import { Cake, Check, Mail, MapPin, PawPrint, Phone, ShieldCheck, Sparkles, Briefcase, Link2, X } from "lucide-react";+import { useEffect, useMemo, useState } from "react";+import { brain, type BrainMemory, type BrainPerson, type PersonMeta } from "~/api/brain";+import { Button } from "~/components/ui/Button";+import { Field, Input } from "~/components/ui/Input";+import { Badge, Segmented, Spinner } from "~/components/ui/bits";+import { ConfirmButton } from "~/components/ui/kit";+import { cx } from "~/lib/cx";++/**+ * A person's contact card: view, edit (name, person or pet, relationship,+ * notes, contact details), merge into another person, or mark "not a+ * person". The id never changes; edits are the owner's and survive every+ * rebuild. Memories that mention them load when the card opens.+ */+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 [editing, setEditing] = useState(false);+ const [error, setError] = useState<string | null>(null);++ async function load() {+ setError(null);+ try {+ const [p, m] = await Promise.all([brain.person(id), brain.personMemories(id)]);+ setPerson(p.person);+ setMemories(m.memories);+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ }+ }+ useEffect(() => { setPerson(null); setMemories(null); setEditing(false); void load(); }, [id]);++ 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>;++ return (+ <div className="flex flex-col gap-5 p-5">+ <div className="flex items-start gap-3">+ <Initials name={person.name} kind={person.kind} size={52} />+ <div className="min-w-0 flex-1">+ <div className="text-lg font-semibold text-ink">{person.name}</div>+ <div className="mt-0.5 flex flex-wrap items-center gap-1.5 text-sm text-ink3">+ {person.relationship && person.relationship !== "known" && <span className="capitalize">{person.relationship}</span>}+ <VerifiedBadge p={person} />+ <span className="text-ink4">· {person.memoryCount} memor{person.memoryCount === 1 ? "y" : "ies"}</span>+ </div>+ </div>+ {onClose && <button onClick={onClose} className="rounded-md p-1 text-ink4 hover:text-ink" aria-label="Close"><X size={16} /></button>}+ </div>++ {editing+ ? <EditForm person={person} onCancel={() => setEditing(false)} onSaved={(p) => { setPerson(p); setEditing(false); onChanged(); }} />+ : <ContactDetails person={person} />}++ {!editing && (+ <div className="flex flex-wrap gap-2">+ <Button size="sm" variant="outline" onClick={() => setEditing(true)}>Edit</Button>+ {person.kind === "unverified" && (+ <>+ <Button size="sm" variant="outline" onClick={() => void brain.updatePerson(id, { kind: "person" }).then((r) => { if (r.person) setPerson(r.person); onChanged(); })}><Check size={13} /> Real person</Button>+ <Button size="sm" variant="outline" onClick={() => void brain.updatePerson(id, { kind: "pet" }).then((r) => { if (r.person) setPerson(r.person); onChanged(); })}><PawPrint size={13} /> A pet</Button>+ </>+ )}+ <MergeInto person={person} people={allPeople} onMerged={(into) => { onChanged(); onClose?.(); void into; }} />+ <ConfirmButton size="sm" confirmLabel="Remove for good?" onConfirm={() => void brain.notAPerson(id).then(() => { onChanged(); onClose?.(); })}>Not a person</ConfirmButton>+ </div>+ )}++ <div>+ <div className="mb-2 text-2xs font-medium uppercase tracking-wider text-ink4">Memories with {person.name.split(" ")[0]}</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) => (+ <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>+ </div>+ </div>+ );+}++function ContactDetails({ person }: { person: BrainPerson }) {+ const m = person.meta ?? {};+ const rows: Array<[typeof Phone, string | undefined, string]> = [+ [Phone, m.phone, "phone"], [Mail, m.email, "email"], [Cake, m.birthday, "birthday"], [MapPin, m.location, "location"], [Briefcase, [m.role, m.company].filter(Boolean).join(" · ") || undefined, "work"],+ ];+ const shown = rows.filter(([, v]) => v);+ return (+ <div className="flex flex-col gap-2">+ {person.summary && <p className="text-sm leading-relaxed text-ink2" data-selectable>{person.summary}</p>}+ {shown.length > 0 && (+ <div className="grid grid-cols-1 gap-1.5 rounded-xl border border-line bg-surface p-3 text-sm">+ {shown.map(([Icon, value, key]) => <div key={key} className="flex items-center gap-2.5 text-ink2" data-selectable><Icon size={14} className="text-ink4" />{value}</div>)}+ {m.links?.map((l) => <a key={l} href={l} target="_blank" rel="noopener noreferrer" className="flex items-center gap-2.5 truncate text-accent hover:underline"><Link2 size={14} className="shrink-0 text-ink4" />{l}</a>)}+ </div>+ )}+ {m.notes && <p className="whitespace-pre-wrap rounded-xl border border-line bg-surface p-3 text-sm text-ink2" data-selectable>{m.notes}</p>}+ {!person.summary && shown.length === 0 && !m.notes && <p className="text-sm text-ink4">No details yet. Add a phone, birthday or notes with Edit.</p>}+ </div>+ );+}++function EditForm({ person, onCancel, onSaved }: { person: BrainPerson; onCancel: () => void; onSaved: (p: BrainPerson) => void }) {+ const [name, setName] = useState(person.name);+ const [kind, setKind] = useState<"person" | "pet">(person.kind === "pet" ? "pet" : "person");+ const [relationship, setRelationship] = useState(person.relationship && person.relationship !== "known" ? person.relationship : "");+ const [summary, setSummary] = useState(person.summary ?? "");+ const [meta, setMeta] = useState<PersonMeta>({ ...person.meta });+ const [links, setLinks] = useState((person.meta.links ?? []).join("\n"));+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const set = (k: keyof PersonMeta) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => setMeta((m) => ({ ...m, [k]: e.target.value }));++ async function save() {+ setBusy(true);+ setError(null);+ try {+ const r = await brain.updatePerson(person.id, {+ name: name.trim() || person.name,+ kind,+ relationship: relationship.trim() || null,+ summary: summary.trim() || null,+ meta: { ...meta, links: links.split(/\s+/).map((l) => l.trim()).filter(Boolean) },+ });+ if (r.person) onSaved(r.person);+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ } finally {+ setBusy(false);+ }+ }++ return (+ <form onSubmit={(e) => { e.preventDefault(); void save(); }} className="flex flex-col gap-3">+ <div className="grid grid-cols-[1fr_auto] items-end gap-3">+ <Field label="Name" htmlFor="pc-name"><Input id="pc-name" value={name} onChange={(e) => setName(e.target.value)} /></Field>+ <Segmented<"person" | "pet"> value={kind} onChange={setKind} options={[{ value: "person", label: "Person" }, { value: "pet", label: "Pet" }]} />+ </div>+ <Field label="Relationship to you" htmlFor="pc-rel"><Input id="pc-rel" value={relationship} onChange={(e) => setRelationship(e.target.value)} placeholder="wife, son, friend, colleague…" /></Field>+ <Field label="About" htmlFor="pc-sum"><textarea id="pc-sum" value={summary} onChange={(e) => setSummary(e.target.value)} rows={2} className="w-full rounded-md border border-line bg-surface px-3 py-2 text-sm text-ink focus:border-accent/60" /></Field>+ <div className="grid grid-cols-2 gap-3">+ <Field label="Phone" htmlFor="pc-phone"><Input id="pc-phone" value={meta.phone ?? ""} onChange={set("phone")} /></Field>+ <Field label="Email" htmlFor="pc-email"><Input id="pc-email" value={meta.email ?? ""} onChange={set("email")} /></Field>+ <Field label="Birthday" htmlFor="pc-bday"><Input id="pc-bday" value={meta.birthday ?? ""} onChange={set("birthday")} placeholder="YYYY-MM-DD" /></Field>+ <Field label="Location" htmlFor="pc-loc"><Input id="pc-loc" value={meta.location ?? ""} onChange={set("location")} /></Field>+ <Field label="Company" htmlFor="pc-co"><Input id="pc-co" value={meta.company ?? ""} onChange={set("company")} /></Field>+ <Field label="Role" htmlFor="pc-role"><Input id="pc-role" value={meta.role ?? ""} onChange={set("role")} /></Field>+ </div>+ <Field label="Links (one per line)" htmlFor="pc-links"><textarea id="pc-links" value={links} onChange={(e) => setLinks(e.target.value)} rows={2} className="w-full rounded-md border border-line bg-surface px-3 py-2 font-mono text-xs text-ink focus:border-accent/60" /></Field>+ <Field label="Notes" htmlFor="pc-notes"><textarea id="pc-notes" value={meta.notes ?? ""} onChange={set("notes")} rows={3} className="w-full rounded-md border border-line bg-surface px-3 py-2 text-sm text-ink focus:border-accent/60" /></Field>+ {error && <p className="text-sm text-red">{error}</p>}+ <div className="flex justify-end gap-2">+ <Button type="button" variant="ghost" onClick={onCancel}>Cancel</Button>+ <Button type="submit" variant="primary" loading={busy}>Save</Button>+ </div>+ </form>+ );+}++function MergeInto({ person, people, onMerged }: { person: BrainPerson; people: BrainPerson[]; onMerged: (into: string) => void }) {+ const [open, setOpen] = useState(false);+ const [q, setQ] = useState("");+ const candidates = useMemo(() => {+ const first = person.name.split(" ")[0].toLowerCase();+ const others = people.filter((p) => p.id !== person.id);+ const query = q.trim().toLowerCase();+ return (query ? others.filter((p) => p.name.toLowerCase().includes(query)) : others.filter((p) => p.name.toLowerCase().includes(first))).slice(0, 8);+ }, [people, person, q]);+ if (!open) return <Button size="sm" variant="outline" onClick={() => setOpen(true)}>Merge into…</Button>;+ return (+ <div className="w-full rounded-xl border border-line bg-surface p-3">+ <div className="mb-2 text-sm text-ink">Merge <span className="font-medium">{person.name}</span> into:</div>+ <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search people" autoFocus />+ <div className="mt-2 flex flex-col gap-1">+ {candidates.map((c) => (+ <button key={c.id} onClick={() => void brain.mergePerson(person.id, c.id).then(() => onMerged(c.id))} className="flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-ink/[0.06]">+ <Initials name={c.name} kind={c.kind} size={22} /> <span className="flex-1 text-ink">{c.name}</span><span className="text-xs text-ink4">{c.memoryCount}</span>+ </button>+ ))}+ {candidates.length === 0 && <p className="px-2 text-xs text-ink4">No match.</p>}+ </div>+ <div className="mt-2 text-right"><Button size="sm" variant="ghost" onClick={() => setOpen(false)}>Cancel</Button></div>+ </div>+ );+}++export function VerifiedBadge({ p }: { p: Pick<BrainPerson, "kind" | "verifiedBy"> }) {+ if (p.verifiedBy === "owner") return <Badge tone="accent"><ShieldCheck size={11} className="mr-1" />{p.kind === "pet" ? "pet · you" : "confirmed by you"}</Badge>;+ if (p.verifiedBy === "model") return <Badge tone="cyan"><Sparkles size={11} className="mr-1" />{p.kind === "pet" ? "pet · checked" : "checked"}</Badge>;+ return <Badge>unreviewed</Badge>;+}++export function Initials({ name, kind, size = 40 }: { name: string; kind: string; size?: number }) {+ let h = 0;+ for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0;+ const hue = kind === "pet" ? 40 : h % 360;+ const letters = name.split(" ").filter(Boolean).slice(0, 2).map((w) => w[0]?.toUpperCase()).join("");+ return (+ <span className={cx("flex shrink-0 items-center justify-center rounded-full font-semibold text-white")}+ style={{ width: size, height: size, fontSize: size * 0.38, background: `linear-gradient(135deg, hsl(${hue} 60% 55%), hsl(${(hue + 30) % 360} 65% 42%))` }} aria-hidden="true">+ {kind === "pet" ? <PawPrint size={size * 0.45} /> : letters}+ </span>+ );+}diff --git a/src/memory/user-memory.ts b/src/memory/user-memory.tsindex a6057676..ac3eafd0 100644--- a/src/memory/user-memory.ts+++ b/src/memory/user-memory.ts@@ -91,7 +91,7 @@ export interface UserPersonRecord {}// 8: stricter name rules, owner overrides, model checks for new names, beliefs indexed.-const PERSON_INDEX_VERSION = '8';+const PERSON_INDEX_VERSION = '9';export class UserMemoryStore {private db: SecondBrainDB;@@ -738,7 +738,7 @@ 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',- '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',+ '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'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',diff --git a/src/web/api/workspace-ide.ts b/src/web/api/workspace-ide.tsindex 6f780ee1..63bc239b 100644--- a/src/web/api/workspace-ide.ts+++ b/src/web/api/workspace-ide.ts@@ -40,6 +40,9 @@ export function git(args: readonly string[], cwd?: string): string {timeout: 15000,maxBuffer: 5 * 1024 * 1024,windowsHide: true,+ // Capture stderr: inheriting it printed "fatal: not a git repository"+ // into the daemon log on every poll of a non-git workspace.+ stdio: ['ignore', 'pipe', 'pipe'],}).trim();}