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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
refactor: use programmatically derived answer excerpt for turn summary body instead of model-written text
0xken15b45c1563feb9
diff --git a/cli/README.md b/cli/README.mdindex 6454f2b65..267dde6f3 100644--- a/cli/README.md+++ b/cli/README.md@@ -252,7 +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 |+| `SUMMARY_MODE` | `model` | who writes the recap HEADLINE. `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. The `text` under the headline is the answer's own excerpt in both modes || `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,17 +269,20 @@ periodic heartbeat).The per-turn **summary/recap** matches the hosted runtime: on turn end, *only while a device isconnected*, 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 ≤120 words`, shows a `Summarizing…` indicator while it runs, persists it per session+(`SUMMARY_MODEL`, `CODEX_SUMMARY_MODEL`, or `CURSOR_SUMMARY_MODEL`) → a one-line `recap ≤15 words`,+shows a `Summarizing…` indicator while it runs, persists `recap\n\ntext` per session(`${ADAPTER_DATA_DIR}/summaries.json`), and returns it on `project_recent` at device boot. A newer-turn aborts a stale recap.+turn aborts a stale recap. The `text` under the headline is NOT model-written: it is the answer+itself, flattened to one line and clipped to 250 characters (`deriveTurnBody`) — the dial shows only+the headline, the device protocol defines `text` as an excerpt, and a paraphrase nobody reads cost+output tokens on every turn.The one-shot is `recap = llm(instruct, previous recap, the user's ask, the answer)`. The previousrecap is the session's last stored summary, quoted as *continuity only* — it lets a turn whoseanswer is "done, same change in the other file" recap as what was done instead of a fragment — andthe 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.+model: the answer's first prose sentence becomes the headline 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 directlydiff --git a/cli/src/lib/summarize.spec.ts b/cli/src/lib/summarize.spec.tsindex 3dddce550..f8afd703b 100644--- a/cli/src/lib/summarize.spec.ts+++ b/cli/src/lib/summarize.spec.ts@@ -42,7 +42,7 @@ vi.mock('./oneshot.js', () => ({shutdownOneShotPool: vi.fn(),}))-import { summarizeTurnText, syncSummaryPoolSessions } from './summarize.js'+import { deriveTurnBody, summarizeTurnText, syncSummaryPoolSessions } from './summarize.js'beforeEach(() => {mocks.runClaude.mockReset()@@ -63,7 +63,7 @@ describe('gateway recap', () => {// The point of the whole path: an `ori claude` user may hold no Anthropic credential at all, so the// engine one-shot would spawn a CLI that cannot authenticate and the recap would never arrive.mocks.resolveKey.mockResolvedValue('sk-or-v1-process')- mocks.complete.mockResolvedValue('Recap works through the gateway.\n\nThe turn recapped without a vendor login.')+ mocks.complete.mockResolvedValue('Recap works through the gateway.')await expect(summarizeTurnText('Wired the gateway recap path.',@@ -71,22 +71,24 @@ describe('gateway recap', () => {'Does the gateway recap work?','claude',gateway,- )).resolves.toBe('Recap works through the gateway.\n\nThe turn recapped without a vendor login.')+ )).resolves.toBe('Recap works through the gateway.\n\nWired the gateway recap path.')expect(mocks.complete).toHaveBeenCalledTimes(1)expect(mocks.complete.mock.calls[0][0]).toMatchObject({model: 'deepseek/deepseek-v4-flash',apiKey: 'sk-or-v1-process',+ // A headline in any script, not a paragraph.+ maxTokens: 160,})expect(mocks.runClaude).not.toHaveBeenCalled()})it('falls back to the engine one-shot when no key resolves', async () => {mocks.resolveKey.mockResolvedValue(null)- mocks.runClaude.mockResolvedValue({ text: 'Engine recap.\n\nThe engine path still runs.', sessionId: null })+ mocks.runClaude.mockResolvedValue({ text: 'Engine recap.', sessionId: null })await expect(summarizeTurnText('Did the work.', undefined, 'Status?', 'claude', gateway))- .resolves.toBe('Engine recap.\n\nThe engine path still runs.')+ .resolves.toBe('Engine recap.\n\nDid the work.')expect(mocks.complete).not.toHaveBeenCalled()expect(mocks.runClaude).toHaveBeenCalledTimes(1)@@ -148,7 +150,7 @@ describe('previous recap', () => {describe('Cursor recap', () => {it('uses a Cursor one-shot with the configured Cursor model', async () => {mocks.runCursor.mockResolvedValue({- text: 'Cursor recap works.\n\nThe Cursor turn now produces a persisted device recap.',+ text: 'Cursor recap works.',sessionId: 'cursor-recap-session',})@@ -158,7 +160,7 @@ describe('Cursor recap', () => {'Does Cursor recap work?','cursor',)).resolves.toBe(- 'Cursor recap works.\n\nThe Cursor turn now produces a persisted device recap.',+ 'Cursor recap works.\n\nImplemented Cursor recap support.',)expect(mocks.runCursor).toHaveBeenCalledOnce()@@ -194,7 +196,7 @@ describe('Cursor recap', () => {describe('Grok recap', () => {it('uses an isolated direct Grok one-shot with the configured model', async () => {mocks.runGrok.mockResolvedValue({- text: 'Grok recap works.\n\nThe Grok turn now produces a persisted device recap.',+ text: 'Grok recap works.',sessionId: 'grok-recap-session',})@@ -203,7 +205,7 @@ describe('Grok recap', () => {undefined,'Does Grok recap work?','grok',- )).resolves.toBe('Grok recap works.\n\nThe Grok turn now produces a persisted device recap.')+ )).resolves.toBe('Grok recap works.\n\nImplemented Grok recap support.')expect(mocks.runGrok).toHaveBeenCalledOnce()expect(mocks.runGrok.mock.calls[0][0]).toMatchObject({ model: 'grok-4.5', effort: 'low' })@@ -273,25 +275,58 @@ describe('language fidelity', () => {})})-describe('summary completeness', () => {- it('strips any ellipsis and ends the summary on a finished sentence', async () => {- const longBody = Array.from({ length: 60 }, (_, i) => `detail number ${i} here.`).join(' ')- mocks.runClaude.mockResolvedValue({- text: `Work is done.\n\n${longBody} and then it trails off…`,- sessionId: 's1',- })+describe('the body under the headline', () => {+ // The dial shows the headline and nothing else; the device protocol defines `text` as the answer+ // flattened and clipped. So the model writes ONE line, and the body is excerpted from the answer+ // itself — never a paraphrase that costs tokens on every turn and is shown nowhere.+ const answer = '## Result\n\n- **Deploy**: finished\n- Service is healthy and serving traffic.\n\nNothing else changed.'++ it('is the answer\'s own excerpt, never the model\'s', async () => {+ mocks.runClaude.mockResolvedValue({ text: 'Deploy finished, service healthy.\n\nSome invented paraphrase.', sessionId: 's1' })+ const out = await summarizeTurnText(answer, undefined, 'Done?', 'claude')+ const [recap, body] = out!.split('\n\n')+ expect(recap).toBe('Deploy finished, service healthy.')+ expect(body).toBe(deriveTurnBody(answer))+ expect(body).toBe('Result Deploy: finished Service is healthy and serving traffic. Nothing else changed.')+ expect(out).not.toContain('invented paraphrase')+ })- const out = await summarizeTurnText('A long English message about the work.', undefined, 'Status?', 'claude')- const body = out!.split('\n\n')[1]+ it('takes the first non-empty line as the headline when the model still writes more', async () => {+ mocks.runClaude.mockResolvedValue({ text: '\n\nAll good.\nAnd a second line.\n\nA third paragraph…', sessionId: 's1' })+ const out = await summarizeTurnText(answer, undefined, 'Done?', 'claude')+ expect(out!.split('\n\n')[0]).toBe('All good.')+ })- expect(body).not.toContain('…')- expect(body).not.toMatch(/\.\.\./)- expect(body).toMatch(/[.!?]$/)+ it('excerpts the whole answer, not the tail the prompt was fed', async () => {+ const opening = 'The opening sentence is what the excerpt should show.'+ const huge = `${opening} ${'filler '.repeat(20_000)}the very end.`+ mocks.runClaude.mockResolvedValue({ text: 'Long answer done.', sessionId: 's1' })+ const out = await summarizeTurnText(huge, undefined, 'Done?', 'claude')+ expect(out!.split('\n\n')[1].startsWith(opening)).toBe(true)+ // The prompt itself still carries only the tail.+ expect((mocks.runClaude.mock.calls[0][0].prompt as string)).not.toContain(opening)})- it('keeps a summary that is already within budget untouched', async () => {- mocks.runClaude.mockResolvedValue({ text: 'All good.\n\nThe deploy finished and the service is healthy.', sessionId: 's1' })+ it('judges language drift on the headline alone', async () => {+ mocks.runClaude.mockResolvedValue({ text: 'All done.\n\nĐoạn thứ hai lạc ngôn ngữ hoàn toàn nhé.', sessionId: 's1' })const out = await summarizeTurnText('The deploy finished and the service is healthy.', undefined, 'Done?', 'claude')- expect(out!.split('\n\n')[1]).toBe('The deploy finished and the service is healthy.')+ expect(out!.split('\n\n')[0]).toBe('All done.')+ expect(mocks.runClaude).toHaveBeenCalledTimes(1)+ })++ it('never lets an ellipsis into the headline', async () => {+ mocks.runClaude.mockResolvedValue({ text: 'Work is done and then it trails off…', sessionId: 's1' })+ const out = await summarizeTurnText(answer, undefined, 'Status?', 'claude')+ expect(out!.split('\n\n')[0]).not.toContain('…')+ })++ it('asks the model for the headline only', async () => {+ mocks.runClaude.mockResolvedValue({ text: 'Done.', sessionId: 's1' })+ await summarizeTurnText(answer, undefined, 'Done?', 'claude')+ const prompt = mocks.runClaude.mock.calls[0][0].prompt as string+ expect(prompt).toContain('Output ONLY the one line')+ expect(prompt).not.toContain('Part 2')+ expect(prompt).not.toContain('LAY PART 2')+ expect(prompt).not.toContain('two parts')})})diff --git a/cli/src/lib/summarize.ts b/cli/src/lib/summarize.tsindex e53842b14..ac8de51fa 100644--- a/cli/src/lib/summarize.ts+++ b/cli/src/lib/summarize.ts@@ -1,9 +1,13 @@/**- * Device turn-recap summarizer — self-contained port of the brain's `summarizeTurnText`- * Summarizes one turn's assistant text into the- * device's `recap\n\nsummary` shape (recap ≤15 words, summary ≤100) via a disposable one-shot- * from the same CLI engine as the interactive session. Honors an AbortSignal so a newer turn can- * supersede a stale recap.+ * Device turn-recap summarizer — self-contained port of the brain's `summarizeTurnText`.+ *+ * Produces the device's `recap\n\ntext` shape for one turn. Only the RECAP — a one-line headline,+ * ≤15 words — comes from a model (a disposable one-shot of the same CLI engine as the interactive+ * session). The `text` under it is the answer itself, flattened and clipped locally+ * (`deriveTurnBody`), the same excerpt `SUMMARY_MODE=local` shows: nothing on the dial reads a+ * model-written body any more (the tile shows the headline, the reader is off), the device protocol+ * defines `text` as an excerpt, and a paraphrase nobody sees cost output tokens on every turn.+ * Honors an AbortSignal so a newer turn can supersede a stale recap.*/import { existsSync, mkdirSync } from 'fs'@@ -37,11 +41,10 @@ import {type OneShotOptions,} from './oneshot.js'-const SUMMARY_MAX_WORDS = 120const 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.+// The previous turn's `recap\n\ntext` is a ≤15-word headline over a ≤250-char excerpt 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_000const SUMMARY_SCRATCH = join(env.ADAPTER_DATA_DIR, 'summary-scratch')@@ -152,28 +155,6 @@ function languageDrifted(src: string, out: string): boolean {return false}-/**- * Cap the SUMMARY the way the recap is capped: never an ellipsis, always a finished sentence. Prefers to- * cut at the last sentence terminator inside the budget — which works for any language that ends a sentence- * with one — and only falls back to the clause/connector trim when there is none.- */-function capComplete(text: string, max: number): string {- let t = (text || '').replace(/…|\.{2,}/g, ' ').replace(/\s+/g, ' ').trim()- const words = t.split(/\s+/)- if (words.length > max) {- const head = words.slice(0, max).join(' ')- const m = [...head.matchAll(/[.!?。!?]/gu)].pop()- t = m && m.index !== undefined && m.index > head.length * 0.4- ? head.slice(0, m.index + 1)- : head- }- if (!/[.!?。!?]$/u.test(t)) {- let prev: string- do { prev = t; t = t.replace(DANGLING_TAIL, '').replace(/[\s,;:–—-]+$/, '').trim() } while (t !== prev)- }- return t-}-// Trailing connectors (VN + EN) a recap must never END on — cutting here would leave it dangling// ("…2-1, nhờ"). Stripped from the tail if a hard cut lands on one. Prefix with a separator rather// than \b: JS \b is ASCII-only, so it fails on a Vietnamese word ending in a diacritic (e.g. "nhờ").@@ -244,7 +225,19 @@ export function deriveTurnSummary(text: string): string | null {const body = stripped.replace(/\s+/g, ' ').trim()if (!body) return nullconst recap = clip(firstProseLine(stripped) || body, RECAP_MAX_CHARS)- return `${recap}\n\n${clip(body, BODY_MAX_CHARS)}`+ return `${recap}\n\n${deriveTurnBody(text)}`+}++/** The `text` under a recap: the answer flattened to one line and clipped — a glance, never a+ * paraphrase. Shared by both recap writers so the body reads the same whoever wrote the headline. */+export function deriveTurnBody(text: string): string {+ return clip(stripMarkdown(text).replace(/\s+/g, ' ').trim(), BODY_MAX_CHARS)+}++/** The headline in a one-shot's output: its first non-empty line. A model that still writes a second+ * paragraph is tolerated, not concatenated — and not judged for language drift either. */+function headlineOf(output: string): string {+ return output.split('\n').map((line) => line.trim()).find(Boolean) ?? ''}/** Cut to `max` characters on a word boundary, marking the cut. Never mid-word if it can be helped. */@@ -370,9 +363,9 @@ export async function summarizeTurnText(`CONTENT back to the user, in the FIRST PERSON as that same assistant (its own "I"). You are ONLY ` +`restating what the message says — you are NOT performing any task and NOT describing this ` +`summarizing job. NEVER write a meta or intent sentence such as "I need to…", "I will ` +- `summarize/convert/translate…", "let me…", or "the message is about…". Output ONLY these two parts ` +- `separated by a blank line, with no headings, labels or preamble:\n` +- `Part 1 (recap) — a NEWSPAPER HEADLINE for this turn: ONE punchy, self-contained line of at most ` ++ `summarize/convert/translate…", "let me…", or "the message is about…". Output ONLY the one line ` ++ `described below — nothing before it, nothing after it, no headings, labels or preamble:\n` ++ `A NEWSPAPER HEADLINE for this turn: ONE punchy, self-contained line of at most ` +`${RECAP_MAX_WORDS} words. State the SINGLE most important thing the user needs from this turn — the ` +`direct answer, decision, result or recommendation to their request (what was said or done, NOT a plan ` +`of what you will do next, NOT a description of the topic) — and FRONT-LOAD it so the first few words ` +@@ -383,29 +376,11 @@ export async function summarizeTurnText(`never end on a connector/preposition/unfinished clause, and NEVER use "…", "..." or any ellipsis or ` +`trailing dots. If you would run long, TIGHTEN the wording into a shorter headline — do not truncate. ` +`Do NOT enumerate long lists — give the gist (use counts like "4 forwards" instead of naming everyone). ` +- `PLAIN TEXT ONLY: no emoji, markdown, tables, bullets or URLs.\n` +- `Part 2 (after a blank line) — a fuller summary: present tense, condensed to the key ` +- `points, markedly shorter than the original; scale to the source (a short message → a ` +- `sentence or two, a long/detailed one → a short recap), never a full restatement, at most ` +- `${SUMMARY_MAX_WORDS} words. Here you MAY include the important specifics/lists that the ` +- `recap omitted. Like the recap it MUST read as finished: end on a COMPLETE sentence, never mid-idea or ` +- `on a dangling connector, and NEVER use "…", "..." or any ellipsis or trailing dots. If you would run ` +- `long, drop the least important detail — do not truncate.\n` +- `LAY PART 2 OUT SO IT CAN BE READ. Use LINE BREAKS, and let the SOURCE decide where they go — there ` +- `is no fixed template to fill:\n` +- ` • material that already has its own lines KEEPS them — a poem or lyric one line per line, steps ` +- `or a short list one per line. Never run such items together into a single sentence.\n` +- ` • a shift to a DIFFERENT point starts a new line.\n` +- ` • one continuous explanation of ONE thing stays as ONE block. Do not break for the sake of ` +- `breaking; a wrongly chopped paragraph is worse than an unbroken one.\n` +- `A LINE BREAK IS THE ONLY FORMATTING YOU HAVE. Still no markdown, no bullet characters, no "-" or ` +- `"*" or "1." at the start of a line, no headings, no tables, no emoji — they are shown literally, ` +- `as the characters you typed. Break the line and start the text.\n` +- `For both parts, restate the substance itself; do NOT narrate the process (avoid ` +- `"I wrote/did…").\n\n---\n${last}\n\n---\n` +- `IMPORTANT: before you answer, re-check the user's request and source message. Write BOTH parts — ` +- `INCLUDING the one-line recap — in their language and register. Do NOT translate or switch to any ` +- `language absent from those two inputs. Keep technical terms, code, and product names as-is.`+ `PLAIN TEXT ONLY: no emoji, markdown, tables, bullets or URLs. Restate the substance itself; do NOT ` ++ `narrate the process (avoid "I wrote/did…").\n\n---\n${last}\n\n---\n` ++ `IMPORTANT: before you answer, re-check the user's request and source message. Write the headline ` ++ `in their language and register. Do NOT translate or switch to any language absent from those two ` ++ `inputs. Keep technical terms, code, and product names as-is.`const scratch = ensureSummaryScratch()@@ -479,11 +454,11 @@ export async function summarizeTurnText(: engine === 'copilot'? runCopilotOneShot: runOpencodeOneShot- // One shape for both paths so the language-drift retry and the two-part capping below stay single-source.+ // One shape for both paths so the language-drift retry and the headline cap below stay single-source.const run: (options: OneShotOptions) => Promise<{ text: string; sessionId: string | null }> = gatewayKey? async (options) => ({text: await openRouterComplete({- prompt: options.prompt, model, apiKey: gatewayKey, signal: options.signal, maxTokens: 1_024,+ prompt: options.prompt, model, apiKey: gatewayKey, signal: options.signal, maxTokens: 160,}) ?? '',sessionId: null,})@@ -493,12 +468,12 @@ export async function summarizeTurnText(await cleanupRecapSession(engine, scratch, r.sessionId)// Language check without naming a language: compare the writing system of the output against the inputs// it was supposed to mirror. Works in both directions and for any language pair.- if (languageDrifted(`${ask} ${last}`, r.text || '')) {+ if (languageDrifted(`${ask} ${last}`, headlineOf(r.text || ''))) {console.warn('[recap] one-shot language drift detected · retrying')r = await run({prompt: prompt + `\n\nRETRY: your previous output was NOT in the same language as the user's request ` +`and the assistant message. Rewrite it in exactly that language — same script and same diacritics — ` +- `preserving the required two-part format.`,+ `as one line.`,model,effort: env.SUMMARY_EFFORT,cwd: scratch,@@ -507,11 +482,10 @@ export async function summarizeTurnText(await cleanupRecapSession(engine, scratch, r.sessionId)}- // Cap the recap (complete-reading) and body independently.- const trimmed = (r.text || '').trim()- const nl = trimmed.indexOf('\n\n')- const recap = capRecap((nl >= 0 ? trimmed.slice(0, nl) : trimmed).trim(), RECAP_MAX_WORDS)- const body = capComplete((nl >= 0 ? trimmed.slice(nl + 2) : '').trim(), SUMMARY_MAX_WORDS)+ const recap = capRecap(headlineOf(r.text || ''), RECAP_MAX_WORDS)if (!recap) { console.warn('[recap] one-shot produced no usable recap (empty after cap)'); return null }+ // The body is the answer's own excerpt, never the model's — and of the whole answer (`text`), not+ // the tail the prompt was fed (`last`), so a very long answer excerpts from its start like local mode.+ const body = deriveTurnBody(text)return body ? `${recap}\n\n${body}` : recap}