Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Session search: index what you typed mid-turn, your /goal, and every hour of a long turn (#373)

Dee524f85d6a849
diff --git a/cli/src/lib/sessionSearch/indexer.spec.ts b/cli/src/lib/sessionSearch/indexer.spec.ts
index 5a588381a..2329efb0b 100644
--- a/cli/src/lib/sessionSearch/indexer.spec.ts
+++ b/cli/src/lib/sessionSearch/indexer.spec.ts
@@ -60,6 +60,33 @@ describe('SessionSearchIndex', () => {
expect(store.search('delta')[0].snippet).toContain('doubled')
})
+ it('writes a long first pass in batches, and a pass stopped between them resumes at the next', async () => {
+ let transcript = ''
+ for (let i = 0; i < 70; i++) transcript += prompt(`step ${i} of the dial rewrite`, i % 60) + answer(`finished step${i}`, i % 60)
+ const { store, index, found } = setup(transcript)
+ const write = vi.spyOn(store, 'writeSession')
+ write.mockImplementationOnce(function (this: SessionSearchStore, ...args) {
+ index.stop()
+ return SessionSearchStore.prototype.writeSession.apply(this, args)
+ })
+ index.sweep()
+ await vi.waitFor(() => { expect((index as unknown as { running: boolean }).running).toBe(false) })
+ // Stopped after the first batch: its rows are in, and the session resumes at the next one.
+ expect(store.counts().turns).toBe(32)
+ expect(store.session('s1')).toMatchObject({ resumeTurn: 32, mtime: 0 })
+ expect(store.session('s1')!.size).toBe(store.session('s1')!.resumeOffset)
+ write.mockRestore()
+
+ const resumed = new SessionSearchIndex({ store, sources: () => [{ agentId: 'agent-1', sessionId: 's1', engine: 'claude', transcriptPath: store.session('s1')!.path, header: 'Dial firmware · harness', updatedAt: 1 }] })
+ cleanups.push(() => resumed.stop())
+ resumed.sweep()
+ await vi.waitFor(() => { expect((resumed as unknown as { running: boolean }).running).toBe(false) })
+ expect(store.counts()).toEqual({ sessions: 1, turns: 70 })
+ for (const i of [0, 31, 32, 33, 64, 69]) expect(found(`step${i}`)).toEqual(['s1'])
+ expect(store.session('s1')).toMatchObject({ resumeTurn: 69, turns: 70 })
+ expect(store.session('s1')!.mtime).toBeGreaterThan(0)
+ })
+
it('starts over when the transcript was rewritten shorter', async () => {
const { path, found, settle } = setup(prompt('first long conversation about cohorts and retention', 0) + answer('Done with the cohort table.', 1))
await settle()
diff --git a/cli/src/lib/sessionSearch/indexer.ts b/cli/src/lib/sessionSearch/indexer.ts
index 8eb883911..dd5c85624 100644
--- a/cli/src/lib/sessionSearch/indexer.ts
+++ b/cli/src/lib/sessionSearch/indexer.ts
@@ -69,6 +69,8 @@ export interface SessionSearchIndexOptions {
}
const NO_TURN_DELETE = Number.MAX_SAFE_INTEGER
+/** Rows written per transaction on a long first pass. */
+const WRITE_BATCH = 32
/** The folders a session ran in, as a person would name them: the last two path segments. */
export function folderWords(cwd: string | null | undefined): string {
@@ -240,7 +242,22 @@ export class SessionSearchIndex {
lastAt: lastAt ?? (resume ? existing.lastAt : null) ?? mtime,
turns: 0,
}
- store.writeSession(session, fromTurn, open ? [...closed, open] : closed)
+ const turns = open ? [...closed, open] : closed
+ // A long session's first pass writes hundreds of rows. In one transaction that held the thread for
+ // 130 ms, so rows go in batches, each but the last saved as a pass that stopped at the next batch:
+ // a daemon stopped between them resumes there.
+ for (let start = WRITE_BATCH; start < turns.length; start += WRITE_BATCH) {
+ const next = turns[start]
+ store.writeSession(
+ { ...session, size: next.offset, mtime: 0, resumeOffset: next.offset, resumeTurn: next.turn },
+ start === WRITE_BATCH ? fromTurn : NO_TURN_DELETE,
+ turns.slice(start - WRITE_BATCH, start),
+ )
+ await this.pace()
+ if (this.stopped) return
+ }
+ const written = Math.floor(Math.max(0, turns.length - 1) / WRITE_BATCH) * WRITE_BATCH
+ store.writeSession(session, written ? NO_TURN_DELETE : fromTurn, turns.slice(written))
if (!resume) {
this.opts.log?.(`[search] indexed ${source.sessionId.slice(0, 8)} · ${source.engine} · ${closed.length + (open ? 1 : 0)} turns · ${Math.round(file.size / 1024)} KB`)
}
diff --git a/cli/src/lib/sessionSearch/store.ts b/cli/src/lib/sessionSearch/store.ts
index a3000ef69..85619ba4b 100644
--- a/cli/src/lib/sessionSearch/store.ts
+++ b/cli/src/lib/sessionSearch/store.ts
@@ -16,7 +16,7 @@ import { chmodSync, existsSync, rmSync } from 'node:fs'
import { builtinSqlite } from '../sqliteRead.js'
import type { IndexedTurn } from './turns.js'
-const SCHEMA_VERSION = '5'
+const SCHEMA_VERSION = '6'
/** The row that holds a session's name, title and folder: searchable beside its turns. */
export const HEADER_TURN = -1
diff --git a/cli/src/lib/sessionSearch/transcript.spec.ts b/cli/src/lib/sessionSearch/transcript.spec.ts
index a7b48c467..58fd3ef8a 100644
--- a/cli/src/lib/sessionSearch/transcript.spec.ts
+++ b/cli/src/lib/sessionSearch/transcript.spec.ts
@@ -119,3 +119,51 @@ describe('skipping tool output', () => {
for (const engine of ['opencode', 'kilo', 'hermes', 'devin', 'terminal']) expect(lineNormalizer(engine, 's')).toBeNull()
})
})
+
+describe("the person's words outside Claude's prompt records", () => {
+ const queued = (prompt: unknown, minute: number, commandMode = 'prompt', origin = 'human') => JSON.stringify({
+ type: 'attachment', uuid: `q${minute}`, timestamp: at(minute),
+ attachment: { type: 'queued_command', prompt, commandMode, origin: { kind: origin }, humanTurn: true },
+ })
+ const meta = (text: string, minute: number) => JSON.stringify({ type: 'user', isMeta: true, uuid: `m${minute}`, timestamp: at(minute), message: { role: 'user', content: text } })
+
+ it('indexes a message typed while the agent worked, and a /goal, as asks', async () => {
+ const path = file([
+ claude.prompt('cmd p search results are not good', 0),
+ claude.answer('Looking at how Cmd-P ranks rows.', 1),
+ queued('are we doing keyword search, vector search or embeddings?', 2),
+ claude.answer('Keyword search over names only, today.', 3),
+ queued([{ type: 'text', text: '[Image #1] this row' }, { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'AAAA' } }], 4),
+ meta('A session-scoped Stop hook is now active with condition: "build the best search engine across all "the" machines". Briefly acknowledge the goal, then immediately start.', 5),
+ claude.answer('On it.', 6),
+ ].join('\n') + '\n')
+ const turns = await turnsOf('claude', path, true)
+ expect(turns.map((turn) => [turn.ask, turn.answer])).toEqual([
+ ['cmd p search results are not good', 'Looking at how Cmd-P ranks rows.'],
+ ['are we doing keyword search, vector search or embeddings?', 'Keyword search over names only, today.'],
+ ['[Image #1] this row', ''],
+ ['build the best search engine across all "the" machines', 'On it.'],
+ ])
+ })
+
+ it('files a hand-back under the agent and leaves task notifications and other bookkeeping out', async () => {
+ const path = file([
+ claude.prompt('audit the dial', 0),
+ queued('<task-notification><task-id>b1</task-id><summary>done</summary></task-notification>', 1, 'task-notification', 'task-notification'),
+ queued('<agent-message from="a1">[Subagent hand-back] found 3 scroll bugs</agent-message>', 2, 'prompt', 'peer'),
+ queued('Goal set: build the best search engine', 2, 'prompt', 'auto-continuation'),
+ meta('Goal check-in: «build the best search engine»', 3),
+ meta('Base directory for this skill: /skills/review', 4),
+ claude.answer('Fixing the three bugs.', 5),
+ ].join('\n') + '\n')
+ const turns = await turnsOf('claude', path, true)
+ expect(turns.map((turn) => turn.ask)).toEqual(['audit the dial', ''])
+ expect(turns[1].answer).toContain('found 3 scroll bugs')
+ expect(turns[1].answer).toContain('Fixing the three bugs.')
+ const text = JSON.stringify(turns)
+ expect(text).not.toContain('task-notification')
+ expect(text).not.toContain('Goal check-in')
+ expect(text).not.toContain('Goal set')
+ expect(text).not.toContain('Base directory')
+ })
+})
diff --git a/cli/src/lib/sessionSearch/transcript.ts b/cli/src/lib/sessionSearch/transcript.ts
index fefb9c8f1..7198148d3 100644
--- a/cli/src/lib/sessionSearch/transcript.ts
+++ b/cli/src/lib/sessionSearch/transcript.ts
@@ -33,7 +33,11 @@ export function lineNormalizer(engine: string, sessionId: string): LineNormalize
switch (engine) {
case 'claude': {
const state = newTurnState()
- return (line) => lineToEvents(line, state)
+ return (line) => {
+ const events = lineToEvents(line, state)
+ const asked = claudeSideAsk(line)
+ return asked ? [{ type: 'user_message', payload: { content: asked } }, ...events] : events
+ }
}
case 'codex': {
// Sub-agent threads are resolved for the live view's cards; search only needs the text.
@@ -55,6 +59,48 @@ export function lineNormalizer(engine: string, sessionId: string): LineNormalize
}
}
+/**
+ * The person's words that Claude Code writes outside its prompt records. The live view leaves them out
+ * on purpose, since neither opens a turn there, but both are things a person remembers asking:
+ * - a message typed while the agent was working, delivered mid-turn as a `queued_command` attachment
+ * (sub-agent hand-backs arrive the same way and are filed under the agent by `askKind`; task
+ * notifications are not prompts and are left out);
+ * - a `/goal`, whose text is recorded only in the bookkeeping line that turns its Stop hook on.
+ */
+export function claudeSideAsk(line: string): string | null {
+ const queued = line.includes('"queued_command"')
+ if (!queued && !(line.includes('"isMeta":true') && line.includes(GOAL_HEAD))) return null
+ let raw: {
+ type?: unknown; isMeta?: unknown; message?: { content?: unknown }
+ attachment?: { type?: unknown; commandMode?: unknown; prompt?: unknown; origin?: { kind?: unknown } }
+ }
+ try { raw = JSON.parse(line) } catch { return null }
+ if (queued) {
+ const attachment = raw.attachment
+ if (attachment?.type !== 'queued_command' || attachment.commandMode !== 'prompt') return null
+ // "Goal set: …", which Claude queues for itself: the goal's own line below already holds it.
+ if (attachment.origin?.kind === 'auto-continuation') return null
+ return promptText(attachment.prompt)
+ }
+ if (raw.type !== 'user' || raw.isMeta !== true) return null
+ const goal = GOAL_SET.exec(promptText(raw.message?.content) ?? '')
+ return goal ? goal[1].trim() || null : null
+}
+
+const GOAL_HEAD = 'A session-scoped Stop hook is now active with condition: '
+const GOAL_SET = /^A session-scoped Stop hook is now active with condition: "([\s\S]*)"\. Briefly acknowledge/
+
+/** A prompt's text: a string, or the text blocks of a content array. */
+function promptText(prompt: unknown): string | null {
+ if (typeof prompt === 'string') return prompt.trim() ? prompt : null
+ if (!Array.isArray(prompt)) return null
+ const text = prompt
+ .map((block) => block && typeof block === 'object' && (block as { type?: unknown }).type === 'text' ? (block as { text?: unknown }).text : null)
+ .filter((part): part is string => typeof part === 'string' && part.trim() !== '')
+ .join('\n')
+ return text || null
+}
+
function ingestWith(normalizer: { ingest(line: string): LiveEvent[] }): LineNormalizer {
return (line) => normalizer.ingest(line)
}
diff --git a/cli/src/lib/sessionSearch/turns.spec.ts b/cli/src/lib/sessionSearch/turns.spec.ts
index 1d934879e..03ca03172 100644
--- a/cli/src/lib/sessionSearch/turns.spec.ts
+++ b/cli/src/lib/sessionSearch/turns.spec.ts
@@ -44,18 +44,60 @@ describe('TurnCollector', () => {
expect(open?.ask).toBe('next')
})
- it('bounds every field, keeping the end of a long answer where the outcome is', () => {
+ it('bounds the ask, and a single message longer than a row keeps its start and its end', () => {
const turns = new TurnCollector(0)
turns.feed([ask('x'.repeat(ASK_MAX * 2))], 0, null)
- for (let i = 0; i < 400; i++) turns.feed([say(`step ${i} ${'y'.repeat(200)}`)], i, null)
- turns.feed([say('FINAL OUTCOME')], 500, null)
- for (let i = 0; i < 200; i++) turns.feed([tool('Bash', { command: `echo ${i} ${'z'.repeat(100)}` })], 600 + i, null)
+ turns.feed([say(`PLAN ${'y'.repeat(ANSWER_MAX * 5)} FINAL OUTCOME`)], 10, null)
const { open } = turns.finish()
expect(open!.ask.length).toBe(ASK_MAX)
expect(open!.answer.length).toBeLessThanOrEqual(ANSWER_MAX + 3)
- expect(open!.answer.startsWith('step 0 ')).toBe(true)
+ expect(open!.answer.startsWith('PLAN ')).toBe(true)
expect(open!.answer.endsWith('FINAL OUTCOME')).toBe(true)
- expect(open!.tools.length).toBeLessThanOrEqual(TOOLS_MAX)
+ })
+
+ it('goes on in continuation rows, so nothing in the middle of a long turn is lost', () => {
+ const turns = new TurnCollector(0)
+ turns.feed([ask('rebuild session search')], 0, 1_000)
+ const lines: Array<[LiveEvent[], number]> = []
+ for (let i = 0; i < 300; i++) lines.push([[say(`step ${i} ${'y'.repeat(200)}`)], 10 + i])
+ for (let i = 0; i < 200; i++) lines.push([[tool('Bash', { command: `echo ${i} ${'zz '.repeat(30)}` })], 400 + i])
+ lines.push([[say('FINAL OUTCOME')], 700])
+ for (const [events, offset] of lines) turns.feed(events, offset, offset * 10)
+ const { closed, open } = turns.finish()
+ const rows = [...closed, open!]
+ expect(rows.length).toBeGreaterThan(3)
+ expect(rows[0].ask).toBe('rebuild session search')
+ for (const row of rows.slice(1)) expect(row.ask).toBe('')
+ const answers = rows.map((row) => row.answer).join(' ')
+ for (let i = 0; i < 300; i++) expect(answers).toContain(`step ${i} `)
+ const tools = rows.map((row) => row.tools).join('\n')
+ for (let i = 0; i < 200; i++) expect(tools).toContain(`echo ${i} `)
+ expect(open!.answer).toContain('FINAL OUTCOME')
+ for (const row of rows) {
+ expect(row.answer.length).toBeLessThanOrEqual(ANSWER_MAX)
+ expect(row.tools.length).toBeLessThanOrEqual(TOOLS_MAX)
+ }
+ // Each continuation opens at a line of its own, dated by that line, numbered in order.
+ expect(rows.map((row) => row.turn)).toEqual(rows.map((_, index) => index))
+ for (const row of rows.slice(1)) expect(row.at).toBe(row.offset * 10)
+
+ // A pass resumed at the last continuation reads it the same way.
+ const last = rows[rows.length - 1]
+ const resumed = new TurnCollector(last.turn)
+ for (const [events, offset] of lines) if (offset >= last.offset) resumed.feed(events, offset, offset * 10)
+ const again = resumed.finish()
+ expect(again.closed).toEqual([])
+ expect(again.open).toEqual(last)
+ })
+
+ it('does not continue a turn on the line that opens the next one', () => {
+ const turns = new TurnCollector(0)
+ turns.feed([ask('first')], 0, null)
+ turns.feed([say('y'.repeat(ANSWER_MAX))], 10, null)
+ turns.feed([ask('second'), say('on it')], 20, null)
+ const { closed, open } = turns.finish()
+ expect(closed.map((row) => [row.turn, row.ask])).toEqual([[0, 'first']])
+ expect(open).toMatchObject({ turn: 1, ask: 'second', answer: 'on it' })
})
})
@@ -92,6 +134,8 @@ describe('searchableText', () => {
expect(searchableText('<command-name>/clear</command-name> hello', 100)).toBe('hello')
expect(searchableText('see <pasted_content id="c200"> https://github.com/x/y/issues/167 </pasted_content id="c200">', 100))
.toBe('see https://github.com/x/y/issues/167')
+ expect(searchableText('<agent-message from="a38952b54daf6403b">[Subagent hand-back] 3 bugs</agent-message>', 100))
+ .toBe('[Subagent hand-back] 3 bugs')
})
})
diff --git a/cli/src/lib/sessionSearch/turns.ts b/cli/src/lib/sessionSearch/turns.ts
index cef0b8b02..723c2a894 100644
--- a/cli/src/lib/sessionSearch/turns.ts
+++ b/cli/src/lib/sessionSearch/turns.ts
@@ -25,8 +25,12 @@ export interface IndexedTurn {
}
export const ASK_MAX = 8_000
+/**
+ * What one row holds of a turn's answer and tool calls. A longer turn goes on in continuation rows of
+ * its own (below), so an agent that works for hours has every hour indexed, not the first and the last.
+ */
export const ANSWER_MAX = 12_000
-/** The start of an answer usually says what it will do and the end what was done: keep both. */
+/** Within one row, a single message longer than the row keeps its start and its end. */
const ANSWER_HEAD = 3_000
export const TOOLS_MAX = 4_000
const TOOL_VALUE_MAX = 300
@@ -58,7 +62,8 @@ export function askKind(text: string): AskKind {
}
// A paste's markers: what was pasted is the person's, and searchable; the tags around it are not.
-const PASTE_TAGS = /<\/?pasted_content\b[^>]*>/g
+// Nor are the tags around another agent's message.
+const PASTE_TAGS = /<\/?(?:pasted_content|agent-message)\b[^>]*>/g
/** Text as it is stored and searched: wrappers out, whitespace folded, secrets blanked, bounded. */
export function searchableText(text: string, max: number): string {
@@ -121,6 +126,22 @@ export function toolText(tool: string, input: unknown): string {
return [tool, ...parts.filter(Boolean)].join(' ')
}
+const opensTurn = (event: LiveEvent): boolean => event.type === 'turn_started' || event.type === 'user_message'
+
+/** Whether one line's text or tool calls would take a row that already holds some past its bounds. */
+function overflows(draft: Draft, events: readonly LiveEvent[], calls: ReadonlyArray<string | null>): boolean {
+ let text = 0
+ let tools = 0
+ for (const [index, event] of events.entries()) {
+ if (event.type === 'text_delta') text += event.payload.content.length + 1
+ const call = calls[index]
+ if (call !== null) tools += call.length + 1
+ }
+ // `answerLength` leaves out the line breaks the parts are joined with.
+ return (text > 0 && draft.answerLength > 0 && draft.answerLength + draft.answer.length + text > ANSWER_MAX)
+ || (tools > 0 && draft.toolsLength > 0 && draft.toolsLength + tools > TOOLS_MAX)
+}
+
interface Draft {
/** The message that opened the turn, as it arrived: a second announcement of it is the same turn. */
opener: string
@@ -150,7 +171,14 @@ export class TurnCollector {
/** Events normalized from one transcript line, with that line's offset and time. */
feed(events: readonly LiveEvent[], offset: number, at: number | null): void {
- for (const event of events) {
+ const calls = events.map((event) => event.type === 'tool_start' ? toolText(event.payload.tool, event.payload.input) : null)
+ // A turn whose row this line would overflow goes on in a continuation: a row with no ask that opens
+ // at this line. Split only between lines, so a pass resumed at the continuation reads it the same way.
+ if (this.draft && !events.some(opensTurn) && overflows(this.draft, events, calls)) {
+ this.close()
+ this.current(offset, at)
+ }
+ for (const [index, event] of events.entries()) {
switch (event.type) {
case 'turn_started':
this.open(event.payload.userMessage, offset, at)
@@ -171,7 +199,7 @@ export class TurnCollector {
case 'tool_start': {
const draft = this.current(offset, at)
if (draft.toolsLength >= TOOLS_MAX) break
- const text = toolText(event.payload.tool, event.payload.input)
+ const text = calls[index]!
draft.tools.push(text)
draft.toolsLength += text.length + 1
break
diff --git a/docs/research/2026-09-26-session-search.md b/docs/research/2026-09-26-session-search.md
index f46c23144..805994b06 100644
--- a/docs/research/2026-09-26-session-search.md
+++ b/docs/research/2026-09-26-session-search.md
@@ -56,9 +56,12 @@ the session named Mobile whose swipe discussion came later.
- **Left out:** tool output, reasoning, images. Tool-output records are recognised by their first
kilobyte and skipped unparsed. Across all 76 real transcripts, asks, answers, turn times and
offsets come out identical with and without the skip.
+- **Beyond the normalizer (Claude):** a message typed while the agent works is written as a
+ `queued_command` attachment, and a `/goal` only as the meta line that turns its Stop hook on.
+ The live view leaves both out, so the index reads them itself.
- **Cleaned:** harness wrappers removed, whitespace folded, secrets blanked with the CLI's
- redactor, encoded blobs dropped. Asks are capped at 8 KB, answers at 12 KB (head and tail kept),
- tool text at 4 KB.
+ redactor, encoded blobs dropped. Asks are capped at 8 KB. A row holds up to 12 KB of answer and
+ 4 KB of tool text; a longer turn goes on in continuation rows, split between lines.
### Keeping it fresh
@@ -229,6 +232,31 @@ What it found, all fixed:
Also by design: a leading `#` in Cmd-P opens projects, so type issue numbers without it ("issue
189", "pr #368").
+## Tested live
+
+On 2026-09-27 main's daemon replaced the development Mac's real one: the machine's own sessions,
+live, with the app attached. The index built in about 12 s, including a 346 MB Codex rollout. It
+found three things the sandbox runs could not, because they come from long, busy sessions:
+
+- **Messages typed mid-turn were lost.** Claude Code writes them as `queued_command` attachments,
+ which the normalizer skips. There were 405 of them on this machine. The one asking "keyword or
+ vectors or embeddings?" is what this project was built on, and it was not findable.
+- **A `/goal` was lost** the same way: it exists only in the meta line that activates the goal.
+- **The middle of a long turn was lost.** The overnight turn that built this kept its first 3 KB
+ and last 9 KB of answer, so "fts5 bm25" found nothing in it. Continuation rows keep all of it.
+
+On one machine's sessions, the fixes took the index from 1,851 to 2,376 rows and from 12 MB to
+17 MB. The first build takes 5.5 s, and its longest stall is 38–47 ms once a long first pass
+writes 32 rows per transaction (130 ms in one). On one query set drawn from the old index, accuracy
+is unchanged (two rare words 88% → 88%, answer words 99% → 99%, prefixes 71% → 72%, one word 62% →
+58%). That set can only ask about what both indexes hold; the gains are in what the old one did not.
+
+The live run also showed the daemon crash-looping out of memory, which is not search: after a
+restart, the first `SessionStart` from a long session replayed its whole transcript live (3,553
+events from the 346 MB rollout). The replay was meant only for a first turn announced before its
+file existed. This machine's log has 28 out-of-memory crashes since 2026-09-23, on every build
+including the v0.3.1 release. It is fixed separately.
+
## Protocol
`session_search { query, limit, from?, to? }` → `{ hits: [{ agentId, sessionId, engine, turn, at,