Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(mcp-host): materialize and project session auto-title (spec 15 Phase A)

Diego Zacarias8ccf3342ddd5
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 989fabd78..229cf9981 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.318",
+ "version": "0.1.319",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.318",
+ "version": "0.1.319",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index ab015268a..21dcbdfcc 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.318",
+ "version": "0.1.319",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts b/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
index 67ef24f71..7c169ca66 100644
--- a/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
+++ b/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
@@ -58,6 +58,7 @@ function makeApp(convManager: ConversationManager) {
const { handleSessionsList, handleSessionMessages } = createSessionRouteHandlers({
getConversationManager: () => convManager,
redactToolError: (_toolName, rawError) => rawError,
+ redactTitle: rawTitle => rawTitle,
})
const handlers = makeHandlers({
sessionsListHandler: handleSessionsList,
diff --git a/mcp-host/src/agent/__tests__/taskExecutor.test.ts b/mcp-host/src/agent/__tests__/taskExecutor.test.ts
index fe21fcc95..a797d7032 100644
--- a/mcp-host/src/agent/__tests__/taskExecutor.test.ts
+++ b/mcp-host/src/agent/__tests__/taskExecutor.test.ts
@@ -241,7 +241,10 @@ describe('TaskExecutor', () => {
expect.objectContaining({
...traceContext,
sessionId: expect.stringMatching(/^conv-user-1:telegram:test-channel:default-/),
- })
+ }),
+ // spec 15 — turn 1 derives the auto-title from the first input (channel
+ // sessions included); a short input passes through deriveAutoTitle intact.
+ 'Hello'
)
expect(task.traceContext?.sessionId).toMatch(/^conv-user-1:telegram:test-channel:default-/)
})
diff --git a/mcp-host/src/agent/taskExecutor.ts b/mcp-host/src/agent/taskExecutor.ts
index 77c1b4e85..bf3deeca2 100644
--- a/mcp-host/src/agent/taskExecutor.ts
+++ b/mcp-host/src/agent/taskExecutor.ts
@@ -14,6 +14,7 @@ import { AdapterStaticContext, LlmPortAdapter } from '../core/adapters/llmPortAd
import { CompositeToolRegistry, McpToolRegistryAdapter } from '../core/adapters/toolRegistryAdapter'
import { compactConversation } from '../core/conversation/compaction'
import { ConversationManager } from '../core/conversation/conversation'
+import { deriveAutoTitle } from '../core/conversation/sessionTitle'
import { LlmError, LlmErrorCode } from '../core/errors'
import { ApprovalController } from '../core/extensions/approvalController'
import type { ApprovalConfig } from '../core/extensions/approvalTypes'
@@ -398,6 +399,37 @@ export class TaskExecutor {
}
}
const userInput = msg?.content || this.task.conversationHistory[0]?.content || ''
+ // Auto-title (spec 15): on turn 1 only, derive the server-authoritative
+ // session title. Security order is FIXED (§5): redact the FULL input with
+ // the operator secret list FIRST, then collapse+truncate — truncating
+ // first would split a secret across the cut and defeat the literal match.
+ // `sanitizeFreeformContent` (not `sanitizeOutput`) so we don't emit a log
+ // line per turn. Applies to channel sessions too (same sanitization).
+ //
+ // "Turn 1" gate: `turns.length === 0` is a RAM proxy for the durable
+ // turn-1 signal. It MUST stay in lock-step with the durable write gate in
+ // `SqliteConversationStore.persistTurnStart` (`turnNumber === 1`): if this
+ // set a RAM title on a turn the durable write skips, the memory store would
+ // project a title the SQLite store does not, breaking dual-store parity.
+ // The two agree today because a fresh session starts at `turns.length === 0`
+ // AND `nextTurnNumber === 1`, and a cold-load rehydrates both together.
+ // They would diverge only if compaction/LRU/paginated cold-load ever shrank
+ // `turns` without resetting the durable `turnNumber` — none of which exist
+ // yet. If any is enabled, gate this on the durable turn number instead
+ // (there is no clean durable turn-1 value at this call site today: the
+ // count lives in each store, so plumbing it up would change the
+ // ConversationStore contract — hence the proxy).
+ const derivedTitle =
+ this.conversation.turns.length === 0
+ ? deriveAutoTitle(
+ this.responseSafety.sanitizeFreeformContent(userInput, {
+ secretWarning: 'Potential secret detected in session title',
+ }).content
+ )
+ : ''
+ // Empty first input (or whitespace-only) → no title; let the client keep
+ // its placeholder rather than persisting an empty string via COALESCE.
+ const autoTitle = derivedTitle.length > 0 ? derivedTitle : undefined
// D3 — awaited durability barrier: the user message must be durable
// before the LLM loop runs (it is the replay anchor after a crash). A
// rejected write rolls back the turn inside startTurn and lands in
@@ -406,7 +438,8 @@ export class TaskExecutor {
this.conversation,
userInput,
this.taskId,
- this.task.traceContext ?? null
+ this.task.traceContext ?? null,
+ autoTitle
)
this.turnTiming?.addSessionLoadMs(Date.now() - sessionLoadStart)
diff --git a/mcp-host/src/core/conversation/__tests__/sessionTitle.test.ts b/mcp-host/src/core/conversation/__tests__/sessionTitle.test.ts
new file mode 100644
index 000000000..aacc7b6c3
--- /dev/null
+++ b/mcp-host/src/core/conversation/__tests__/sessionTitle.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it } from 'vitest'
+import { BasicSafety } from '../../safety/safety'
+import { AUTO_TITLE_MAX_CODE_POINTS, AUTO_TITLE_SUFFIX, deriveAutoTitle } from '../sessionTitle'
+
+describe('deriveAutoTitle — pure truncation (spec 15 §2.4)', () => {
+ it('returns a short input unchanged', () => {
+ expect(deriveAutoTitle('Plan my trip to Japan')).toBe('Plan my trip to Japan')
+ })
+
+ it('collapses whitespace runs (newlines, tabs, multiple spaces) to single spaces', () => {
+ expect(deriveAutoTitle('hello \n\t world\n\nagain')).toBe('hello world again')
+ })
+
+ it('trims leading/trailing whitespace', () => {
+ expect(deriveAutoTitle(' spaced out ')).toBe('spaced out')
+ })
+
+ it('truncates at the last space within the first 60 code points and appends the suffix', () => {
+ // 12 words of 6 chars ("abcdef") joined by spaces → far over 60 chars, with
+ // spaces available inside the first 60. Cut must land on a word boundary.
+ const input = Array.from({ length: 12 }, () => 'abcdef').join(' ')
+ const out = deriveAutoTitle(input)
+ expect(out.endsWith(AUTO_TITLE_SUFFIX)).toBe(true)
+ const content = out.slice(0, -AUTO_TITLE_SUFFIX.length)
+ // No trailing space before the suffix (cut excludes the space).
+ expect(content.endsWith(' ')).toBe(false)
+ expect(Array.from(content).length).toBeLessThanOrEqual(AUTO_TITLE_MAX_CODE_POINTS)
+ // Cut is on a boundary, so the content is a whole-word prefix of the input.
+ expect(input.startsWith(content)).toBe(true)
+ })
+
+ it('BUG GUARD (§2.4): no space in the first 60 chars → hard cut at 60, NOT the bare suffix', () => {
+ // The client's `substring(0, lastIndexOf(' ',60) || 60)` yields "…" here
+ // because lastIndexOf returns -1. This must NEVER happen.
+ const input = 'x'.repeat(100)
+ const out = deriveAutoTitle(input)
+ expect(out).not.toBe(AUTO_TITLE_SUFFIX)
+ expect(out).toBe('x'.repeat(60) + AUTO_TITLE_SUFFIX)
+ expect(Array.from(out).length).toBe(61)
+ })
+
+ it('strips bidi overrides and zero-width chars (channel input is stored verbatim, §6)', () => {
+ // U+202E RIGHT-TO-LEFT OVERRIDE inside a word, and U+200B ZERO WIDTH SPACE
+ // between two letters. JS `\s` matches neither, so plain collapse leaves them.
+ const bidi = 'abc‮def'
+ const zeroWidth = 'a​b'
+ const bidiOut = deriveAutoTitle(bidi)
+ const zwOut = deriveAutoTitle(zeroWidth)
+
+ expect(bidiOut).toBe('abcdef')
+ expect(zwOut).toBe('ab')
+ // No invisible control/format code point survives in either title.
+ expect(/\p{C}/u.test(bidiOut)).toBe(false)
+ expect(/\p{C}/u.test(zwOut)).toBe(false)
+ })
+
+ it('folds a newline into a space instead of deleting it (no word-join)', () => {
+ // Guards the strip order: `\n` is a `\p{C}` control char, so a naive
+ // strip-before-collapse would yield "helloworld".
+ expect(deriveAutoTitle('hello\nworld')).toBe('hello world')
+ })
+
+ it('counts code points, not UTF-16 units, so a surrogate pair is never split', () => {
+ // 😀 is a surrogate pair (2 UTF-16 units, 1 code point). 70 of them exceed
+ // the 60 code-point cap; a UTF-16-based cut would slice a pair in half.
+ const input = '😀'.repeat(70)
+ const out = deriveAutoTitle(input)
+ const content = out.slice(0, out.length - AUTO_TITLE_SUFFIX.length)
+ // Content must be exactly 60 whole emoji — no lone surrogate.
+ expect(Array.from(content)).toEqual(Array.from('😀'.repeat(60)))
+ expect(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(out)).toBe(false)
+ })
+})
+
+describe('auto-title orchestration — redact BEFORE truncate (spec 15 §5)', () => {
+ // Exercises the exact composition TaskExecutor uses: the REAL BasicSafety
+ // producer (T1) redacts the full input, then deriveAutoTitle truncates. No
+ // hand-built redaction fixture.
+ const redactThenDerive = (input: string, secrets: Array<{ name: string; value: string }>) => {
+ const safety = new BasicSafety(() => secrets)
+ const redacted = safety.sanitizeFreeformContent(input, {
+ secretWarning: 'Potential secret detected in session title',
+ }).content
+ return deriveAutoTitle(redacted)
+ }
+
+ it('redacts a secret that straddles the 60-code-point cut so it never survives into the title', () => {
+ const secret = 'S3cretValueThatIsQuiteLongAndSpansTheBoundary1234567890'
+ // Position the secret so it crosses index 60 of the raw input.
+ const prefix = 'my api key is '.padEnd(40, 'z') + ' '
+ const input = `${prefix}${secret} and more trailing text here`
+ expect(input.indexOf(secret)).toBeLessThan(60)
+ expect(input.indexOf(secret) + secret.length).toBeGreaterThan(60)
+
+ const title = redactThenDerive(input, [{ name: 'API_KEY', value: secret }])
+
+ // The literal secret (or any prefix of it long enough to leak) must be gone.
+ expect(title.includes(secret)).toBe(false)
+ expect(title.includes(secret.slice(0, 20))).toBe(false)
+ expect(title.includes('[REDACTED:API_KEY]')).toBe(true)
+ })
+
+ it('redacts a well-known secret shape (regex) before truncating', () => {
+ const input =
+ 'here is a token AKIAIOSFODNN7EXAMPLE plus a long tail of words to force truncation'
+ const title = redactThenDerive(input, [])
+ expect(title.includes('AKIAIOSFODNN7EXAMPLE')).toBe(false)
+ })
+})
diff --git a/mcp-host/src/core/conversation/conversation.ts b/mcp-host/src/core/conversation/conversation.ts
index a57831d66..5c7e2e715 100644
--- a/mcp-host/src/core/conversation/conversation.ts
+++ b/mcp-host/src/core/conversation/conversation.ts
@@ -215,10 +215,7 @@ export class ConversationManager {
private assertSessionOwner(conversation: Conversation, expectedUserId?: string): void {
if (expectedUserId !== undefined && conversation.user_id !== expectedUserId) {
- throw new ConversationError(
- 'Session access denied',
- ConversationErrorCode.OwnershipMismatch
- )
+ throw new ConversationError('Session access denied', ConversationErrorCode.OwnershipMismatch)
}
}
@@ -237,7 +234,15 @@ export class ConversationManager {
conversation: Conversation,
userInput: string,
taskId: string,
- traceContext: TraceContextV1 | null = null
+ traceContext: TraceContextV1 | null = null,
+ /**
+ * Server-authoritative auto-title (spec 15), already redacted + truncated by
+ * the caller (TaskExecutor, which owns the secret list). Only supplied on
+ * turn 1. Applied with `??=` so it never clobbers a title already set (a
+ * future rename); `persistTurnStart` gates the durable COALESCE write on the
+ * durable `turnNumber === 1`, so an out-of-turn value is harmless.
+ */
+ autoTitle?: string
): Promise<Turn> {
if (conversation.state !== ConversationState.Idle) {
throw new ConversationError(
@@ -247,6 +252,7 @@ export class ConversationManager {
}
const previousTraceContext = conversation.traceContext
+ const previousTitle = conversation.title
conversation.state = ConversationState.Processing
// D.1 — record the in-flight task so it can be exposed via /sessions and
// mirrored to sessions.active_task_id by persistTurnStart.
@@ -257,6 +263,11 @@ export class ConversationManager {
// Clear per-turn wildcard approval — each new message requires fresh approval
conversation.auto_approved_tools.delete('*')
+ // Materialize the auto-title (spec 15) in RAM before persisting so the
+ // dual-store projection and the durable COALESCE write agree. `??=` keeps
+ // any title already set.
+ if (autoTitle !== undefined) conversation.title ??= autoTitle
+
const turn: Turn = {
number: conversation.turns.length + 1,
user_input: userInput,
@@ -276,6 +287,9 @@ export class ConversationManager {
conversation.state = ConversationState.Idle
conversation.activeTaskId = undefined
conversation.traceContext = previousTraceContext
+ // Roll back the auto-title too, so a failed turn-1 write leaves no RAM
+ // title that SQLite never persisted (would break dual-store parity).
+ conversation.title = previousTitle
conversation.updated_at = new Date()
throw err
}
diff --git a/mcp-host/src/core/conversation/conversationStore.ts b/mcp-host/src/core/conversation/conversationStore.ts
index 591210c82..6b10a71a7 100644
--- a/mcp-host/src/core/conversation/conversationStore.ts
+++ b/mcp-host/src/core/conversation/conversationStore.ts
@@ -98,8 +98,15 @@ export interface ConversationSessionSummary {
cache_read_tokens?: number
cache_write_tokens?: number
cacheTokensReported?: boolean
+ /** Server-authoritative session title (spec 15). `undefined` until turn 1. */
+ title?: string
}
+// NOTE (spec 15 debt): `ConversationSessionMessages` inherits `title?` from the
+// summary via Omit, but the messages projections (`getSessionMessagesByKey`) do
+// NOT populate it and the `/messages` wire does not emit it — Fase A only
+// projects `title` on the LIST endpoint. Left unpopulated on purpose; threading
+// it through the two messages paths would add surface with no observable effect.
export interface ConversationSessionMessages extends Omit<
ConversationSessionSummary,
'lastActivityAt' | 'turnCount' | 'messageCount'
@@ -421,6 +428,8 @@ export class InMemoryConversationStore implements ConversationStore {
cache_read_tokens: conversation.cache_read_tokens,
cache_write_tokens: conversation.cache_write_tokens,
cacheTokensReported: conversation.cacheTokensReported,
+ // Auto-title (spec 15) — hot/memory projection.
+ title: conversation.title,
})
}
diff --git a/mcp-host/src/core/conversation/persistence/__tests__/sessionTitle.persistence.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/sessionTitle.persistence.test.ts
new file mode 100644
index 000000000..2e9c3e1b7
--- /dev/null
+++ b/mcp-host/src/core/conversation/persistence/__tests__/sessionTitle.persistence.test.ts
@@ -0,0 +1,147 @@
+import { describe, expect, it } from 'vitest'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { ConversationManager } from '../../conversation'
+import { InMemoryConversationStore } from '../../conversationStore'
+import { DualConversationStore } from '../dualConversationStore'
+import { makeSqliteStore } from './testHelpers'
+
+const KEY = 'u-title:rpc:a:chat-1'
+const PREFIX = 'u-title:rpc:'
+
+function readTitle(db: import('better-sqlite3').Database, sessionKey: string): string | null {
+ const row = db.prepare('SELECT title FROM sessions WHERE session_key = ?').get(sessionKey) as
+ | { title: string | null }
+ | undefined
+ return row ? row.title : null
+}
+
+describe('auto-title persistence — COALESCE / turn gating (spec 15 A4/A6/A7)', () => {
+ it('materializes the title on turn 1 (COALESCE from empty)', async () => {
+ const sqlite = makeSqliteStore()
+ try {
+ const manager = new ConversationManager(sqlite.store)
+ const conv = await manager.getOrCreate(KEY)
+ await manager.startTurn(conv, 'plan a trip', 'task-1', null, 'Plan a trip')
+ expect(readTitle(sqlite.worker.db, KEY)).toBe('Plan a trip')
+ expect(conv.title).toBe('Plan a trip')
+ } finally {
+ await sqlite.shutdown()
+ }
+ })
+
+ it('COALESCE keeps the first title when turn 1 is retried with a different value (idempotency)', async () => {
+ const sqlite = makeSqliteStore()
+ try {
+ const manager = new ConversationManager(sqlite.store)
+ const conv = await manager.getOrCreate(KEY)
+ // Turn 1: writes 'First Title'. nextTurnNumber stays 1 until completeTurn.
+ await manager.startTurn(conv, 'hello', 'task-1', null, 'First Title')
+ // Simulate a retry of turn 1 that derived a different title: same
+ // turnNumber (1) so the durable write runs again, but COALESCE ignores it.
+ conv.title = 'Hijacked Title'
+ await sqlite.store.persistTurnStart(conv, 'hello')
+ expect(readTitle(sqlite.worker.db, KEY)).toBe('First Title')
+ } finally {
+ await sqlite.shutdown()
+ }
+ })
+
+ it('turn 2 does NOT overwrite the turn-1 title (durable turnNumber gate + RAM ??=)', async () => {
+ const sqlite = makeSqliteStore()
+ try {
+ const manager = new ConversationManager(sqlite.store)
+ const conv = await manager.getOrCreate(KEY)
+ await manager.startTurn(conv, 'first', 'task-1', null, 'First Title')
+ await manager.completeTurn(conv, 'ok')
+ // A second turn deriving a different title must not touch the column.
+ await manager.startTurn(conv, 'second', 'task-2', null, 'Second Title')
+ expect(readTitle(sqlite.worker.db, KEY)).toBe('First Title')
+ expect(conv.title).toBe('First Title')
+ } finally {
+ await sqlite.shutdown()
+ }
+ })
+})
+
+describe('auto-title dual-store parity (spec 15 A10/A11 — assert observable output, T4)', () => {
+ it('memory and SQLite project the SAME title (hot path) with no parity mismatch', async () => {
+ const sqlite = makeSqliteStore()
+ try {
+ const memory = new InMemoryConversationStore()
+ const mismatches: Array<{ op: string; match: boolean }> = []
+ const dual = new DualConversationStore(memory, sqlite.store, {
+ recordParity: (op, match) => {
+ if (!match) mismatches.push({ op, match })
+ },
+ })
+ const manager = new ConversationManager(dual)
+ const conv = await manager.getOrCreate(KEY)
+ await manager.startTurn(conv, 'hello', 'task-1', null, 'My Title')
+ await manager.completeTurn(conv, 'hi')
+
+ const memSummaries = await memory.listSessionSummariesByPrefix(PREFIX, {})
+ const sqlSummaries = await sqlite.store.listSessionSummariesByPrefix(PREFIX, {})
+ expect(memSummaries[0]?.title).toBe('My Title')
+ expect(sqlSummaries[0]?.title).toBe('My Title')
+
+ // The dual store's own list must not detect a parity mismatch on title.
+ await dual.listSessionSummariesByPrefix(PREFIX, {})
+ expect(mismatches).toEqual([])
+ } finally {
+ await sqlite.shutdown()
+ }
+ })
+
+ it('cold projection returns undefined (never null) for a session without a title', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'clerum-title-'))
+ const dbPath = join(dir, 'sessions.db')
+ // Seed with NO title, then shut the store to force a cold read from a fresh
+ // store over the same file (cache empty → the `row.session.title` branch).
+ const seed = makeSqliteStore({ dbPath })
+ try {
+ const manager = new ConversationManager(seed.store)
+ const conv = await manager.getOrCreate(KEY)
+ await manager.startTurn(conv, 'no title here', 'task-1') // autoTitle omitted
+ await manager.completeTurn(conv, 'ok')
+ } finally {
+ await seed.shutdown()
+ }
+
+ const cold = makeSqliteStore({ dbPath })
+ try {
+ const summaries = await cold.store.listSessionSummariesByPrefix(PREFIX, {})
+ expect(summaries).toHaveLength(1)
+ // Must be undefined so normalizeParityValue drops it exactly like the
+ // memory store; a null would survive and break dual-store parity.
+ expect(summaries[0]?.title).toBeUndefined()
+ } finally {
+ await cold.shutdown()
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('cold projection surfaces a persisted title from row.session.title', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'clerum-title-'))
+ const dbPath = join(dir, 'sessions.db')
+ const seed = makeSqliteStore({ dbPath })
+ try {
+ const manager = new ConversationManager(seed.store)
+ const conv = await manager.getOrCreate(KEY)
+ await manager.startTurn(conv, 'hello', 'task-1', null, 'Cold Title')
+ await manager.completeTurn(conv, 'ok')
+ } finally {
+ await seed.shutdown()
+ }
+
+ const cold = makeSqliteStore({ dbPath })
+ try {
+ const summaries = await cold.store.listSessionSummariesByPrefix(PREFIX, {})
+ expect(summaries[0]?.title).toBe('Cold Title')
+ } finally {
+ await cold.shutdown()
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/mcp-host/src/core/conversation/persistence/reconstruct.ts b/mcp-host/src/core/conversation/persistence/reconstruct.ts
index 5189a67e8..51303dd1e 100644
--- a/mcp-host/src/core/conversation/persistence/reconstruct.ts
+++ b/mcp-host/src/core/conversation/persistence/reconstruct.ts
@@ -76,6 +76,10 @@ export function reconstructConversation(persisted: PersistedSession): Reconstruc
// restart this may point at a task whose reporter is gone (ghost); the D.2
// processing reaper reconciles that at boot.
activeTaskId: persisted.session.active_task_id ?? undefined,
+ // Server-authoritative title (spec 15). `?? undefined` (not null) so the
+ // RAM shape matches the memory store for dual-store parity (a persisted
+ // NULL becomes undefined, which `normalizeParityValue` drops on both sides).
+ title: persisted.session.title ?? undefined,
traceContext:
parseTraceContext(persisted.session.active_trace_context) ?? pending?.traceContext ?? null,
// Lifetime token totals — rehydrate the RAM mirror from the durable columns.
diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
index 17772d7fb..f6d98a9e2 100644
--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
@@ -415,6 +415,10 @@ export class SqliteConversationStore implements ConversationStore {
cache_read_tokens: row.session.cache_read_tokens,
cache_write_tokens: row.session.cache_write_tokens,
cacheTokensReported: row.session.cache_tokens_reported === 1,
+ // Auto-title (spec 15) — cold projection. `?? undefined` (never null) so
+ // `normalizeParityValue` treats a missing title identically to the memory
+ // store (which yields undefined); a null would survive and break parity.
+ title: cached ? cached.title : (row.session.title ?? undefined),
})
}
return out
@@ -734,6 +738,10 @@ export class SqliteConversationStore implements ConversationStore {
// D.1 — mirror the in-RAM activeTaskId (set by startTurn) to the column.
activeTaskId: conv.activeTaskId ?? null,
activeTraceContext: conv.traceContext ? JSON.stringify(conv.traceContext) : null,
+ // Auto-title (spec 15): materialize only on turn 1, gated on the durable
+ // `turnNumber` (not `turns.length`, which is RAM-fragile). The dispatcher
+ // runs a COALESCE write so a retried turn 1 is idempotent.
+ title: turnNumber === 1 ? (conv.title ?? undefined) : undefined,
},
sessionKey
)
diff --git a/mcp-host/src/core/conversation/sessionTitle.ts b/mcp-host/src/core/conversation/sessionTitle.ts
new file mode 100644
index 000000000..ec5d60d6c
--- /dev/null
+++ b/mcp-host/src/core/conversation/sessionTitle.ts
@@ -0,0 +1,72 @@
+/**
+ * Pure derivation of the server-authoritative auto-title for a session's first
+ * turn (spec 15, Fase A). The title is materialized once, on turn 1, into
+ * `sessions.title` via COALESCE and projected to the desktop catalog so a client
+ * with no local cache no longer has to fabricate a `Remote · <id>` placeholder.
+ *
+ * This helper is deliberately NOT responsible for redaction: the caller
+ * (TaskExecutor) redacts the FULL user input with the operator secret list
+ * BEFORE calling this, because truncating first would break literal secret
+ * matching (a value split across the 60-code-point cut would never match). The
+ * fixed order is: redact(full input) → deriveAutoTitle (normalize + strip
+ * invisibles + collapse + truncate).
+ *
+ * The first input can come from a third party (channel sessions: Slack/Telegram)
+ * and is stored verbatim, so this also normalizes (NFC) and strips invisible
+ * control/format code points — bidi overrides (U+202A–202E, U+2066–2069) and
+ * zero-width chars that JS `\s` does not match and that could spoof or hide text
+ * in the title. Redaction tokens (`[REDACTED:…]`) contain none of these, so they
+ * pass through intact.
+ */
+
+/** Single suffix for a truncated title, shared so client/server stay unified. */
+export const AUTO_TITLE_SUFFIX = '…' // … (U+2026 HORIZONTAL ELLIPSIS)
+
+/**
+ * Maximum length of the title *content* (excluding the suffix), counted in
+ * Unicode code points — never UTF-16 units — so a surrogate pair (emoji, etc.)
+ * is never sliced in half.
+ */
+export const AUTO_TITLE_MAX_CODE_POINTS = 60
+
+/**
+ * Derive a short session title from a (already-redacted) user input.
+ *
+ * Rules (spec §2.4, with the client's `substring(0, lastIndexOf(' ',60) || 60)`
+ * bug corrected — that expression yields the garbage title `"…"` when the first
+ * 60 chars have no space, because `lastIndexOf` returns -1):
+ * 1. NFC-normalize, fold whitespace, and strip invisible control/format chars.
+ * 2. If ≤ 60 code points, return as-is.
+ * 3. Otherwise cut at the last space within the first 60 code points; if there
+ * is no space, cut at 60 hard. Append the suffix in both cases.
+ */
+export function deriveAutoTitle(userInput: string): string {
+ const collapsed = userInput
+ .normalize('NFC')
+ // Fold every whitespace variant (newline, tab, NBSP, line/para separators)
+ // to a single space FIRST, so the control-char strip below never joins two
+ // words across a newline — `\n` is itself a `\p{C}` control char, so a
+ // strip-before-collapse order would delete it and glue the words together.
+ .replace(/\s+/g, ' ')
+ // Strip bidi overrides, zero-width, and any other invisible control/format
+ // code point (`\p{C}`) that `\s` does not cover. Spaces are `\p{Zs}`, not
+ // `\p{C}`, so word boundaries survive; valid astral chars (emoji) are their
+ // own category, so only lone surrogates are dropped.
+ .replace(/\p{C}/gu, '')
+ // A stripped format char sitting between two spaces leaves a double space.
+ .replace(/\s+/g, ' ')
+ .trim()
+ // Code points, not UTF-16 units — Array.from iterates by code point.
+ const codePoints = Array.from(collapsed)
+ if (codePoints.length <= AUTO_TITLE_MAX_CODE_POINTS) return collapsed
+
+ // Last space strictly within the first MAX code points. `> 0` (not `>= 0`)
+ // guards against an empty content slice — a leading space cannot occur here
+ // because collapse trims, but this keeps the invariant explicit.
+ let lastSpace = -1
+ for (let i = 0; i < AUTO_TITLE_MAX_CODE_POINTS; i++) {
+ if (codePoints[i] === ' ') lastSpace = i
+ }
+ const cut = lastSpace > 0 ? lastSpace : AUTO_TITLE_MAX_CODE_POINTS
+ return codePoints.slice(0, cut).join('') + AUTO_TITLE_SUFFIX
+}
diff --git a/mcp-host/src/core/safety/safety.ts b/mcp-host/src/core/safety/safety.ts
index 0c95740e5..6322914e3 100644
--- a/mcp-host/src/core/safety/safety.ts
+++ b/mcp-host/src/core/safety/safety.ts
@@ -260,7 +260,14 @@ export class BasicSafety implements Safety {
return wrapped
}
- private sanitizeFreeformContent(
+ /**
+ * The core redaction primitive: strip injection patterns, well-known secret
+ * shapes, and operator-configured secret values by literal match. Public so
+ * callers that must redact WITHOUT the per-call logging of `sanitizeOutput`
+ * (e.g. the session auto-title derivation and list projection, spec 15) can
+ * reuse the exact same secret list. Does NOT log — the caller decides.
+ */
+ sanitizeFreeformContent(
content: string,
options: {
secretWarning: string
diff --git a/mcp-host/src/core/types.ts b/mcp-host/src/core/types.ts
index d38072ecd..8a9a60da0 100644
--- a/mcp-host/src/core/types.ts
+++ b/mcp-host/src/core/types.ts
@@ -321,6 +321,14 @@ export interface Conversation {
guardrail_doom_loop?: { lastKey?: string; count: number }
created_at: Date
updated_at: Date
+ /**
+ * Server-authoritative session title (spec 15). Materialized on turn 1 from
+ * the first user input (redacted + truncated) and projected to the desktop
+ * catalog. RAM mirror of the durable `sessions.title` column, rehydrated on
+ * cold-load (`reconstruct.ts`). Kept in RAM for dual-store projection parity.
+ * `undefined` until the first turn materializes it (or a future rename sets it).
+ */
+ title?: string
/**
* D.1 — task currently in flight for this conversation. Set on `startTurn`,
* cleared on any terminal transition (complete/fail/cancel). Lives in RAM
diff --git a/mcp-host/src/db/statements.ts b/mcp-host/src/db/statements.ts
index 21004ba90..459931125 100644
--- a/mcp-host/src/db/statements.ts
+++ b/mcp-host/src/db/statements.ts
@@ -25,6 +25,7 @@ export interface PreparedStatements {
recomputeSessionMessageSummary: Statement
updateSessionPromptStableHash: Statement
updateSessionModelSelections: Statement
+ setSessionTitleIfAbsent: Statement
selectSessionBySessionKey: Statement
selectSessionsByPrefix: Statement
selectSessionSummariesByPrefix: Statement
@@ -174,6 +175,15 @@ export function prepareStatements(db: Database): PreparedStatements {
SET model_selections = @model_selections
WHERE id = @id
`),
+ // Auto-title (spec 15) — write the derived title only if the column is still
+ // empty. COALESCE keeps a rename set earlier and makes a retried turn 1
+ // idempotent. A dedicated statement (NOT `updateSessionState`, which is
+ // shared with `persistTurnFail` and would break on a missing @title param).
+ setSessionTitleIfAbsent: db.prepare(`
+ UPDATE sessions
+ SET title = COALESCE(title, @title)
+ WHERE id = @id
+ `),
updateSessionCounters: db.prepare(`
UPDATE sessions
SET message_count = message_count + @message_count_delta,
diff --git a/mcp-host/src/db/worker/dispatcher.ts b/mcp-host/src/db/worker/dispatcher.ts
index d4cac5fa3..91a1a55d2 100644
--- a/mcp-host/src/db/worker/dispatcher.ts
+++ b/mcp-host/src/db/worker/dispatcher.ts
@@ -518,6 +518,12 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn
if (op.activeTaskId === null) {
s.clearSessionActiveTask.run({ id: op.sessionId })
}
+ // Auto-title (spec 15) — turn 1 only carries a title. COALESCE inside
+ // the statement makes a retried turn 1 idempotent and preserves a
+ // rename. Run in the SAME transaction as the boundary message.
+ if (op.title !== undefined) {
+ s.setSessionTitleIfAbsent.run({ id: op.sessionId, title: op.title })
+ }
})
tx.immediate()
return { ok: true }
diff --git a/mcp-host/src/db/worker/protocol.ts b/mcp-host/src/db/worker/protocol.ts
index d7449e472..0bde5e0ea 100644
--- a/mcp-host/src/db/worker/protocol.ts
+++ b/mcp-host/src/db/worker/protocol.ts
@@ -241,6 +241,12 @@ export type WorkerOp =
activeTaskId?: string | null
/** Same keep/set/clear semantics as update_session_state. */
activeTraceContext?: string | null
+ /**
+ * Server-authoritative auto-title (spec 15). Present only on turn 1; the
+ * dispatcher runs `setSessionTitleIfAbsent` (COALESCE) so a retried turn 1
+ * never overwrites, and a rename set earlier wins.
+ */
+ title?: string
}
| { kind: 'replace_messages'; sessionId: string; messages: MessageRow[] }
| { kind: 'insert_pending_approval'; payload: PendingApprovalRow }
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index 4f6a56ea8..04f86e6a2 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -2575,10 +2575,19 @@ async function startRPCServer(): Promise<void> {
const toolErrorSafety = new BasicSafety(() => configStore?.listSecretEntries() ?? [])
const redactToolError = (toolName: string, rawError: string): string =>
sanitizeError(toolErrorSafety.sanitizeOutput(toolName, rawError).content)
+ // spec 15 — re-redact a session title before it hits the list wire (defense in
+ // depth §5). Uses the non-logging redaction primitive so a 100-item page does
+ // not emit 100 log lines, and skips `sanitizeError` (which would truncate a
+ // legit title). Same operator secret list as the tool-error path.
+ const redactTitle = (rawTitle: string): string =>
+ toolErrorSafety.sanitizeFreeformContent(rawTitle, {
+ secretWarning: 'Potential secret detected in session title',
+ }).content
const { handleSessionsList, handleSessionMessages } = createSessionRouteHandlers({
getConversationManager: () => agent!.getConversationManager(),
redactToolError,
+ redactTitle,
})
const handleContextBreakdown = async (userSub: string, agentName: string, chatId: string) => {
diff --git a/mcp-host/src/server/__tests__/sessionRouteHandlers.test.ts b/mcp-host/src/server/__tests__/sessionRouteHandlers.test.ts
index 6bc90b992..6e4845dad 100644
--- a/mcp-host/src/server/__tests__/sessionRouteHandlers.test.ts
+++ b/mcp-host/src/server/__tests__/sessionRouteHandlers.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import { ConversationManager } from '../../core/conversation/conversation'
import { buildConnectRequiredApproval } from '../../core/extensions/mcpApprovalGateController'
+import { BasicSafety } from '../../core/safety/safety'
import { createSessionRouteHandlers } from '../sessionRouteHandlers'
function makeHandlersUnderTest() {
@@ -8,6 +9,7 @@ function makeHandlersUnderTest() {
const { handleSessionsList, handleSessionMessages } = createSessionRouteHandlers({
getConversationManager: () => convManager,
redactToolError: (_toolName, rawError) => rawError,
+ redactTitle: rawTitle => rawTitle,
})
return { convManager, handleSessionsList, handleSessionMessages }
}
@@ -109,3 +111,57 @@ describe('createSessionRouteHandlers — handleSessionsList (R1-L2)', () => {
expect(empty).toEqual(absent)
})
})
+
+describe('createSessionRouteHandlers — handleSessionsList title projection (spec 15 A12)', () => {
+ async function seedWithTitle(
+ convManager: ConversationManager,
+ key: string,
+ title: string
+ ): Promise<void> {
+ const conv = await convManager.getOrCreate(key)
+ await convManager.startTurn(conv, 'first message', 'task', null, title)
+ await convManager.completeTurn(conv, 'a')
+ }
+
+ it('includes the session title in the list payload', async () => {
+ const { convManager, handleSessionsList } = makeHandlersUnderTest()
+ await seedWithTitle(convManager, 'user-A:rpc:agent-x:chat-1', 'Plan a trip to Japan')
+
+ const res = await handleSessionsList('user-A', {})
+ expect(res.items[0]).toMatchObject({ chatId: 'chat-1', title: 'Plan a trip to Japan' })
+ })
+
+ it('omits the title field entirely when the session has none', async () => {
+ const { convManager, handleSessionsList } = makeHandlersUnderTest()
+ const conv = await convManager.getOrCreate('user-A:rpc:agent-x:chat-1')
+ await convManager.startTurn(conv, 'q', 'task') // no autoTitle
+ await convManager.completeTurn(conv, 'a')
+
+ const res = await handleSessionsList('user-A', {})
+ expect(res.items[0]).not.toHaveProperty('title')
+ })
+
+ it('re-redacts a secret in the title at projection time (defense in depth §5)', async () => {
+ // Build handlers with the REAL BasicSafety redaction primitive (T1), matching
+ // the main.ts wiring. Simulates a title that was materialized before the
+ // operator marked the value secret (rotation) — the read path must still scrub it.
+ const secret = 'S3cretRotatedInLater1234567890'
+ const convManager = new ConversationManager()
+ const safety = new BasicSafety(() => [{ name: 'API_KEY', value: secret }])
+ const { handleSessionsList } = createSessionRouteHandlers({
+ getConversationManager: () => convManager,
+ redactToolError: (_t, e) => e,
+ redactTitle: raw =>
+ safety.sanitizeFreeformContent(raw, { secretWarning: 'secret in title' }).content,
+ })
+
+ const conv = await convManager.getOrCreate('user-A:rpc:agent-x:chat-1')
+ // Title stored raw (redaction at materialization ran with an empty secret list).
+ await convManager.startTurn(conv, 'msg', 'task', null, `key ${secret}`)
+ await convManager.completeTurn(conv, 'a')
+
+ const res = await handleSessionsList('user-A', {})
+ expect(res.items[0]?.title).toBe('key [REDACTED:API_KEY]')
+ expect(res.items[0]?.title).not.toContain(secret)
+ })
+})
diff --git a/mcp-host/src/server/sessionRouteHandlers.ts b/mcp-host/src/server/sessionRouteHandlers.ts
index 46b2c989a..65c44cc50 100644
--- a/mcp-host/src/server/sessionRouteHandlers.ts
+++ b/mcp-host/src/server/sessionRouteHandlers.ts
@@ -25,10 +25,18 @@ import {
export interface SessionRouteHandlerDeps {
getConversationManager: () => ConversationManager
redactToolError: (toolName: string, rawError: string) => string
+ /**
+ * Defense-in-depth redaction of a session title at projection time (spec 15
+ * §5). The title is already redacted when materialized, but re-redacting on
+ * read covers a secret rotated in after materialization and a mis-wired
+ * secret provider that returned `[]` at write time. Owned by `main.ts` (closes
+ * over the operator secret list). Non-logging (unlike `redactToolError`).
+ */
+ redactTitle: (rawTitle: string) => string
}
export function createSessionRouteHandlers(deps: SessionRouteHandlerDeps) {
- const { getConversationManager, redactToolError } = deps
+ const { getConversationManager, redactToolError, redactTitle } = deps
// Common projection: state + active task + pending approval + lifetime token
// totals, shared by the list and messages handlers (RPC token exposure
@@ -103,6 +111,8 @@ export function createSessionRouteHandlers(deps: SessionRouteHandlerDeps) {
turnCount: summary.turnCount,
messageCount: summary.messageCount,
lastActivityAt: summary.lastActivityAt.toISOString(),
+ // spec 15 — omit when unset; re-redact on read (defense in depth §5).
+ ...(summary.title !== undefined ? { title: redactTitle(summary.title) } : {}),
...sessionStateView(summary),
})),
...(nextCursor ? { nextCursor } : {}),
diff --git a/mcp-host/src/server/types.ts b/mcp-host/src/server/types.ts
index 1d156c6e8..63e18787e 100644
--- a/mcp-host/src/server/types.ts
+++ b/mcp-host/src/server/types.ts
@@ -508,6 +508,8 @@ export type SessionsListItem = {
turnCount: number
messageCount?: number
lastActivityAt: string
+ /** Server-authoritative session title (spec 15); omitted when unset. */
+ title?: string
} & SessionStateWire
export type SessionsListQuery = {