ei-tui 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -193,7 +193,9 @@ Personas can use tools. Not just read-from-memory tools — *actual* tools. Web
193
193
 
194
194
  | Tool | What it does |
195
195
  |------|-------------|
196
- | `read_memory` | Semantic search of your personal memory — facts, traits, topics, people, quotes. Personas call this automatically when the conversation touches something they might know about you. Supports the `persona` filter to scope results to what a specific persona has learned. |
196
+ | `find_memory` | Semantic search of your personal memory — facts, traits, topics, people, quotes. Personas call this automatically when the conversation touches something they might know about you. Supports the `persona` filter to scope results to what a specific persona has learned. |
197
+ | `fetch_memory` | Full-record lookup for a specific human entity (Fact, Topic, Person, or Quote) by ID. Use after `find_memory` to retrieve complete details. |
198
+ | `fetch_message` | Retrieve a specific message by ID with optional surrounding context. Searches persona conversations and room messages. |
197
199
  | `file_read` | Read a file from your local filesystem *(TUI only)* |
198
200
  | `list_directory` | Explore folder structure *(TUI only)* |
199
201
  | `directory_tree` | Recursive directory tree *(TUI only)* |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ei-tui",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "author": "Flare576",
5
5
  "repository": {
6
6
  "type": "git",
@@ -63,6 +63,8 @@
63
63
  "test:evals:rewrite-real-data": "vite-node tests/evals/rewrite-real-data.eval.ts",
64
64
  "test:evals:topic-validate": "vite-node tests/evals/topic-validate.eval.ts",
65
65
  "test:evals:person-scan": "vite-node tests/evals/person-scan.eval.ts",
66
+ "test:evals:person-scan-confidence": "vite-node tests/evals/person-scan-confidence.eval.ts",
67
+
66
68
  "test:evals:person-update": "vite-node tests/evals/person-update.eval.ts",
67
69
  "test:evals:persona-trait": "vite-node tests/evals/persona-trait-extraction.eval.ts",
68
70
  "test:evals:dedup": "vite-node tests/evals/dedup-tool-calls.eval.ts",
package/src/cli/README.md CHANGED
@@ -37,13 +37,29 @@ ei "memory leak" | jq '.[0].id' | ei --id
37
37
  ei --install
38
38
  ```
39
39
 
40
- This registers Ei with every supported agent environment it detects:
41
-
42
- - **OpenCode**: writes `~/.config/opencode/tools/ei.ts`
43
- - **Claude Code**: runs `claude mcp add` (or writes `~/.claude.json` as fallback)
44
- - **Cursor**: writes `~/.cursor/mcp.json`
40
+ This registers Ei with Claude Code and Cursor via MCP:
41
+
42
+ - **Claude Code**: writes `~/.claude.json` with an MCP server entry
43
+ - **Cursor**: writes `~/.cursor/mcp.json` with an MCP server entry
44
+
45
+ **OpenCode**: add the MCP server manually to `~/.config/opencode/opencode.jsonc`:
46
+
47
+ ```json
48
+ {
49
+ "mcp": {
50
+ "ei": {
51
+ "type": "local",
52
+ "command": ["bunx", "ei-tui", "mcp"],
53
+ "enabled": true,
54
+ "environment": {
55
+ "EI_DATA_PATH": "/path/to/your/ei/data"
56
+ }
57
+ }
58
+ }
59
+ }
60
+ ```
45
61
 
46
- Restart your agent tool after running to activate.
62
+ Restart your agent tool after changes to activate.
47
63
 
48
64
  ### MCP Server
49
65
 
@@ -123,23 +139,35 @@ conversations (facts, people, topics, quotes, personas).
123
139
 
124
140
  **How to use:**
125
141
  1. Call `ei_search` (server `user-ei`) with a natural-language query (or omit query and use `recent: true` to browse); optionally filter by `type` (facts, people, topics, quotes, personas) or `persona` display_name.
126
- 2. If you need full detail for a result, call `ei_lookup` with the entity `id` from step 1.
142
+ 2. If you need full detail for a human entity (fact, topic, person, quote), call `ei_fetch_memory` with the entity `id`.
143
+ 3. If you need full detail for a result including personas, call `ei_lookup` with the entity `id` from step 1.
144
+ 4. To fetch a specific message with surrounding context, call `ei_fetch_message` with the message `id` and optional `before`/`after` counts.
127
145
 
128
146
  Prefer querying Ei before asking the user for context they may have already shared.
129
147
  ```
130
148
 
131
- ## What the Tool Provides
149
+ ## MCP Tools Reference
150
+
151
+ The MCP server exposes these tools to Claude Code, Cursor, and OpenCode:
152
+
153
+ | Tool | Description |
154
+ |------|-------------|
155
+ | `ei_search` | Balanced search across all five data types (facts, topics, people, quotes, personas). Supports `type`, `persona`, `source`, `recent`, `limit` filters. |
156
+ | `ei_lookup` | Full-record lookup for any entity by ID (facts, topics, people, quotes, personas). |
157
+ | `ei_find_memory` | Grouped human-data search — facts, topics, people, quotes. Returns results grouped by type. Mirrors the persona `find_memory` tool interface. |
158
+ | `ei_fetch_memory` | Full-record lookup for a human entity (Fact, Topic, Person, or Quote) by ID. Returns the complete record including all fields. |
159
+ | `ei_fetch_message` | Retrieve a specific message by ID with optional `before`/`after` context window. Searches persona conversations and room messages. |
132
160
 
133
- The installed tool gives OpenCode agents access to all five data types with proper Zod-validated args:
161
+ ### `ei_search` / `ei_find_memory` arguments
134
162
 
135
163
  | Arg | Type | Description |
136
164
  |-----|------|-------------|
137
- | `query` | string (optional) | Search text, or entity ID when `lookup=true`. Omit to browse by recency. |
138
- | `persona` | string (optional) | Persona display_name to filter results only returns entities that persona has extracted |
139
- | `type` | enum (optional) | `facts` \| `people` \| `topics` \| `quotes` \| `personas` — omit for balanced results |
165
+ | `query` | string (optional) | Search text. Omit to browse by recency. |
166
+ | `persona` | string (optional) | Persona display_name to scope results to what that persona has learned |
167
+ | `type` | enum (optional, `ei_search` only) | `facts` \| `people` \| `topics` \| `quotes` \| `personas` — omit for balanced results |
168
+ | `types` | array (optional, `ei_find_memory` only) | `["facts", "topics", "people", "quotes"]` — omit for all human types |
140
169
  | `limit` | number (optional) | Max results, default 10 |
141
- | `lookup` | boolean (optional) | If true, fetch single entity by ID |
142
- | `recent` | boolean (optional) | If true, sort by most recently mentioned. Can be combined with `persona` or `query`. |
170
+ | `recent` | boolean (optional) | Sort by most recently mentioned instead of relevance |
143
171
 
144
172
  ## Output Shapes
145
173
 
package/src/cli/mcp.ts CHANGED
@@ -3,6 +3,8 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
3
3
  import { z } from "zod";
4
4
  import { retrieveBalanced, lookupById, loadLatestState, type BalancedResult } from "./retrieval.js";
5
5
  import type { StorageState } from "../core/types.js";
6
+ import type { Message } from "../core/types.js";
7
+ import type { RoomMessage } from "../core/types/rooms.js";
6
8
  import { resolvePersonaId, filterByPersona, filterTypeSpecificByPersona, filterBySource, filterTypeSpecificBySource } from "./persona-filter.js";
7
9
 
8
10
  // Exported so tests can inject their own transport
@@ -128,6 +130,241 @@ export function createMcpServer(): McpServer {
128
130
  }
129
131
  );
