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.

fix: modify to edit the previous recap instead of generate a new one for each agent turn

b17245b09ab10135eadee316b20f
diff --git a/cli/README.md b/cli/README.md
index c325a90ac..6454f2b65 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -252,6 +252,7 @@ reported as such, not described as exercised.
| `ADAPTER_CLI_DIR` | `~/.harness/cli` | install dir holding the `cli.js`/`notify.mjs` the updater swaps |
| `LOG_FRAMES` | `false` | one log line per backend frame — type, audience and opaque ids, never a payload body. Every content-bearing frame is encrypted before it reaches the socket, so this is the only way to see what the daemon actually sent |
| `HARNESS_HOOK_DEADLINE_MS` | `4500` | wall-clock budget a hook gives itself before abandoning optional work. Raise it on a slow or heavily loaded machine, where the budget is spent on load rather than on the hook and the offline registry fallback silently does nothing. Clamped, never below the default |
+| `SUMMARY_MODE` | `model` | how the device recap is written. `model`: a one-shot of the session's own engine, fed the previous recap, the user's ask and the answer. `local`: no model — the answer's first sentence is excerpted, instantly, but each recap stands alone |
| `ORI_SUMMARY_MODEL` | `deepseek/deepseek-v4-flash` | recap model for agents routed through an OpenRouter gateway (`ori claude`), which have no vendor credential to spend |
| `ORI_VOICE_ROUTE_MODEL` | `deepseek/deepseek-v4-flash` | same, for the voice router's classification |
| `ORI_CREDENTIALS_PATH` | `~/.ori/credentials.json` | where `ori login` stores its key; read only when neither the daemon env nor the agent's own process supplies one |
@@ -269,10 +270,17 @@ periodic heartbeat).
The per-turn **summary/recap** matches the hosted runtime: on turn end, *only while a device is
connected*, the adapter runs a disposable one-shot from the session's own CLI engine
(`SUMMARY_MODEL`, `CODEX_SUMMARY_MODEL`, or `CURSOR_SUMMARY_MODEL`) → `recap ≤15 words\n\n
-body ≤200`, shows a `Summarizing…` indicator while it runs, persists it per session
+body ≤120 words`, shows a `Summarizing…` indicator while it runs, persists it per session
(`${ADAPTER_DATA_DIR}/summaries.json`), and returns it on `project_recent` at device boot. A newer
turn aborts a stale recap.
+The one-shot is `recap = llm(instruct, previous recap, the user's ask, the answer)`. The previous
+recap is the session's last stored summary, quoted as *continuity only* — it lets a turn whose
+answer is "done, same change in the other file" recap as what was done instead of a fragment — and
+the prompt forbids repeating it or reporting it as this turn's news. `SUMMARY_MODE=local` drops the
+model: the answer's first prose sentence is excerpted in the same tick (no `Summarizing…`), which is
+the right trade when the dial sits next to a window already showing the full text.
+
## Pair an Autonomous device directly
Harness discovers the OS's existing `_autonomous._tcp` advertisement. Select a discovered device
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 7c90fdc4f..2d5ab1d2c 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -109,11 +109,12 @@ import { RemoteRelayPool } from './lib/remoteRelay.js'
import { TERMINAL_BINARY_VERSION } from './lib/terminalBinary.js'
import { foldTranscript, lastTurnTextFromRawLines, lineToEvents, newTurnState, type LiveEvent, type TurnState } from './lib/normalize.js'
import { AskQuestionController, pollsQuestions, QuestionWatcher } from './lib/askQuestion.js'
-import { CommanderMirror } from './lib/commander.js'
+import { CommanderMirror, type CommanderMirrorOpts } from './lib/commander.js'
import {
setSummaryPoolDeviceConnected,
shutdownSummaryPool,
deriveTurnSummary,
+ summarizeTurnText,
syncSummaryPoolSessions,
} from './lib/summarize.js'
import type { CableAgent } from './cable/cableSession.js'
@@ -1876,6 +1877,27 @@ async function runForeground(session: AuthSession): Promise<void> {
})
+ // SUMMARY_MODE picks the recap writer.
+ // model (default) — recap = llm(instruct, previous recap, the user's ask, the answer): a disposable
+ // one-shot of the session's own engine. The previous recap is what lets "same fix, other file"
+ // recap as what was done rather than as a fragment. Costs the one-shot's latency on every turn.
+ // local — NO MODEL IN THE LOOP. The dial is cabled to the Mac whose window already shows this text
+ // in full, so the recap is a glance and the detail is one turn of the head away; the one-shot cost
+ // ~9s of the user's turn to say something they were already looking at. Instant, but every recap
+ // stands alone.
+ const summarizer: Pick<CommanderMirrorOpts, 'summarize' | 'summarizeIsLocal'> = env.SUMMARY_MODE === 'local'
+ ? { summarize: async (text) => deriveTurnSummary(text), summarizeIsLocal: true }
+ : {
+ summarize: async (text, signal, userMessage, sessionId, previousRecap) => {
+ const session = sessionId ? registry.bySession(sessionId) : undefined
+ // Gateway agents recap through OpenRouter directly (no vendor credential to spend). The probe is
+ // cached per live process, so this resolves without touching the process table again.
+ const gateway = session?.gateway === 'ori' && session.processIdentity
+ ? await probeGatewayRuntime(session.processIdentity)
+ : undefined
+ return summarizeTurnText(text, signal, userMessage, session?.engine ?? 'claude', gateway, previousRecap)
+ },
+ }
const mirror = new CommanderMirror({
send: (frame) => backend.sendCommander(frame),
sendWeb: (frame) => backend.send(frame), // turn_summary_pending / turn_summary → web indicator
@@ -1883,11 +1905,7 @@ async function runForeground(session: AuthSession): Promise<void> {
// Live cards stream to whatever is actually rendering. The dial has one screen and it is always the
// one in front of the user, so a cable session counts as active by construction.
active: () => backend.hasActiveCommander() || cableWatchingLocal(),
- // NO MODEL IN THE LOOP. The dial is cabled to the Mac whose window already shows this text in
- // full, so the recap is a glance and the detail is one turn of the head away. A one-shot recap
- // cost ~9s of the user's turn to say something they were already looking at.
- summarize: async (text) => deriveTurnSummary(text),
- summarizeIsLocal: true,
+ ...summarizer,
nameFor: (sessionId) => { const s = registry.bySession(sessionId); return s ? projectDisplayName(s) : undefined },
agentIdFor: (sessionId) => registry.bySession(sessionId)?.agentId,
readLastTurn: async (sessionId) => {
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index 15c1af34a..011e97b7b 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -326,6 +326,11 @@ const envSchema = z.object({
AMP_SUMMARY_MODE: z.string().default('medium'),
// Shared recap reasoning level for Claude and Codex. Cursor effort is part of its model identifier.
SUMMARY_EFFORT: z.enum(['low', 'medium', 'high']).default('low'),
+ // How the device recap is written. `model`: a disposable one-shot of the session's own engine, fed the
+ // PREVIOUS recap, the user's ask and the answer — so a turn that says "same fix, other file" recaps as
+ // what it did, not as a fragment; costs the one-shot's latency per turn. `local`: no model in the loop,
+ // the answer's first sentence is excerpted — instant, but every recap stands alone.
+ SUMMARY_MODE: z.enum(['model', 'local']).default('model'),
// Model for the voice router one-shot classifier (Overview voice → pick the agent). Small/fast by default.
VOICE_ROUTE_MODEL: z.string().default('haiku'),
// Test override: run the recap even with no device connected (mirrors node isRecapForced()).
diff --git a/cli/src/lib/commander.spec.ts b/cli/src/lib/commander.spec.ts
index 3bbdf9f79..21246e613 100644
--- a/cli/src/lib/commander.spec.ts
+++ b/cli/src/lib/commander.spec.ts
@@ -263,6 +263,40 @@ describe('CommanderMirror recap events', () => {
expect(deviceFrames.filter((f) => f.payload.kind === 'summary')).toHaveLength(1)
})
+ it('hands the summariser the previous turn\'s recap, and nothing on the first turn', async () => {
+ // recap = llm(instruct, previous_recap, ask, answer). The previous recap is read from the store
+ // BEFORE this turn's lands there — otherwise "previous" is the turn being summarised.
+ const previous: Array<string | undefined> = []
+ let turn = 0
+ const mirror = new CommanderMirror({
+ send: () => {},
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async (_text, _signal, _ask, _sessionId, previousRecap) => {
+ previous.push(previousRecap)
+ turn++
+ return `Recap ${turn}\n\nBody ${turn}`
+ },
+ dataDir,
+ })
+
+ const oneTurn = (ask: string, answer: string) => mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: ask } },
+ { type: 'text_delta', payload: { content: answer } },
+ { type: 'turn_ended', payload: {} },
+ ] as LiveEvent[], 'session-prev')
+
+ oneTurn('fix the retry path', 'Fixed the retry path in client.ts.')
+ await vi.runAllTimersAsync()
+ await Promise.resolve()
+ oneTurn('same fix in the other file', 'Done, applied the same change to server.ts.')
+ await vi.runAllTimersAsync()
+ await Promise.resolve()
+
+ expect(previous).toEqual([undefined, 'Recap 1\n\nBody 1'])
+ expect(mirror.recent('session-prev', 3).map((r) => r.recap)).toEqual(['Recap 2', 'Recap 1'])
+ })
+
it('renders normalized Codex Task and child tools through the same device cards as Claude', () => {
const deviceFrames: CommanderFrame[] = []
const mirror = new CommanderMirror({
diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.ts
index b45590f3d..cd16bfa0f 100644
--- a/cli/src/lib/commander.ts
+++ b/cli/src/lib/commander.ts
@@ -8,7 +8,8 @@
* tool_start Task/Agent → + {kind:'agents', agents:[{text,color}]} (live sub-agent list)
* subagent_finished → + {kind:'agents', …} with that row ticked off
* turn_ended (device on) → {kind:'processing', text:'Summarizing…'} then, once the LLM one-shot
- * returns, {kind:'summary', text:body, recap} (persisted per session)
+ * returns, {kind:'summary', text:body, recap} (persisted per session,
+ * and handed to the NEXT turn's summariser as its previous recap)
* turn_ended (no device) → nothing (device-gated; the summary map is left untouched)
* turn_ended (empty text) → {kind:'done'} (clear busy)
*
@@ -38,7 +39,16 @@ export interface CommanderMirrorOpts {
* Gates the live turn-card STREAM; the turn-done `summary` card ignores it so a background machine still
* badges. Omitted → defaults to hasDevice (single-machine firmware: attached == active, streams as before). */
active?: () => boolean
- summarize: (text: string, signal?: AbortSignal, userMessage?: string, sessionId?: string) => Promise<string | null>
+ /** `previousRecap` is the stored `recap\n\nbody` of this session's last summarised turn, when there is
+ * one — the continuity a recap of THIS turn alone cannot carry ("same fix, other file" is a fragment
+ * without it). Undefined on a session's first turn. */
+ summarize: (
+ text: string,
+ signal?: AbortSignal,
+ userMessage?: string,
+ sessionId?: string,
+ previousRecap?: string,
+ ) => Promise<string | null>
/** True when `summarize` is a local derivation rather than a model call — see startSummary. */
summarizeIsLocal?: boolean
/** Agent display name for a sessionId — rides the summary's outer frame so a BACKGROUND machine's device
@@ -613,7 +623,9 @@ export class CommanderMirror {
}
const ask = userMessage.replace(/\s+/g, ' ').trim().slice(0, 60)
- this.trace(sessionId, `${sid} summarizing · source=${source} · textLen=${text.length} · device=${device}${this.opts.recapForce ? ' · recapForce' : ''}${ask ? ` · ask="${ask}"` : ''}`)
+ // Read BEFORE the new summary is stored below, or the "previous" recap is this turn's own.
+ const previousRecap = this.summaries.get(sessionId)
+ this.trace(sessionId, `${sid} summarizing · source=${source} · textLen=${text.length} · device=${device}${this.opts.recapForce ? ' · recapForce' : ''}${ask ? ` · ask="${ask}"` : ''} · prev=${previousRecap ? 'yes' : 'none'}`)
// Device: busy "Summarizing…" card. Web: the "Summarizing for device…" indicator (mirrors the
// node's handleBrainSummaryEvent — the web ignores the summary text, only toggles the flag).
//
@@ -626,7 +638,7 @@ export class CommanderMirror {
}
this.opts
- .summarize(text, ac.signal, userMessage, sessionId)
+ .summarize(text, ac.signal, userMessage, sessionId, previousRecap)
.then((summary) => {
const ms = Date.now() - t0
if (ac.signal.aborted) { this.trace(sessionId, `${sid} superseded after ${ms}ms (newer turn) — dropping result`); return }
diff --git a/cli/src/lib/summarize.spec.ts b/cli/src/lib/summarize.spec.ts
index 9df327911..3dddce550 100644
--- a/cli/src/lib/summarize.spec.ts
+++ b/cli/src/lib/summarize.spec.ts
@@ -103,6 +103,48 @@ describe('gateway recap', () => {
})
})
+describe('previous recap', () => {
+ it('quotes the previous turn\'s recap as continuity context, fenced off from the content', async () => {
+ mocks.runClaude.mockResolvedValue({ text: 'Applied the same change to server.ts.\n\nDone.', sessionId: null })
+
+ await summarizeTurnText(
+ 'Done, applied the same change to server.ts.',
+ undefined,
+ 'same fix in the other file',
+ 'claude',
+ undefined,
+ 'Fixed the retry path in client.ts.\n\nThe retry now backs off\nand caps at five attempts.',
+ )
+
+ const prompt = mocks.runClaude.mock.calls[0][0].prompt as string
+ // Flattened — the stored body's line breaks must not read as structure to preserve.
+ expect(prompt).toContain('«Fixed the retry path in client.ts. The retry now backs off and caps at five attempts.»')
+ expect(prompt).toContain('PREVIOUS turn')
+ // Context, not content: the block sits BEFORE the turn's own message, and the message is unchanged.
+ expect(prompt.indexOf('PREVIOUS turn')).toBeLessThan(prompt.indexOf('---\nDone, applied the same change'))
+ })
+
+ it('says nothing about a previous turn when there is none', async () => {
+ mocks.runClaude.mockResolvedValue({ text: 'Fixed the retry path.\n\nDone.', sessionId: null })
+
+ await summarizeTurnText('Fixed the retry path in client.ts.', undefined, 'fix the retry path', 'claude')
+
+ const prompt = mocks.runClaude.mock.calls[0][0].prompt as string
+ expect(prompt).not.toContain('PREVIOUS turn')
+ })
+
+ it('does not let the previous recap\'s language trigger the drift retry', async () => {
+ // The language check compares the OUTPUT against the ask + answer only. A previous recap in another
+ // script is context the model was told to ignore for language, so it must not count as a mismatch.
+ mocks.runClaude.mockResolvedValue({ text: 'Deploy finished.\n\nThe service is healthy.', sessionId: null })
+
+ await summarizeTurnText('Deploy finished; service healthy.', undefined, 'deploy status?', 'claude', undefined,
+ 'Đã sửa đường retry.\n\nRetry giờ lùi dần và dừng ở năm lần.')
+
+ expect(mocks.runClaude).toHaveBeenCalledTimes(1)
+ })
+})
+
describe('Cursor recap', () => {
it('uses a Cursor one-shot with the configured Cursor model', async () => {
mocks.runCursor.mockResolvedValue({
diff --git a/cli/src/lib/summarize.ts b/cli/src/lib/summarize.ts
index ffe09abd3..e53842b14 100644
--- a/cli/src/lib/summarize.ts
+++ b/cli/src/lib/summarize.ts
@@ -40,6 +40,9 @@ import {
const SUMMARY_MAX_WORDS = 120
const RECAP_MAX_WORDS = 15 // ~12-15 words; ONE complete sentence (20 overflowed the device tile).
const MAX_INPUT_CHARS = 50_000
+// The previous turn's `recap\n\nbody` is ≤ 135 words by construction; this is a guard against a
+// stored summary from an older build, not a budget anyone is expected to hit.
+const PREVIOUS_RECAP_MAX_CHARS = 1_000
const SUMMARY_SCRATCH = join(env.ADAPTER_DATA_DIR, 'summary-scratch')
function ensureSummaryScratch(): string {
@@ -304,17 +307,38 @@ function firstProseLine(stripped: string): string {
/** Longer than this and a line is saying something, not naming a section. */
const LABEL_MAX_CHARS = 24
+/**
+ * `recap = llm(instruct, previousRecap, userMessage, text)`.
+ *
+ * `previousRecap` is the stored summary of this agent's LAST turn. It is context, not content: it lets
+ * a turn whose answer is "Done — same change in the other two files" recap as what was done, instead of
+ * a fragment that names nothing. The prompt fences it off so it can only resolve references, never be
+ * reported as this turn's news. Absent on a session's first turn.
+ */
export async function summarizeTurnText(
text: string,
signal?: AbortSignal,
userMessage?: string,
engine: AgentEngine = 'claude',
gateway?: GatewayRuntime,
+ previousRecap?: string,
): Promise<string | null> {
let last = (text || '').trim()
if (!last) return null
if (last.length > MAX_INPUT_CHARS) last = last.slice(-MAX_INPUT_CHARS)
+ // Continuity only. Flattened — the stored body carries line breaks the model would otherwise
+ // read as structure to preserve — and capped so an odd stored value cannot crowd out the turn.
+ const prev = (previousRecap || '').replace(/\s+/g, ' ').trim().slice(0, PREVIOUS_RECAP_MAX_CHARS)
+ const prevBlock = prev
+ ? `For continuity ONLY, the recap of this assistant's PREVIOUS turn was: «${prev}». Use it to ` +
+ `resolve references in this turn ("it", "that one", "the same fix", "as before", "the other file") ` +
+ `and to keep names and terms consistent — nothing more. Your recap describes THIS turn's message ` +
+ `alone: do NOT repeat, restate or merge in the previous recap, and do NOT report anything from it ` +
+ `as if it happened now. If this turn's message is complete on its own, ignore the previous recap ` +
+ `entirely.\n\n`
+ : ''
+
// If we know the user's request for this turn, tell the recap to LEAD with the direct answer to it
// (asked a price → give the price), not a generic characterization of the topic — the answer text
// still comes from the assistant's message. Whitespace-flattened + capped so a long paste can't
@@ -338,7 +362,9 @@ export async function summarizeTurnText(
`turn and the assistant message between the --- markers below. If both are in English, output English. ` +
`If they use another language, output that language. If they mix languages, preserve that mix naturally. ` +
`Never switch to a language that does not appear in the user's request or the assistant message. Ignore ` +
- `previous conversation, account locale, environment locale, and the language of these instructions.\n\n` +
+ `previous conversation (including the previous recap, if one is quoted below), account locale, ` +
+ `environment locale, and the language of these instructions.\n\n` +
+ prevBlock +
askBlock +
`Between the --- markers below is a message the assistant already sent to the user. Re-voice its ` +
`CONTENT back to the user, in the FIRST PERSON as that same assistant (its own "I"). You are ONLY ` +
@@ -423,8 +449,8 @@ export async function summarizeTurnText(
const effort = engine === 'cursor' ? 'model-defined' : env.SUMMARY_EFFORT
console.log(
gatewayKey
- ? `[recap] openrouter ${engine} · model=${model} · inputChars=${last.length}${ask ? ' · withAsk' : ''}`
- : `[recap] one-shot ${engine} · model=${model} · effort=${effort} · inputChars=${last.length}${ask ? ' · withAsk' : ''}`,
+ ? `[recap] openrouter ${engine} · model=${model} · inputChars=${last.length}${ask ? ' · withAsk' : ''}${prev ? ' · withPrev' : ''}`
+ : `[recap] one-shot ${engine} · model=${model} · effort=${effort} · inputChars=${last.length}${ask ? ' · withAsk' : ''}${prev ? ' · withPrev' : ''}`,
)
const runEngine = engine === 'claude'
? runClaudeOneShot