From 637a7ccfc465fd4c0f38e3d1ef4262a9cffb52e5 Mon Sep 17 00:00:00 2001 From: forrestlinfeng Date: Tue, 24 Nov 2026 00:42:50 +0800 Subject: [PATCH 1/4] feat(claude-code): pin the recall's status line, and say what the turn summary actually knows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The relay rewrite (c6520b7) dropped the status line the hooks module kept under the prompt. Since then a turn showed nothing while it recalled, and nothing at all when the recall injected nothing. The turn summary read "✓ Goal reached · reused EvoMap strategy" whenever a strategy had been injected, even when no check ran and the model never used it. Status line (Claude Code): - promptSubmitted returns `traced`, the recall's last trace (absent for a turn nobody typed for). The relay answers turn.start with a "recalling…" status and /late with what the recall decided: injected (name, how many the Hub returned), none fits, none relevant enough or new, too few steps, Proxy did not answer, or arrived after the turn ended. The module pins it with $.ui.status. Turn summary (Claude Code, Codex, Grok, Qoder, MiniMax): - Names each injected strategy with its short asset id. - Says what the last check shows ("no check ran, so its use is unverified" when none ran) instead of "Goal reached". - Says what EvoMap was told, and "without evidence" for a report with no check behind it. - Drops the fresh-token count; a saving is still shown only behind a passing check. Co-Authored-By: Claude Opus 5.5 --- docs/architecture.md | 8 ++- hosts/README.md | 2 +- hosts/claude-code/dist/hooks/register.ts | 16 +++-- hosts/claude-code/profile.js | 2 +- hosts/codex/profile.js | 2 +- hosts/grok/profile.js | 2 +- hosts/minimax/profile.js | 2 +- hosts/qoder/profile.js | 2 +- lib/agent/driver.js | 4 +- lib/app/prompt.js | 16 +++-- lib/channels/relay/server.js | 18 +++-- lib/recall-status.js | 39 +++++++++++ lib/turn-summary.js | 83 +++++++++++++++--------- test/app/recipe-turn.test.js | 2 +- test/channels/relay.test.js | 18 ++++- test/hosts/claude-code/module.test.js | 8 ++- test/hosts/claude-code/profile.test.js | 4 +- test/hosts/codex/hooks.test.js | 2 +- test/hosts/grok/hooks.test.js | 2 +- test/hosts/qoder/hooks.test.js | 2 +- test/recall-status.test.js | 20 ++++++ test/turn-summary.test.js | 71 ++++++++------------ 22 files changed, 212 insertions(+), 113 deletions(-) create mode 100644 lib/recall-status.js create mode 100644 test/recall-status.test.js diff --git a/docs/architecture.md b/docs/architecture.md index 402f4312..10899de9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -198,8 +198,12 @@ functions declared in the module's own file (`claude plugin validate` refuses `$ `bin/relay.mjs claude-code` with `$.process.spawn`, which prints `{ port, token }` once it listens on loopback; the spawn's loop is the relay's life, so the relay ends with the module, and a relay that died is started again by the next event. The module sends each event over `$.http.fetch` with that token, as the profile's host events, and -applies the answers: `$.session.append` for a strategy, `$.ui.toast` for a notice, `{ text, context }` for a -command, `$.prompt.submit` for `/evolver-evolve`, and the turn summary as `turn.complete`'s `{ text }`. Text +applies the answers: `$.session.append` for a strategy, `$.ui.toast` for a notice, `$.ui.status` for the recall's +status line under the prompt (recalling, then what it decided: injected, none fits, none relevant enough, the Proxy +did not answer, or arrived after the turn ended), `{ text, context }` for a command, `$.prompt.submit` for +`/evolver-evolve`, and the turn summary as `turn.complete`'s `{ text }`. The turn summary names each injected +strategy and its asset id, what the turn's last check says of its use (none ran: unverified), what EvoMap was told +(and whether the report carried evidence), and a saving only behind a passing check. Text appended in `turn.start` never reaches the turn's first request, so a recall never waits there: the strategy is appended when it lands, only while its turn is still open (and is then kept out of the session's later recalls), and booked at the turn's next main-loop `turn.step` after the first; a turn that ends first books nothing. In the diff --git a/hosts/README.md b/hosts/README.md index 80fbd6ce..4eee7f64 100644 --- a/hosts/README.md +++ b/hosts/README.md @@ -15,7 +15,7 @@ a channel. | Events | `events: { hostEvent: canonicalEvent }`, onto `sessionStart`, `prompt`, `toolResult`, `beforeEdit`, `turnEnd`, `sessionEnd`, `command`, `agentGene` | — (MCP: its seven tools) | | Payload | `payload: { sessionId, turnId, prompt, projectDir, isIgnored, model, transcriptPath, gene, writtenFor }`, each `(payload, context)`; `context` has `env`, `transcriptSize()`, `transcriptSince(offset)`, and `turnStart` at a turn's end. `isIgnored` skips a subagent's event or any other that is no turn of the person's | Claude Code's field names | | Session start | `sessionStart: 'event' \| 'owner-change' \| 'connection'` | `event` | -| Answer | `reply: { context, notice, empty, command, turnEnd, late?, lifetime: 'turn' \| 'call', strategyAt: 'prompt' \| 'tool-result', toolResultContext }`, each `(value, hostEvent, payload)`; `lifetime: 'call'` replays the turn's strategy before every model call; `late(answer, late)` lets a host that can add context to a running turn take a recall slower than the wait (`late` resolves to `{ text, show, join }`: `show()` while the turn is open, for a host that adds it before a model step carries it; `join()` books it once one does); `strategyAt: 'tool-result'`, for a host whose prompt hook cannot add context, holds the strategy recalled at the prompt for the open turn, unbooked, and `context(strategy, toolEvent)` answers the turn's first tool hook with it, under that tool event's name, booking it then; a turn with no tool call never gets it. Such a host takes no `owner-change` session start and no `late`; `toolResultContext: true` says `context(strategy, toolEvent)` reaches the model from any tool hook, which turns on the recall after a failed check (a `tool-result` host has it already) | `hookSpecificOutput.additionalContext`, `{}`, `strategyAt: 'prompt'`, `toolResultContext: false` | +| Answer | `reply: { context, notice, empty, command, turnEnd, late?, lifetime: 'turn' \| 'call', strategyAt: 'prompt' \| 'tool-result', toolResultContext }`, each `(value, hostEvent, payload)`; `lifetime: 'call'` replays the turn's strategy before every model call; `late(answer, late, hostEvent, payload, traced)` lets a host that can add context to a running turn take a recall slower than the wait (`late` resolves to `{ text, show, join }`: `show()` while the turn is open, for a host that adds it before a model step carries it; `join()` books it once one does; `traced`, absent for a turn nobody typed for, resolves to the recall's last trace, which Claude Code pins as its status line under the prompt); `strategyAt: 'tool-result'`, for a host whose prompt hook cannot add context, holds the strategy recalled at the prompt for the open turn, unbooked, and `context(strategy, toolEvent)` answers the turn's first tool hook with it, under that tool event's name, booking it then; a turn with no tool call never gets it. Such a host takes no `owner-change` session start and no `late`; `toolResultContext: true` says `context(strategy, toolEvent)` reaches the model from any tool hook, which turns on the recall after a failed check (a `tool-result` host has it already) | `hookSpecificOutput.additionalContext`, `{}`, `strategyAt: 'prompt'`, `toolResultContext: false` | | Evidence | `evidence: { toolNote, editedFile \| editedFiles, turnStart?, turnRecord?, source }`: tool notes as hooks see them, or a turn record read from the host's transcript | required | | Turn end | `turnEnd: { reason → 'answer' \| 'aborted' \| 'refusal' \| 'error' \| 'unknown', answer, unclosed: { settleMs, as } }` | every end is `answer`; a turn with no end closes as `error` at the next prompt | | Commands | `commands: { entry: 'intercept' \| 'inline-script' \| 'prompt' \| 'tool' \| 'cli-only', parse, sessionOf?(env), scriptArgs?(text), scriptAnswer?(result, script), answerReachesModel }`; a script runs `bin/command.mjs [args…]`, from a host or a terminal; `answerReachesModel` defaults to true for `inline-script`, `prompt` and `tool` | `cli-only` | diff --git a/hosts/claude-code/dist/hooks/register.ts b/hosts/claude-code/dist/hooks/register.ts index d5d5a8ac..313e00c5 100644 --- a/hosts/claude-code/dist/hooks/register.ts +++ b/hosts/claude-code/dist/hooks/register.ts @@ -8,10 +8,11 @@ import type { EngineInterface, PluginOptions, Register } from 'claude-code' // and runs the model completions the relay asks for, since only the module holds the session's model. type Relay = { url: string; token: string } -type Answer = { append?: string; toast?: string; submit?: string; text?: string; context?: string[]; exitCode?: number; late?: string } +type Answer = { append?: string; toast?: string; submit?: string; text?: string; context?: string[]; exitCode?: number; late?: string; status?: string } type CatalogCommand = { name: string; description: string; hint?: string } type ModelRequest = { id: string; model: string; prompt: string } type Landed = { id: string; text: string } +type LateAnswer = { id?: string; text?: string; status?: string } const AGENT = 'claude-code' const RELAY_START_MS = 15_000 @@ -184,12 +185,14 @@ async function startSession($: EngineInterface, options: PluginOptions): Promise // A recall lands after `turn.start`, whose text never reaches the turn's first request: the strategy is added to the // conversation when it lands, while its turn is open, and booked by the relay at the turn's next main-loop step after -// the first, the first that can carry it. A turn that ends first books nothing. +// the first, the first that can carry it. A turn that ends first books nothing. Whatever the recall decided, injected or +// not, replaces the plugin's status line under the prompt. async function addWhenLanded($: EngineInterface, options: PluginOptions, turnId: string, id: string): Promise { - const landed: Landed | null = await post($, options, '/late', { id }) - if (!landed) return - await appendHidden($, landed.text) - carried.set(turnId, landed) + const answer: LateAnswer | null = await post($, options, '/late', { id }) + if (answer?.status) $.ui.status(answer.status) + if (!answer?.id || !answer.text) return + await appendHidden($, answer.text) + carried.set(turnId, { id: answer.id, text: answer.text }) } async function bookCarried($: EngineInterface, options: PluginOptions, turnId: string): Promise { @@ -201,6 +204,7 @@ async function bookCarried($: EngineInterface, options: PluginOptions, turnId: s async function startTurn($: EngineInterface, options: PluginOptions, e: { text: string; turnId: string }, origin: unknown): Promise { const answer = await raise($, options, 'turn.start', { turn_id: e.turnId, text: e.text, origin }) + if (answer.status) $.ui.status(answer.status) if (answer.append) await appendHidden($, answer.append) if (answer.late) void quietly(addWhenLanded($, options, e.turnId, answer.late)) } diff --git a/hosts/claude-code/profile.js b/hosts/claude-code/profile.js index 8e467c55..d7facfe8 100644 --- a/hosts/claude-code/profile.js +++ b/hosts/claude-code/profile.js @@ -55,7 +55,7 @@ export default defineProfile({ const line = endedTurnSummaryOf(ended, payload); return line ? { text: line } : {}; }, - late: (answer, late) => ({ ...answer, late }), + late: (answer, late, hostEvent, payload, traced) => ({ ...answer, late, ...(traced && { traced }) }), lifetime: 'turn', toolResultContext: true, }, diff --git a/hosts/codex/profile.js b/hosts/codex/profile.js index a30128d6..90aa3fde 100644 --- a/hosts/codex/profile.js +++ b/hosts/codex/profile.js @@ -38,7 +38,7 @@ export default defineProfile({ command: (result) => ({ decision: 'block', reason: result.text }), // Codex shows a Stop hook's systemMessage to the person only. turnEnd: (ended, hostEvent) => { - const line = hostEvent === INTERRUPT ? null : endedTurnSummaryOf(ended, { reason: 'answer' }); + const line = hostEvent === INTERRUPT ? null : endedTurnSummaryOf(ended); return line ? { systemMessage: line } : {}; }, }, diff --git a/hosts/grok/profile.js b/hosts/grok/profile.js index eab4dd2e..c29d0698 100644 --- a/hosts/grok/profile.js +++ b/hosts/grok/profile.js @@ -62,7 +62,7 @@ export default defineProfile({ // A blocked prompt reaches no model and opens no turn; grok shows the reason to the person. command: (result) => ({ decision: 'block', reason: result.text }), turnEnd: (ended, hostEvent) => { - const line = hostEvent === STOP ? endedTurnSummaryOf(ended, { reason: 'answer' }) : null; + const line = hostEvent === STOP ? endedTurnSummaryOf(ended) : null; return line ? { systemMessage: line } : {}; }, }, diff --git a/hosts/minimax/profile.js b/hosts/minimax/profile.js index 9c50b653..2dde74cb 100644 --- a/hosts/minimax/profile.js +++ b/hosts/minimax/profile.js @@ -20,7 +20,7 @@ export default defineProfile({ commands: { entry: 'intercept', parse: promptCommandOf, background: isBackgroundCommand }, reply: { command: result => ({ decision: 'block', reason: result.text, systemMessage: result.text }), - turnEnd: ended => { const line = endedTurnSummaryOf(ended, { reason: 'answer' }); return line ? { systemMessage: line } : {}; }, + turnEnd: ended => { const line = endedTurnSummaryOf(ended); return line ? { systemMessage: line } : {}; }, }, evidence: { toolNote: toolNoteOf, editedFiles: editedFilesOf }, turnEnd: { diff --git a/hosts/qoder/profile.js b/hosts/qoder/profile.js index e661937a..54901a10 100644 --- a/hosts/qoder/profile.js +++ b/hosts/qoder/profile.js @@ -55,7 +55,7 @@ export default defineProfile({ command: (result) => ({ decision: 'block', reason: result.text, systemMessage: result.text }), // Qoder shows a Stop hook's systemMessage to the person only, and ignores what StopFailure and QueryEnd answer. turnEnd: (ended, hostEvent) => { - const line = hostEvent === STOP ? endedTurnSummaryOf(ended, { reason: 'answer' }) : null; + const line = hostEvent === STOP ? endedTurnSummaryOf(ended) : null; return line ? { systemMessage: line } : {}; }, }, diff --git a/lib/agent/driver.js b/lib/agent/driver.js index 945470f0..fdcc5e9a 100644 --- a/lib/agent/driver.js +++ b/lib/agent/driver.js @@ -77,12 +77,12 @@ 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 { turn, sessionEpoch, injection, late, traced, deferred, skipped } = await promptSubmitted(ports, { sessionId, prompt, projectDir, turnId, turnStart, hostTurn, 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 }); const answer = profile.reply.context(joined(notice, await checkpointOf(), injection), hostEvent, payload); - return late ? profile.reply.late(answer, late, hostEvent, payload) : answer; + return late ? profile.reply.late(answer, late, hostEvent, payload, traced) : answer; }, async [EVENTS.TURN_START]({ profile, ports, hostEvent, payload, context, at }) { diff --git a/lib/app/prompt.js b/lib/app/prompt.js index 27802dce..ef169890 100644 --- a/lib/app/prompt.js +++ b/lib/app/prompt.js @@ -134,7 +134,10 @@ async function recalled(ports, sessionId, { turn, prompt, projectDir, waitMs, ke const { request: proxyFetch, signal, cancel } = recallRequestOf(ports.proxy, { timeoutMs }); 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); - const recall = recallStrategy(proxyFetch, promptTextOf(prompt), { context, projectDir, listedIds, onWithheld, closingOf: () => CLOSING, recipeCutoff }); + const text = promptTextOf(prompt); + let lastTrace = null; + const onTrace = (trace) => { lastTrace = trace; }; + const recall = recallStrategy(proxyFetch, text, { context, projectDir, listedIds, onWithheld, onTrace, closingOf: () => CLOSING, recipeCutoff }); const TIMED_OUT = Symbol('timed out'); const match = waitMs > 0 ? await Promise.race([recall, ports.clock.sleep(waitMs, signal).then(() => TIMED_OUT)]) : TIMED_OUT; if (match !== TIMED_OUT || !keepLate) cancel(); @@ -150,7 +153,9 @@ async function recalled(ports, sessionId, { turn, prompt, projectDir, waitMs, ke show: () => shown(ports, sessionId, { turn, ids: landed.ids }), join: async () => (await booked(ports, sessionId, { turn, match: landed, onlyWhileOpen: true })) !== '', } : null)).catch(() => null).finally(cancel); - return { injection: '', late }; + // A turn nobody typed for (a task notification) recalls for nothing, which is no decision to show. + const traced = text ? late.then(() => lastTrace) : null; + return { injection: '', late, ...(traced && { traced }) }; } // The commit a turn begins on is where a range of work turns starting with it takes its diff from, so work it commits @@ -170,7 +175,8 @@ async function rememberTurnHead({ project, sessions }, sessionId, { turn, sessio * it has answered. With `keepLate`, for a host that can add context to a running turn, a slower recall keeps going: * `late` resolves to `{ text, show, join }`. `show()` answers whether the turn is still open and keeps the strategy * out of the session's later recalls, for a host that adds it before a model step carries it; `join()` books it, - * only while the turn is still open, once a model step does. With `holdForToolResult`, for a host whose prompt hook + * only while the turn is still open, once a model step does; `traced` resolves, with it, to the recall's last trace + * (`recallStrategy`'s `onTrace`), or is absent for a turn nobody typed for. With `holdForToolResult`, for a host whose prompt hook * cannot add context, a strategy that lands in time waits for the turn's first tool result instead (see * `takeWaitingStrategy`). A plugin command's turn keeps the last real turn's reuses for the next prompt to label, is * recalled for nothing and never joins the session's range of work turns. `skipped` is the error of a correction or @@ -190,8 +196,8 @@ export async function promptSubmitted(ports, { sessionId, prompt, projectDir = n const wantsRecall = !isCommand && ports.settings?.recall !== false; const recall = wantsRecall ? recalled(ports, sessionId, { turn: opened.turn, prompt, projectDir, waitMs, keepLate, holdForToolResult, lateAtToolResult }) : { injection: '' }; const headRead = isCommand || !projectDir ? null : rememberTurnHead(ports, sessionId, { turn: opened.turn, sessionEpoch: opened.sessionEpoch, projectDir }); - const [{ injection, late, deferred }] = await Promise.all([recall, headRead]); - return { turn: opened.turn, sessionEpoch: opened.sessionEpoch, injection, ...(late && { late }), ...(deferred && { deferred }), ...(skipped && { skipped }) }; + const [{ injection, late, traced, deferred }] = await Promise.all([recall, headRead]); + return { turn: opened.turn, sessionEpoch: opened.sessionEpoch, injection, ...(late && { late }), ...(traced && { traced }), ...(deferred && { deferred }), ...(skipped && { skipped }) }; } /** diff --git a/lib/channels/relay/server.js b/lib/channels/relay/server.js index 29dde677..6c7cc9c2 100644 --- a/lib/channels/relay/server.js +++ b/lib/channels/relay/server.js @@ -6,6 +6,7 @@ import { createServer } from 'node:http'; import { CHANNELS } from '../../agent/events.js'; import { profileNamed } from '../../agent/registry.js'; +import { arrivedLateStatusOf, recallStatusOf, RECALLING_STATUS } from '../../recall-status.js'; import { ownerIsGone } from '../../runtime/process/owner.js'; import { createPluginChannel } from '../plugin/adapter.js'; import { createModelQueue } from './model-queue.js'; @@ -46,6 +47,7 @@ const reply = (response, status, value) => response.writeHead(status, { 'Content // A recall slower than the prompt's wait answers later: the module asks for it by id, and gets it only while its turn // is still open, then joins it to the turn once a model step carries it, which books it only while that turn is open. +// The answer carries the status line of what the recall decided, also when it brought nothing to add. function lateBook() { const entries = new Map(); const remember = (value) => { @@ -55,12 +57,16 @@ function lateBook() { return id; }; return { - held: (late) => remember({ late }), + held: (late, traced) => remember({ late, traced }), async landed(id) { - const landed = await entries.get(id)?.late; + const entry = entries.get(id); + const landed = await entry?.late; + const trace = await entry?.traced; entries.delete(id); - if (!landed || !(await landed.show())) return null; - return { id: remember({ join: landed.join }), text: landed.text }; + const status = trace ? recallStatusOf(trace) : null; + if (!landed) return status ? { status } : null; + if (!(await landed.show())) return { status: arrivedLateStatusOf(trace?.name) }; + return { id: remember({ join: landed.join }), text: landed.text, ...(status && { status }) }; }, async joined(id) { const join = entries.get(id)?.join; @@ -82,8 +88,8 @@ export function createRelay({ profile, env = process.env, token = randomBytes(24 const lates = lateBook(); const routes = { '/event': async ({ hostEvent, payload }) => { - const { late, ...answer } = await channel.handle(hostEvent, payload); - return late ? { ...answer, late: lates.held(late) } : answer; + const { late, traced, ...answer } = await channel.handle(hostEvent, payload); + return late ? { ...answer, late: lates.held(late, traced), ...(traced && { status: RECALLING_STATUS }) } : answer; }, '/late': ({ id }) => lates.landed(id), '/late/join': ({ id }) => lates.joined(id), diff --git a/lib/recall-status.js b/lib/recall-status.js new file mode 100644 index 00000000..f0913402 --- /dev/null +++ b/lib/recall-status.js @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 EvoMap + +// The one line a host pins under its prompt while a turn runs: what the recall for that turn decided, including the +// recalls that injected nothing, so a quiet turn is told apart from one that never recalled. + +const NAME_MAX_CHARS = 48; +const PREFIX = 'evolver ·'; + +const quoted = (name) => `"${String(name ?? 'EvoMap strategy').slice(0, NAME_MAX_CHARS)}"`; + +export const RECALLING_STATUS = `${PREFIX} recalling an EvoMap strategy for this prompt…`; + +function skippedStatusOf({ recalled, eligible }) { + if (!recalled) return `${PREFIX} no EvoMap strategy fits this prompt`; + const why = eligible ? 'none has enough steps to follow' : 'none is relevant enough or new to this session'; + return `${PREFIX} none injected: the Hub returned ${recalled}, ${why}`; +} + +/** The status line for a recall's last trace (`recallStrategy`'s `onTrace`), or null for one it does not describe. */ +export function recallStatusOf(trace) { + switch (trace?.outcome) { + case 'injected': + return trace.kind === 'recipe' + ? `${PREFIX} injected Recipe ${quoted(trace.name)} (${trace.steps} steps)` + : `${PREFIX} injected ${quoted(trace.name)} (the Hub returned ${trace.recalled})`; + case 'skipped': + return skippedStatusOf(trace); + case 'unavailable': + return `${PREFIX} recall skipped: the Evolver Proxy did not answer (/evolver-status)`; + case 'short': + return `${PREFIX} prompt too short to recall for`; + default: + return null; + } +} + +/** The status line for a strategy that landed once its turn had ended, so it was never added. */ +export const arrivedLateStatusOf = (name) => `${PREFIX} ${quoted(name)} arrived after this turn ended, not injected`; diff --git a/lib/turn-summary.js b/lib/turn-summary.js index e4e802c3..7a0891c7 100644 --- a/lib/turn-summary.js +++ b/lib/turn-summary.js @@ -3,9 +3,10 @@ import { verdictOf } from './checks.js'; import { referenceReuseSavings, usdOf } from './savings.js'; -import { outcomeOfReason } from './turn-outcomes.js'; const NAME_MAX_CHARS = 48; +const ASSET_ID_HEX_CHARS = 8; +const NO_EVIDENCE_TIER = 'none'; function compactTokens(tokens) { if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`; @@ -23,54 +24,74 @@ function freshTokens(usage) { return counted.length === 0 ? null : counted.reduce((sum, value) => sum + value, 0); } -function goalPart({ lastCheck, turnReason }) { - if (!lastCheck) return outcomeOfReason(turnReason) === 'success' ? '✓ Goal reached' : null; +const shortIdOf = (assetId) => { + const match = /^sha256:([0-9a-f]+)$/.exec(String(assetId ?? '')); + return match ? `sha256:${match[1].slice(0, ASSET_ID_HEX_CHARS)}` : null; +}; + +function strategyLabelOf({ name, assetId }) { + const shortId = shortIdOf(assetId); + return `"${String(name).slice(0, NAME_MAX_CHARS)}"${shortId ? ` (${shortId})` : ''}`; +} + +function injectedPart(reused) { + const labels = reused.map(strategyLabelOf).join(', '); + return reused.length === 1 ? `Evolver · injected ${labels}` : `Evolver · injected ${reused.length} strategies: ${labels}`; +} + +// What the turn's last check says of the injected strategy's use. Without one, nothing shows the strategy helped. +function checkPart(lastCheck) { + if (!lastCheck) return 'no check ran, so its use is unverified'; const label = lastCheck.label || lastCheck.command; const verdict = verdictOf(lastCheck); - if (verdict === 'unknown') return `? Goal unverified (last check result unknown: ${label})`; - return verdict === 'failed' - ? `✗ Goal not reached (last check failed: ${label})` - : `✓ Goal reached (last check passed: ${label})`; + if (verdict === 'unknown') return `? last check result unknown: ${label}`; + return verdict === 'failed' ? `✗ last check failed: ${label}` : `✓ last check passed: ${label}`; +} + +// What EvoMap was told, as the queued reports say it: a report with no check behind it carries no evidence. +function reportedPart(reused) { + const reports = reused.filter((strategy) => strategy.outcome); + if (reports.length === 0) return null; + const outcomes = [...new Set(reports.map((report) => report.outcome))].join('/'); + const isUnevidenced = reports.every((report) => report.tier === NO_EVIDENCE_TIER); + return `reported to EvoMap as ${outcomes}${isUnevidenced ? ' without evidence' : ''}`; } // A saving is claimed only for a reuse a passing check vouched for, and never // above what the turn itself spent: the estimator prices deriving a whole // approach from scratch, which a single answered question never cost. -function savingOf({ lastCheck, changedLines, usage }) { +function savedPart({ lastCheck, changedLines, usage }) { const used = freshTokens(usage); if (verdictOf(lastCheck) !== 'passed' || used === null) return null; - return Math.min(referenceReuseSavings(changedLines).tokens, used); -} - -function savedPart(turn) { - const saved = savingOf(turn); - return saved === null ? null : `est. ~${compactTokens(saved)} tokens saved (≈$${usdOf(saved).toFixed(2)})`; -} - -function usedPart(usage) { - const used = freshTokens(usage); - return used === null ? null : `this turn used ${compactTokens(used)} fresh tokens`; + const saved = Math.min(referenceReuseSavings(changedLines).tokens, used); + return `est. ~${compactTokens(saved)} tokens saved (≈$${usdOf(saved).toFixed(2)})`; } -// One line, shown only for a turn that reused a strategy: the desktop draws it -// as a notice that renders no line breaks. It says whether the goal was -// reached, judged by the last check as the reuse report is, and what the reuse -// is estimated to have saved; a part with nothing to say is left out. -export function turnSummaryOf(turn) { - if (!turn?.reusedNames?.length) return null; - const names = turn.reusedNames.map((name) => `"${String(name).slice(0, NAME_MAX_CHARS)}"`).join(', '); - return [goalPart(turn), `reused EvoMap strategy ${names}`, savedPart(turn), usedPart(turn.usage)].filter(Boolean).join(' · '); +/** + * One line, shown only for a turn a strategy was injected into: the desktop draws it as a notice that renders no + * line breaks. It names each strategy and its asset id, what the last check says of its use, what EvoMap was told, + * and, only behind a passing check, the estimated saving. `reused` holds `{ name, assetId?, outcome?, tier? }`. + */ +export function turnSummaryOf({ reused = [], lastCheck, changedLines = 0, usage } = {}) { + if (reused.length === 0) return null; + return [injectedPart(reused), checkPart(lastCheck), reportedPart(reused), savedPart({ lastCheck, changedLines, usage })] + .filter(Boolean).join(' · '); } const STRATEGY_NAME = /^\[Evolution Memory\] (.+?) \(EvoMap network\):/; const strategyNameOf = (strategy) => STRATEGY_NAME.exec(String(strategy ?? ''))?.[1] ?? 'EvoMap strategy'; -/** The summary of a turn as it ended (`turnEnded`'s answer: its record and the strategies it reported), or null. */ -export function endedTurnSummaryOf({ record, strategies }, { reason, usage } = {}) { +/** + * The summary of a turn as it ended (`turnEnded`'s answer: its record, the strategies it reported and their reports, + * in the same order), or null. + */ +export function endedTurnSummaryOf({ record, strategies, reports }, { usage } = {}) { return turnSummaryOf({ - reusedNames: (strategies ?? []).map(strategyNameOf), + reused: (strategies ?? []).map((strategy, index) => { + const report = reports?.[index]; + return { name: strategyNameOf(strategy), assetId: report?.asset_id, outcome: report?.outcome, tier: report?.evidence?.tier }; + }), lastCheck: record?.checks?.at(-1), - turnReason: reason, changedLines: record?.changedLines ?? 0, usage, }); diff --git a/test/app/recipe-turn.test.js b/test/app/recipe-turn.test.js index 7af671f9..b0c3e750 100644 --- a/test/app/recipe-turn.test.js +++ b/test/app/recipe-turn.test.js @@ -33,7 +33,7 @@ test('each step of a Recipe is reported on its own under the turn\'s task id, an await toolFinished(ports, { sessionId: 's1', note: { kind: 'shell', command: 'npm test', exit: 0, output: 'ℹ pass 3\nℹ fail 0' } }); const ended = await end(ports); assert.deepEqual(ended.reports.map((report) => [report.asset_id, report.task_id, report.outcome]), STEP_IDS.map((id) => [id, 'testagent:s1:1', 'success'])); - assert.match(endedTurnSummaryOf(ended, { reason: 'answer' }), /reused EvoMap strategy "Unbound redis retries", "Close the redis client"/); + assert.match(endedTurnSummaryOf(ended), /injected 2 strategies: "Unbound redis retries", "Close the redis client" · ✓ last check passed: npm test · reported to EvoMap as success$/); await promptSubmitted(ports, { sessionId: 's1', prompt: '还是报错', ...WAIT }); const corrections = queued.filter(({ report }) => report.task_id.endsWith(':correction')); assert.deepEqual(corrections.map(({ report }) => [report.asset_id, report.outcome]), STEP_IDS.map((id) => [id, 'failed'])); diff --git a/test/channels/relay.test.js b/test/channels/relay.test.js index d2d7e6c9..6ac39f03 100644 --- a/test/channels/relay.test.js +++ b/test/channels/relay.test.js @@ -11,8 +11,8 @@ import { fakeProxy } from '../helpers/fake-proxy.js'; const RELAY = fileURLToPath(new URL('../../bin/relay.mjs', import.meta.url)); -async function started(t, { delays } = {}) { - const proxy = await fakeProxy({ delays }); +async function started(t, { delays, assets } = {}) { + const proxy = await fakeProxy({ delays, ...(assets && { assets }) }); const relay = createRelay({ profile: claudeCode, env: proxy.env }); const port = await relay.listen(); t.after(() => { @@ -40,13 +40,27 @@ test('a turn\'s recall answers later, by id; the strategy is joined to its turn const turn = { session_id: 's1', cwd: '/proj', turn_id: 't1', text: PROMPT, origin: { kind: 'composer' } }; const { body: answer } = await post('/event', { hostEvent: 'turn.start', payload: turn }); assert.equal(answer.append, undefined); + assert.equal(answer.status, 'evolver · recalling an EvoMap strategy for this prompt…'); const { body: landed } = await post('/late', { id: answer.late }); assert.match(landed.text, /^\[Evolution Memory\] Fix flaky Redis connection retries/); + assert.match(landed.status, /^evolver · injected "Fix flaky Redis connection retries" \(the Hub returned \d+\)$/); assert.deepEqual((await post('/late/join', { id: landed.id })).body, { joined: true }); assert.deepEqual((await post('/late/join', { id: landed.id })).body, { joined: false }); assert.deepEqual((await post('/event', { hostEvent: 'no.such.event', payload: turn })).body, {}); }); +test('a recall that injects nothing still answers what it decided; a turn nobody typed for sets no status', async (t) => { + const { post } = await started(t, { assets: [] }); + const typed = { session_id: 's2', cwd: '/proj', turn_id: 't1', text: 'translate the release notes into Japanese please', origin: { kind: 'composer' } }; + const { body: answer } = await post('/event', { hostEvent: 'turn.start', payload: typed }); + const { body: late } = await post('/late', { id: answer.late }); + assert.deepEqual(late, { status: 'evolver · no EvoMap strategy fits this prompt' }); + const notification = { session_id: 's2', cwd: '/proj', turn_id: 't2', text: 'done', origin: { kind: 'task-notification' } }; + const { body: quiet } = await post('/event', { hostEvent: 'turn.start', payload: notification }); + assert.equal(quiet.status, undefined); + if (quiet.late) assert.equal((await post('/late', { id: quiet.late })).body, null); +}); + test('a model request waits for the module, which answers it by id; an abandoned one is withdrawn', async () => { const queue = createModelQueue(); const completion = queue.port.complete('claude-haiku-5-5', 'distill this', new AbortController().signal); diff --git a/test/hosts/claude-code/module.test.js b/test/hosts/claude-code/module.test.js index 8a8e7ab2..cb99d0c2 100644 --- a/test/hosts/claude-code/module.test.js +++ b/test/hosts/claude-code/module.test.js @@ -64,7 +64,7 @@ async function session(t, { options = { node_path: process.execPath }, spawnOf, proxy.close(); rmSync(project, { recursive: true, force: true }); }); - const seen = { appended: [], toasts: [], submitted: [], commands: [], completions: [] }; + const seen = { appended: [], toasts: [], submitted: [], commands: [], completions: [], statuses: [] }; const $ = { plugin: { name: 'evolver-plugin', root }, session: { @@ -97,7 +97,7 @@ async function session(t, { options = { node_path: process.execPath }, spawnOf, } }, command: { register: async (spec) => { seen.commands.push(spec); } }, prompt: { submit: async ({ text }) => { seen.submitted.push(text); } }, - ui: { toast: (text) => { seen.toasts.push(text); } }, + ui: { toast: (text) => { seen.toasts.push(text); }, status: (text) => { seen.statuses.push(text); } }, }; loads += 1; const { register } = await import(`${pathToFileURL(join(root, 'hooks', 'register.mjs')).href}?load=${loads}`); @@ -156,7 +156,9 @@ test('a session starts the relay, registers the commands, and a whole turn is re const ended = await verifiedTurn(cc); assert.match(cc.seen.appended[0], /^\[Evolution Memory\] Fix flaky Redis connection retries[\s\S]*Apply them where they fit\.$/); - assert.match(ended.text, /^✓ Goal reached \(last check passed: Run the tests\) · reused EvoMap strategy "Fix flaky Redis connection retries"/); + assert.equal(cc.seen.statuses[0], 'evolver · recalling an EvoMap strategy for this prompt…'); + assert.match(cc.seen.statuses.at(-1), /^evolver · injected "Fix flaky Redis connection retries"/); + assert.match(ended.text, /^Evolver · injected "Fix flaky Redis connection retries" \(sha256:aaaaaaaa\) · ✓ last check passed: Run the tests · reported to EvoMap as success/); const state = join(cc.proxy.env.HOME, '.evolver', 'state'); const [sessionFile] = readdirSync(state).filter((name) => /^claude-code-session-.*\.json$/.test(name)); assert.equal(JSON.parse(readFileSync(join(state, sessionFile), 'utf8')).pid, process.pid, 'the session belongs to Claude Code, the relay\'s parent'); diff --git a/test/hosts/claude-code/profile.test.js b/test/hosts/claude-code/profile.test.js index 1d1333b6..85b54ef5 100644 --- a/test/hosts/claude-code/profile.test.js +++ b/test/hosts/claude-code/profile.test.js @@ -72,8 +72,8 @@ test('a turn that reused a strategy ends with the one-line summary; any other tu const strategies = ['[Evolution Memory] Fix flaky Redis connection retries (EvoMap network):\n1. a.']; const record = { checks: [{ command: 'npm test', failed: false, label: 'Run the tests' }], changedLines: 12 }; const line = summaryLineOf({ strategies, record }, { reason: 'answer', usage: { input_tokens: 1_000, output_tokens: 500 } }); - assert.match(line, /^✓ Goal reached \(last check passed: Run the tests\) · reused EvoMap strategy "Fix flaky Redis connection retries"/); - assert.equal(summaryLineOf({ strategies, record: { checks: [] } }, { reason: 'answer' }), '✓ Goal reached · reused EvoMap strategy "Fix flaky Redis connection retries"'); + assert.match(line, /^Evolver · injected "Fix flaky Redis connection retries" · ✓ last check passed: Run the tests/); + assert.equal(summaryLineOf({ strategies, record: { checks: [] } }), 'Evolver · injected "Fix flaky Redis connection retries" · no check ran, so its use is unverified'); assert.deepEqual(profile.reply.turnEnd({ strategies: [], record: { checks: [] } }, 'turn.complete', {}), {}); }); diff --git a/test/hosts/codex/hooks.test.js b/test/hosts/codex/hooks.test.js index 03f836e1..f66b6d3c 100644 --- a/test/hosts/codex/hooks.test.js +++ b/test/hosts/codex/hooks.test.js @@ -153,7 +153,7 @@ test('a whole turn through the packed hooks: the strategy rides the prompt, the assert.deepEqual(await s.patch(), {}); assert.deepEqual(await s.bash('npm test 2>&1 | tail -5', PASSED_RUN), {}); assert.deepEqual(await s.stop('Retries fixed: maxRetriesPerRequest is null and npm test passes.'), { - systemMessage: `✓ Goal reached (last check passed: npm test 2>&1 | tail -5) · reused EvoMap strategy "${ASSET.short_title}"`, + systemMessage: `Evolver · injected "${ASSET.short_title}" (sha256:aaaaaaaa) · ✓ last check passed: npm test 2>&1 | tail -5 · reported to EvoMap as success`, }); assert.deepEqual(await waitFor(() => reportOf('codex:s-turn:1')), { diff --git a/test/hosts/grok/hooks.test.js b/test/hosts/grok/hooks.test.js index 4be4a96d..556de85a 100644 --- a/test/hosts/grok/hooks.test.js +++ b/test/hosts/grok/hooks.test.js @@ -150,7 +150,7 @@ test('a whole turn through the packed hooks: the strategy reaches the first tool assert.deepEqual(await s.edit(), {}, 'only the first tool result carries it'); assert.deepEqual((await s.bash('npm test 2>&1 | tail -5', PASSED_RUN)).answer, {}); assert.deepEqual(await s.stop('Retries fixed: maxRetriesPerRequest is null and npm test passes.'), { - systemMessage: `✓ Goal reached (last check passed: npm test 2>&1 | tail -5) · reused EvoMap strategy "${ASSET.short_title}"`, + systemMessage: `Evolver · injected "${ASSET.short_title}" (sha256:aaaaaaaa) · ✓ last check passed: npm test 2>&1 | tail -5 · reported to EvoMap as success`, }); assert.deepEqual(await waitFor(() => reportOf('grok:s-turn:1')), { asset_id: ASSET.asset_id, diff --git a/test/hosts/qoder/hooks.test.js b/test/hosts/qoder/hooks.test.js index dae604f4..42aaa521 100644 --- a/test/hosts/qoder/hooks.test.js +++ b/test/hosts/qoder/hooks.test.js @@ -145,7 +145,7 @@ test('a whole turn through the packed hooks: the strategy rides the prompt, the assert.deepEqual(await s.edit(), {}); assert.deepEqual(await s.passing('npm test 2>&1 | tail -5'), {}); const summary = await s.stop('Retries fixed: maxRetriesPerRequest is null and npm test passes.'); - assert.match(summary.systemMessage, new RegExp(`^✓ Goal reached \\(last check passed: npm test 2>&1 \\| tail -5\\) · reused EvoMap strategy "${ASSET.short_title}"`)); + assert.match(summary.systemMessage, new RegExp(`^Evolver · injected "${ASSET.short_title}" \\(sha256:aaaaaaaa\\) · ✓ last check passed: npm test 2>&1 \\| tail -5 · reported to EvoMap as success`)); assert.deepEqual(await waitFor(() => reportOf('qoder:s-turn:1')), { asset_id: ASSET.asset_id, diff --git a/test/recall-status.test.js b/test/recall-status.test.js new file mode 100644 index 00000000..36865c5f --- /dev/null +++ b/test/recall-status.test.js @@ -0,0 +1,20 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { arrivedLateStatusOf, recallStatusOf } from '../lib/recall-status.js'; + +test('each recall decision has its own status line, injected or not', () => { + assert.equal(recallStatusOf({ outcome: 'injected', recalled: 2, eligible: 2, name: 'Fix flaky Redis retries' }), 'evolver · injected "Fix flaky Redis retries" (the Hub returned 2)'); + assert.equal(recallStatusOf({ outcome: 'injected', kind: 'recipe', name: 'Redis pipeline', steps: 3 }), 'evolver · injected Recipe "Redis pipeline" (3 steps)'); + assert.equal(recallStatusOf({ outcome: 'skipped', recalled: 0, eligible: 0 }), 'evolver · no EvoMap strategy fits this prompt'); + assert.equal(recallStatusOf({ outcome: 'skipped', recalled: 2, eligible: 0 }), 'evolver · none injected: the Hub returned 2, none is relevant enough or new to this session'); + assert.equal(recallStatusOf({ outcome: 'skipped', recalled: 2, eligible: 1 }), 'evolver · none injected: the Hub returned 2, none has enough steps to follow'); + assert.equal(recallStatusOf({ outcome: 'unavailable' }), 'evolver · recall skipped: the Evolver Proxy did not answer (/evolver-status)'); + assert.equal(recallStatusOf({ outcome: 'short' }), 'evolver · prompt too short to recall for'); +}); + +test('a trace it does not describe has no line, and a long name is cut', () => { + assert.equal(recallStatusOf(null), null); + assert.equal(recallStatusOf({ outcome: 'passed_over' }), null); + assert.equal(arrivedLateStatusOf('x'.repeat(80)), `evolver · "${'x'.repeat(48)}" arrived after this turn ended, not injected`); +}); diff --git a/test/turn-summary.test.js b/test/turn-summary.test.js index 538e2c82..7aad581d 100644 --- a/test/turn-summary.test.js +++ b/test/turn-summary.test.js @@ -12,70 +12,53 @@ test('savings follow evolver-core savingsCore 0.3.0 for a reference reuse', () = assert.equal(referenceReuseSavings(10_000).tokens, 240_000); }); -test('a turn that reused nothing shows nothing', () => { - assert.equal(turnSummaryOf({ reusedNames: [], lastCheck: { command: 'npm test', failed: false } }), null); -}); - -test('a passing check vouches for a saving, never above what the turn spent', () => { - assert.equal( - turnSummaryOf({ reusedNames: ['Redis connection pool tuning'], lastCheck: { command: 'npm test', failed: false }, changedLines: 30, usage: USAGE }), - '✓ Goal reached (last check passed: npm test) · reused EvoMap strategy "Redis connection pool tuning" · est. ~6k tokens saved (≈$0.05) · this turn used 6k fresh tokens', - ); -}); +const POOL = { name: 'Redis connection pool tuning', assetId: `sha256:5f1fdc60${'a'.repeat(56)}`, outcome: 'success', tier: 'L1' }; +const PASSED = { command: 'npm test', failed: false }; -test('a saving under the turn\'s own spend is the estimator\'s figure', () => { - const heavy = { input_tokens: 90_000, output_tokens: 10_000, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 }; - assert.match( - turnSummaryOf({ reusedNames: ['Redis pool'], lastCheck: { command: 'npm test', failed: false }, changedLines: 30, usage: heavy }), - /est\. ~58k tokens saved \(≈\$0\.52\) · this turn used 100k fresh tokens$/, - ); +test('a turn nothing was injected into shows nothing', () => { + assert.equal(turnSummaryOf({ reused: [], lastCheck: PASSED }), null); }); -test('a failed check counts no saving, and the summary leaves the saving out', () => { +test('a passing check names the strategy, its asset id, what EvoMap was told and a saving never above the turn\'s spend', () => { assert.equal( - turnSummaryOf({ reusedNames: ['Redis pool'], lastCheck: { command: 'npm test', failed: true }, turnReason: 'answer', changedLines: 30, usage: USAGE }), - '✗ Goal not reached (last check failed: npm test) · reused EvoMap strategy "Redis pool" · this turn used 6k fresh tokens', + turnSummaryOf({ reused: [POOL], lastCheck: PASSED, changedLines: 30, usage: USAGE }), + 'Evolver · injected "Redis connection pool tuning" (sha256:5f1fdc60) · ✓ last check passed: npm test · reported to EvoMap as success · est. ~6k tokens saved (≈$0.05)', ); + const heavy = { input_tokens: 90_000, output_tokens: 10_000, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 }; + assert.match(turnSummaryOf({ reused: [POOL], lastCheck: PASSED, changedLines: 30, usage: heavy }), /est\. ~58k tokens saved \(≈\$0\.52\)$/); }); -test('a turn that ran no check and ended normally reached its goal, with no saving claimed', () => { +test('a failed check claims no saving and says EvoMap was told it failed', () => { assert.equal( - turnSummaryOf({ reusedNames: ['Redis pool'], turnReason: 'answer', changedLines: 0, usage: USAGE }), - '✓ Goal reached · reused EvoMap strategy "Redis pool" · this turn used 6k fresh tokens', + turnSummaryOf({ reused: [{ ...POOL, outcome: 'failed' }], lastCheck: { command: 'npm test', failed: true }, changedLines: 30, usage: USAGE }), + 'Evolver · injected "Redis connection pool tuning" (sha256:5f1fdc60) · ✗ last check failed: npm test · reported to EvoMap as failed', ); }); -test('a turn that ran no check and did not end normally says nothing about the goal', () => { - for (const turnReason of ['aborted', 'error', 'refusal', undefined]) { - assert.equal( - turnSummaryOf({ reusedNames: ['Redis pool'], turnReason, usage: USAGE }), - 'reused EvoMap strategy "Redis pool" · this turn used 6k fresh tokens', - String(turnReason), - ); - } +test('a turn with no check says its use is unverified and that the report carried no evidence, never that a goal was reached', () => { + const line = turnSummaryOf({ reused: [{ ...POOL, tier: 'none' }], changedLines: 0, usage: USAGE }); + assert.equal(line, 'Evolver · injected "Redis connection pool tuning" (sha256:5f1fdc60) · no check ran, so its use is unverified · reported to EvoMap as success without evidence'); + assert.doesNotMatch(line, /Goal reached|tokens saved|fresh tokens/); }); -test('a turn whose usage is unknown counts no saving and states no usage', () => { +test('an unknown last check claims no saving', () => { assert.equal( - turnSummaryOf({ reusedNames: ['Redis pool'], lastCheck: { command: 'npm test', failed: false }, changedLines: 10 }), - '✓ Goal reached (last check passed: npm test) · reused EvoMap strategy "Redis pool"', + turnSummaryOf({ reused: [{ ...POOL, outcome: 'failed', tier: 'none' }], lastCheck: { command: 'npm test', failed: null }, changedLines: 30, usage: USAGE }), + 'Evolver · injected "Redis connection pool tuning" (sha256:5f1fdc60) · ? last check result unknown: npm test · reported to EvoMap as failed without evidence', ); }); -test('an unknown last check claims neither a reached goal nor a saving', () => { - assert.equal( - turnSummaryOf({ reusedNames: ['Redis pool'], lastCheck: { command: 'npm test', failed: null }, turnReason: 'answer', changedLines: 30, usage: USAGE }), - '? Goal unverified (last check result unknown: npm test) · reused EvoMap strategy "Redis pool" · this turn used 6k fresh tokens', - ); +test('a strategy with no report or asset id is still named, with no claim about what EvoMap was told', () => { + assert.equal(turnSummaryOf({ reused: [{ name: 'Redis pool' }], lastCheck: PASSED }), 'Evolver · injected "Redis pool" · ✓ last check passed: npm test'); }); -test('the summary is one line, since the desktop notice renders no line breaks', () => { - const summary = turnSummaryOf({ reusedNames: ['Redis pool'], lastCheck: { command: 'npm test', failed: false }, usage: USAGE }); - assert.equal(summary.includes('\n'), false); +test('a Recipe\'s steps are counted and each named', () => { + const steps = [{ ...POOL, name: 'Unbound redis retries' }, { ...POOL, name: 'Close the redis client', assetId: `sha256:${'b'.repeat(64)}` }]; + assert.match(turnSummaryOf({ reused: steps, lastCheck: PASSED }), /^Evolver · injected 2 strategies: "Unbound redis retries" \(sha256:5f1fdc60\), "Close the redis client" \(sha256:bbbbbbbb\) · /); }); -test('the goal names the check by its label, so a multi-line script never reaches the one-line notice', () => { - const summary = turnSummaryOf({ reusedNames: ['Redis pool'], lastCheck: { command: "python3 - <<'EOF'\nassert ok\nEOF", label: 'Check the README edits', failed: false }, changedLines: 10 }); - assert.match(summary, /^✓ Goal reached \(last check passed: Check the README edits\) · /); +test('the summary is one line, naming the check by its label, since the desktop notice renders no line breaks', () => { + const summary = turnSummaryOf({ reused: [POOL], lastCheck: { command: "python3 - <<'EOF'\nassert ok\nEOF", label: 'Check the README edits', failed: false }, changedLines: 10 }); + assert.match(summary, /· ✓ last check passed: Check the README edits ·/); assert.doesNotMatch(summary, /\n/); }); From 3263f7fb9e95fe7597cf010d2cc67d8822a81625 Mon Sep 17 00:00:00 2001 From: forrestlinfeng Date: Tue, 24 Nov 2026 01:07:03 +0800 Subject: [PATCH 2/4] fix(claude-code): only the running turn writes the status line, and a recall that cannot answer settles it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A recall that answered once a later turn had started (its own turn ended first, or its /late answer was slow) overwrote the later turn's line with its result. The module now keeps the id of the turn that runs, and a late answer writes the line only for that turn. - A turn that showed "recalling…" stayed on it when /late failed or the relay restarted between requests. Its line now settles on "recall did not finish for this prompt". Turns that showed no status (task notifications) are left alone. Co-Authored-By: Claude Opus 5.5 --- hosts/claude-code/dist/hooks/register.ts | 22 ++++++++++---- test/hosts/claude-code/module.test.js | 37 ++++++++++++++++++++++-- 2 files changed, 50 insertions(+), 9 deletions(-) diff --git a/hosts/claude-code/dist/hooks/register.ts b/hosts/claude-code/dist/hooks/register.ts index 313e00c5..be6d6ad2 100644 --- a/hosts/claude-code/dist/hooks/register.ts +++ b/hosts/claude-code/dist/hooks/register.ts @@ -24,7 +24,11 @@ const MODEL_MAX_TOKENS = 4_096 const MODEL_TIMEOUT_MS = 120_000 const MAX_PENDING_PROMPTS = 32 const UNKNOWN_ORIGIN = { kind: 'unknown' } +const RECALL_UNFINISHED_STATUS = 'evolver · recall did not finish for this prompt' +// The status line is one per plugin, so only the turn that runs now may write it: a recall that answers once a later +// turn has started describes a turn nobody is looking at. +let statusTurnId: string | null = null let relay: Promise | null = null let current: Relay | null = null let failedStarts = 0 @@ -186,10 +190,15 @@ async function startSession($: EngineInterface, options: PluginOptions): Promise // A recall lands after `turn.start`, whose text never reaches the turn's first request: the strategy is added to the // conversation when it lands, while its turn is open, and booked by the relay at the turn's next main-loop step after // the first, the first that can carry it. A turn that ends first books nothing. Whatever the recall decided, injected or -// not, replaces the plugin's status line under the prompt. -async function addWhenLanded($: EngineInterface, options: PluginOptions, turnId: string, id: string): Promise { - const answer: LateAnswer | null = await post($, options, '/late', { id }) - if (answer?.status) $.ui.status(answer.status) +// not, replaces the plugin's status line under the prompt while its turn is the one running. A turn that showed it was +// recalling always settles: a recall the relay could not answer (it failed or restarted) says it did not finish. +async function addWhenLanded($: EngineInterface, options: PluginOptions, turnId: string, id: string, showsStatus: boolean): Promise { + let answer: LateAnswer | null = null + try { + answer = await post($, options, '/late', { id }) + } finally { + if (showsStatus && turnId === statusTurnId) $.ui.status(answer?.status ?? RECALL_UNFINISHED_STATUS) + } if (!answer?.id || !answer.text) return await appendHidden($, answer.text) carried.set(turnId, { id: answer.id, text: answer.text }) @@ -203,10 +212,11 @@ async function bookCarried($: EngineInterface, options: PluginOptions, turnId: s } async function startTurn($: EngineInterface, options: PluginOptions, e: { text: string; turnId: string }, origin: unknown): Promise { + statusTurnId = e.turnId const answer = await raise($, options, 'turn.start', { turn_id: e.turnId, text: e.text, origin }) - if (answer.status) $.ui.status(answer.status) + if (answer.status && e.turnId === statusTurnId) $.ui.status(answer.status) if (answer.append) await appendHidden($, answer.append) - if (answer.late) void quietly(addWhenLanded($, options, e.turnId, answer.late)) + if (answer.late) void quietly(addWhenLanded($, options, e.turnId, answer.late, Boolean(answer.status))) } function rememberOrigin(text: string, origin: unknown): void { diff --git a/test/hosts/claude-code/module.test.js b/test/hosts/claude-code/module.test.js index cb99d0c2..8c9078d4 100644 --- a/test/hosts/claude-code/module.test.js +++ b/test/hosts/claude-code/module.test.js @@ -53,7 +53,7 @@ function streamOf(child) { } /** A Claude Code session over the packed module: `call(event, input, ran)` raises a hook as the engine does. */ -async function session(t, { options = { node_path: process.execPath }, spawnOf, delays, assets } = {}) { +async function session(t, { options = { node_path: process.execPath }, spawnOf, delays, assets, late } = {}) { const proxy = await fakeProxy({ distillAnswer: DRAFTED, delays, ...(assets && { assets }) }); const project = realpathSync(mkdtempSync(join(tmpdir(), 'evolver-claude-code-project-'))); mkdirSync(join(project, 'lib')); @@ -76,8 +76,11 @@ async function session(t, { options = { node_path: process.execPath }, spawnOf, fs: { stat: async (path) => ({ realPath: path }), read: async (path) => readFileSync(path, 'utf8') }, http: { fetch: async (url, init) => { - const response = await fetch(url, init); - return { ok: response.ok, status: response.status, text: await response.text() }; + const real = async () => { + const response = await fetch(url, init); + return { ok: response.ok, status: response.status, text: await response.text() }; + }; + return late && String(url).endsWith('/late') ? late(real) : real(); }, }, clock: { now: async () => Date.now(), sleep: (ms, { signal } = {}) => new Promise((resolve, reject) => { @@ -308,3 +311,31 @@ test('a failed check recalls for its output and hands the strategy to the model project_dir: cc.project, }); }); + +test('a recall that answers once a later turn has started leaves that turn\'s status line alone', async (t) => { + let release; + const held = new Promise((resolve) => { release = resolve; }); + let lates = 0; + const cc = await session(t, { late: async (real) => { lates += 1; if (lates === 1) await held; return real(); } }); + await cc.call('session.start'); + await cc.call('prompt.submit', { ...captured.promptSubmit, text: PROMPT, origin: { kind: 'composer' } }); + await cc.call('turn.start', { text: PROMPT, turnId: 't1' }); + await cc.call('prompt.submit', { ...captured.promptSubmit, text: PROMPT, origin: { kind: 'composer' } }); + await cc.call('turn.start', { text: PROMPT, turnId: 't2' }); + await until(() => cc.seen.statuses.some((line) => /^evolver · injected /.test(line)), 'the second turn\'s recall'); + const settled = cc.seen.statuses.length; + release(); + await until(() => lates === 2 && cc.seen.appended.length > 0, 'the first turn\'s answer'); + await new Promise((resolve) => setTimeout(resolve, 200)); + assert.equal(cc.seen.statuses.length, settled, 'the first turn wrote nothing once the second had started'); + assert.match(cc.seen.statuses.at(-1), /^evolver · injected /); +}); + +test('a recall the relay cannot answer settles the status line instead of leaving it recalling', async (t) => { + const cc = await session(t, { late: async () => ({ ok: false, status: 500, text: '{"error":"gone"}' }) }); + await cc.call('session.start'); + await cc.call('prompt.submit', { ...captured.promptSubmit, text: PROMPT, origin: { kind: 'composer' } }); + await cc.call('turn.start', { text: PROMPT, turnId: 't1' }); + await until(() => cc.seen.statuses.length >= 2, 'the settled status'); + assert.deepEqual(cc.seen.statuses, ['evolver · recalling an EvoMap strategy for this prompt…', 'evolver · recall did not finish for this prompt']); +}); From 0011814edc1962c9d06a3e5d8dc960d4097149ed Mon Sep 17 00:00:00 2001 From: forrestlinfeng Date: Tue, 24 Nov 2026 01:17:29 +0800 Subject: [PATCH 3/4] fix(relay): answer /late with a status only to a module that asks for it A hooks module older than the status line, running beside a newer relay (e.g. while the plugin is updated under a running session), read any non-null /late answer as a landed strategy, so a status-only answer would have appended `undefined` to the conversation. The current module now asks with `withStatus: true`. Without it, the relay answers as before: a strategy or null. Co-Authored-By: Claude Opus 5.5 --- hosts/claude-code/dist/hooks/register.ts | 2 +- lib/channels/relay/server.js | 11 ++++++----- test/channels/relay.test.js | 6 ++++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/hosts/claude-code/dist/hooks/register.ts b/hosts/claude-code/dist/hooks/register.ts index be6d6ad2..1a7ef473 100644 --- a/hosts/claude-code/dist/hooks/register.ts +++ b/hosts/claude-code/dist/hooks/register.ts @@ -195,7 +195,7 @@ async function startSession($: EngineInterface, options: PluginOptions): Promise async function addWhenLanded($: EngineInterface, options: PluginOptions, turnId: string, id: string, showsStatus: boolean): Promise { let answer: LateAnswer | null = null try { - answer = await post($, options, '/late', { id }) + answer = await post($, options, '/late', { id, withStatus: true }) } finally { if (showsStatus && turnId === statusTurnId) $.ui.status(answer?.status ?? RECALL_UNFINISHED_STATUS) } diff --git a/lib/channels/relay/server.js b/lib/channels/relay/server.js index 6c7cc9c2..6fdf2ebe 100644 --- a/lib/channels/relay/server.js +++ b/lib/channels/relay/server.js @@ -47,7 +47,8 @@ const reply = (response, status, value) => response.writeHead(status, { 'Content // A recall slower than the prompt's wait answers later: the module asks for it by id, and gets it only while its turn // is still open, then joins it to the turn once a model step carries it, which books it only while that turn is open. -// The answer carries the status line of what the recall decided, also when it brought nothing to add. +// A module that asks `withStatus` also gets the status line of what the recall decided, even when it brought nothing to +// add; one that does not (a module older than the status line, beside a newer relay) gets only a strategy, as before. function lateBook() { const entries = new Map(); const remember = (value) => { @@ -58,14 +59,14 @@ function lateBook() { }; return { held: (late, traced) => remember({ late, traced }), - async landed(id) { + async landed(id, { withStatus = false } = {}) { const entry = entries.get(id); const landed = await entry?.late; - const trace = await entry?.traced; + const trace = withStatus ? await entry?.traced : null; entries.delete(id); const status = trace ? recallStatusOf(trace) : null; if (!landed) return status ? { status } : null; - if (!(await landed.show())) return { status: arrivedLateStatusOf(trace?.name) }; + if (!(await landed.show())) return withStatus ? { status: arrivedLateStatusOf(trace?.name) } : null; return { id: remember({ join: landed.join }), text: landed.text, ...(status && { status }) }; }, async joined(id) { @@ -91,7 +92,7 @@ export function createRelay({ profile, env = process.env, token = randomBytes(24 const { late, traced, ...answer } = await channel.handle(hostEvent, payload); return late ? { ...answer, late: lates.held(late, traced), ...(traced && { status: RECALLING_STATUS }) } : answer; }, - '/late': ({ id }) => lates.landed(id), + '/late': ({ id, withStatus }) => lates.landed(id, { withStatus: withStatus === true }), '/late/join': ({ id }) => lates.joined(id), '/model/next': ({ waitMs }) => models.next(Math.min(Number(waitMs) || MODEL_POLL_MS, MODEL_POLL_MS)), '/model/answer': (outcome) => ({ taken: models.answer(outcome) }), diff --git a/test/channels/relay.test.js b/test/channels/relay.test.js index 6ac39f03..5ef452fb 100644 --- a/test/channels/relay.test.js +++ b/test/channels/relay.test.js @@ -41,7 +41,7 @@ test('a turn\'s recall answers later, by id; the strategy is joined to its turn const { body: answer } = await post('/event', { hostEvent: 'turn.start', payload: turn }); assert.equal(answer.append, undefined); assert.equal(answer.status, 'evolver · recalling an EvoMap strategy for this prompt…'); - const { body: landed } = await post('/late', { id: answer.late }); + const { body: landed } = await post('/late', { id: answer.late, withStatus: true }); assert.match(landed.text, /^\[Evolution Memory\] Fix flaky Redis connection retries/); assert.match(landed.status, /^evolver · injected "Fix flaky Redis connection retries" \(the Hub returned \d+\)$/); assert.deepEqual((await post('/late/join', { id: landed.id })).body, { joined: true }); @@ -53,8 +53,10 @@ test('a recall that injects nothing still answers what it decided; a turn nobody const { post } = await started(t, { assets: [] }); const typed = { session_id: 's2', cwd: '/proj', turn_id: 't1', text: 'translate the release notes into Japanese please', origin: { kind: 'composer' } }; const { body: answer } = await post('/event', { hostEvent: 'turn.start', payload: typed }); - const { body: late } = await post('/late', { id: answer.late }); + const { body: late } = await post('/late', { id: answer.late, withStatus: true }); assert.deepEqual(late, { status: 'evolver · no EvoMap strategy fits this prompt' }); + const { body: older } = await post('/event', { hostEvent: 'turn.start', payload: { ...typed, turn_id: 't1b' } }); + assert.equal((await post('/late', { id: older.late })).body, null, 'a module older than the status line gets only a strategy, as before'); const notification = { session_id: 's2', cwd: '/proj', turn_id: 't2', text: 'done', origin: { kind: 'task-notification' } }; const { body: quiet } = await post('/event', { hostEvent: 'turn.start', payload: notification }); assert.equal(quiet.status, undefined); From 660dd35555151d34d8a00735a76c3102c20ad457 Mon Sep 17 00:00:00 2001 From: forrestlinfeng Date: Tue, 24 Nov 2026 01:23:05 +0800 Subject: [PATCH 4/4] fix(relay): a recall that finished always answers a status, so "did not finish" means only a failed request A trace with no line of its own (or a recall with no trace) made /late answer null, which the module showed as "recall did not finish". Any finished recall with a trace now answers a status, with "no EvoMap strategy injected" for decisions the line names nothing else for. The module keeps "did not finish" for a /late request that failed. Co-Authored-By: Claude Opus 5.5 --- lib/channels/relay/server.js | 5 +++-- lib/recall-status.js | 4 ++-- test/recall-status.test.js | 6 +++--- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/lib/channels/relay/server.js b/lib/channels/relay/server.js index 6fdf2ebe..f0f6dd3a 100644 --- a/lib/channels/relay/server.js +++ b/lib/channels/relay/server.js @@ -62,9 +62,10 @@ function lateBook() { async landed(id, { withStatus = false } = {}) { const entry = entries.get(id); const landed = await entry?.late; - const trace = withStatus ? await entry?.traced : null; + const isTraced = withStatus && Boolean(entry?.traced); + const trace = isTraced ? await entry.traced : null; entries.delete(id); - const status = trace ? recallStatusOf(trace) : null; + const status = isTraced ? recallStatusOf(trace) : null; if (!landed) return status ? { status } : null; if (!(await landed.show())) return withStatus ? { status: arrivedLateStatusOf(trace?.name) } : null; return { id: remember({ join: landed.join }), text: landed.text, ...(status && { status }) }; diff --git a/lib/recall-status.js b/lib/recall-status.js index f0913402..d886c052 100644 --- a/lib/recall-status.js +++ b/lib/recall-status.js @@ -17,7 +17,7 @@ function skippedStatusOf({ recalled, eligible }) { return `${PREFIX} none injected: the Hub returned ${recalled}, ${why}`; } -/** The status line for a recall's last trace (`recallStrategy`'s `onTrace`), or null for one it does not describe. */ +/** The status line for a recall's last trace (`recallStrategy`'s `onTrace`); any other recall injected nothing. */ export function recallStatusOf(trace) { switch (trace?.outcome) { case 'injected': @@ -31,7 +31,7 @@ export function recallStatusOf(trace) { case 'short': return `${PREFIX} prompt too short to recall for`; default: - return null; + return `${PREFIX} no EvoMap strategy injected`; } } diff --git a/test/recall-status.test.js b/test/recall-status.test.js index 36865c5f..f22e09b8 100644 --- a/test/recall-status.test.js +++ b/test/recall-status.test.js @@ -13,8 +13,8 @@ test('each recall decision has its own status line, injected or not', () => { assert.equal(recallStatusOf({ outcome: 'short' }), 'evolver · prompt too short to recall for'); }); -test('a trace it does not describe has no line, and a long name is cut', () => { - assert.equal(recallStatusOf(null), null); - assert.equal(recallStatusOf({ outcome: 'passed_over' }), null); +test('a recall whose trace names no other decision says it injected nothing, and a long name is cut', () => { + assert.equal(recallStatusOf(null), 'evolver · no EvoMap strategy injected'); + assert.equal(recallStatusOf({ outcome: 'passed_over' }), 'evolver · no EvoMap strategy injected'); assert.equal(arrivedLateStatusOf('x'.repeat(80)), `evolver · "${'x'.repeat(48)}" arrived after this turn ended, not injected`); });