130
132
 
133
+ server.registerTool(
134
+ "ei_find_memory",
135
+ {
136
+ description:
137
+ "Search Ei's persistent knowledge base — facts, topics, people, and quotes learned across ALL conversations over time. Use when you need context about the user, their life, relationships, or interests that may not be visible in the current exchange. Returns results grouped by type. Use `recent: true` to retrieve what's been discussed recently.",
138
+ inputSchema: {
139
+ query: z
140
+ .string()
141
+ .optional()
142
+ .describe(
143
+ "What to search for — a person, topic, fact, or anything Ei has learned about the user. Omit with recent: true to browse recent items."
144
+ ),
145
+ types: z
146
+ .array(z.enum(["facts", "topics", "people", "quotes"]))
147
+ .optional()
148
+ .describe("Limit search to specific memory types (default: all types)"),
149
+ limit: z
150
+ .number()
151
+ .optional()
152
+ .default(10)
153
+ .describe("Max results per type to return (default: 10, max: 20)"),
154
+ recent: z
155
+ .boolean()
156
+ .optional()
157
+ .describe(
158
+ "If true, return recently-mentioned results sorted by last_mentioned date instead of relevance. Combine with a query to filter recent results by topic."
159
+ ),
160
+ persona: z
161
+ .string()
162
+ .optional()
163
+ .describe(
164
+ "Filter results to what a specific persona has learned. Use the persona display name."
165
+ ),
166
+ },
167
+ },
168
+ async ({ query: rawQuery, types, limit, recent, persona }) => {
169
+ const query = rawQuery ?? "";
170
+ const effectiveLimit = Math.min(limit ?? 10, 20);
171
+ const options = { recent: recent ?? false };
172
+
173
+ const humanTypes = ["facts", "topics", "people", "quotes"] as const;
174
+ type HumanType = (typeof humanTypes)[number];
175
+ const requestedTypes: HumanType[] =
176
+ types && types.length > 0
177
+ ? (types as HumanType[])
178
+ : [...humanTypes];
179
+
180
+ let state: StorageState | null = null;
181
+ let personaId: string | undefined;
182
+ if (persona) {
183
+ state = await loadLatestState();
184
+ if (state) {
185
+ personaId = resolvePersonaId(state, persona) ?? undefined;
186
+ if (!personaId) {
187
+ return {
188
+ content: [{ type: "text" as const, text: `Persona "${persona}" not found.` }],
189
+ };
190
+ }
191
+ }
192
+ }
193
+
194
+ const grouped: Record<string, unknown[]> = {};
195
+ for (const t of requestedTypes) {
196
+ const module = await import(`./commands/${t}.js`);
197
+ let results = await (
198
+ module.execute as (
199
+ q: string,
200
+ l: number,
201
+ o: { recent: boolean }
202
+ ) => Promise<{ id: string }[]>
203
+ )(query, effectiveLimit, options);
204
+ if (personaId && state) {
205
+ results = filterTypeSpecificByPersona(results, state, personaId, t);
206
+ }
207
+ if (results.length > 0) {
208
+ grouped[t] = results;
209
+ }
210
+ }
211
+
212
+ if (Object.keys(grouped).length === 0) {
213
+ return {
214
+ content: [
215
+ {
216
+ type: "text" as const,
217
+ text: JSON.stringify({ result: "No relevant memories found for this query." }),
218
+ },
219
+ ],
220
+ };
221
+ }
222
+
223
+ return {
224
+ content: [{ type: "text" as const, text: JSON.stringify(grouped, null, 2) }],
225
+ };
226
+ }
227
+ );
228
+
229
+ server.registerTool(
230
+ "ei_fetch_memory",
231
+ {
232
+ description:
233
+ "Retrieve the full record for a specific memory by its ID. Use when ei_find_memory or ei_search returns an item and you need its complete details. Returns the full Fact, Topic, Person, or Quote record.",
234
+ inputSchema: {
235
+ id: z.string().describe("The ID of the memory record to retrieve"),
236
+ },
237
+ },
238
+ async ({ id }) => {
239
+ const result = await lookupById(id);
240
+
241
+ if (result === null || result.type === "persona") {
242
+ return {
243
+ content: [{ type: "text" as const, text: `No memory record found with ID: ${id}` }],
244
+ };
245
+ }
246
+
247
+ return {
248
+ content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
249
+ };
250
+ }
251
+ );
252
+
253
+ server.registerTool(
254
+ "ei_fetch_message",
255
+ {
256
+ description:
257
+ "Retrieve a specific message by its ID, with optional surrounding context. Use when ei_find_memory returns a quote with a message_id and you want to read the original conversation. The 'before' and 'after' parameters return that many additional messages for context (default 0).",
258
+ inputSchema: {
259
+ id: z.string().describe("The ID of the message to retrieve"),
260
+ before: z
261
+ .number()
262
+ .optional()
263
+ .default(0)
264
+ .describe("Number of preceding messages to include (default 0)"),
265
+ after: z
266
+ .number()
267
+ .optional()
268
+ .default(0)
269
+ .describe("Number of following messages to include (default 0)"),
270
+ },
271
+ },
272
+ async ({ id, before: beforeCount, after: afterCount }) => {
273
+ const state = await loadLatestState();
274
+ if (!state) {
275
+ return {
276
+ content: [{ type: "text" as const, text: "No saved state found. Is EI_DATA_PATH set correctly?" }],
277
+ };
278
+ }
279
+
280
+ const beforeN = Math.max(0, Math.floor(beforeCount ?? 0));
281
+ const afterN = Math.max(0, Math.floor(afterCount ?? 0));
282
+
283
+ const stripPersonaMessage = (m: Message) => ({
284
+ id: m.id,
285
+ role: m.role,
286
+ ...(m.content !== undefined ? { content: m.content } : {}),
287
+ ...(m.silence_reason !== undefined ? { silence_reason: m.silence_reason } : {}),
288
+ timestamp: m.timestamp,
289
+ ...(m.speaker_name !== undefined ? { speaker_name: m.speaker_name } : {}),
290
+ });
291
+
292
+ for (const { entity: persona, messages } of Object.values(state.personas)) {
293
+ const idx = messages.findIndex((m) => m.id === id);
294
+ if (idx === -1) continue;
295
+
296
+ const msg = messages[idx];
297
+ const beforeMsgs = messages.slice(Math.max(0, idx - beforeN), idx).map(stripPersonaMessage);
298
+ const afterMsgs = messages.slice(idx + 1, idx + 1 + afterN).map(stripPersonaMessage);
299
+
300
+ return {
301
+ content: [
302
+ {
303
+ type: "text" as const,
304
+ text: JSON.stringify(
305
+ { message: stripPersonaMessage(msg), before: beforeMsgs, after: afterMsgs, source: persona.display_name },
306
+ null,
307
+ 2
308
+ ),
309
+ },
310
+ ],
311
+ };
312
+ }
313
+
314
+ const resolveRoomPersonaName = (
315
+ m: RoomMessage,
316
+ personaMap: Record<string, { entity: { display_name: string }; messages: Message[] }>
317
+ ): string | undefined => {
318
+ if (m.role !== "persona" || !m.persona_id) return undefined;
319
+ return personaMap[m.persona_id]?.entity.display_name;
320
+ };
321
+
322
+ const stripRoomMessage = (
323
+ m: RoomMessage,
324
+ personaMap: Record<string, { entity: { display_name: string }; messages: Message[] }>
325
+ ) => ({
326
+ id: m.id,
327
+ role: m.role,
328
+ ...(m.content !== undefined ? { content: m.content } : {}),
329
+ ...(m.silence_reason !== undefined ? { silence_reason: m.silence_reason } : {}),
330
+ timestamp: m.timestamp,
331
+ ...(resolveRoomPersonaName(m, personaMap) !== undefined
332
+ ? { speaker_name: resolveRoomPersonaName(m, personaMap) }
333
+ : {}),
334
+ });
335
+
336
+ for (const room of Object.values(state.rooms ?? {})) {
337
+ const idx = room.messages.findIndex((m) => m.id === id);
338
+ if (idx === -1) continue;
339
+
340
+ const msg = room.messages[idx];
341
+ const beforeMsgs = room.messages
342
+ .slice(Math.max(0, idx - beforeN), idx)
343
+ .map((m) => stripRoomMessage(m, state.personas));
344
+ const afterMsgs = room.messages
345
+ .slice(idx + 1, idx + 1 + afterN)
346
+ .map((m) => stripRoomMessage(m, state.personas));
347
+
348
+ return {
349
+ content: [
350
+ {
351
+ type: "text" as const,
352
+ text: JSON.stringify(
353
+ { message: stripRoomMessage(msg, state.personas), before: beforeMsgs, after: afterMsgs, source: room.display_name },
354
+ null,
355
+ 2
356
+ ),
357
+ },
358
+ ],
359
+ };
360
+ }
361
+
362
+ return {
363
+ content: [{ type: "text" as const, text: `Message not found: ${id}` }],
364
+ };
365
+ }
366
+ );
367
+
131
368
  return server;
