From da03c1268468f03c251c8f1572203337e8a6ace6 Mon Sep 17 00:00:00 2001 From: forrestlinfeng Date: Wed, 18 Nov 2026 10:07:03 +0800 Subject: [PATCH 1/3] feat(recall): send the session's recent prompts as recent_turns A recall's context now carries the typed prompts before this turn's, oldest first, as recent_turns ({ role: 'user', text }; at most 5, 1000 characters each and 4000 in all, cleaned and redacted like a prompt; commands excluded). The Hub records them beside the recall for evaluation and does not rank by them yet, so a follow-up like "and step three?" can be studied with what it refers to. The context limit follows the Proxy the plugin requires (2.0.50 keeps up to 16 KiB, not 4096 bytes): the oldest recent turns are dropped first, and only then is the task cut. Co-Authored-By: Claude Opus 5.5 --- docs/architecture.md | 11 ++++++--- lib/app/prompt.js | 5 ++-- lib/recall.js | 39 ++++++++++++++++++++++++----- lib/session/state.js | 12 +++++++-- test/app/recall-context.test.js | 26 +++++++++++++++++++ test/recall.test.js | 44 ++++++++++++++++++++++++++++----- 6 files changed, 117 insertions(+), 20 deletions(-) create mode 100644 test/app/recall-context.test.js diff --git a/docs/architecture.md b/docs/architecture.md index 7ce3abd1..e67d2ead 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -277,10 +277,13 @@ scripts/ pack.mjs, publish-tag.sh Recipe whose required steps the session has seen is passed over before its steps are fetched, so an optional step the Hub did not return never brings it back. - **Task context.** Every recall sends `context` beside `text`: an object the Hub defines and the Proxy forwards - whole, here `{ task, trigger, language? }`. `task` is the session's first typed prompt (4000 characters, cleaned as - a prompt is, and cut further so the context stays within the Proxy's 4096-byte limit), `trigger` is `turn_start` - or `check_failed`, and `language` the touched files' languages. The Hub judges each recalled asset's fit to the - task with it, never recalls by it. The text recall also carries `project_dir`, the session's project directory, + whole, here `{ task, trigger, language?, recent_turns? }`. `task` is the session's first typed prompt (4000 + characters, cleaned as a prompt is), `trigger` is `turn_start` or `check_failed`, and `language` the touched files' + languages. A prompt's recall also sends `recent_turns`: the session's typed prompts before it, oldest first, as + `{ role: 'user', text }` (at most 5, 1000 characters each and 4000 in all, cleaned as a prompt is; commands are + none). The Hub records them for evaluation and does not rank by them yet. The context stays within the Proxy's + 16 KiB (2.0.50; 4096 bytes up to 2.0.48): the oldest recent turns go first, and only then is the task cut. The Hub + judges each recalled asset's fit to the task with it, never recalls by it. The text recall also carries `project_dir`, the session's project directory, for the Proxy to recognise the project by, so its local project notes and project-bound Genes can be recalled. A prompt's opening is often its boilerplate, and an error line alone names no task: an offline replay of 53 SWE runs fired on 15 failed diff --git a/lib/app/prompt.js b/lib/app/prompt.js index a96616f9..d1ee122f 100644 --- a/lib/app/prompt.js +++ b/lib/app/prompt.js @@ -4,7 +4,7 @@ import { draftSourcesOf, withoutDraftsForTurn } from '../distill.js'; import { rangeOf, withCorrection, withSessionActivity } from '../distill/range.js'; import { correctionTextOf } from '../distill/work-turn.js'; -import { promptTextOf, recallStrategy, taskTextOf } from '../recall.js'; +import { promptTextOf, recallStrategy, recentTurnsOf, taskTextOf } from '../recall.js'; import { correctionReportsOf, followUpLabelOf } from '../session/follow-ups.js'; import { boundTurn, joinedWaiting, listedIdsOf, openedTurn, sessionOf, withInjection, withShown, withTurnHead, withWaiting, withWithheld } from '../session/state.js'; import { scheduleDueDistillation } from './distill-session.js'; @@ -123,7 +123,8 @@ export const rememberWithheld = ({ sessions }, sessionId, turn) => (withheld) => async function recalled(ports, sessionId, { turn, prompt, projectDir, waitMs, keepLate, holdForToolResult }) { const session = sessionOf(await ports.sessions.read(sessionId)); const listedIds = listedIdsOf(session); - const context = session.task ? { task: session.task, trigger: 'turn_start' } : null; + const recentTurns = recentTurnsOf(session.recentPrompts); + const context = session.task ? { task: session.task, trigger: 'turn_start', ...(recentTurns.length > 0 && { recent_turns: recentTurns }) } : null; const { request: proxyFetch, signal, cancel } = recallRequestOf(ports.proxy); const recipeCutoff = ports.clock.sleep(waitMs > 0 ? Math.max(0, waitMs - RECIPE_MARGIN_MS) : LATE_RECIPE_WAIT_MS, signal); const onWithheld = rememberWithheld(ports, sessionId, turn); diff --git a/lib/recall.js b/lib/recall.js index 529c90d7..1bfe2d1d 100644 --- a/lib/recall.js +++ b/lib/recall.js @@ -15,10 +15,13 @@ const MIN_PROMPT_CHARS = 8; // kind; at 400 characters the recall text was that preamble and nothing else. const PROMPT_MAX_CHARS = 2000; const TASK_MAX_CHARS = 4000; -// The Evolver Proxy (2.0.48 and earlier) drops a recall context whose JSON is over -// 4096 bytes whole, and the Hub then judges nothing: a CJK task reaches that at -// about 1,350 characters. -const PROXY_CONTEXT_MAX_BYTES = 4096; +// The Evolver Proxy drops a recall context whose JSON is over 16 KiB whole (4096 bytes up to 2.0.48; the plugin +// requires 2.0.50), and the Hub then judges nothing. +const PROXY_CONTEXT_MAX_BYTES = 16_384; +// The Hub records the session's recent prompts beside a recall for evaluation and does not rank by them yet. +const RECENT_TURNS_MAX = 5; +const RECENT_TURN_MAX_CHARS = 1000; +const RECENT_TURNS_MAX_CHARS = 4000; // One strategy should read as an approach, not a transcript: a longer one keeps // its opening and safety lines and as many others as fit. const MAX_STRATEGY_TOKENS = 1000; @@ -72,6 +75,19 @@ export function taskTextOf(text) { return promptTextOf(text, TASK_MAX_CHARS); } +/** The session's earlier prompts, oldest first, as the `recent_turns` of a recall context: the newest that fit. */ +export function recentTurnsOf(prompts) { + const turns = []; + let total = 0; + for (const prompt of (prompts ?? []).slice(-RECENT_TURNS_MAX).reverse()) { + const text = promptTextOf(prompt, RECENT_TURN_MAX_CHARS); + if (!text || total + text.length > RECENT_TURNS_MAX_CHARS) break; + total += text.length; + turns.unshift({ role: 'user', text }); + } + return turns; +} + function recalledAssets(data) { const found = [data?.assets, data?.results, data?.payload?.results].find(Array.isArray) ?? []; return found.filter((asset) => asset && typeof asset.asset_id === 'string' && asset.asset_id); @@ -146,8 +162,19 @@ function withheldOf(recalled) { return typeof assetId === 'string' && assetId && isTextUpTo(withheldId, WITHHELD_ID_MAX_CHARS) ? { asset_id: assetId, withheld_id: withheldId } : null; } -function withinProxyLimit(context) { - const excess = context?.task ? Buffer.byteLength(JSON.stringify(context)) - PROXY_CONTEXT_MAX_BYTES : 0; +const contextBytes = (context) => Buffer.byteLength(JSON.stringify(context)); + +function withoutOldestTurns(context) { + const fitted = { ...context }; + while (fitted.recent_turns?.length && contextBytes(fitted) > PROXY_CONTEXT_MAX_BYTES) fitted.recent_turns = fitted.recent_turns.slice(1); + if (fitted.recent_turns?.length === 0) delete fitted.recent_turns; + return fitted; +} + +// The task outranks the recent prompts: the oldest prompts go first, and only then is the task cut. +function withinProxyLimit(full) { + const context = full ? withoutOldestTurns(full) : full; + const excess = context?.task ? contextBytes(context) - PROXY_CONTEXT_MAX_BYTES : 0; if (excess <= 0) return context; const task = Buffer.from(context.task); return { ...context, task: new TextDecoder().decode(task.subarray(0, Math.max(0, task.length - excess))).replace(/\uFFFD+$/u, '') }; diff --git a/lib/session/state.js b/lib/session/state.js index f6953b93..155f1166 100644 --- a/lib/session/state.js +++ b/lib/session/state.js @@ -9,7 +9,7 @@ import { unreportedAssets, withInjected, withReported } from '../injected-ledger export const EMPTY_SESSION = Object.freeze({ turn: 0, turnId: null, open: false, turnStart: null, prompt: '', isCommand: false, strategy: '', labelable: [], injected: {}, pid: null, startedUnder: null, settling: null, turnIds: [], shown: [], - waiting: null, task: '', stuckQueries: [], turnHead: null, withheld: [], pendingControls: [], + waiting: null, task: '', stuckQueries: [], turnHead: null, withheld: [], pendingControls: [], recentPrompts: [], }); const MAX_STUCK_RECALLS_PER_TURN = 2; @@ -18,6 +18,12 @@ const MAX_SHOWN = 50; const MAX_TURN_IDS = 20; +const MAX_RECENT_PROMPTS = 5; + +// A typed turn keeps the turn before it as recent: a command, or a turn nobody typed for, adds nothing. +const recentPromptsOf = (session, prompt) => (prompt !== null && session.turn > 0 && !session.isCommand && session.prompt + ? [...session.recentPrompts, session.prompt].slice(-MAX_RECENT_PROMPTS) : session.recentPrompts); + // A turn end that died halfway leaves `settling` behind; past this age it no longer holds the next prompt up. const SETTLING_STALE_MS = 30_000; @@ -27,7 +33,8 @@ export const sessionOf = (stored) => ({ ...EMPTY_SESSION, ...stored }); * The session's next turn. A turn nobody typed a prompt for (`prompt` null) carries on the last turn's task. A host * that numbers its own turns (`hostTurn`) keeps the count at least there, so a session resumed after its state was * gone never repeats a task id. The session's `task` is its first typed prompt, kept for the Hub to judge each later - * recall's fit against; a resumed session keeps the task it had. + * recall's fit against; a resumed session keeps the task it had. `recentPrompts` holds the typed prompts before this + * turn's, oldest first. * A fresh session file gets an epoch so retained drafts cannot share a correction key with reused turn numbers. */ export function openedTurn(session, { turnId = null, turnStart = null, hostTurn = null, prompt = null, task = '', pid = null, isCommand = false, now }) { @@ -47,6 +54,7 @@ export function openedTurn(session, { turnId = null, turnStart = null, hostTurn labelable: isCommand ? session.labelable : [], waiting: null, task: session.task || (isCommand ? '' : task), + recentPrompts: recentPromptsOf(session, prompt), stuckQueries: [], turnHead: null, withheld: [], diff --git a/test/app/recall-context.test.js b/test/app/recall-context.test.js new file mode 100644 index 00000000..77131fe6 --- /dev/null +++ b/test/app/recall-context.test.js @@ -0,0 +1,26 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { promptSubmitted } from '../../lib/app/prompt.js'; +import { memoryPorts } from './memory-ports.js'; + +const fetchContexts = (requests) => requests.filter(({ path }) => path === '/asset/fetch').map(({ body }) => body.context); + +test('a recall carries the typed prompts before it as recent turns, oldest first, and the first prompt carries none', async () => { + const { ports, requests } = memoryPorts(); + const prompts = ['How do I grow a Xiaohongshu account?', 'Which note formats work best?', 'And how often should I post?']; + for (const prompt of prompts) await promptSubmitted(ports, { sessionId: 's', prompt, waitMs: 5_000 }); + const [first, second, third] = fetchContexts(requests); + assert.equal(first.recent_turns, undefined); + assert.deepEqual(second.recent_turns, [{ role: 'user', text: prompts[0] }]); + assert.deepEqual(third.recent_turns, [{ role: 'user', text: prompts[0] }, { role: 'user', text: prompts[1] }]); + assert.equal(third.task, prompts[0], 'the task stays the session\'s first prompt'); +}); + +test('a typed command is not a recent turn', async () => { + const { ports, requests } = memoryPorts(); + await promptSubmitted(ports, { sessionId: 's', prompt: 'Add retries to the uploader client', waitMs: 5_000 }); + await promptSubmitted(ports, { sessionId: 's', prompt: '/evolver-status', isCommand: true, waitMs: 5_000 }); + await promptSubmitted(ports, { sessionId: 's', prompt: 'Now cap the retries at five', waitMs: 5_000 }); + assert.deepEqual(fetchContexts(requests).at(-1).recent_turns, [{ role: 'user', text: 'Add retries to the uploader client' }]); +}); diff --git a/test/recall.test.js b/test/recall.test.js index a1d73785..f20dcce3 100644 --- a/test/recall.test.js +++ b/test/recall.test.js @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { recallStrategy, promptTextOf, taskTextOf } from '../lib/recall.js'; +import { recallStrategy, promptTextOf, recentTurnsOf, taskTextOf } from '../lib/recall.js'; function stubProxy(recalled) { const calls = []; @@ -60,20 +60,52 @@ test('quoted JSON credentials are redacted from the recall query and task contex } }); -test('a task context over the Proxy limit is cut to fit, never dropped', async () => { +test('a CJK task of 4000 characters leaves for the Proxy whole within its 16 KiB', async () => { const { proxyFetch, calls, searches } = stubProxy({ assets: [] }); const task = taskTextOf('上传失败后重试'.repeat(600)); - const context = { task, trigger: 'check_failed', language: ['TypeScript', 'Go'] }; + await recallStrategy(proxyFetch, 'upload retry fails', { context: { task, trigger: 'turn_start' } }); + assert.equal(task.length, 4000); + for (const sent of [calls[0].body.context, searches[0].context]) assert.equal(sent.task, task); +}); + +test('recent turns over the Proxy limit go oldest first, and the task stays whole', async () => { + const { proxyFetch, calls, searches } = stubProxy({ assets: [] }); + const task = taskTextOf('上传失败后重试'.repeat(600)); + const turns = ['一', '二', '三', '四'].map((mark) => ({ role: 'user', text: mark.repeat(1000) })); + await recallStrategy(proxyFetch, 'upload retry fails', { context: { task, trigger: 'turn_start', recent_turns: turns } }); + for (const sent of [calls[0].body.context, searches[0].context]) { + assert.ok(Buffer.byteLength(JSON.stringify(sent)) <= 16_384); + assert.equal(sent.task, task); + assert.ok(sent.recent_turns.length > 0 && sent.recent_turns.length < turns.length); + assert.deepEqual(sent.recent_turns, turns.slice(-sent.recent_turns.length), 'the newest turns are the ones kept'); + } +}); + +test('a task context over the Proxy limit is cut to fit, never dropped', async () => { + const { proxyFetch, calls, searches } = stubProxy({ assets: [] }); + const task = taskTextOf('🔁'.repeat(4000)); + const context = { task, trigger: 'check_failed', language: Array.from({ length: 40 }, (_, index) => `Language${index}`) }; await recallStrategy(proxyFetch, 'upload retry fails', { context }); for (const sent of [calls[0].body.context, searches[0].context]) { - assert.ok(Buffer.byteLength(JSON.stringify(sent)) <= 4096); - assert.ok(sent.task.length > 1300); + assert.ok(Buffer.byteLength(JSON.stringify(sent)) <= 16_384); + assert.ok(sent.task.length > 1000); assert.ok(task.startsWith(sent.task)); assert.doesNotMatch(sent.task, /\uFFFD/u); - assert.deepEqual(sent.language, ['TypeScript', 'Go']); + assert.deepEqual(sent.language, context.language); } }); +test('recent turns are the newest earlier prompts that fit, cleaned like a prompt, oldest first', () => { + assert.deepEqual(recentTurnsOf([]), []); + assert.deepEqual(recentTurnsOf(undefined), []); + assert.deepEqual(recentTurnsOf(['first', ' second ']), [{ role: 'user', text: 'first' }, { role: 'user', text: 'second' }]); + assert.deepEqual(recentTurnsOf(['1', '2', '3', '4', '5', '6', '7']).map(({ text }) => text), ['3', '4', '5', '6', '7']); + assert.equal(recentTurnsOf(['x'.repeat(1500)])[0].text.length, 1000); + const long = ['a', 'b', 'c', 'd', 'e'].map((mark) => mark.repeat(1000)); + assert.deepEqual(recentTurnsOf(long).map(({ text }) => text[0]), ['b', 'c', 'd', 'e'], 'at most 4000 characters, the newest kept'); + assert.doesNotMatch(JSON.stringify(recentTurnsOf(['use {"token":"fixtureCredential123456"} to retry'])), /fixtureCredential123456/); +}); + test('one call recalls by text and injects that asset\'s strategy alone', async () => { const { proxyFetch, calls } = stubProxy({ assets: [ASSET] }); const { ids, text } = await recallStrategy(proxyFetch, 'add a retry to the uploader'); From 507dd5283bf73e1b566cf09000443a1670bc2f42 Mon Sep 17 00:00:00 2001 From: forrestlinfeng Date: Mon, 23 Nov 2026 14:45:51 +0800 Subject: [PATCH 2/3] feat(recall): recent turns carry each turn's answer, and the session title A short follow-up such as "how many assets in all?" was recalled with only the session's first prompt beside it. A Gene for counting an EvoX asset library was taken for it in a session that counted a distillation pipeline's output. The prompts before it ("report progress") said as little. - recent_turns now holds the last three typed turns, each prompt then the answer the turn ended with, as { role: 'user' | 'assistant', text }. A prompt keeps 500 characters and an answer its first 800, 4000 in all, whole turns only, cleaned and redacted as a prompt is. The answer is kept at turn end, or at settle from a host that tells it among its tool notes (Cursor, ZCode). - context.title is the host's newest name for the session. Claude Code gives it as the last custom-title in its transcript, which the hooks module now names through $.session.info(). - Over the Proxy limit, the oldest turn goes whole, prompt with answer, before the task is cut. Co-Authored-By: Claude Opus 5.5 --- docs/architecture.md | 14 ++++-- hosts/claude-code/dist/hooks/register.ts | 8 ++- hosts/claude-code/profile.js | 16 ++++++ lib/agent/driver.js | 3 +- lib/agent/profile.js | 4 +- lib/app/prompt.js | 19 +++++--- lib/app/turn-end.js | 16 +++--- lib/recall.js | 57 ++++++++++++++++------ lib/session/state.js | 31 ++++++------ test/app/recall-context.test.js | 62 ++++++++++++++++++++---- test/hosts/claude-code/profile.test.js | 15 ++++++ test/recall.test.js | 25 ++++++---- 12 files changed, 200 insertions(+), 70 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 939cb101..8593ea92 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -277,12 +277,16 @@ scripts/ pack.mjs, publish-tag.sh Recipe whose required steps the session has seen is passed over before its steps are fetched, so an optional step the Hub did not return never brings it back. - **Task context.** Every recall sends `context` beside `text`: an object the Hub defines and the Proxy forwards - whole, here `{ task, trigger, language?, recent_turns? }`. `task` is the session's first typed prompt (4000 + whole, here `{ task, trigger, language?, recent_turns?, title? }`. `task` is the session's first typed prompt (4000 characters, cleaned as a prompt is), `trigger` is `turn_start` or `check_failed`, and `language` the touched files' - languages. A prompt's recall also sends `recent_turns`: the session's typed prompts before it, oldest first, as - `{ role: 'user', text }` (at most 5, 1000 characters each and 4000 in all, cleaned as a prompt is; commands are - none). The Hub records them for evaluation and does not rank by them yet. The context stays within the Proxy's - 16 KiB (2.0.50; 4096 bytes up to 2.0.48): the oldest recent turns go first, and only then is the task cut. The Hub + languages. A prompt's recall also sends `recent_turns`: the session's last three typed turns before it, oldest + first, each as `{ role: 'user', text }` and then the answer the turn ended with as `{ role: 'assistant', text }` + (500 characters of a prompt and the first 800 of an answer, 4000 in all, whole turns only, cleaned and redacted + as a prompt is; commands are none), so a short follow-up ("how many assets in all?") is judged with what it refers + to. `title` is the host's newest name for the session (120 characters), where it gives one: Claude Code's + `custom-title` from the end of its transcript. The Hub records both for evaluation and does not rank by them yet. + The context stays within the Proxy's 16 KiB (2.0.50; 4096 bytes up to 2.0.48): the oldest recent turns go first, + a prompt with its answer, and only then is the task cut. The Hub judges each recalled asset's fit to the task with it, never recalls by it. The text recall also carries `project_dir`, the session's project directory, for the Proxy to recognise the project by, so its local project notes and project-bound Genes can be recalled. A prompt's opening is often its boilerplate, and an error line alone names no diff --git a/hosts/claude-code/dist/hooks/register.ts b/hosts/claude-code/dist/hooks/register.ts index d5d5a8ac..dc7857a3 100644 --- a/hosts/claude-code/dist/hooks/register.ts +++ b/hosts/claude-code/dist/hooks/register.ts @@ -118,12 +118,16 @@ async function post($: EngineInterface, options: PluginOptions, path: string, bo return postTo($, await relayOf($, options, await $.clock.now()), path, body) } -async function sessionFields($: EngineInterface): Promise<{ session_id: string; cwd: string; agent_version?: string }> { +async function sessionFields($: EngineInterface): Promise<{ session_id: string; cwd: string; agent_version?: string; transcript_path?: string }> { const cwd = await $.session.cwd() const stat = await $.fs.stat(cwd, { resolve: true }).catch(() => undefined) const release = await quietly(Promise.resolve().then(() => $.session.version())) const agentVersion = release?.base ?? release?.version - return { session_id: await $.session.id(), cwd: stat?.realPath ?? cwd, ...(agentVersion ? { agent_version: agentVersion } : {}) } + const transcriptPath = (await quietly(Promise.resolve().then(() => $.session.info())))?.transcriptPath + return { + session_id: await $.session.id(), cwd: stat?.realPath ?? cwd, + ...(agentVersion ? { agent_version: agentVersion } : {}), ...(transcriptPath ? { transcript_path: transcriptPath } : {}), + } } async function raise($: EngineInterface, options: PluginOptions, hostEvent: string, fields: Record = {}): Promise { diff --git a/hosts/claude-code/profile.js b/hosts/claude-code/profile.js index 8e467c55..1a45cb65 100644 --- a/hosts/claude-code/profile.js +++ b/hosts/claude-code/profile.js @@ -20,6 +20,21 @@ import { editedFilesOf, toolNoteOf } from './tool-calls.js'; const text = (value) => (typeof value === 'string' ? value : ''); +// Claude Code appends the session's name to its transcript as a `custom-title` entry each time it is set or the +// session resumes, so the newest one sits near the end. +const TITLE_TAIL_BYTES = 256 * 1024; +const CUSTOM_TITLE = /"type":"custom-title","customTitle":("(?:[^"\\]|\\.)*")/g; + +function latestTitleOf(context) { + const tail = context.transcriptSince(Math.max(0, context.transcriptSize() - TITLE_TAIL_BYTES)); + const quoted = [...tail.matchAll(CUSTOM_TITLE)].at(-1)?.[1]; + try { + return quoted ? text(JSON.parse(quoted)) || null : null; + } catch { + return null; + } +} + const CLAUDE_REASONS = new Set(REASONS.filter((reason) => reason !== 'unknown')); export default defineProfile({ @@ -43,6 +58,7 @@ export default defineProfile({ isIgnored: (payload) => Boolean(payload.agent_id), model: (payload) => text(payload.model) || null, agentVersion: (payload) => text(payload.agent_version) || null, + title: (payload, context) => latestTitleOf(context), }, reply: { context: (strategy) => (strategy ? { append: strategy } : {}), diff --git a/lib/agent/driver.js b/lib/agent/driver.js index 945470f0..9a184156 100644 --- a/lib/agent/driver.js +++ b/lib/agent/driver.js @@ -77,7 +77,8 @@ const HANDLERS = { const hostTurn = profile.payload.hostTurn(payload, context); const holdForToolResult = profile.reply.strategyAt === STRATEGY_AT.TOOL_RESULT; const lateAtToolResult = typeof profile.reply.lateAtToolResult === 'function'; - const { turn, sessionEpoch, injection, late, deferred, skipped } = await promptSubmitted(ports, { sessionId, prompt, projectDir, turnId, turnStart, hostTurn, isCommand: Boolean(typed), waitMs: waitLeft(), keepLate, holdForToolResult, lateAtToolResult }); + const title = profile.payload.title(payload, context) ?? ''; + const { turn, sessionEpoch, injection, late, deferred, skipped } = await promptSubmitted(ports, { sessionId, prompt, projectDir, turnId, turnStart, hostTurn, title, isCommand: Boolean(typed), waitMs: waitLeft(), keepLate, holdForToolResult, lateAtToolResult }); if (skipped) options.onError?.(skipped); if (deferred) ports.scheduler.schedule([`recall:${JSON.stringify({ ...at, turn, sessionEpoch })}`]); if (profile.turnEnd.statusRecord && turnId) await scheduleTurn(ports, at, { turn, turnId, sessionEpoch }); diff --git a/lib/agent/profile.js b/lib/agent/profile.js index 0b0c6de5..8fee59c3 100644 --- a/lib/agent/profile.js +++ b/lib/agent/profile.js @@ -25,7 +25,7 @@ const COMMON = Object.freeze({ stateDir: defaultStateDir, legacy: Object.freeze([]), reply: Object.freeze({ strategyAt: STRATEGY_AT.PROMPT, toolResultContext: false }), - payload: Object.freeze({ transcriptPath: (payload) => payload.transcript_path ?? null, gene: (payload) => payload.gene, writtenFor: (payload) => payload.written_for, hostTurn: () => null, agentVersion: () => null }), + payload: Object.freeze({ transcriptPath: (payload) => payload.transcript_path ?? null, gene: (payload) => payload.gene, writtenFor: (payload) => payload.written_for, hostTurn: () => null, agentVersion: () => null, title: () => null }), commands: Object.freeze({ entry: COMMAND_ENTRIES.CLI_ONLY, parse: typedFromPrompt, scriptArgs: (text) => text, scriptAnswer: (result) => result.text }), }); @@ -42,7 +42,7 @@ const BY_CHANNEL = Object.freeze({ const NESTED = ['payload', 'reply', 'turnEnd', 'commands', 'evidence', 'budgets']; const REPLY_FUNCTIONS = ['context', 'notice', 'empty', 'command', 'turnEnd']; const OPTIONAL_REPLY_FUNCTIONS = ['late']; -const PAYLOAD_FUNCTIONS = ['sessionId', 'turnId', 'prompt', 'projectDir', 'isIgnored', 'model', 'transcriptPath', 'gene', 'writtenFor', 'hostTurn', 'agentVersion']; +const PAYLOAD_FUNCTIONS = ['sessionId', 'turnId', 'prompt', 'projectDir', 'isIgnored', 'model', 'transcriptPath', 'gene', 'writtenFor', 'hostTurn', 'agentVersion', 'title']; const MODEL_KINDS = ['cli', 'sdk', 'in-session', 'acp']; // Where a command's answer becomes part of what the model reads, a strategy it found is a reuse to report. const MODEL_SEES_ANSWER = new Set([COMMAND_ENTRIES.INLINE_SCRIPT, COMMAND_ENTRIES.PROMPT, COMMAND_ENTRIES.TOOL]); diff --git a/lib/app/prompt.js b/lib/app/prompt.js index ccbcd120..7faf15ae 100644 --- a/lib/app/prompt.js +++ b/lib/app/prompt.js @@ -4,7 +4,7 @@ import { draftSourcesOf, withoutDraftsForTurn } from '../distill.js'; import { rangeOf, withCorrection, withSessionActivity } from '../distill/range.js'; import { correctionTextOf } from '../distill/work-turn.js'; -import { promptTextOf, recallStrategy, recentTurnsOf, taskTextOf } from '../recall.js'; +import { promptTextOf, recallStrategy, recentTurnsOf, sessionTitleOf, taskTextOf } from '../recall.js'; import { correctionReportsOf, followUpLabelOf } from '../session/follow-ups.js'; import { boundTurn, joinedWaiting, listedIdsOf, openedTurn, sessionOf, withInjection, withShown, withTurnHead, withWaiting, withWithheld } from '../session/state.js'; import { scheduleDueDistillation } from './distill-session.js'; @@ -120,14 +120,21 @@ async function waitForToolResult({ sessions }, sessionId, { turn, match }) { } /** Remembers a trial Gene the Proxy withheld from `turn`, which that turn's end reports as a control. */ +/** What the Hub judges a turn's recall against: the session's task and, where known, its recent turns and title. */ +function recallContextOf(session) { + if (!session.task) return null; + const recentTurns = recentTurnsOf(session.recentTurns); + const title = sessionTitleOf(session.title); + return { task: session.task, trigger: 'turn_start', ...(recentTurns.length > 0 && { recent_turns: recentTurns }), ...(title && { title }) }; +} + export const rememberWithheld = ({ sessions }, sessionId, turn) => (withheld) => sessions.update(sessionId, (stored) => withWithheld(sessionOf(stored), withheld, turn)); async function recalled(ports, sessionId, { turn, prompt, projectDir, waitMs, keepLate, holdForToolResult, lateAtToolResult }) { const session = sessionOf(await ports.sessions.read(sessionId)); const listedIds = listedIdsOf(session); - const recentTurns = recentTurnsOf(session.recentPrompts); - const context = session.task ? { task: session.task, trigger: 'turn_start', ...(recentTurns.length > 0 && { recent_turns: recentTurns }) } : null; + const context = recallContextOf(session); // Without a late answer the wait cancels every request when it ends anyway, so a request may run for all of it. A host // that sends a missed recall to the background needs the wait to end first: a request cut at or before it (the // Proxy client's own default is 8 s) settles the recall empty, and it would never be deferred. @@ -177,13 +184,13 @@ async function rememberTurnHead({ project, sessions }, sessionId, { turn, sessio * recalled for nothing and never joins the session's range of work turns. `skipped` is the error of a correction or * session lifecycle lock the prompt went without. */ -export async function promptSubmitted(ports, { sessionId, prompt, projectDir = null, turnId = null, turnStart = null, hostTurn = null, isCommand = false, waitMs, keepLate = false, holdForToolResult = false, lateAtToolResult = false }) { +export async function promptSubmitted(ports, { sessionId, prompt, projectDir = null, turnId = null, turnStart = null, hostTurn = null, title = '', isCommand = false, waitMs, keepLate = false, holdForToolResult = false, lateAtToolResult = false }) { const labelled = isCommand ? {} : await labelFollowUp(ports, sessionId, prompt); const pid = ports.owner.current(); const fenced = await fencedOpen(ports, sessionId, async () => { if (!isCommand) await ports.candidates.update((pending) => withSessionActivity(pending, sessionId, ports.clock.now())); return ports.sessions.update(sessionId, (stored) => - openedTurn(sessionOf(stored), { turnId, turnStart, hostTurn, prompt: prompt ? promptTextOf(prompt) : null, task: taskTextOf(prompt), pid, isCommand, now: ports.clock.now() })); + openedTurn(sessionOf(stored), { turnId, turnStart, hostTurn, prompt: prompt ? promptTextOf(prompt) : null, task: taskTextOf(prompt), title, pid, isCommand, now: ports.clock.now() })); }); const { opened } = fenced; const skipped = labelled.skipped ?? fenced.skipped; @@ -204,7 +211,7 @@ export async function recallForToolResult(ports, { sessionId, projectDir = null, const isThisTurn = (session) => session.open && session.turn === turn && session.sessionEpoch === sessionEpoch; const session = sessionOf(await ports.sessions.read(sessionId)); if (!isThisTurn(session) || !session.prompt) return; - const context = session.task ? { task: session.task, trigger: 'turn_start' } : null; + const context = recallContextOf(session); const { request: proxyFetch, signal, cancel } = recallRequestOf(ports.proxy, { timeoutMs: DEFERRED_RECALL_MS }); try { const match = await recallStrategy(proxyFetch, promptTextOf(session.prompt), { diff --git a/lib/app/turn-end.js b/lib/app/turn-end.js index 84603158..f24fe099 100644 --- a/lib/app/turn-end.js +++ b/lib/app/turn-end.js @@ -5,6 +5,7 @@ import { verdictOf } from '../checks.js'; import { gateOf } from '../distill/gate.js'; import { baseFor, rangeOf, withSessionActivity, withWorkTurn, withoutWorkTurn } from '../distill/range.js'; import { isWorkTurn, workTurnOf } from '../distill/work-turn.js'; +import { answerTextOf } from '../recall.js'; import { reportedReuseOf } from '../reuse.js'; import { closedTurn, isSettling, markedReported, pendingReportsOf, sessionOf, settledSession, unreportedOf, withPendingReports } from '../session/state.js'; import { trialControlEntriesOf } from '../trial-control.js'; @@ -22,19 +23,20 @@ const SETTLING_WAIT_MS = 2_000; const sameTurn = (session, expected) => session.turnId === expected.turnId && session.turn === expected.turn && session.sessionEpoch === expected.sessionEpoch; // A turn end that began later (a re-judge of the same turn) owns `settling` from then on; an earlier one leaves it. -// A native turn whose evidence or bookkeeping could not finish reopens for the next turn end or recovery. -const settleTurn = (ports, sessionId, opened, reopen = false) => ports.sessions.update(sessionId, (stored) => { +// A native turn whose evidence or bookkeeping could not finish reopens for the next turn end or recovery. A host that +// told the turn's answer among its tool notes, not at its end, leaves it to the turn's record. +const settleTurn = (ports, sessionId, opened, reopen = false, recordedAnswer = '') => ports.sessions.update(sessionId, (stored) => { const current = sessionOf(stored); if (!sameTurn(current, opened) || current.settling !== opened.settling) return undefined; - const settled = settledSession(current); + const settled = { ...settledSession(current), ...(recordedAnswer && { answer: answerTextOf(recordedAnswer) }) }; return reopen ? { ...settled, open: true, waiting: opened.waiting } : settled; }); -async function closeTurn({ sessions, clock }, sessionId, turnId, expected) { +async function closeTurn({ sessions, clock }, sessionId, turnId, expected, answer) { let opened = null; await sessions.update(sessionId, (stored) => { if (expected && !sameTurn(sessionOf(stored), expected)) return undefined; - const result = closedTurn(sessionOf(stored), turnId, clock.now()); + const result = closedTurn(sessionOf(stored), turnId, clock.now(), answerTextOf(answer)); opened = result.opened && { ...result.opened, settling: result.next.settling }; return result.next; }); @@ -224,7 +226,7 @@ async function recordTurn(ports, sessionId, opened, { reason, answer, model, pro } export async function turnEnded(ports, { sessionId, turnId, reason, answer = '', model = null, projectDir, recordOf = null, source = OBSERVED, expectedTurn }) { - const opened = await closeTurn(ports, sessionId, turnId, expectedTurn); + const opened = await closeTurn(ports, sessionId, turnId, expectedTurn, answer); if (!opened) { if (ports.confirmTurnCompletion || !(turnId && recordOf && source === OBSERVED)) return null; await rejudgeWorkTurn(ports, sessionId, turnId, { answer, model, projectDir, recordOf }); @@ -248,7 +250,7 @@ export async function turnEnded(ports, { sessionId, turnId, reason, answer = '', if (!processingComplete) throw error; cleanupFailure = error; } finally { - await settleTurn(ports, sessionId, opened, ports.confirmTurnCompletion && !processingComplete); + await settleTurn(ports, sessionId, opened, ports.confirmTurnCompletion && !processingComplete, ended?.record.answer); } if (!ended) { if (cleanupFailure) throw cleanupFailure; diff --git a/lib/recall.js b/lib/recall.js index d8123487..29848dfd 100644 --- a/lib/recall.js +++ b/lib/recall.js @@ -19,10 +19,12 @@ const TASK_MAX_CHARS = 4000; // The Evolver Proxy drops a recall context whose JSON is over 16 KiB whole (4096 bytes up to 2.0.48; the plugin // requires 2.0.50), and the Hub then judges nothing. const PROXY_CONTEXT_MAX_BYTES = 16_384; -// The Hub records the session's recent prompts beside a recall for evaluation and does not rank by them yet. -const RECENT_TURNS_MAX = 5; -const RECENT_TURN_MAX_CHARS = 1000; +// A short follow-up ("how many assets in all?") says little alone: the turns before it, and what the agent last +// answered, say what it refers to. Each answer keeps its opening, where an agent states the outcome. +const RECENT_PROMPT_MAX_CHARS = 500; +const RECENT_ANSWER_MAX_CHARS = 800; const RECENT_TURNS_MAX_CHARS = 4000; +const SESSION_TITLE_MAX_CHARS = 120; // One strategy should read as an approach, not a transcript: a longer one keeps // its opening and safety lines and as many others as fit. const MAX_STRATEGY_TOKENS = 1000; @@ -76,17 +78,38 @@ export function taskTextOf(text) { return promptTextOf(text, TASK_MAX_CHARS); } -/** The session's earlier prompts, oldest first, as the `recent_turns` of a recall context: the newest that fit. */ -export function recentTurnsOf(prompts) { - const turns = []; +/** A turn's final answer as later recalls see it: its opening, cleaned and redacted as a prompt is. */ +export function answerTextOf(text) { + return promptTextOf(text, RECENT_ANSWER_MAX_CHARS); +} + +/** A host's name for the session, cleaned and redacted as a prompt is; '' when it gives none. */ +export function sessionTitleOf(text) { + return promptTextOf(text, SESSION_TITLE_MAX_CHARS); +} + +function messagesOf(turn) { + return [ + { role: 'user', text: promptTextOf(turn?.prompt, RECENT_PROMPT_MAX_CHARS) }, + { role: 'assistant', text: answerTextOf(turn?.answer) }, + ].filter((message) => message.text); +} + +/** + * The session's earlier turns, oldest first, as the `recent_turns` of a recall context: each turn's prompt, then + * its answer, for the newest turns that fit whole. + */ +export function recentTurnsOf(turns) { + const messages = []; let total = 0; - for (const prompt of (prompts ?? []).slice(-RECENT_TURNS_MAX).reverse()) { - const text = promptTextOf(prompt, RECENT_TURN_MAX_CHARS); - if (!text || total + text.length > RECENT_TURNS_MAX_CHARS) break; - total += text.length; - turns.unshift({ role: 'user', text }); + for (const turn of [...(turns ?? [])].reverse()) { + const ofTurn = messagesOf(turn); + const size = ofTurn.reduce((sum, message) => sum + message.text.length, 0); + if (total + size > RECENT_TURNS_MAX_CHARS) break; + total += size; + messages.unshift(...ofTurn); } - return turns; + return messages; } function recalledAssets(data) { @@ -165,14 +188,20 @@ function withheldOf(recalled) { const contextBytes = (context) => Buffer.byteLength(JSON.stringify(context)); +// A turn goes whole: its prompt and the answer to it. +function withoutOldestTurn(messages) { + const rest = messages.slice(1); + return rest[0]?.role === 'assistant' ? rest.slice(1) : rest; +} + function withoutOldestTurns(context) { const fitted = { ...context }; - while (fitted.recent_turns?.length && contextBytes(fitted) > PROXY_CONTEXT_MAX_BYTES) fitted.recent_turns = fitted.recent_turns.slice(1); + while (fitted.recent_turns?.length && contextBytes(fitted) > PROXY_CONTEXT_MAX_BYTES) fitted.recent_turns = withoutOldestTurn(fitted.recent_turns); if (fitted.recent_turns?.length === 0) delete fitted.recent_turns; return fitted; } -// The task outranks the recent prompts: the oldest prompts go first, and only then is the task cut. +// The task outranks the recent turns: the oldest turns go first, and only then is the task cut. function withinProxyLimit(full) { const context = full ? withoutOldestTurns(full) : full; const excess = context?.task ? contextBytes(context) - PROXY_CONTEXT_MAX_BYTES : 0; diff --git a/lib/session/state.js b/lib/session/state.js index 155f1166..ad6a7e39 100644 --- a/lib/session/state.js +++ b/lib/session/state.js @@ -9,7 +9,7 @@ import { unreportedAssets, withInjected, withReported } from '../injected-ledger export const EMPTY_SESSION = Object.freeze({ turn: 0, turnId: null, open: false, turnStart: null, prompt: '', isCommand: false, strategy: '', labelable: [], injected: {}, pid: null, startedUnder: null, settling: null, turnIds: [], shown: [], - waiting: null, task: '', stuckQueries: [], turnHead: null, withheld: [], pendingControls: [], recentPrompts: [], + waiting: null, task: '', stuckQueries: [], turnHead: null, withheld: [], pendingControls: [], recentTurns: [], answer: '', title: '', }); const MAX_STUCK_RECALLS_PER_TURN = 2; @@ -18,11 +18,12 @@ const MAX_SHOWN = 50; const MAX_TURN_IDS = 20; -const MAX_RECENT_PROMPTS = 5; +const MAX_RECENT_TURNS = 3; -// A typed turn keeps the turn before it as recent: a command, or a turn nobody typed for, adds nothing. -const recentPromptsOf = (session, prompt) => (prompt !== null && session.turn > 0 && !session.isCommand && session.prompt - ? [...session.recentPrompts, session.prompt].slice(-MAX_RECENT_PROMPTS) : session.recentPrompts); +// A typed turn keeps the turn before it, its prompt and the answer it ended with, as recent: a command, or a turn +// nobody typed for, adds nothing. +const recentTurnsOf = (session, prompt) => (prompt !== null && session.turn > 0 && !session.isCommand && session.prompt + ? [...session.recentTurns, { prompt: session.prompt, answer: session.answer }].slice(-MAX_RECENT_TURNS) : session.recentTurns); // A turn end that died halfway leaves `settling` behind; past this age it no longer holds the next prompt up. const SETTLING_STALE_MS = 30_000; @@ -33,11 +34,11 @@ export const sessionOf = (stored) => ({ ...EMPTY_SESSION, ...stored }); * The session's next turn. A turn nobody typed a prompt for (`prompt` null) carries on the last turn's task. A host * that numbers its own turns (`hostTurn`) keeps the count at least there, so a session resumed after its state was * gone never repeats a task id. The session's `task` is its first typed prompt, kept for the Hub to judge each later - * recall's fit against; a resumed session keeps the task it had. `recentPrompts` holds the typed prompts before this - * turn's, oldest first. + * recall's fit against; a resumed session keeps the task it had. `recentTurns` holds the typed turns before this one, + * oldest first, each `{ prompt, answer }`; `title` is the host's latest name for the session, kept when it names none. * A fresh session file gets an epoch so retained drafts cannot share a correction key with reused turn numbers. */ -export function openedTurn(session, { turnId = null, turnStart = null, hostTurn = null, prompt = null, task = '', pid = null, isCommand = false, now }) { +export function openedTurn(session, { turnId = null, turnStart = null, hostTurn = null, prompt = null, task = '', title = '', pid = null, isCommand = false, now }) { return { ...session, sessionEpoch: session.turn === 0 ? now : session.sessionEpoch, @@ -54,7 +55,9 @@ export function openedTurn(session, { turnId = null, turnStart = null, hostTurn labelable: isCommand ? session.labelable : [], waiting: null, task: session.task || (isCommand ? '' : task), - recentPrompts: recentPromptsOf(session, prompt), + recentTurns: recentTurnsOf(session, prompt), + answer: '', + title: title || session.title, stuckQueries: [], turnHead: null, withheld: [], @@ -100,13 +103,13 @@ export function withStuckQuery(session, query, turn) { const isOpenTurn = (session, turnId) => session.open && (!turnId || !session.turnId || turnId === session.turnId); /** - * The session with `turnId` (any turn when omitted) closed, and the turn as it was; `next` is undefined when none was - * open. It stays `settling` until the turn's reports and candidate are written, so a prompt that arrives meanwhile - * waits rather than labelling or dropping what is not there yet. + * The session with `turnId` (any turn when omitted) closed on `answer`, and the turn as it was; `next` is undefined + * when none was open. It stays `settling` until the turn's reports and candidate are written, so a prompt that arrives + * meanwhile waits rather than labelling or dropping what is not there yet. */ -export function closedTurn(session, turnId, now) { +export function closedTurn(session, turnId, now, answer = '') { if (!isOpenTurn(session, turnId)) return { next: undefined, opened: null }; - return { next: { ...session, open: false, settling: now, waiting: null }, opened: session }; + return { next: { ...session, open: false, settling: now, waiting: null, answer }, opened: session }; } /** Whether the last turn is still closing: its reports and candidate are not all written yet. */ diff --git a/test/app/recall-context.test.js b/test/app/recall-context.test.js index 77131fe6..ba844048 100644 --- a/test/app/recall-context.test.js +++ b/test/app/recall-context.test.js @@ -2,25 +2,69 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { promptSubmitted } from '../../lib/app/prompt.js'; +import { toolFinished } from '../../lib/app/tool-result.js'; +import { turnEnded } from '../../lib/app/turn-end.js'; import { memoryPorts } from './memory-ports.js'; const fetchContexts = (requests) => requests.filter(({ path }) => path === '/asset/fetch').map(({ body }) => body.context); -test('a recall carries the typed prompts before it as recent turns, oldest first, and the first prompt carries none', async () => { +async function turn(ports, prompt, answer, options = {}) { + await promptSubmitted(ports, { sessionId: 's', prompt, waitMs: 5_000, ...options }); + if (answer !== undefined) await turnEnded(ports, { sessionId: 's', reason: 'answer', answer }); +} + +test('a recall carries the turns before it, each prompt then its answer, and the first prompt carries none', async () => { const { ports, requests } = memoryPorts(); - const prompts = ['How do I grow a Xiaohongshu account?', 'Which note formats work best?', 'And how often should I post?']; - for (const prompt of prompts) await promptSubmitted(ports, { sessionId: 's', prompt, waitMs: 5_000 }); + await turn(ports, 'Distill the nexu-io sources into Genes', '56 sources: 12 published, 114 assets, 1 quarantined by the Hub.'); + await turn(ports, 'Report progress', 'All 56 published; 704 assets in all.'); + await turn(ports, 'How many assets in all? Report after the evaluation'); const [first, second, third] = fetchContexts(requests); assert.equal(first.recent_turns, undefined); - assert.deepEqual(second.recent_turns, [{ role: 'user', text: prompts[0] }]); - assert.deepEqual(third.recent_turns, [{ role: 'user', text: prompts[0] }, { role: 'user', text: prompts[1] }]); - assert.equal(third.task, prompts[0], 'the task stays the session\'s first prompt'); + assert.deepEqual(second.recent_turns, [ + { role: 'user', text: 'Distill the nexu-io sources into Genes' }, + { role: 'assistant', text: '56 sources: 12 published, 114 assets, 1 quarantined by the Hub.' }, + ]); + assert.equal(third.recent_turns.length, 4); + assert.deepEqual(third.recent_turns.at(-1), { role: 'assistant', text: 'All 56 published; 704 assets in all.' }); + assert.equal(third.task, 'Distill the nexu-io sources into Genes', 'the task stays the session\'s first prompt'); +}); + +test('only the last three turns are kept, and a turn that ended without an answer keeps its prompt', async () => { + const { ports, requests } = memoryPorts(); + for (const mark of ['one', 'two', 'three', 'four']) await turn(ports, `Prompt ${mark} for the uploader`, `Answer ${mark}`); + await turn(ports, 'Prompt five for the uploader', ''); + await turn(ports, 'Prompt six for the uploader'); + const texts = fetchContexts(requests).at(-1).recent_turns.map(({ text }) => text); + assert.deepEqual(texts, ['Prompt three for the uploader', 'Answer three', 'Prompt four for the uploader', 'Answer four', 'Prompt five for the uploader']); +}); + +test('the host\'s latest title rides every recall, and a prompt that names none keeps the last one', async () => { + const { ports, requests } = memoryPorts(); + await turn(ports, 'Distill openmotion for dsh', 'Done.', { title: 'Distill openmotion' }); + await turn(ports, 'Now the nexu-io sources', 'Started.', { title: 'Distill openmotion and nexu-io' }); + await turn(ports, 'How many assets in all?'); + const [first, second, third] = fetchContexts(requests); + assert.equal(first.title, 'Distill openmotion'); + assert.equal(second.title, 'Distill openmotion and nexu-io'); + assert.equal(third.title, 'Distill openmotion and nexu-io'); }); test('a typed command is not a recent turn', async () => { const { ports, requests } = memoryPorts(); - await promptSubmitted(ports, { sessionId: 's', prompt: 'Add retries to the uploader client', waitMs: 5_000 }); + await turn(ports, 'Add retries to the uploader client', 'Added, capped at five.'); await promptSubmitted(ports, { sessionId: 's', prompt: '/evolver-status', isCommand: true, waitMs: 5_000 }); - await promptSubmitted(ports, { sessionId: 's', prompt: 'Now cap the retries at five', waitMs: 5_000 }); - assert.deepEqual(fetchContexts(requests).at(-1).recent_turns, [{ role: 'user', text: 'Add retries to the uploader client' }]); + await turn(ports, 'Now cap the retries at three'); + assert.deepEqual(fetchContexts(requests).at(-1).recent_turns, [ + { role: 'user', text: 'Add retries to the uploader client' }, + { role: 'assistant', text: 'Added, capped at five.' }, + ]); +}); + +test('a host that tells the answer among its tool notes, not at the turn end, still has it recalled with', async () => { + const { ports, requests } = memoryPorts(); + await turn(ports, 'Summarise the failing uploads'); + await toolFinished(ports, { sessionId: 's', note: { kind: 'answer', text: 'Three uploads failed on a 413.' } }); + await turnEnded(ports, { sessionId: 's', reason: 'answer' }); + await turn(ports, 'Fix those'); + assert.deepEqual(fetchContexts(requests).at(-1).recent_turns.at(-1), { role: 'assistant', text: 'Three uploads failed on a 413.' }); }); diff --git a/test/hosts/claude-code/profile.test.js b/test/hosts/claude-code/profile.test.js index 1d1333b6..d3573fa3 100644 --- a/test/hosts/claude-code/profile.test.js +++ b/test/hosts/claude-code/profile.test.js @@ -85,3 +85,18 @@ test('the relay runs under Claude Code: its owner is the process that started it assert.deepEqual(profile.model, { kind: 'sdk' }); assert.equal(profile.payload.model({ model: captured.session.model }), 'claude-haiku-5-5'); }); + +test('the session title is the newest custom-title in the transcript, and none without one', () => { + const transcriptOf = (lines) => { + const text = lines.map((line) => JSON.stringify(line)).join('\n'); + return { transcriptSize: () => text.length, transcriptSince: () => text }; + }; + const named = transcriptOf([ + { type: 'custom-title', customTitle: 'Distill openmotion', sessionId: 's' }, + { type: 'user', message: { content: 'go' } }, + { type: 'custom-title', customTitle: 'Distill "nexu-io"(视频)', sessionId: 's' }, + ]); + assert.equal(profile.payload.title({}, named), 'Distill "nexu-io"(视频)'); + assert.equal(profile.payload.title({}, transcriptOf([{ type: 'user', message: { content: 'go' } }])), null); + assert.equal(profile.payload.title({}, { transcriptSize: () => 0, transcriptSince: () => '' }), null); +}); diff --git a/test/recall.test.js b/test/recall.test.js index f20dcce3..b7fa1864 100644 --- a/test/recall.test.js +++ b/test/recall.test.js @@ -68,15 +68,17 @@ test('a CJK task of 4000 characters leaves for the Proxy whole within its 16 KiB for (const sent of [calls[0].body.context, searches[0].context]) assert.equal(sent.task, task); }); -test('recent turns over the Proxy limit go oldest first, and the task stays whole', async () => { +test('recent turns over the Proxy limit go oldest first, a prompt with its answer, and the task stays whole', async () => { const { proxyFetch, calls, searches } = stubProxy({ assets: [] }); const task = taskTextOf('上传失败后重试'.repeat(600)); - const turns = ['一', '二', '三', '四'].map((mark) => ({ role: 'user', text: mark.repeat(1000) })); - await recallStrategy(proxyFetch, 'upload retry fails', { context: { task, trigger: 'turn_start', recent_turns: turns } }); + const turns = ['一', '二', '三'].flatMap((mark) => [{ role: 'user', text: mark.repeat(500) }, { role: 'assistant', text: mark.repeat(800) }]); + await recallStrategy(proxyFetch, 'upload retry fails', { context: { task, trigger: 'turn_start', recent_turns: turns, title: '上传重试' } }); for (const sent of [calls[0].body.context, searches[0].context]) { assert.ok(Buffer.byteLength(JSON.stringify(sent)) <= 16_384); assert.equal(sent.task, task); + assert.equal(sent.title, '上传重试'); assert.ok(sent.recent_turns.length > 0 && sent.recent_turns.length < turns.length); + assert.equal(sent.recent_turns[0].role, 'user', 'no answer is kept without its prompt'); assert.deepEqual(sent.recent_turns, turns.slice(-sent.recent_turns.length), 'the newest turns are the ones kept'); } }); @@ -95,15 +97,18 @@ test('a task context over the Proxy limit is cut to fit, never dropped', async ( } }); -test('recent turns are the newest earlier prompts that fit, cleaned like a prompt, oldest first', () => { +test('recent turns are each earlier prompt then its answer, oldest first, cleaned like a prompt', () => { assert.deepEqual(recentTurnsOf([]), []); assert.deepEqual(recentTurnsOf(undefined), []); - assert.deepEqual(recentTurnsOf(['first', ' second ']), [{ role: 'user', text: 'first' }, { role: 'user', text: 'second' }]); - assert.deepEqual(recentTurnsOf(['1', '2', '3', '4', '5', '6', '7']).map(({ text }) => text), ['3', '4', '5', '6', '7']); - assert.equal(recentTurnsOf(['x'.repeat(1500)])[0].text.length, 1000); - const long = ['a', 'b', 'c', 'd', 'e'].map((mark) => mark.repeat(1000)); - assert.deepEqual(recentTurnsOf(long).map(({ text }) => text[0]), ['b', 'c', 'd', 'e'], 'at most 4000 characters, the newest kept'); - assert.doesNotMatch(JSON.stringify(recentTurnsOf(['use {"token":"fixtureCredential123456"} to retry'])), /fixtureCredential123456/); + assert.deepEqual(recentTurnsOf([{ prompt: 'first', answer: ' done, 114 assets ' }, { prompt: 'second', answer: '' }]), [ + { role: 'user', text: 'first' }, { role: 'assistant', text: 'done, 114 assets' }, { role: 'user', text: 'second' }, + ]); + const [prompt, answer] = recentTurnsOf([{ prompt: 'x'.repeat(900), answer: 'y'.repeat(1500) }]); + assert.equal(prompt.text.length, 500); + assert.equal(answer.text.length, 800, 'an answer keeps its opening'); + const long = ['a', 'b', 'c', 'd'].map((mark) => ({ prompt: mark.repeat(500), answer: mark.repeat(800) })); + assert.deepEqual(recentTurnsOf(long).map(({ text }) => text[0]), ['b', 'b', 'c', 'c', 'd', 'd'], 'at most 4000 characters, whole turns, the newest kept'); + assert.doesNotMatch(JSON.stringify(recentTurnsOf([{ prompt: 'retry it', answer: 'used {"token":"fixtureCredential123456"} to retry' }])), /fixtureCredential123456/); }); test('one call recalls by text and injects that asset\'s strategy alone', async () => { From 99866df5d9880eba582ba355f94c842b206890d3 Mon Sep 17 00:00:00 2001 From: forrestlinfeng Date: Mon, 23 Nov 2026 16:52:23 +0800 Subject: [PATCH 3/3] fix(recall): an untyped turn keeps the typed turn's answer; a resume keeps recent turns - A turn joined the recent turns only when the next turn was typed. So a task notification's turn between two typed turns lost the first typed turn's answer, and its own answer was recorded under that turn's prompt. Each turn now records whether a person typed it, and a typed turn joins the recent turns when the next turn of any kind opens. - endedSession dropped the recent turns and title. A session ended and resumed under the same id then recalled with its task alone. It now keeps both, with the last typed turn added. Found by replaying each host's captured payloads over three turns. Every host passed before and after the fix; the untyped-turn and resume cases failed before it. Co-Authored-By: Claude Opus 5.5 --- lib/session/state.js | 21 ++++++++++++++------- test/app/recall-context.test.js | 27 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/lib/session/state.js b/lib/session/state.js index ad6a7e39..86c23136 100644 --- a/lib/session/state.js +++ b/lib/session/state.js @@ -9,7 +9,7 @@ import { unreportedAssets, withInjected, withReported } from '../injected-ledger export const EMPTY_SESSION = Object.freeze({ turn: 0, turnId: null, open: false, turnStart: null, prompt: '', isCommand: false, strategy: '', labelable: [], injected: {}, pid: null, startedUnder: null, settling: null, turnIds: [], shown: [], - waiting: null, task: '', stuckQueries: [], turnHead: null, withheld: [], pendingControls: [], recentTurns: [], answer: '', title: '', + waiting: null, task: '', stuckQueries: [], turnHead: null, withheld: [], pendingControls: [], recentTurns: [], answer: '', isTyped: false, title: '', }); const MAX_STUCK_RECALLS_PER_TURN = 2; @@ -20,9 +20,9 @@ const MAX_TURN_IDS = 20; const MAX_RECENT_TURNS = 3; -// A typed turn keeps the turn before it, its prompt and the answer it ended with, as recent: a command, or a turn -// nobody typed for, adds nothing. -const recentTurnsOf = (session, prompt) => (prompt !== null && session.turn > 0 && !session.isCommand && session.prompt +// The last turn joins the recent turns, its prompt with the answer it ended with, once it is over, if a person typed +// it: a command, or a turn nobody typed for (a task notification), adds nothing and takes no other turn's answer. +const withLastTurnRecent = (session) => (session.isTyped && session.prompt ? [...session.recentTurns, { prompt: session.prompt, answer: session.answer }].slice(-MAX_RECENT_TURNS) : session.recentTurns); // A turn end that died halfway leaves `settling` behind; past this age it no longer holds the next prompt up. @@ -55,8 +55,9 @@ export function openedTurn(session, { turnId = null, turnStart = null, hostTurn labelable: isCommand ? session.labelable : [], waiting: null, task: session.task || (isCommand ? '' : task), - recentTurns: recentTurnsOf(session, prompt), + recentTurns: withLastTurnRecent(session), answer: '', + isTyped: prompt !== null && !isCommand, title: title || session.title, stuckQueries: [], turnHead: null, @@ -217,7 +218,13 @@ export function orphansOf(session, sessionId, isGone) { */ export const isEarlierTurn = (session, turnId) => Boolean(turnId) && turnId !== session.turnId && session.turnIds.includes(turnId); -/** What an ended session keeps: its turn counter, owner and ledger, so a resume neither repeats a task id nor re-injects. */ +/** + * What an ended session keeps: its turn counter, owner and ledger, so a resume neither repeats a task id nor re-injects, + * and its task, recent turns and title, so a resume's first recall is judged with what came before. + */ export function endedSession(session) { - return { ...EMPTY_SESSION, turn: session.turn, sessionEpoch: session.sessionEpoch, pid: session.pid, injected: session.injected, turnIds: session.turnIds, shown: session.shown, task: session.task, pendingControls: session.pendingControls }; + return { + ...EMPTY_SESSION, turn: session.turn, sessionEpoch: session.sessionEpoch, pid: session.pid, injected: session.injected, turnIds: session.turnIds, + shown: session.shown, task: session.task, pendingControls: session.pendingControls, recentTurns: withLastTurnRecent(session), title: session.title, + }; } diff --git a/test/app/recall-context.test.js b/test/app/recall-context.test.js index ba844048..5b02aa50 100644 --- a/test/app/recall-context.test.js +++ b/test/app/recall-context.test.js @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { promptSubmitted } from '../../lib/app/prompt.js'; +import { sessionEnded } from '../../lib/app/session-end.js'; import { toolFinished } from '../../lib/app/tool-result.js'; import { turnEnded } from '../../lib/app/turn-end.js'; import { memoryPorts } from './memory-ports.js'; @@ -68,3 +69,29 @@ test('a host that tells the answer among its tool notes, not at the turn end, st await turn(ports, 'Fix those'); assert.deepEqual(fetchContexts(requests).at(-1).recent_turns.at(-1), { role: 'assistant', text: 'Three uploads failed on a 413.' }); }); + +test('a turn nobody typed for keeps neither its own answer nor the typed turn before it from the recent turns', async () => { + const { ports, requests } = memoryPorts(); + await turn(ports, 'Distill the nexu-io sources into Genes', '56 sources queued.'); + await promptSubmitted(ports, { sessionId: 's', prompt: null, waitMs: 5_000 }); + await turnEnded(ports, { sessionId: 's', reason: 'answer', answer: 'The background job finished.' }); + await turn(ports, 'How many assets in all?'); + assert.deepEqual(fetchContexts(requests).at(-1).recent_turns, [ + { role: 'user', text: 'Distill the nexu-io sources into Genes' }, + { role: 'assistant', text: '56 sources queued.' }, + ]); +}); + +test('a resumed session keeps its recent turns and title, the last turn before the end among them', async () => { + const { ports, requests } = memoryPorts(); + await turn(ports, 'Distill openmotion for dsh', 'Published 8 Genes.', { title: 'Distill openmotion' }); + await sessionEnded(ports, { sessionId: 's', projectDir: null }); + await turn(ports, 'Now evaluate their recall'); + const context = fetchContexts(requests).at(-1); + assert.deepEqual(context.recent_turns, [ + { role: 'user', text: 'Distill openmotion for dsh' }, + { role: 'assistant', text: 'Published 8 Genes.' }, + ]); + assert.equal(context.title, 'Distill openmotion'); + assert.equal(context.task, 'Distill openmotion for dsh'); +});