Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions hosts/claude-code/dist/hooks/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> = {}): Promise<Answer> {
Expand Down
16 changes: 16 additions & 0 deletions hosts/claude-code/profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand All @@ -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 } : {}),
Expand Down
3 changes: 2 additions & 1 deletion lib/agent/driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down
4 changes: 2 additions & 2 deletions lib/agent/profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 }),
});

Expand All @@ -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]);
Expand Down
18 changes: 13 additions & 5 deletions lib/app/prompt.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
Expand All @@ -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), {
Expand Down
16 changes: 9 additions & 7 deletions lib/app/turn-end.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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;
});
Expand Down Expand Up @@ -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 });
Expand All @@ -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;
Expand Down
68 changes: 62 additions & 6 deletions lib/recall.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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, '') };
Expand Down
Loading
Loading