132
369
  }
133
370
 
package/src/cli.ts CHANGED
@@ -68,7 +68,7 @@ Options:
68
68
  --persona, -p Filter to entities a specific persona has learned about
69
69
  --source, -s Filter to entities from a specific source (prefix match, e.g. "cursor", "opencode:my-machine", "opencode:my-machine:ses_abc123")
70
70
  --id Look up entity by ID (accepts value or stdin)
71
- --install Register Ei with OpenCode, Claude Code, and Cursor
71
+ --install Register Ei with Claude Code and Cursor via MCP
72
72
  --help, -h Show this help message
73
73
 
74
74
  Examples:
@@ -85,50 +85,9 @@ Examples:
85
85
  }
86
86
 
87
87
 
88
- async function installOpenCodeMcp(): Promise<void> {
89
- const home = process.env.HOME || "~";
90
- const opencodeDir = join(home, ".config", "opencode");
91
- const opencodeJsoncPath = join(opencodeDir, "opencode.jsonc");
92
-
93
- const eiDataPath = process.env.EI_DATA_PATH ?? (() => {
94
- const xdgData = process.env.XDG_DATA_HOME || join(home, ".local", "share");
95
- return join(xdgData, "ei");
96
- })();
97
-
98
- const mcpEntry = {
99
- type: "local",
100
- command: ["bunx", "ei-tui", "mcp"],
101
- enabled: true,
102
- environment: {
103
- EI_DATA_PATH: eiDataPath,
104
- },
105
- };
106
-
107
- let config: Record<string, unknown> = {};
108
- try {
109
- const rawText = await Bun.file(opencodeJsoncPath).text();
110
- // Strip // line comments before parsing — opencode.jsonc uses line comments only
111
- const stripped = rawText
112
- .split("\n")
113
- .map(line => line.replace(/\/\/.*$/, ""))
114
- .join("\n");
115
- config = JSON.parse(stripped) as Record<string, unknown>;
116
- } catch {
117
- // File doesn't exist or isn't valid — start fresh
118
- }
119
-
120
- const mcp = (config.mcp ?? {}) as Record<string, unknown>;
121
- mcp["ei"] = mcpEntry;
122
- config.mcp = mcp;
123
-
124
- await Bun.$`mkdir -p ${opencodeDir}`;
125
- const tmpPath = `${opencodeJsoncPath}.ei-install.tmp`;
126
- await Bun.write(tmpPath, JSON.stringify(config, null, 2) + "\n");
127
- const { rename } = await import(/* @vite-ignore */ "fs/promises");
128
- await rename(tmpPath, opencodeJsoncPath);
129
-
130
- console.log(`✓ Installed Ei MCP server to ~/.config/opencode/opencode.jsonc`);
131
- console.log(` Restart OpenCode to activate.`);
88
+ async function installMcpClients(): Promise<void> {
89
+ await installClaudeCode();
90
+ await installCursor();
132
91
  }
133
92
 
134
93
  async function installClaudeCode(): Promise<void> {
@@ -202,11 +161,6 @@ async function installCursor(): Promise<void> {
202
161
  console.log(` Restart Cursor to activate.`);
203
162
  }
204
163
 
205
- async function installMcpClients(): Promise<void> {
206
- await installClaudeCode();
207
- await installCursor();
208
- }
209
-
210
164
  async function main(): Promise<void> {
211
165
  const args = process.argv.slice(2);
212
166
 
@@ -228,9 +182,21 @@ async function main(): Promise<void> {
228
182
  }
229
183
 
230
184
  if (args[0] === "--install") {
231
- await installOpenCodeMcp();
232
185
  await installMcpClients();
233
186
  console.log(`
187
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
188
+ OpenCode: add to ~/.config/opencode/opencode.jsonc
189
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
190
+
191
+ "mcp": {
192
+ "ei": {
193
+ "type": "local",
194
+ "command": ["bunx", "ei-tui", "mcp"],
195
+ "enabled": true,
196
+ "environment": { "EI_DATA_PATH": "${process.env.EI_DATA_PATH ?? "~/.local/share/ei"}" }
197
+ }
198
+ }
199
+
234
200
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
235
201
  Add this to ~/.config/opencode/AGENTS.md
236
202
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
@@ -92,7 +92,7 @@ export async function handleFactFind(response: LLMResponse, state: StateManager)
92
92
  markMessagesExtracted(response, state, "f");
93
93
 
94
94
  if (!result?.facts || !Array.isArray(result.facts)) {
95
- console.log("[handleFactFind] No facts detected or invalid result");
95
+ console.debug("[handleFactFind] No facts detected or invalid result");
96
96
  return;
97
97
  }
98
98
 
@@ -106,26 +106,26 @@ export async function handleFactFind(response: LLMResponse, state: StateManager)
106
106
  for (const factResult of result.facts) {
107
107
  // Only upsert facts that match a built-in name
108
108
  if (!BUILT_IN_FACT_NAMES.has(factResult.name)) {
109
- console.log(`[handleFactFind] Skipping non-built-in fact: "${factResult.name}"`);
109
+ console.warn(`[handleFactFind] Skipping non-built-in fact: "${factResult.name}"`);
110
110
  continue;
111
111
  }
112
112
 
113
113
  // Find the existing fact in state
114
114
  const existingFact = human.facts.find(f => f.name === factResult.name);
115
115
  if (!existingFact) {
116
- console.log(`[handleFactFind] Skipping unknown fact: "${factResult.name}"`);
116
+ console.warn(`[handleFactFind] Skipping unknown fact: "${factResult.name}"`);
117
117
  continue;
118
118
  }
119
119
 
120
120
  // Skip facts that already have descriptions (only fill empty ones)
121
121
  if (existingFact.description && existingFact.description !== "") {
122
- console.log(`[handleFactFind] Skipping fact with existing description: "${factResult.name}"`);
122
+ console.debug(`[handleFactFind] Skipping fact with existing description: "${factResult.name}"`);
123
123
  continue;
124
124
  }
125
125
 
126
126
  // Skip if the LLM returned a null/empty/non-string value — don't store booleans or nulls
127
127
  if (!factResult.value || typeof factResult.value !== 'string') {
128
- console.log(`[handleFactFind] Skipping fact with null/empty/non-string value: "${factResult.name}" (got ${typeof factResult.value})`);
128
+ console.warn(`[handleFactFind] Skipping fact with null/empty/non-string value: "${factResult.name}" (got ${typeof factResult.value})`);
129
129
  continue;
130
130
  }
131
131
 
@@ -165,7 +165,7 @@ export async function handleHumanTopicScan(response: LLMResponse, state: StateMa
165
165
  markMessagesExtracted(response, state, "t");
166
166
 
167
167
  if (!result?.topics || !Array.isArray(result.topics)) {
168
- console.log("[handleHumanTopicScan] No topics detected or invalid result");
168
+ console.debug("[handleHumanTopicScan] No topics detected or invalid result");
169
169
  return;
170
170
  }
171
171
 
@@ -185,7 +185,7 @@ export async function handleHumanPersonScan(response: LLMResponse, state: StateM
185
185
  markMessagesExtracted(response, state, "p");
186
186
 
187
187
  if (!result?.people || !Array.isArray(result.people)) {
188
- console.log("[handleHumanPersonScan] No people detected or invalid result");
188
+ console.debug("[handleHumanPersonScan] No people detected or invalid result");
189
189
  return;
190
190
  }
191
191
 
@@ -231,7 +231,7 @@ export async function handleHumanPersonScan(response: LLMResponse, state: StateM
231
231
  }
232
232
  }
233
233
  if (!matchedPerson) {
234
- console.log(`[handleHumanPersonScan] Multi-match for "${candidate.name}" (${matches.length} hits) — no embedding above threshold, creating new record`);
234
+ console.debug(`[handleHumanPersonScan] Multi-match for "${candidate.name}" (${matches.length} hits) — no embedding above threshold, creating new record`);
235
235
  }
236
236
  } catch (err) {
237
237
  console.warn(`[handleHumanPersonScan] Multi-match embedding failed for "${candidate.name}", using first match:`, err);
@@ -253,7 +253,7 @@ export async function handleHumanPersonScan(response: LLMResponse, state: StateM
253
253
  if (isUnknownPlaceholder || isSingleton) {
254
254
  matchedPerson = existing;
255
255
  const reason = isUnknownPlaceholder ? 'unnamed placeholder' : 'singleton relationship';
256
- console.log(`[handleHumanPersonScan] Relationship unique match: "${candidate.name}" → "${existing.name}" (sole ${candidate.relationship}, ${reason})`);
256
+ console.debug(`[handleHumanPersonScan] Relationship unique match: "${candidate.name}" → "${existing.name}" (sole ${candidate.relationship}, ${reason})`);
257
257
  }
258
258
  } else {
259
259
  // N>1 same relationship → cosine within that subset.
@@ -267,7 +267,7 @@ export async function handleHumanPersonScan(response: LLMResponse, state: StateM
267
267
  : `all ${human.people.length} people`;
268
268
 
269
269
  if (searchPool.length > 0) {
270
- console.log(`[handleHumanPersonScan] "${candidate.name}": cosine against ${searchPool.length} embedded (${poolLabel})`);
270
+ console.debug(`[handleHumanPersonScan] "${candidate.name}": cosine against ${searchPool.length} embedded (${poolLabel})`);
271
271
  try {
272
272
  const embeddingService = getEmbeddingService();
273
273
  const candidateText = getPersonEmbeddingText({
@@ -288,15 +288,15 @@ export async function handleHumanPersonScan(response: LLMResponse, state: StateM
288
288
  }
289
289
  const top3 = scores.sort((a, b) => b.sim - a.sim).slice(0, 3).map(s => `"${s.name}"=${s.sim.toFixed(3)}`).join(', ');
290
290
  if (matchedPerson) {
291
- console.log(`[handleHumanPersonScan] Cosine matched "${candidate.name}" → "${matchedPerson.name}" (${bestSimilarity.toFixed(3)}) | top3: ${top3}`);
291
+ console.debug(`[handleHumanPersonScan] Cosine matched "${candidate.name}" → "${matchedPerson.name}" (${bestSimilarity.toFixed(3)}) | top3: ${top3}`);
292
292
  } else {
293
- console.log(`[handleHumanPersonScan] Cosine: no match above ${ZERO_MATCH_COSINE_THRESHOLD} for "${candidate.name}" | top3: ${top3}`);
293
+ console.debug(`[handleHumanPersonScan] Cosine: no match above ${ZERO_MATCH_COSINE_THRESHOLD} for "${candidate.name}" | top3: ${top3}`);
294
294
  }
295
295
  } catch (err) {
296
296
  console.warn(`[handleHumanPersonScan] Cosine failed for "${candidate.name}":`, err);
297
297
  }
298
298
  } else {
299
- console.log(`[handleHumanPersonScan] "${candidate.name}": no embedded people in pool (${poolLabel}) — new person`);
299
+ console.debug(`[handleHumanPersonScan] "${candidate.name}": no embedded people in pool (${poolLabel}) — new person`);
300
300
  }
301
301
  }
302
302
  }
@@ -305,11 +305,17 @@ export async function handleHumanPersonScan(response: LLMResponse, state: StateM
305
305
  const linkedPersonaId = matchedPerson.identifiers
306
306
  ?.find(i => i.type === "Ei Persona")?.value;
307
307
  if (linkedPersonaId) {
308
- console.log(`[handleHumanPersonScan] Skipping update for "${candidate.name}" — scan marked as reflection drain (reflection_progress=1)`);
308
+ console.debug(`[handleHumanPersonScan] Skipping update for "${candidate.name}" — scan marked as reflection drain (reflection_progress=1)`);
309
309
  continue;
310
310
  }
311
311
  }
312
312
 
313
+ const confidence = typeof candidate.confidence === 'number' ? candidate.confidence : null;
314
+ if (confidence !== null && confidence <= 2 && !matchedPerson) {
315
+ console.debug(`[handleHumanPersonScan] Skipping low-confidence new person "${candidate.name}" (confidence=${confidence}, relationship_type=${candidate.relationship_type ?? 'none'})`);
316
+ continue;
317
+ }
318
+
313
319
  const matchResult: ItemMatchResult = { matched_guid: matchedPerson?.id ?? null };
314
320
  queuePersonUpdate(matchResult, {
315
321
  ...context,
@@ -326,7 +332,7 @@ export async function handleHumanPersonScan(response: LLMResponse, state: StateM
326
332
  : matches.length > 1
327
333
  ? `multi-match ambiguous (${matches.length} hits) — new record`
328
334
  : "no match (new person)";
329
- console.log(`[handleHumanPersonScan] person "${candidate.name}": ${matched}`);
335
+ console.debug(`[handleHumanPersonScan] person "${candidate.name}": ${matched}`);
330
336
  }
331
337
  console.log(`[handleHumanPersonScan] Processed ${result.people.length} person(s)`);
332
338
  }
@@ -337,7 +343,7 @@ export async function handleEventScan(response: LLMResponse, state: StateManager
337
343
  const result = response.parsed as { events?: Array<{ name: string; description: string; reason: string }> } | undefined;
338
344
 
339
345
  if (!result?.events || !Array.isArray(result.events) || result.events.length === 0) {
340
- console.log("[handleEventScan] No epic events detected");
346
+ console.debug("[handleEventScan] No epic events detected");
341
347
  return;
342
348
  }
343
349