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.

Memories: search conversations with Cmd-P's search (#1148)

Dee98027f615709
diff --git a/store/agents/memories/lib/sessions.mjs b/store/agents/memories/lib/sessions.mjs
index 6952a1567..f11d7a156 100644
--- a/store/agents/memories/lib/sessions.mjs
+++ b/store/agents/memories/lib/sessions.mjs
@@ -150,3 +150,24 @@ export function overview(db, { now = Date.now() } = {}) {
folders: folders(db),
}
}
+
+/** What the index calls each of these sessions: its title, folder and header (a Harness session's name). */
+export function headings(db, sessionIds) {
+ const ids = [...new Set(sessionIds.filter((id) => typeof id === 'string' && id))].slice(0, 200)
+ if (!ids.length) return new Map()
+ const found = rows(db, `SELECT session_id AS sessionId, title, cwd, header FROM sessions WHERE session_id IN (${ids.map(() => '?').join(', ')})`, ...ids)
+ return new Map(found.map((row) => [row.sessionId, { title: row.title ?? '', cwd: row.cwd ?? '', header: row.header ?? '' }]))
+}
+
+/**
+ * The turns around one turn of a session, oldest first: what was said where a search found it. Without a
+ * turn (a hit on the session's name), its last few.
+ */
+export function around(db, sessionId, turn, { before = 3, after = 1, maxChars = 2000 } = {}) {
+ const chars = Math.max(40, Math.min(8000, maxChars))
+ const columns = `turn, at, substr(ask, 1, ${chars}) AS ask, substr(answer, 1, ${chars}) AS answer`
+ if (!Number.isInteger(turn) || turn < 0) {
+ return rows(db, `SELECT ${columns} FROM turns WHERE session_id = ? AND turn >= 0 ORDER BY turn DESC LIMIT ?`, sessionId, before + after + 1).reverse()
+ }
+ return rows(db, `SELECT ${columns} FROM turns WHERE session_id = ? AND turn BETWEEN ? AND ? ORDER BY turn`, sessionId, Math.max(0, turn - before), turn + after)
+}
diff --git a/store/agents/memories/test/search.test.mjs b/store/agents/memories/test/search.test.mjs
new file mode 100644
index 000000000..acbb42fe3
--- /dev/null
+++ b/store/agents/memories/test/search.test.mjs
@@ -0,0 +1,101 @@
+/**
+ * Search: conversations found by the daemon's session search (Cmd-P's), labeled from the index here, with the
+ * package's own search when no daemon answers; and the words around where a search found a conversation.
+ */
+import assert from 'node:assert/strict'
+import { mkdtempSync } from 'node:fs'
+import { request } from 'node:http'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { after, before, beforeEach, test } from 'node:test'
+import { createViewer } from '../viewer.mjs'
+import { makeHome } from './fixtures.mjs'
+
+const { home, env } = makeHome()
+const workspace = mkdtempSync(join(tmpdir(), 'memories-search-'))
+
+/** A daemon as the bridge reaches it: what it was asked, and what it answers. */
+const daemon = { reports: 0, asked: [], answer: () => ({ hits: [] }), machines: [{ machineId: 'here', name: 'studio', current: true, online: true }] }
+const fleet = {
+ machinesReport: async () => { daemon.reports++; return { machines: daemon.machines } },
+ request: async (machineId, type, payload) => {
+ if (type !== 'session_search') return {}
+ daemon.asked.push({ machineId, type, payload })
+ return daemon.answer(payload)
+ },
+}
+let viewer, port
+before(async () => { viewer = createViewer({ workspace, env, home, intervalMs: 60_000, fleetIntervalMs: 3_600_000, idleFleetIntervalMs: 3_600_000, fleet }); port = await viewer.start() })
+after(async () => { await viewer.close() })
+beforeEach(() => {
+ daemon.asked = []
+ daemon.answer = () => ({ hits: [] })
+ daemon.machines = [{ machineId: 'here', name: 'studio', current: true, online: true }]
+})
+
+function get(path, host = `127.0.0.1:${port}`) {
+ return new Promise((resolve, reject) => {
+ const req = request({ host: '127.0.0.1', port, path, headers: { host } }, (res) => {
+ let body = ''
+ res.on('data', (chunk) => { body += chunk })
+ res.on('end', () => resolve({ status: res.statusCode, body: body ? JSON.parse(body) : null }))
+ })
+ req.on('error', reject)
+ req.end()
+ })
+}
+
+test('asks the daemon, as Cmd-P does, and labels its hits from the index here', async () => {
+ daemon.answer = () => ({ hits: [
+ { sessionId: 's1', agentId: 'agent-s1', engine: 'claude', turn: 1, at: 5, lastAt: 9, field: 'ask', snippet: 'no, too \u0002long\u0003 again', together: true, score: 1 },
+ { sessionId: 'outside', agentId: '', engine: 'codex', turn: 0, at: null, lastAt: 7, field: 'ask', snippet: 'x', external: { title: 'Their own title', cwd: '/w', origin: 'terminal' } },
+ { sessionId: 'unknown', engine: 'grok', turn: 'x', snippet: null },
+ { agentId: 'no-session' },
+ ] })
+ const { body } = await get('/api/search?q=too%20long')
+ assert.deepEqual(daemon.asked.map(({ machineId, type, payload }) => [machineId, type, payload]), [['here', 'session_search', { query: 'too long', limit: 20 }]])
+ assert.deepEqual(body.hits[0], { sessionId: 's1', turn: 1, at: 5, engine: 'claude', title: 'Fix login', cwd: body.hits[0].cwd, snippet: 'no, too \u0002long\u0003 again' })
+ assert.match(body.hits[0].cwd, /my-app$/)
+ assert.deepEqual([body.hits[1].title, body.hits[1].cwd, body.hits[1].at], ['Their own title', '/w', 7])
+ assert.deepEqual(body.hits[2], { sessionId: 'unknown', turn: -1, at: null, engine: 'grok', title: '', cwd: '', snippet: '' })
+ assert.equal(body.hits.length, 3)
+ // The machine is looked up once, not on every keystroke.
+ const before = daemon.reports
+ await get('/api/search?q=again')
+ assert.equal(daemon.reports, before)
+})
+
+test('without a daemon that answers, finds with its own search, and looks for the machine again next time', async () => {
+ daemon.answer = () => { throw new Error('the bridge is down') }
+ const failed = (await get('/api/search?q=fridays')).body
+ assert.equal(failed.hits.length, 1)
+ assert.equal(failed.hits[0].engine, 'codex')
+ const before = daemon.reports
+ daemon.answer = () => ({ error: 'UNSUPPORTED' })
+ assert.equal((await get('/api/search?q=fridays')).body.hits.length, 1)
+ assert.equal(daemon.reports, before + 1)
+ daemon.machines = [{ machineId: 'elsewhere', current: false }]
+ daemon.answer = () => { throw new Error('forget the machine') }
+ await get('/api/search?q=fridays')
+ assert.equal((await get('/api/search?q=fridays')).body.hits.length, 1)
+ assert.equal(daemon.asked.filter((ask) => ask.machineId === 'elsewhere').length, 0)
+})
+
+test('related conversations want any of the words, so they stay with its own search', async () => {
+ const state = (await get('/api/state')).body
+ const short = state.memories.find((row) => row.title === 'Short answers')
+ const related = (await get(`/api/related?id=${encodeURIComponent(short.id)}`)).body
+ assert.ok(Array.isArray(related.hits))
+ assert.equal(daemon.asked.length, 0)
+})
+
+test('the words around a hit: its turn and the ones before it, or a conversation\'s last ones, read from the index', async () => {
+ const at = (await get('/api/conversation?sessionId=s1&turn=1')).body
+ assert.equal(at.title, 'Fix login')
+ assert.deepEqual(at.turns.map((turn) => [turn.turn, turn.ask]), [[0, 'please keep it short, tldr only'], [1, 'no, too long again']])
+ const last = (await get('/api/conversation?sessionId=s1')).body
+ assert.deepEqual(last.turns.map((turn) => turn.turn), [0, 1])
+ assert.deepEqual((await get('/api/conversation?sessionId=nope&turn=0')).body.turns, [])
+ assert.deepEqual((await get('/api/conversation')).body, { turns: [] })
+ assert.equal((await get('/api/conversation?sessionId=s1', 'evil.example')).status, 403)
+})
diff --git a/store/agents/memories/viewer.mjs b/store/agents/memories/viewer.mjs
index a7003b615..8ca345881 100644
--- a/store/agents/memories/viewer.mjs
+++ b/store/agents/memories/viewer.mjs
@@ -16,7 +16,7 @@ import { homes } from './lib/agents.mjs'
import { noteSeen, writeAbout } from './lib/about.mjs'
import { DEFAULT_CHOICE_AT, deliver } from './lib/deliver.mjs'
import { askMachines, merge, newestChoice, syncAbout, syncChoice } from './lib/fleet.mjs'
-import { search } from './lib/sessions.mjs'
+import { around, headings, search } from './lib/sessions.mjs'
import { closeIndex, fingerprint, sessionIndex, snapshot as takeSnapshot, writeVerdict } from './lib/state.mjs'
const PACKAGE = dirname(fileURLToPath(import.meta.url))
@@ -189,12 +189,62 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, env = pro
timer = setTimeout(async () => { await look(); schedule() }, intervalMs)
}
+ // This machine's id as the bridge names it: asked once, and again after a failure.
+ let hereId = null
+ async function thisMachine() {
+ if (hereId) return hereId
+ const report = await fleet.machinesReport()
+ hereId = report?.machines?.find((machine) => machine.current)?.machineId ?? null
+ return hereId
+ }
+
+ /**
+ * Conversations, found by the same search as Cmd-P: the daemon's session index service (`session_search`),
+ * so the same words find the same sessions in both. Measured on one Mac's 9,928 messages (2026-10-10), this
+ * package's own search wanted every word in one turn, ranked tool output like what the person said, and
+ * found nothing for a question ("what did i decide about pricing": one unrelated session); the daemon's
+ * found twelve, from what the person asked. Its hits are labeled from the index here. The package's own
+ * search stays for a daemon that cannot answer (none running, or too old) and for related conversations,
+ * which want any of the words rather than all.
+ */
async function sessionSearch(text, options) {
+ if (fleet && !options.any) {
+ try {
+ const here = await thisMachine()
+ const answer = here ? await fleet.request(here, 'session_search', { query: text, limit: options.limit }, { timeoutMs: 5000 }) : null
+ if (Array.isArray(answer?.hits)) return { hits: await labeled(answer.hits) }
+ } catch { hereId = null }
+ }
const index = await sessionIndex(homes(env, home))
if (!index.db) return { hits: [], error: index.error }
try { return { hits: search(index.db, text, options) } } catch (error) { return { hits: [], error: String(error?.message ?? error) } }
}
+ /** The daemon's hits in this viewer's shape, titled and placed from the index. */
+ async function labeled(hits) {
+ const index = await sessionIndex(homes(env, home))
+ let known = new Map()
+ try { if (index.db) known = headings(index.db, hits.map((hit) => hit?.sessionId)) } catch { /* unlabeled is still found */ }
+ return hits.filter((hit) => typeof hit?.sessionId === 'string').map((hit) => {
+ const heading = known.get(hit.sessionId)
+ return {
+ sessionId: hit.sessionId, turn: Number.isInteger(hit.turn) ? hit.turn : -1, at: hit.at ?? hit.lastAt ?? null, engine: String(hit.engine ?? ''),
+ title: String(hit.external?.title || heading?.title || heading?.header || ''), cwd: String(hit.external?.cwd || heading?.cwd || ''),
+ snippet: String(hit.snippet ?? '').replace(/\s+/g, ' ').slice(0, 400),
+ }
+ })
+ }
+
+ /** What was said around where a search found a conversation: read from the index, never a transcript. */
+ async function conversation(sessionId, turn) {
+ const index = await sessionIndex(homes(env, home))
+ if (!index.db) return { turns: [], error: index.error }
+ try {
+ const [heading] = headings(index.db, [sessionId]).values()
+ return { sessionId, title: heading?.title || heading?.header || '', cwd: heading?.cwd ?? '', turns: around(index.db, sessionId, turn) }
+ } catch (error) { return { turns: [], error: String(error?.message ?? error) } }
+ }
+
const server = createServer(async (req, res) => {
try {
const address = server.address()
@@ -228,7 +278,13 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, env = pro
}
if (url.pathname === '/api/search') {
const q = (url.searchParams.get('q') ?? '').slice(0, 200)
- json(res, 200, { q, ...(await sessionSearch(q, { limit: 12 })) })
+ json(res, 200, { q, ...(await sessionSearch(q, { limit: 20 })) })
+ return
+ }
+ if (url.pathname === '/api/conversation') {
+ const sessionId = (url.searchParams.get('sessionId') ?? '').slice(0, 200)
+ const turn = Number.parseInt(url.searchParams.get('turn') ?? '', 10)
+ json(res, 200, sessionId ? await conversation(sessionId, Number.isInteger(turn) ? turn : null) : { turns: [] })
return
}
if (url.pathname === '/api/related') {