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.

Core boundary, part 8: the service boundary, with search and the DSH viewers on it (#730)

Dee4ef4f58952f0
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 9481c597e..1d4ea3ec5 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -100,10 +100,8 @@ import { sessionCheckpoints } from './lib/sessionCheckpoint.js'
import { repairClaudeCwd } from './lib/cwdRepair.js'
import { stoppedAgents } from './lib/stoppedAgents.js'
import { prepareAgentHandoff } from './lib/agentHandoff.js'
-import { SessionSearchIndex, folderWords, type SearchSource } from './lib/sessionSearch/indexer.js'
import { ExternalSessions, OpenSessions } from './lib/sessionSearch/external.js'
import { externalProviders } from './lib/sessionSearch/externals/index.js'
-import { SessionSearchStore } from './lib/sessionSearch/store.js'
import { SESSION_SEARCH_FILE, searchCommand } from './lib/sessionSearch/command.js'
import { sweepWorktrees } from './lib/worktreeSweep.js'
import { nameBranchAfterSession } from './lib/branchNaming.js'
@@ -112,13 +110,8 @@ import { type LaunchOverridesDeps } from './lib/launchOverrides.js'
import { buildHarnessSessionLabel } from './lib/harnessSessionLabel.js'
import { adoptLegacyHarnessSessions, listTmuxPanes } from './lib/tmuxAgentDiscovery.js'
import { installedDsh } from './dsh/installed.js'
-import { dshVerdictPath, dshViewerName } from './dsh/manifest.js'
-import { catalogEntry } from './dsh/catalog.js'
import { removeDsh } from './dsh/install.js'
import { prepareHarnessLaunch } from './dsh/runtime.js'
-import { DshViewerManager } from './dsh/viewer.js'
-import { ViewerLedger } from './dsh/viewerLedger.js'
-import { DshVerdictWatcher, type DshVerdict } from './dsh/verdict.js'
import { dshCommand, dshUsage } from './dsh/command.js'
import { ApiConnections } from './lib/apiConnections.js'
import { rememberSavedApis } from './lib/apiModels.js'
@@ -173,6 +166,10 @@ import { createAgentLifecycle } from './core/agents/lifecycle.js'
import { createAgentClosing } from './core/agents/close.js'
import { createEngineHooks, installEngineHooks } from './core/engines/hooks.js'
import { createCursorTaskHooks } from './core/engines/cursorTasks.js'
+import { databaseHistory } from './core/transcripts/databaseHistory.js'
+import { createCoreApi, emptyPorts } from './core/api.js'
+import { startSearch } from './services/search.js'
+import { startViewers } from './services/viewers.js'
import { describeMasterStatus, readStatusFile, runMaster } from './harnessd/master.js'
import { CORE_EXIT_STOP, CORE_EXIT_UPDATE } from './harnessd/protocol.js'
import { isLocalSocketName, localSocketPath, type LocalSocketServer } from './lib/localSocket.js'
@@ -189,7 +186,6 @@ import { WindowVisit } from './cable/windowVisit.js'
import { WindowForm } from './cable/windowForm.js'
import { RemoteRelayPool } from './lib/remoteRelay.js'
import { TERMINAL_BINARY_VERSION } from './lib/terminalBinary.js'
-import { type LiveEvent } from './lib/normalize.js'
import { TeamError } from './teams/model.js'
import { routeVoiceTask, setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter, type RouterAgent } from './lib/voiceRouter.js'
import { E2eeStore, identitySpent, peekIdentityPub } from './lib/e2ee/store.js'
@@ -216,16 +212,8 @@ import { type ActivityFrame } from './lib/turnActivity.js'
import { CursorTranscriptDiscovery } from './engines/cursor/discovery.js'
import { cursorDataDir } from './engines/cursor/home.js'
import { loadCursorPendingTasks } from './engines/cursor/pendingTasks.js'
-import { readOpencodeMessages } from './engines/opencode/reader.js'
import { opencodeMajorVersion } from './engines/opencode/version.js'
-import { opencodeMessagesToEvents } from './engines/opencode/normalizer.js'
-import { readKiloMessages } from './engines/kilo/reader.js'
-import { kiloMessagesToEvents } from './engines/kilo/normalizer.js'
-import { readHermesMessages } from './engines/hermes/reader.js'
import { hermesDbForSession } from './lib/hermesHome.js'
-import { readDevinMessages } from './engines/devin/reader.js'
-import { hermesMessagesToEvents } from './engines/hermes/normalizer.js'
-import { devinMessagesToEvents } from './engines/devin/normalizer.js'
import { agentFrame, lastActivityAt, type AgentFrame } from './lib/agentFrame.js'
import { agentTokenUsage } from './lib/agentTokenUsage.js'
import { DeviceResultJournal } from './lib/autonomous-device/resultJournal.js'
@@ -1765,89 +1753,32 @@ async function runForeground(session: AuthSession | null): Promise<void> {
agentTokenUsage.onChanged = agentEvents.onTokenUsageChanged
const announceSession = agentEvents.announceSession
- // ── Domain-specific harness companions ──────────────────────────────────────────────────────────
- // A DSH agent has two things beside its pane that the daemon owns for as long as the agent exists:
- // its viewer server (a URL the desktop shows in a pane next to the terminal) and a watch on the
- // verdict file its scripts write. Both are keyed on the agent, attached wherever an agent with a
- // `dsh` comes into being (create, restore, discovery) and detached where it is forgotten.
- const dshFrames = new Map<string, { viewerUrl: string | null; verdict: DshVerdict | null }>()
- const dshFrameFor = (agentId: string): { viewerUrl: string | null; verdict: DshVerdict | null } => {
- let state = dshFrames.get(agentId)
- if (!state) { state = { viewerUrl: null, verdict: null }; dshFrames.set(agentId, state) }
- return state
- }
- const dshFrameContext = (s: RegisteredSession): AgentDshContext | null => {
- if (!s.dsh) return null
- const state = dshFrames.get(s.agentId)
- const installed = installedDsh(s.dsh)
- return {
- // The current id, so a face drawn by id survives a rename the agent predates.
- id: installed?.id ?? s.dsh,
- name: installed?.manifest.name ?? catalogEntry(s.dsh)?.name ?? null,
- viewerUrl: state?.viewerUrl ?? null,
- // The pane beside the terminal says what it is, so the harness's name is not printed twice.
- viewerName: installed ? dshViewerName(installed.manifest, (id) => installedDsh(id)?.manifest.name ?? catalogEntry(id)?.name) : null,
- verdict: state?.verdict ?? null,
- }
- }
- dshFrameContextRef = dshFrameContext
- // A companion's news (a viewer URL, a verdict) is pushed on the agent's frame — but only once
- // the agent's terminal is attached. During a daemon start the viewer is often up before the
- // pane is re-attached, and a frame with no terminal reads to the desktop as "agent gone": it
- // closed the tiles of every harness agent on every restart (seen 2026-09-15, three times). The
- // attach's own sync carries whatever arrived first.
- const syncCompanion = (agentId: string): void => {
- const session = registry.byAgent(agentId)
- if (session && registry.terminalAvailable(agentId)) syncSession(session)
- }
- // Viewers an earlier daemon started and never stopped (crash, force quit, SIGKILL) are still running
- // and still polling; stop them BEFORE this daemon starts its own, or they accumulate a generation per
- // restart. Only pids whose live start time matches what that daemon recorded are touched.
- const viewerLedger = new ViewerLedger({ log: (line) => console.log(line) })
- viewerLedger.reapOrphans()
- const dshViewers = new DshViewerManager({
- onUrl: (agentId, url) => {
- dshFrameFor(agentId).viewerUrl = url
+ // Conversations on this machine that Harness did not start, found where each engine keeps them so
+ // Cmd-P can find them and open one here; and which sessions a process has open right now. Harness's
+ // own byproducts (recaps run in its data folder) are never among them.
+ const externalEngines = externalProviders()
+ const externalSessions = new ExternalSessions({ providers: externalEngines, excluded: [env.ADAPTER_DATA_DIR], log: (line) => console.warn(line) })
+ const openSessions = new OpenSessions({ providers: externalEngines, log: (line) => console.warn(line) })
+ // The core's side of the boundary its services stand on, and the ports it reaches them through (core/api.ts).
+ const coreApi = createCoreApi({
+ dataDir: env.ADAPTER_DATA_DIR,
+ registry,
+ stoppedAgents,
+ databaseHistory,
+ externalSessions,
+ openSessions,
+ syncSession,
+ viewerChanged: (agentId) => {
backendRef?.viewerForwarder.refresh(agentId)
backendRef?.interactiveViewers.refresh(agentId)
- syncCompanion(agentId)
},
- log: (line) => console.log(line),
- ledger: viewerLedger,
})
- const dshVerdicts = new DshVerdictWatcher({
- onChange: (agentId, verdict) => {
- dshFrameFor(agentId).verdict = verdict
- // The verdict's artifact is what the viewer should show, when it names one.
- dshViewers.setVerdictArtifact(agentId, verdict?.artifact ?? null)
- syncCompanion(agentId)
- },
- log: (line) => console.log(line),
- })
- const dshWarned = new Set<string>()
- /** Idempotent: safe to call on every observation of the agent. */
- const attachDsh = (s: RegisteredSession): void => {
- if (!s.dsh || !s.cwd) return
- const installed = installedDsh(s.dsh)
- if (!installed) {
- if (!dshWarned.has(s.dsh)) {
- dshWarned.add(s.dsh)
- console.warn(`[dsh] ${s.dsh} is not installed on this machine · agent ${sid(s.agentId)} runs as plain ${s.engine} (no viewer, no verdict)`)
- }
- return
- }
- dshVerdicts.watch(s.agentId, join(s.cwd, dshVerdictPath(installed.manifest)))
- if (installed.manifest.viewer) {
- void dshViewers.start(s.agentId, installed, s.cwd).catch((error) => {
- console.warn(`[dsh] ${s.dsh} viewer failed to start · ${error instanceof Error ? error.message : error}`)
- })
- }
- }
- const detachDsh = (agentId: string): void => {
- dshVerdicts.unwatch(agentId)
- void dshViewers.stop(agentId)
- dshFrames.delete(agentId)
- }
+ const ports = emptyPorts()
+ // The DSH companions: each harness agent's viewer and verdict watch (services/viewers.ts).
+ startViewers(coreApi, ports)
+ dshFrameContextRef = (s) => ports.viewers?.frameContext(s) ?? null
+ const attachDsh = (s: RegisteredSession): void => ports.viewers?.attach(s)
+ const detachDsh = (agentId: string): void => ports.viewers?.detach(agentId)
// A worktree branch Harness made up at Start takes its session's name once it has one
// (lib/branchNaming.ts). Each agent is looked at once per daemon; the git reads are the cost.
@@ -1927,7 +1858,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Nothing is answered until start-up is done (see the end of this function).
backend.holdRequests()
daemonBoot.openRequests = () => backend.openRequests()
- backend.viewerTargetProvider = (agentId) => dshViewers.forwardingUrl(agentId)
+ backend.viewerTargetProvider = (agentId) => ports.viewers?.forwardingUrl(agentId) ?? null
ensureBundledCoreHarnesses()
@@ -2244,18 +2175,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
backend.recentProvider = recaps.recent
backend.recentAsksProvider = recaps.recentAsks
- // The engines that keep a conversation in a database instead of a transcript file, read through
- // the same readers and replay normalizers as `session_get`.
- const databaseHistory = (s: RegisteredSession): (() => Promise<readonly LiveEvent[]>) | undefined => {
- switch (s.engine) {
- case 'opencode': return async () => opencodeMessagesToEvents(await readOpencodeMessages(join(env.OPENCODE_DATA_DIR, 'opencode.db'), s.sessionId))
- case 'kilo': return async () => kiloMessagesToEvents(await readKiloMessages(join(env.KILO_DATA_DIR, 'kilo.db'), s.sessionId))
- case 'devin': return async () => devinMessagesToEvents(await readDevinMessages(join(env.DEVIN_HOME, 'sessions.db'), s.sessionId))
- case 'hermes': return async () => hermesMessagesToEvents(await readHermesMessages(await hermesDbForSession(s), s.sessionId))
- default: return undefined
- }
- }
-
// "Change agent": the desktop asks for the structured handoff file (lib/agentHandoff.ts) before it
// closes the old engine; the new one is then told to read it.
// Built ONCE: its discovery keeps "one search per agent" across requests.
@@ -2276,66 +2195,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
})
backend.handoffProvider = (req) => prepareAgentHandoff(handoffDeps, req)
- // Session search: every turn of every conversation on this machine, live and stopped, indexed from
- // its transcript and searched by `session_search` (lib/sessionSearch/). Nothing leaves the machine
- // but the hits for a query. A Node without `node:sqlite` has no index; the RPC then says so.
- // Conversations on this machine that Harness did not start, found where each engine keeps them so
- // Cmd-P can find them and open one here; and which sessions a process has open right now. Harness's
- // own byproducts (recaps run in its data folder) are never among them.
- const externalEngines = externalProviders()
- const externalSessions = new ExternalSessions({ providers: externalEngines, excluded: [env.ADAPTER_DATA_DIR], log: (line) => console.warn(line) })
- const openSessions = new OpenSessions({ providers: externalEngines, log: (line) => console.warn(line) })
- const sessionSearch = (() => {
- try {
- const store = SessionSearchStore.open(join(env.ADAPTER_DATA_DIR, SESSION_SEARCH_FILE))
- if (!store) {
- console.warn('[search] node:sqlite is not available on this Node — session search is off')
- return null
- }
- const index = new SessionSearchIndex({
- store,
- sources: () => {
- const own = [...registry.list(), ...stoppedAgents.list()]
- const sources = own.flatMap((s): SearchSource[] => {
- const readHistory = s.transcriptPath ? undefined : databaseHistory(s)
- if (!s.sessionId || (!s.transcriptPath && !readHistory)) return []
- return [{
- agentId: s.agentId,
- sessionId: s.sessionId,
- engine: s.engine,
- transcriptPath: s.transcriptPath || null,
- header: [projectDisplayName(s), s.title, folderWords(s.cwd)].filter(Boolean).join(' · '),
- // Conversation stamps only: the row's `touchedAt` includes discovery bookkeeping.
- changedAt: Math.max(s.lastTranscriptAt || 0, s.lastHookAt || 0) || s.boundAt || s.registeredAt || 0,
- readHistory,
- }]
- })
- // Conversations Harness did not start — any Harness agent's, earlier ones included, are not.
- const known = store.ownedSessionIds()
- for (const s of own) if (s.sessionId) known.add(s.sessionId)
- for (const e of externalSessions.list()) {
- // A conversation Harness holds under any of its ids is Harness's.
- if (known.has(e.sessionId) || e.aliases?.some((id) => known.has(id)) || (!e.transcriptPath && !e.readHistory)) continue
- sources.push({
- agentId: '', sessionId: e.sessionId, engine: e.engine, transcriptPath: e.transcriptPath,
- header: '', changedAt: e.mtime, external: { cwd: e.cwd, origin: e.origin, title: e.title },
- ...(e.readHistory ? { readHistory: e.readHistory } : {}),
- })
- }
- return sources
- },
- agents: () => [...registry.list(), ...stoppedAgents.list()].map((s) => s.agentId),
- discover: () => externalSessions.scan(),
- openSessions,
- log: (line) => console.log(line),
- })
- index.start()
- return index
- } catch (error) {
- console.error('[search] could not open the session index:', error instanceof Error ? error.message : error)
- return null
- }
- })()
+ // Session search (services/search.ts).
+ startSearch(coreApi, ports)
+ const sessionSearch = ports.search
backend.sessionSearchProvider = sessionSearch ? (query, options) => sessionSearch.search(query, options) : null
backend.sessionTailProvider = sessionSearch ? (sessionId, options) => sessionSearch.tail(sessionId, options) : null
@@ -2363,7 +2225,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
return session ? runtimeProfiles.modelsForSession(session) : Promise.resolve([])
}
backend.runtimeProfileProvider = (session) => runtimeProfiles.selectedModel(session)
- backend.dshFrameProvider = dshFrameContext
+ backend.dshFrameProvider = (s) => ports.viewers?.frameContext(s) ?? null
backend.onDshRemove = (id) => removeDsh(id)
// `harness remote` names the tile it was typed in by its tmux pane; the registry knows whose it is.
backend.onTerminalHandoff = (tmuxPane) => registry.advertised()
@@ -3872,8 +3734,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
codexActivity.close()
shutdownVoiceRouter()
// The new daemon starts its own viewers for the agents it restores; ours must not hold the ports.
- await dshViewers.stopAll()
- await dshVerdicts.stop()
+ await ports.viewers?.stop()
autonomousDeviceDirect?.stop()
await backend.stop() // graceful WS close → releases the Redis machine-owner claim
await new Promise((r) => setTimeout(r, 1000)) // grace before the same-machine reclaim
@@ -3985,8 +3846,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
await localSocket?.close()
codexActivity.close()
shutdownVoiceRouter()
- await dshViewers.stopAll()
- await dshVerdicts.stop()
+ await ports.viewers?.stop()
autonomousDeviceDirect?.stop()
await backend.stop()
try { if (readPid() === process.pid) rmSync(PID_FILE, { force: true }) } catch { /* ignore */ }
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
new file mode 100644
index 000000000..3184e6266
--- /dev/null
+++ b/cli/src/core/api.spec.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it, vi } from 'vitest'
+import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'
+import { createCoreApi, emptyPorts, type CoreApiDeps } from './api.js'
+
+const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession
+
+describe('the core API services stand on', () => {
+ it('lists every agent, live then stopped, and names them as the apps do', () => {
+ const deps: CoreApiDeps = {
+ dataDir: '/data',
+ registry: {
+ list: vi.fn(() => [row('live')]),
+ byAgent: vi.fn((agentId: string) => (agentId === 'live' ? row('live') : undefined)),
+ terminalAvailable: vi.fn((agentId: string) => agentId === 'live'),
+ } as unknown as CoreApiDeps['registry'],
+ stoppedAgents: { list: vi.fn(() => [row('stopped')]) } as unknown as CoreApiDeps['stoppedAgents'],
+ databaseHistory: vi.fn(),
+ externalSessions: { list: vi.fn(), scan: vi.fn() } as unknown as CoreApiDeps['externalSessions'],
+ openSessions: { known: vi.fn(), fresh: vi.fn() } as unknown as CoreApiDeps['openSessions'],
+ syncSession: vi.fn(),
+ viewerChanged: vi.fn(),
+ }
+ const core = createCoreApi(deps)
+ expect(core.dataDir).toBe('/data')
+ expect(core.agents.all().map((s) => s.agentId)).toEqual(['live', 'stopped'])
+ expect(core.agents.displayName).toBe(projectDisplayName)
+ expect(core.transcripts.databaseHistory).toBe(deps.databaseHistory)
+ expect(core.external.sessions).toBe(deps.externalSessions)
+ expect(core.external.open).toBe(deps.openSessions)
+ expect(core.agents.byAgent('live')?.agentId).toBe('live')
+ expect(core.agents.byAgent('gone')).toBeUndefined()
+ expect(core.agents.terminalAvailable('live')).toBe(true)
+ expect(core.agents.sync).toBe(deps.syncSession)
+ expect(core.clients.viewerChanged).toBe(deps.viewerChanged)
+ })
+
+ it('starts with every port empty: a service fills its own when it starts', () => {
+ expect(emptyPorts()).toEqual({ search: null, viewers: null })
+ expect(emptyPorts()).not.toBe(emptyPorts())
+ })
+})
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
new file mode 100644
index 000000000..b95764e93
--- /dev/null
+++ b/cli/src/core/api.ts
@@ -0,0 +1,106 @@
+/**
+ * The boundary the services stand on (docs/design/2026-10-03-harnessd.md, "The core boundary"):
+ * `CoreApi` is what a service may ask of the core, and `CorePorts` is what the core asks of services.
+ *
+ * Both are in process today. When a service moves into a process of its own, its `CoreApi` calls
+ * become requests on the local socket and its port becomes a proxy that sends them; the service's
+ * code stays as it is. Members are added as services move behind it, each a call that exists today,
+ * never a generic `call(name, args)`.
+ */
+import type { AgentDshContext } from '../lib/agentFrame.js'
+import type { LiveEvent } from '../lib/normalize.js'
+import { projectDisplayName, type registry, type RegisteredSession } from '../lib/registry.js'
+import type { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.js'
+import type { SessionSearchIndex } from '../lib/sessionSearch/indexer.js'
+import type { StoppedAgentStore } from '../lib/stoppedAgents.js'
+
+export interface CoreApi {
+ /** The daemon's data folder; a service keeps its own files in it. */
+ dataDir: string
+ agents: {
+ /** Every agent on this machine: the live ones, then the stopped ones. */
+ all(): RegisteredSession[]
+ /** The name the apps show for an agent. */
+ displayName(session: RegisteredSession): string
+ /** A live agent, by its agent id. */
+ byAgent(agentId: string): RegisteredSession | undefined
+ /** Whether the agent's terminal is attached: a frame without one reads to the apps as "agent gone". */
+ terminalAvailable(agentId: string): boolean
+ /** Send the agent's frame to the apps again. */
+ sync(session: RegisteredSession): void
+ }
+ transcripts: {
+ /** How to read a conversation its engine keeps in a database instead of a transcript file;
+ * undefined for every other engine. */
+ databaseHistory(session: RegisteredSession): (() => Promise<readonly LiveEvent[]>) | undefined
+ }
+ /** Conversations on this machine that Harness did not start, and which of them a process has open. */
+ external: {
+ sessions: Pick<ExternalSessions, 'list' | 'scan'>
+ open: Pick<OpenSessions, 'known' | 'fresh'>
+ }
+ clients: {
+ /** An agent's viewer moved: the windows' viewer panes forward to the new one. */
+ viewerChanged(agentId: string): void
+ }
+}
+
+/** The core's calls into session search: index a session at its turn boundaries, forget a purged
+ * conversation, the title it indexed for one being adopted, and the two requests it answers
+ * (`session_search`, `session_tail`). */
+export type SearchPort = Pick<SessionSearchIndex, 'touch' | 'deleteHistory' | 'session' | 'search' | 'tail'>
+
+/** The core's calls into the DSH viewers: each harness agent's viewer server and verdict watch. */
+export interface ViewersPort {
+ /** Start the agent's viewer and verdict watch when it has a DSH. Idempotent: called on every
+ * observation of the agent. */
+ attach(session: RegisteredSession): void
+ /** Stop them: the agent was forgotten. */
+ detach(agentId: string): void
+ /** What the agent's frame says about its DSH: its name, its viewer and its verdict. */
+ frameContext(session: RegisteredSession): AgentDshContext | null
+ /** Where the windows' viewer pane for the agent forwards to. */
+ forwardingUrl(agentId: string): string | null
+ /** Stop every viewer and watch, for a restart or a shutdown. */
+ stop(): Promise<void>
+}
+
+/** Each port is filled by the service that owns it when that service starts, and is null while the
+ * service is off: the core never waits on one. */
+export interface CorePorts {
+ search: SearchPort | null
+ viewers: ViewersPort | null
+}
+
+export function emptyPorts(): CorePorts {
+ return { search: null, viewers: null }
+}
+
+export interface CoreApiDeps {
+ dataDir: string
+ registry: Pick<typeof registry, 'list' | 'byAgent' | 'terminalAvailable'>
+ stoppedAgents: Pick<StoppedAgentStore, 'list'>
+ databaseHistory: CoreApi['transcripts']['databaseHistory']
+ externalSessions: CoreApi['external']['sessions']
+ openSessions: CoreApi['external']['open']
+ syncSession: CoreApi['agents']['sync']
+ viewerChanged: CoreApi['clients']['viewerChanged']
+}
+
+export function createCoreApi({
+ dataDir, registry, stoppedAgents, databaseHistory, externalSessions, openSessions, syncSession, viewerChanged,
+}: CoreApiDeps): CoreApi {
+ return {
+ dataDir,
+ agents: {
+ all: () => [...registry.list(), ...stoppedAgents.list()],
+ displayName: projectDisplayName,
+ byAgent: (agentId) => registry.byAgent(agentId),
+ terminalAvailable: (agentId) => registry.terminalAvailable(agentId),
+ sync: syncSession,
+ },
+ transcripts: { databaseHistory },
+ external: { sessions: externalSessions, open: openSessions },
+ clients: { viewerChanged },
+ }
+}
diff --git a/cli/src/core/transcripts/databaseHistory.spec.ts b/cli/src/core/transcripts/databaseHistory.spec.ts
new file mode 100644
index 000000000..da31764d1
--- /dev/null
+++ b/cli/src/core/transcripts/databaseHistory.spec.ts
@@ -0,0 +1,46 @@
+import { join } from 'node:path'
+import { describe, expect, it, vi } from 'vitest'
+import { env } from '../../config/env.js'
+import { readDevinMessages } from '../../engines/devin/reader.js'
+import { readHermesMessages } from '../../engines/hermes/reader.js'
+import { readKiloMessages } from '../../engines/kilo/reader.js'
+import { readOpencodeMessages } from '../../engines/opencode/reader.js'
+import { hermesDbForSession } from '../../lib/hermesHome.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { databaseHistory } from './databaseHistory.js'
+
+vi.mock('../../engines/opencode/reader.js', () => ({ readOpencodeMessages: vi.fn(async () => ['opencode rows']) }))
+vi.mock('../../engines/opencode/normalizer.js', () => ({ opencodeMessagesToEvents: vi.fn((rows: unknown[]) => [{ from: 'opencode', rows }]) }))
+vi.mock('../../engines/kilo/reader.js', () => ({ readKiloMessages: vi.fn(async () => ['kilo rows']) }))
+vi.mock('../../engines/kilo/normalizer.js', () => ({ kiloMessagesToEvents: vi.fn((rows: unknown[]) => [{ from: 'kilo', rows }]) }))
+vi.mock('../../engines/devin/reader.js', () => ({ readDevinMessages: vi.fn(async () => ['devin rows']) }))
+vi.mock('../../engines/devin/normalizer.js', () => ({ devinMessagesToEvents: vi.fn((rows: unknown[]) => [{ from: 'devin', rows }]) }))
+vi.mock('../../engines/hermes/reader.js', () => ({ readHermesMessages: vi.fn(async () => ['hermes rows']) }))
+vi.mock('../../engines/hermes/normalizer.js', () => ({ hermesMessagesToEvents: vi.fn((rows: unknown[]) => [{ from: 'hermes', rows }]) }))
+vi.mock('../../lib/hermesHome.js', () => ({ hermesDbForSession: vi.fn(async () => '/profiles/work/state.db') }))
+
+const session = (engine: string) => ({ agentId: 'a1', sessionId: 's1', engine }) as RegisteredSession
+
+describe('reading a conversation its engine keeps in a database', () => {
+ it('OpenCode, Kilo and Devin from their own stores, through the replay normalizers', async () => {
+ expect(await databaseHistory(session('opencode'))!()).toEqual([{ from: 'opencode', rows: ['opencode rows'] }])
+ expect(readOpencodeMessages).toHaveBeenCalledWith(join(env.OPENCODE_DATA_DIR, 'opencode.db'), 's1')
+ expect(await databaseHistory(session('kilo'))!()).toEqual([{ from: 'kilo', rows: ['kilo rows'] }])
+ expect(readKiloMessages).toHaveBeenCalledWith(join(env.KILO_DATA_DIR, 'kilo.db'), 's1')
+ expect(await databaseHistory(session('devin'))!()).toEqual([{ from: 'devin', rows: ['devin rows'] }])
+ expect(readDevinMessages).toHaveBeenCalledWith(join(env.DEVIN_HOME, 'sessions.db'), 's1')
+ })
+
+ it('Hermes from the profile home its session lives in', async () => {
+ const hermes = session('hermes')
+ expect(await databaseHistory(hermes)!()).toEqual([{ from: 'hermes', rows: ['hermes rows'] }])
+ expect(hermesDbForSession).toHaveBeenCalledWith(hermes)
+ expect(readHermesMessages).toHaveBeenCalledWith('/profiles/work/state.db', 's1')
+ })
+
+ it('nothing to read for an engine with a transcript file, and nothing read until asked', () => {
+ expect(databaseHistory(session('claude'))).toBeUndefined()
+ databaseHistory(session('opencode'))
+ expect(readOpencodeMessages).not.toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/cli/src/core/transcripts/databaseHistory.ts b/cli/src/core/transcripts/databaseHistory.ts
new file mode 100644
index 000000000..6bf643510
--- /dev/null
+++ b/cli/src/core/transcripts/databaseHistory.ts
@@ -0,0 +1,29 @@
+/**
+ * The engines that keep a conversation in a database instead of a transcript file, read through
+ * the same readers and replay normalizers as `session_get`.
+ *
+ * Moved verbatim out of `runForeground` (the core boundary, step 13: docs/design/2026-10-03-harnessd.md).
+ */
+import { join } from 'node:path'
+import { env } from '../../config/env.js'
+import { devinMessagesToEvents } from '../../engines/devin/normalizer.js'
+import { readDevinMessages } from '../../engines/devin/reader.js'
+import { hermesMessagesToEvents } from '../../engines/hermes/normalizer.js'
+import { readHermesMessages } from '../../engines/hermes/reader.js'
+import { kiloMessagesToEvents } from '../../engines/kilo/normalizer.js'
+import { readKiloMessages } from '../../engines/kilo/reader.js'
+import { opencodeMessagesToEvents } from '../../engines/opencode/normalizer.js'
+import { readOpencodeMessages } from '../../engines/opencode/reader.js'
+import { hermesDbForSession } from '../../lib/hermesHome.js'
+import type { LiveEvent } from '../../lib/normalize.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+
+export const databaseHistory = (s: RegisteredSession): (() => Promise<readonly LiveEvent[]>) | undefined => {
+ switch (s.engine) {
+ case 'opencode': return async () => opencodeMessagesToEvents(await readOpencodeMessages(join(env.OPENCODE_DATA_DIR, 'opencode.db'), s.sessionId))
+ case 'kilo': return async () => kiloMessagesToEvents(await readKiloMessages(join(env.KILO_DATA_DIR, 'kilo.db'), s.sessionId))
+ case 'devin': return async () => devinMessagesToEvents(await readDevinMessages(join(env.DEVIN_HOME, 'sessions.db'), s.sessionId))
+ case 'hermes': return async () => hermesMessagesToEvents(await readHermesMessages(await hermesDbForSession(s), s.sessionId))
+ default: return undefined
+ }
+}
diff --git a/cli/src/services/search.spec.ts b/cli/src/services/search.spec.ts
new file mode 100644
index 000000000..b6d2faabc
--- /dev/null
+++ b/cli/src/services/search.spec.ts
@@ -0,0 +1,128 @@
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { emptyPorts, type CoreApi } from '../core/api.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import type { SessionSearchIndexOptions } from '../lib/sessionSearch/indexer.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { SESSION_SEARCH_FILE } from '../lib/sessionSearch/command.js'
+import { SessionSearchStore } from '../lib/sessionSearch/store.js'
+import { startSearch } from './search.js'
+
+vi.mock('../lib/sessionSearch/store.js', () => ({ SessionSearchStore: { open: vi.fn() } }))
+// The index, recording what it was built with so its callbacks can be driven directly.
+vi.mock('../lib/sessionSearch/indexer.js', async (real) => {
+ const actual = await real<typeof import('../lib/sessionSearch/indexer.js')>()
+ return {
+ ...actual,
+ SessionSearchIndex: class {
+ started = false
+ constructor(readonly opts: SessionSearchIndexOptions) {}
+ start() { this.started = true }
+ },
+ }
+})
+
+type Recorded = { opts: SessionSearchIndexOptions; started: boolean }
+const row = (over: Partial<RegisteredSession>) =>
+ ({ agentId: 'a1', sessionId: 's1', engine: 'claude', registeredAt: 1, ...over }) as RegisteredSession
+const reader = async () => []
+
+function setup(agents: RegisteredSession[] = [], external: unknown[] = [], owned: string[] = []) {
+ const store = { ownedSessionIds: vi.fn(() => new Set(owned)) }
+ vi.mocked(SessionSearchStore.open).mockReturnValue(store as never)
+ const core = fakeCore({
+ agents: { all: vi.fn(() => agents), displayName: vi.fn((s: RegisteredSession) => `name of ${s.agentId}`) },
+ transcripts: { databaseHistory: vi.fn((s: RegisteredSession) => (s.engine === 'opencode' ? reader : undefined)) },
+ external: {
+ sessions: { list: vi.fn(() => external), scan: vi.fn(async () => []) } as unknown as CoreApi['external']['sessions'],
+ open: { known: vi.fn(), fresh: vi.fn() } as unknown as CoreApi['external']['open'],
+ },
+ })
+ const ports = emptyPorts()
+ startSearch(core, ports)
+ return { core, ports, store, index: ports.search as unknown as Recorded }
+}
+
+describe('the session search service', () => {
+ beforeEach(() => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ })
+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })
+
+ describe('starting', () => {
+ it('opens the index in the core\'s data folder, starts it, and answers the core through its port', () => {
+ const { core, index } = setup()
+ expect(SessionSearchStore.open).toHaveBeenCalledWith(join('/data', SESSION_SEARCH_FILE))
+ expect(index.started).toBe(true)
+ expect(index.opts.openSessions).toBe(core.external.open)
+ })
+
+ it('leaves the port empty, and says so, on a Node without node:sqlite', () => {
+ const { core } = setup()
+ vi.mocked(SessionSearchStore.open).mockReturnValueOnce(null)
+ const ports = emptyPorts()
+ startSearch(core, ports)
+ expect(ports.search).toBeNull()
+ expect(console.warn).toHaveBeenCalledWith('[search] node:sqlite is not available on this Node — session search is off')
+ })
+
+ it('leaves the port empty, and says why, when the index cannot be opened', () => {
+ const ports = emptyPorts()
+ const { core } = setup()
+ vi.mocked(SessionSearchStore.open).mockImplementationOnce(() => { throw new Error('disk I/O error') })
+ startSearch(core, ports)
+ expect(ports.search).toBeNull()
+ expect(console.error).toHaveBeenCalledWith('[search] could not open the session index:', 'disk I/O error')
+ vi.mocked(SessionSearchStore.open).mockImplementationOnce(() => { throw 'locked' })
+ startSearch(core, ports)
+ expect(console.error).toHaveBeenLastCalledWith('[search] could not open the session index:', 'locked')
+ })
+ })
+
+ describe('what it indexes', () => {
+ it('every agent with a transcript or a database history, named and stamped by its conversation', () => {
+ const agents = [
+ row({ agentId: 'file', sessionId: 's-file', transcriptPath: '/t/file.jsonl', title: 'Fix login', cwd: '/work/app/api', lastTranscriptAt: 50, lastHookAt: 70 }),
+ row({ agentId: 'db', sessionId: 's-db', engine: 'opencode', boundAt: 40 }),
+ row({ agentId: 'fresh', sessionId: 's-fresh', transcriptPath: '/t/fresh.jsonl', registeredAt: 30 }),
+ row({ agentId: 'unstamped', sessionId: 's-un', transcriptPath: '/t/un.jsonl', registeredAt: 0 }),
+ row({ agentId: 'no-session', sessionId: '', transcriptPath: '/t/x.jsonl' }),
+ row({ agentId: 'nothing-to-read', sessionId: 's-none' }),
+ ]
+ const { index } = setup(agents)
+ expect(index.opts.sources()).toEqual([
+ { agentId: 'file', sessionId: 's-file', engine: 'claude', transcriptPath: '/t/file.jsonl', header: 'name of file · Fix login · api app', changedAt: 70, readHistory: undefined },
+ { agentId: 'db', sessionId: 's-db', engine: 'opencode', transcriptPath: null, header: 'name of db', changedAt: 40, readHistory: reader },
+ { agentId: 'fresh', sessionId: 's-fresh', engine: 'claude', transcriptPath: '/t/fresh.jsonl', header: 'name of fresh', changedAt: 30, readHistory: undefined },
+ { agentId: 'unstamped', sessionId: 's-un', engine: 'claude', transcriptPath: '/t/un.jsonl', header: 'name of unstamped', changedAt: 0, readHistory: undefined },
+ ])
+ })
+
+ it('conversations Harness did not start, unless Harness holds them under any of their ids', () => {
+ const external = [
+ { sessionId: 'mine-now', engine: 'claude', transcriptPath: '/t/a.jsonl', mtime: 1 },
+ { sessionId: 'mine-before', engine: 'claude', transcriptPath: '/t/b.jsonl', mtime: 1 },
+ { sessionId: 'forked', aliases: ['s1'], engine: 'claude', transcriptPath: '/t/c.jsonl', mtime: 1 },
+ { sessionId: 'unreadable', engine: 'codex', transcriptPath: null, mtime: 1 },
+ { sessionId: 'theirs', engine: 'codex', transcriptPath: '/t/d.jsonl', mtime: 9, cwd: '/work/tool', origin: 'terminal', title: 'Refactor', aliases: ['other'] },
+ { sessionId: 'their-db', engine: 'opencode', transcriptPath: null, readHistory: reader, mtime: 8, cwd: '/w', origin: 'app' },
+ ]
+ const { index } = setup([row({ sessionId: 'mine-now', transcriptPath: '/t/a.jsonl' }), row({ agentId: 'a2', sessionId: '' })], external, ['mine-before', 's1'])
+ expect(index.opts.sources().filter((s) => !s.agentId)).toEqual([
+ { agentId: '', sessionId: 'theirs', engine: 'codex', transcriptPath: '/t/d.jsonl', header: '', changedAt: 9, external: { cwd: '/work/tool', origin: 'terminal', title: 'Refactor' } },
+ { agentId: '', sessionId: 'their-db', engine: 'opencode', transcriptPath: null, header: '', changedAt: 8, external: { cwd: '/w', origin: 'app', title: undefined }, readHistory: reader },
+ ])
+ })
+
+ it('keeps every agent\'s sessions while the agent exists, looks again for others, and logs as the daemon does', async () => {
+ const { core, index } = setup([row({ agentId: 'a1' }), row({ agentId: 'a2' })])
+ expect([...index.opts.agents!()]).toEqual(['a1', 'a2'])
+ await index.opts.discover!()
+ expect(core.external.sessions.scan).toHaveBeenCalled()
+ index.opts.log!('[search] indexed 3 sessions')
+ expect(console.log).toHaveBeenCalledWith('[search] indexed 3 sessions')
+ })
+ })
+})
diff --git a/cli/src/services/search.ts b/cli/src/services/search.ts
new file mode 100644
index 000000000..47332ec0c
--- /dev/null
+++ b/cli/src/services/search.ts
@@ -0,0 +1,68 @@
+/**
+ * Session search: every turn of every conversation on this machine, live and stopped, indexed from
+ * its transcript and searched by `session_search` (lib/sessionSearch/). Nothing leaves the machine
+ * but the hits for a query. A Node without `node:sqlite` has no index; the RPC then says so.
+ *
+ * A service on the core boundary (docs/design/2026-10-03-harnessd.md, step 13): it reads the core
+ * only through `CoreApi`, and the core reaches it only through `ports.search`, which stays null when
+ * there is no index.
+ */
+import { join } from 'node:path'
+import type { CoreApi, CorePorts } from '../core/api.js'
+import { SESSION_SEARCH_FILE } from '../lib/sessionSearch/command.js'
+import { SessionSearchIndex, folderWords, type SearchSource } from '../lib/sessionSearch/indexer.js'
+import { SessionSearchStore } from '../lib/sessionSearch/store.js'
+
+export function startSearch(core: CoreApi, ports: CorePorts): void {
+ ports.search = (() => {
+ try {
+ const store = SessionSearchStore.open(join(core.dataDir, SESSION_SEARCH_FILE))
+ if (!store) {
+ console.warn('[search] node:sqlite is not available on this Node — session search is off')
+ return null
+ }
+ const index = new SessionSearchIndex({
+ store,
+ sources: () => {
+ const own = core.agents.all()
+ const sources = own.flatMap((s): SearchSource[] => {
+ const readHistory = s.transcriptPath ? undefined : core.transcripts.databaseHistory(s)
+ if (!s.sessionId || (!s.transcriptPath && !readHistory)) return []
+ return [{
+ agentId: s.agentId,
+ sessionId: s.sessionId,
+ engine: s.engine,
+ transcriptPath: s.transcriptPath || null,
+ header: [core.agents.displayName(s), s.title, folderWords(s.cwd)].filter(Boolean).join(' · '),
+ // Conversation stamps only: the row's `touchedAt` includes discovery bookkeeping.
+ changedAt: Math.max(s.lastTranscriptAt || 0, s.lastHookAt || 0) || s.boundAt || s.registeredAt || 0,
+ readHistory,
+ }]
+ })
+ // Conversations Harness did not start — any Harness agent's, earlier ones included, are not.
+ const known = store.ownedSessionIds()
+ for (const s of own) if (s.sessionId) known.add(s.sessionId)
+ for (const e of core.external.sessions.list()) {
+ // A conversation Harness holds under any of its ids is Harness's.
+ if (known.has(e.sessionId) || e.aliases?.some((id) => known.has(id)) || (!e.transcriptPath && !e.readHistory)) continue
+ sources.push({
+ agentId: '', sessionId: e.sessionId, engine: e.engine, transcriptPath: e.transcriptPath,
+ header: '', changedAt: e.mtime, external: { cwd: e.cwd, origin: e.origin, title: e.title },
+ ...(e.readHistory ? { readHistory: e.readHistory } : {}),
+ })
+ }
+ return sources
+ },
+ agents: () => core.agents.all().map((s) => s.agentId),
+ discover: () => core.external.sessions.scan(),
+ openSessions: core.external.open,
+ log: (line) => console.log(line),
+ })
+ index.start()
+ return index
+ } catch (error) {
+ console.error('[search] could not open the session index:', error instanceof Error ? error.message : error)
+ return null
+ }
+ })()
+}
diff --git a/cli/src/services/viewers.spec.ts b/cli/src/services/viewers.spec.ts
new file mode 100644
index 000000000..216d79a95
--- /dev/null
+++ b/cli/src/services/viewers.spec.ts
@@ -0,0 +1,187 @@
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { emptyPorts, type ViewersPort } from '../core/api.js'
+import { catalogEntry } from '../dsh/catalog.js'
+import { installedDsh } from '../dsh/installed.js'
+import { dshViewerName } from '../dsh/manifest.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { startViewers } from './viewers.js'
+
+const built = vi.hoisted(() => ({ ledger: [] as any[], viewers: [] as any[], verdicts: [] as any[], order: [] as string[] }))
+vi.mock('../dsh/installed.js', () => ({ installedDsh: vi.fn() }))
+vi.mock('../dsh/catalog.js', () => ({ catalogEntry: vi.fn() }))
+vi.mock('../dsh/manifest.js', () => ({ dshVerdictPath: vi.fn(() => '.harness/verdict.json'), dshViewerName: vi.fn(() => 'Blender view') }))
+vi.mock('../dsh/viewerLedger.js', () => ({
+ ViewerLedger: class {
+ constructor(readonly deps: { log: (line: string) => void }) { built.ledger.push(this) }
+ reapOrphans() { built.order.push('reap') }
+ },
+}))
+vi.mock('../dsh/viewer.js', () => ({
+ DshViewerManager: class {
+ start = vi.fn(async () => {})
+ stop = vi.fn(async () => {})
+ stopAll = vi.fn(async () => { built.order.push('viewers stopped') })
+ forwardingUrl = vi.fn((agentId: string) => `http://127.0.0.1:9/${agentId}`)
+ setVerdictArtifact = vi.fn()
+ constructor(readonly deps: any) { built.order.push('viewers'); built.viewers.push(this) }
+ },
+}))
+vi.mock('../dsh/verdict.js', () => ({
+ DshVerdictWatcher: class {
+ watch = vi.fn()
+ unwatch = vi.fn()
+ stop = vi.fn(async () => { built.order.push('verdicts stopped') })
+ constructor(readonly deps: any) { built.verdicts.push(this) }
+ },
+}))
+
+const blender = { id: 'blender', manifest: { name: 'Blender', viewer: { command: 'serve' } } }
+const agent = (over: Partial<RegisteredSession> = {}) =>
+ ({ agentId: 'a1', sessionId: 's1', engine: 'claude', dsh: 'blender', cwd: '/work/scene', ...over }) as RegisteredSession
+
+function setup(live: RegisteredSession | null = agent(), terminalAvailable = true) {
+ built.ledger.length = 0; built.viewers.length = 0; built.verdicts.length = 0; built.order.length = 0
+ const core = fakeCore({
+ agents: { byAgent: vi.fn(() => live ?? undefined), terminalAvailable: vi.fn(() => terminalAvailable), sync: vi.fn() },
+ })
+ const ports = emptyPorts()
+ startViewers(core, ports)
+ return { core, port: ports.viewers as ViewersPort, ledger: built.ledger[0], viewers: built.viewers[0], verdicts: built.verdicts[0] }
+}
+
+describe('the DSH viewers service', () => {
+ beforeEach(() => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.mocked(installedDsh).mockReturnValue(blender as never)
+ vi.mocked(catalogEntry).mockReturnValue(undefined)
+ })
+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })
+
+ it('stops the viewers an earlier daemon left running before it starts any of its own', () => {
+ const { ledger, viewers, verdicts } = setup()
+ expect(built.order).toEqual(['reap', 'viewers'])
+ expect(viewers.deps.ledger).toBe(ledger)
+ for (const log of [ledger.deps.log, viewers.deps.log, verdicts.deps.log]) log('[dsh] line')
+ expect(console.log).toHaveBeenCalledTimes(3)
+ })
+
+ describe('an agent\'s frame', () => {
+ it('names its harness and its viewer, with no viewer or verdict until they arrive', () => {
+ const { port } = setup()
+ expect(port.frameContext(agent())).toEqual({ id: 'blender', name: 'Blender', viewerUrl: null, viewerName: 'Blender view', verdict: null })
+ const [manifest, nameOf] = vi.mocked(dshViewerName).mock.calls[0]
+ expect(manifest).toBe(blender.manifest)
+ expect(nameOf('blender')).toBe('Blender')
+ vi.mocked(installedDsh).mockReturnValueOnce(undefined)
+ vi.mocked(catalogEntry).mockReturnValueOnce({ name: 'Shelf name' } as never)
+ expect(nameOf('other')).toBe('Shelf name')
+ })
+
+ it('carries the catalog\'s name, or none, for a harness this machine does not have', () => {
+ const { port } = setup()
+ vi.mocked(installedDsh).mockReturnValue(undefined)
+ vi.mocked(catalogEntry).mockReturnValueOnce({ name: 'Blender (store)' } as never)
+ expect(port.frameContext(agent())).toEqual({ id: 'blender', name: 'Blender (store)', viewerUrl: null, viewerName: null, verdict: null })
+ expect(port.frameContext(agent())).toMatchObject({ name: null })
+ })
+
+ it('has nothing to say for an agent without a harness', () => {
+ expect(setup().port.frameContext(agent({ dsh: undefined }))).toBeNull()
+ })
+ })
+
+ describe('news from a viewer or a verdict', () => {
+ it('a viewer URL is forwarded to the windows and pushed on the frame of an agent whose terminal is attached', () => {
+ const { core, port, viewers } = setup()
+ viewers.deps.onUrl('a1', 'http://127.0.0.1:7000')
+ expect(core.clients.viewerChanged).toHaveBeenCalledWith('a1')
+ expect(core.agents.sync).toHaveBeenCalledWith(agent())
+ expect(port.frameContext(agent())).toMatchObject({ viewerUrl: 'http://127.0.0.1:7000' })
+ })
+
+ it('a verdict points the viewer at its artifact, or at none', () => {
+ const { core, port, viewers, verdicts } = setup()
+ const verdict = { status: 'pass', artifact: 'render.png' }
+ verdicts.deps.onChange('a1', verdict)
+ expect(viewers.setVerdictArtifact).toHaveBeenCalledWith('a1', 'render.png')
+ expect(port.frameContext(agent())).toMatchObject({ verdict })
+ verdicts.deps.onChange('a1', null)
+ expect(viewers.setVerdictArtifact).toHaveBeenLastCalledWith('a1', null)
+ expect(core.agents.sync).toHaveBeenCalledTimes(2)
+ })
+
+ it('waits for the terminal before pushing a frame, which would otherwise read as "agent gone"', () => {
+ const detached = setup(agent(), false)
+ detached.viewers.deps.onUrl('a1', 'http://127.0.0.1:7000')
+ expect(detached.core.agents.sync).not.toHaveBeenCalled()
+ const gone = setup(null)
+ gone.verdicts.deps.onChange('a1', null)
+ expect(gone.core.agents.sync).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('attaching and detaching', () => {
+ it('watches the verdict file in the agent\'s folder and starts its viewer', () => {
+ const { port, viewers, verdicts } = setup()
+ port.attach(agent())
+ expect(verdicts.watch).toHaveBeenCalledWith('a1', join('/work/scene', '.harness/verdict.json'))
+ expect(viewers.start).toHaveBeenCalledWith('a1', blender, '/work/scene')
+ })
+
+ it('watches only the verdict of a harness with no viewer', () => {
+ const { port, viewers, verdicts } = setup()
+ vi.mocked(installedDsh).mockReturnValueOnce({ id: 'cad', manifest: { name: 'CAD' } } as never)
+ port.attach(agent({ dsh: 'cad' }))
+ expect(verdicts.watch).toHaveBeenCalled()
+ expect(viewers.start).not.toHaveBeenCalled()
+ })
+
+ it('says once per harness when it is not installed, and attaches nothing', () => {
+ const { port, verdicts } = setup()
+ vi.mocked(installedDsh).mockReturnValue(undefined)
+ port.attach(agent())
+ port.attach(agent({ agentId: 'a2' }))
+ expect(console.warn).toHaveBeenCalledTimes(1)
+ expect(console.warn).toHaveBeenCalledWith('[dsh] blender is not installed on this machine · agent a1 runs as plain claude (no viewer, no verdict)')
+ expect(verdicts.watch).not.toHaveBeenCalled()
+ })
+
+ it('attaches nothing for an agent with no harness or no folder', () => {
+ const { port, verdicts } = setup()
+ port.attach(agent({ dsh: undefined }))
+ port.attach(agent({ cwd: undefined }))
+ expect(installedDsh).not.toHaveBeenCalled()
+ expect(verdicts.watch).not.toHaveBeenCalled()
+ })
+
+ it('says why a viewer failed to start', async () => {
+ const { port, viewers } = setup()
+ viewers.start.mockRejectedValueOnce(new Error('port in use')).mockRejectedValueOnce('no python')
+ port.attach(agent())
+ port.attach(agent())
+ await vi.waitFor(() => expect(console.warn).toHaveBeenCalledTimes(2))
+ expect(console.warn).toHaveBeenCalledWith('[dsh] blender viewer failed to start · port in use')
+ expect(console.warn).toHaveBeenCalledWith('[dsh] blender viewer failed to start · no python')
+ })
+
+ it('detaching stops the watch and the viewer and forgets what the frame said', () => {
+ const { port, viewers, verdicts } = setup()
+ viewers.deps.onUrl('a1', 'http://127.0.0.1:7000')
+ port.detach('a1')
+ expect(verdicts.unwatch).toHaveBeenCalledWith('a1')
+ expect(viewers.stop).toHaveBeenCalledWith('a1')
+ expect(port.frameContext(agent())).toMatchObject({ viewerUrl: null })
+ })
+ })
+
+ it('forwards the windows to the viewer, and stops every viewer and then every watch', async () => {
+ const { port, viewers } = setup()
+ expect(port.forwardingUrl('a1')).toBe('http://127.0.0.1:9/a1')
+ expect(viewers.forwardingUrl).toHaveBeenCalledWith('a1')
+ await port.stop()
+ expect(built.order.slice(-2)).toEqual(['viewers stopped', 'verdicts stopped'])
+ })
+})
diff --git a/cli/src/services/viewers.ts b/cli/src/services/viewers.ts
new file mode 100644
index 000000000..108a35070
--- /dev/null
+++ b/cli/src/services/viewers.ts
@@ -0,0 +1,110 @@
+/**
+ * A DSH agent has two things beside its pane that the daemon owns for as long as the agent exists:
+ * its viewer server (a URL the desktop shows in a pane next to the terminal) and a watch on the
+ * verdict file its scripts write. Both are keyed on the agent, attached wherever an agent with a
+ * `dsh` comes into being (create, restore, discovery) and detached where it is forgotten.
+ *
+ * A service on the core boundary (docs/design/2026-10-03-harnessd.md, step 13): it reads the core
+ * only through `CoreApi`, and the core reaches it only through `ports.viewers`.
+ */
+import { join } from 'node:path'
+import type { CoreApi, CorePorts } from '../core/api.js'
+import { catalogEntry } from '../dsh/catalog.js'
+import { installedDsh } from '../dsh/installed.js'
+import { dshVerdictPath, dshViewerName } from '../dsh/manifest.js'
+import { DshVerdictWatcher, type DshVerdict } from '../dsh/verdict.js'
+import { DshViewerManager } from '../dsh/viewer.js'
+import { ViewerLedger } from '../dsh/viewerLedger.js'
+import type { AgentDshContext } from '../lib/agentFrame.js'
+import { sid } from '../lib/log.js'
+import type { RegisteredSession } from '../lib/registry.js'
+
+export function startViewers(core: CoreApi, ports: CorePorts): void {
+ const dshFrames = new Map<string, { viewerUrl: string | null; verdict: DshVerdict | null }>()
+ const dshFrameFor = (agentId: string): { viewerUrl: string | null; verdict: DshVerdict | null } => {
+ let state = dshFrames.get(agentId)
+ if (!state) { state = { viewerUrl: null, verdict: null }; dshFrames.set(agentId, state) }
+ return state
+ }
+ const dshFrameContext = (s: RegisteredSession): AgentDshContext | null => {
+ if (!s.dsh) return null
+ const state = dshFrames.get(s.agentId)
+ const installed = installedDsh(s.dsh)
+ return {
+ // The current id, so a face drawn by id survives a rename the agent predates.
+ id: installed?.id ?? s.dsh,
+ name: installed?.manifest.name ?? catalogEntry(s.dsh)?.name ?? null,
+ viewerUrl: state?.viewerUrl ?? null,
+ // The pane beside the terminal says what it is, so the harness's name is not printed twice.
+ viewerName: installed ? dshViewerName(installed.manifest, (id) => installedDsh(id)?.manifest.name ?? catalogEntry(id)?.name) : null,
+ verdict: state?.verdict ?? null,
+ }
+ }
+ // A companion's news (a viewer URL, a verdict) is pushed on the agent's frame — but only once
+ // the agent's terminal is attached. During a daemon start the viewer is often up before the
+ // pane is re-attached, and a frame with no terminal reads to the desktop as "agent gone": it
+ // closed the tiles of every harness agent on every restart (seen 2026-09-15, three times). The
+ // attach's own sync carries whatever arrived first.
+ const syncCompanion = (agentId: string): void => {
+ const session = core.agents.byAgent(agentId)
+ if (session && core.agents.terminalAvailable(agentId)) core.agents.sync(session)
+ }
+ // Viewers an earlier daemon started and never stopped (crash, force quit, SIGKILL) are still running
+ // and still polling; stop them BEFORE this daemon starts its own, or they accumulate a generation per
+ // restart. Only pids whose live start time matches what that daemon recorded are touched.
+ const viewerLedger = new ViewerLedger({ log: (line) => console.log(line) })
+ viewerLedger.reapOrphans()
+ const dshViewers = new DshViewerManager({
+ onUrl: (agentId, url) => {
+ dshFrameFor(agentId).viewerUrl = url
+ core.clients.viewerChanged(agentId)
+ syncCompanion(agentId)
+ },
+ log: (line) => console.log(line),
+ ledger: viewerLedger,
+ })
+ const dshVerdicts = new DshVerdictWatcher({
+ onChange: (agentId, verdict) => {
+ dshFrameFor(agentId).verdict = verdict
+ // The verdict's artifact is what the viewer should show, when it names one.
+ dshViewers.setVerdictArtifact(agentId, verdict?.artifact ?? null)
+ syncCompanion(agentId)
+ },
+ log: (line) => console.log(line),
+ })
+ const dshWarned = new Set<string>()
+ /** Idempotent: safe to call on every observation of the agent. */
+ const attachDsh = (s: RegisteredSession): void => {
+ if (!s.dsh || !s.cwd) return
+ const installed = installedDsh(s.dsh)
+ if (!installed) {
+ if (!dshWarned.has(s.dsh)) {
+ dshWarned.add(s.dsh)
+ console.warn(`[dsh] ${s.dsh} is not installed on this machine · agent ${sid(s.agentId)} runs as plain ${s.engine} (no viewer, no verdict)`)
+ }
+ return
+ }
+ dshVerdicts.watch(s.agentId, join(s.cwd, dshVerdictPath(installed.manifest)))
+ if (installed.manifest.viewer) {
+ void dshViewers.start(s.agentId, installed, s.cwd).catch((error) => {
+ console.warn(`[dsh] ${s.dsh} viewer failed to start · ${error instanceof Error ? error.message : error}`)
+ })
+ }
+ }
+ const detachDsh = (agentId: string): void => {
+ dshVerdicts.unwatch(agentId)
+ void dshViewers.stop(agentId)
+ dshFrames.delete(agentId)
+ }
+ ports.viewers = {
+ attach: attachDsh,
+ detach: detachDsh,
+ frameContext: dshFrameContext,
+ forwardingUrl: (agentId) => dshViewers.forwardingUrl(agentId),
+ // The next daemon starts its own viewers for the agents it restores; these must not hold the ports.
+ stop: async () => {
+ await dshViewers.stopAll()
+ await dshVerdicts.stop()
+ },
+ }
+}
diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.ts
new file mode 100644
index 000000000..f279864fb
--- /dev/null
+++ b/cli/src/testing/fakeCore.ts
@@ -0,0 +1,30 @@
+/**
+ * A `CoreApi` for a service's spec: every member a `vi.fn` with an empty answer, any of them replaced
+ * through `over`. Services read the core only through `CoreApi`, so this is all a spec needs to start
+ * one (docs/design/2026-10-03-harnessd.md, the core boundary).
+ */
+import { vi } from 'vitest'
+import type { CoreApi } from '../core/api.js'
+
+type Overrides = { [K in keyof CoreApi]?: CoreApi[K] extends object ? Partial<CoreApi[K]> : CoreApi[K] }
+
+export function fakeCore(over: Overrides = {}): CoreApi {
+ return {
+ dataDir: over.dataDir ?? '/data',
+ agents: {
+ all: vi.fn(() => []),
+ displayName: vi.fn(() => ''),
+ byAgent: vi.fn(() => undefined),
+ terminalAvailable: vi.fn(() => false),
+ sync: vi.fn(),
+ ...over.agents,
+ },
+ transcripts: { databaseHistory: vi.fn(() => undefined), ...over.transcripts },
+ external: {
+ sessions: { list: vi.fn(() => []), scan: vi.fn(async () => []) },
+ open: { known: vi.fn(() => new Map()), fresh: vi.fn(async () => new Map()) },
+ ...over.external,
+ },
+ clients: { viewerChanged: vi.fn(), ...over.clients },
+ }
+}
diff --git a/cli/vitest.core.config.ts b/cli/vitest.core.config.ts
index 63d21e92a..6d64816f6 100644
--- a/cli/vitest.core.config.ts
+++ b/cli/vitest.core.config.ts
@@ -1,17 +1,18 @@
import { defineConfig } from 'vitest/config'
import base from './vitest.config.js'
-/** The daemon's core modules (cli/src/core), held to 100% in every file as they move out of
- * runForeground (docs/design/2026-10-03-harnessd.md, the core boundary). */
+/** The daemon's core modules (cli/src/core) and the services on its boundary (cli/src/services), held
+ * to 100% in every file as they move out of runForeground (docs/design/2026-10-03-harnessd.md, the
+ * core boundary). */
export default defineConfig({
test: {
...base.test,
- include: ['src/core/**/*.spec.ts'],
+ include: ['src/core/**/*.spec.ts', 'src/services/**/*.spec.ts'],
coverage: {
enabled: true,
provider: 'v8',
- include: ['src/core/**/*.ts'],
- exclude: ['src/core/**/*.spec.ts'],
+ include: ['src/core/**/*.ts', 'src/services/**/*.ts'],
+ exclude: ['src/core/**/*.spec.ts', 'src/services/**/*.spec.ts'],
reporter: ['text', 'json-summary'],
reportsDirectory: 'coverage/core',
thresholds: { perFile: true, statements: 100, branches: 100, functions: 100, lines: 100 },
diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.md
index 6a60d99b8..aeae57621 100644
--- a/docs/design/2026-10-03-harnessd.md
+++ b/docs/design/2026-10-03-harnessd.md
@@ -398,8 +398,13 @@ Done so far:
last turn), the agent lifecycle (forget, bind, discovery, launch, new panes, adoption, create,
fork, the pane swap, retarget, restart, stop, purge, resume, close) and the engines' hooks (which
agent a hook belongs to, Cursor's Task hooks, installing every engine's hooks). Each file is held
- to 100% by `npm run test:core`, which CI runs; the unit and e2e suites pass at every step. Steps
- 13 and 14 remain.
+ to 100% by `npm run test:core`, which CI runs; the unit and e2e suites pass at every step.
+- **Services in process, the first two** (step 13, part 8): `cli/src/core/api.ts` holds the
+ boundary itself. `CoreApi` is what a service may ask of the core; `CorePorts` is what the core
+ asks of services, each port filled by its service when it starts and null while it is off, so
+ the core never waits on one. Session search (`services/search.ts`) and the DSH viewers
+ (`services/viewers.ts`) stand on it, held to 100% beside the core. The rest of step 13 and
+ step 14 remain.
Next, in order:
@@ -468,7 +473,8 @@ start-up lint stay as they are; each is checked by `tsc`, the unit suites and th
10. Agent discovery and binding.
11. The agent lifecycle.
12. Engine hooks.
-13. Services in process, each behind `start(core, ports)`.
+13. Services in process, each behind `start(core, ports)`: search and viewers first, then models,
+ workspaces, teams, the light host, relay and devices.
14. One `bindBackendSocket` for all 53 assignments.
Moving the request switch's case bodies into a file per owner comes after.