diff --git a/docs/architecture.md b/docs/architecture.md index 402f4312..8593ea92 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -277,10 +277,17 @@ 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?, 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 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 task: an offline replay of 53 SWE runs fired on 15 failed 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 27802dce..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, 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,13 +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 context = session.task ? { task: session.task, trigger: 'turn_start' } : 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. @@ -176,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; @@ -203,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 5b2eed72..29848dfd 100644 --- a/lib/recall.js +++ b/lib/recall.js @@ -16,10 +16,15 @@ 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; +// 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; @@ -73,6 +78,40 @@ export function taskTextOf(text) { return promptTextOf(text, TASK_MAX_CHARS); } +/** 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 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 messages; +} + 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); @@ -147,8 +186,25 @@ 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)); + +// 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 = withoutOldestTurn(fitted.recent_turns); + if (fitted.recent_turns?.length === 0) delete fitted.recent_turns; + return fitted; +} + +// 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; 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..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: [], + waiting: null, task: '', stuckQueries: [], turnHead: null, withheld: [], pendingControls: [], recentTurns: [], answer: '', isTyped: false, title: '', }); const MAX_STUCK_RECALLS_PER_TURN = 2; @@ -18,6 +18,13 @@ const MAX_SHOWN = 50; const MAX_TURN_IDS = 20; +const MAX_RECENT_TURNS = 3; + +// 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. const SETTLING_STALE_MS = 30_000; @@ -27,10 +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. + * 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, @@ -47,6 +55,10 @@ export function openedTurn(session, { turnId = null, turnStart = null, hostTurn labelable: isCommand ? session.labelable : [], waiting: null, task: session.task || (isCommand ? '' : task), + recentTurns: withLastTurnRecent(session), + answer: '', + isTyped: prompt !== null && !isCommand, + title: title || session.title, stuckQueries: [], turnHead: null, withheld: [], @@ -92,13 +104,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. */ @@ -206,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 new file mode 100644 index 00000000..5b02aa50 --- /dev/null +++ b/test/app/recall-context.test.js @@ -0,0 +1,97 @@ +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'; + +const fetchContexts = (requests) => requests.filter(({ path }) => path === '/asset/fetch').map(({ body }) => body.context); + +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(); + 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: '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 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 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.' }); +}); + +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'); +}); 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 a1d73785..b7fa1864 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,57 @@ 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, a prompt with its answer, and the task stays whole', async () => { + const { proxyFetch, calls, searches } = stubProxy({ assets: [] }); + const task = taskTextOf('上传失败后重试'.repeat(600)); + 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'); + } +}); + +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 each earlier prompt then its answer, oldest first, cleaned like a prompt', () => { + assert.deepEqual(recentTurnsOf([]), []); + assert.deepEqual(recentTurnsOf(undefined), []); + 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 () => { const { proxyFetch, calls } = stubProxy({ assets: [ASSET] }); const { ids, text } = await recallStrategy(proxyFetch, 'add a retry to the uploader');