Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(cost): the volatile half of the prompt moves to the end, and both loops build their request

Davidd6e75726d3f4
diff --git a/src/hooks/__tests__/decay-wiring.test.ts b/src/hooks/__tests__/decay-wiring.test.ts
new file mode 100644
index 00000000..bd8876d2
--- /dev/null
+++ b/src/hooks/__tests__/decay-wiring.test.ts
@@ -0,0 +1,108 @@
+/**
+ * A1/A2/A3 wiring: the two agent loops actually use the builder, in the
+ * binding order, and on a COPY.
+ *
+ * There is no render harness for these hooks in this repo, so the contract is
+ * guarded at the source the way host-platform.test.ts guards the prompt. These
+ * are the properties that a well-meaning refactor would silently undo, and each
+ * one has a price attached: decaying the working array would put shortened
+ * results into the store and into the next session; running the budget before
+ * the decay would drop whole messages the decay would have made fit; sending
+ * `messages` instead of `sendMessages` would keep paying full price while every
+ * unit test still passed.
+ */
+
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+const read = (file: string) => readFileSync(resolve(__dirname, '..', file), 'utf8')
+const codex = read('useCodex.ts')
+const agent = read('useAgentChat.ts')
+
+describe.each([
+ ['useCodex', codex, 'messages', 'sendMessages'],
+ ['useAgentChat', agent, 'agentMessages', 'sendMessages'],
+])('%s builds the request instead of trimming the history', (_name, source, working, send) => {
+ it('calls the request builder', () => {
+ expect(source).toMatch(/buildRequestMessages\(/)
+ })
+
+ it('no longer calls compactMessages behind the back of the builder', () => {
+ expect(source).not.toMatch(/compactMessages\(/)
+ })
+
+ it('never assigns the built request back onto the working history', () => {
+ // This is the line that would push decayed results into the store.
+ expect(source).not.toMatch(new RegExp(`${working}\\s*=\\s*buildRequestMessages`))
+ expect(source).not.toMatch(new RegExp(`${working}\\s*=\\s*built\\.messages`))
+ })
+
+ it('derives the budget from the effective send window', () => {
+ expect(source).toMatch(/effectiveSendWindow\(\{/)
+ expect(source).toMatch(/sendWindowTokens: settings\.codexSendWindowTokens/)
+ expect(source).toMatch(/capEnabled: decayOn/)
+ })
+
+ it('honours the contextDecay notaus', () => {
+ expect(source).toMatch(/const decayOn = settings\.contextDecay !== false/)
+ expect(source).toMatch(/enabled: decayOn/)
+ expect(source).toMatch(/hysteresis: decayOn/)
+ })
+
+ it('reports the built size for the token counter', () => {
+ expect(source).toMatch(/useSendSizeStore\.getState\(\)\.report\(/)
+ expect(source).toMatch(/tokens: built\.promptTokens/)
+ })
+
+ it('leaves a decay row in the tool audit so support can see it', () => {
+ expect(source).toMatch(/toolName: 'context_decay'/)
+ expect(source).toMatch(/savedChars: built\.savedChars/)
+ })
+
+ it('tells the loop guard which reads went out capped', () => {
+ expect(source).toMatch(/\{ trimmedReadKeys \}/)
+ expect(source).toMatch(/guardKeyOfResult\.set\(/)
+ expect(source).toMatch(/keyOf: \(m\) => guardKeyOfResult\.get\(/)
+ })
+
+ it('surfaces loop-guard steers and halts as notes in the thread', () => {
+ expect(source).toMatch(/Loop guard halted the run/)
+ expect(source).toMatch(/Loop guard steered the model/)
+ })
+
+ it('sends the built copy, not the working history', () => {
+ expect(source).toMatch(new RegExp(`streamProviderTurn\\(provider, modelToUse, ${send}`))
+ })
+})
+
+describe('useCodex keeps the working history whole for the store', () => {
+ it('still persists the hidden tool chain from the untouched array', () => {
+ expect(codex).toMatch(/const toolHistoryAll = messages\.slice\(messagesStartLen\)/)
+ })
+
+ it('shortens restored tool messages of PREVIOUS turns', () => {
+ expect(codex).toMatch(/decayRestoredToolResult\(msg\.content\)/)
+ expect(codex).toMatch(/decayRestored && m\.hidden && isToolResult\(msg\)/)
+ })
+
+ it('leaves the restore alone when the notaus is off', () => {
+ expect(codex).toMatch(/const decayRestored = settings\.contextDecay !== false/)
+ })
+})
+
+describe('the builder runs before the model call, every step', () => {
+ it('useCodex builds inside the iteration loop, ahead of the transports', () => {
+ const buildAt = codex.indexOf('const built = buildRequestMessages(messages, {')
+ const nativeAt = codex.indexOf("if (strategy === 'native') {")
+ expect(buildAt).toBeGreaterThan(-1)
+ expect(buildAt).toBeLessThan(nativeAt)
+ })
+
+ it('useAgentChat builds ahead of its transports too', () => {
+ const buildAt = agent.indexOf('const built = buildRequestMessages(agentMessages, {')
+ const nativeAt = agent.indexOf("if (strategy === 'native') {")
+ expect(buildAt).toBeGreaterThan(-1)
+ expect(buildAt).toBeLessThan(nativeAt)
+ })
+})
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 01b2011a..aae3a121 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -36,7 +36,10 @@ import { parseLooseToolCalls, stripMatchedCalls, stripToolCallText, canonicalToo
import { mediaCallSucceeded } from '../lib/media-result'
import { summarizeTurn } from '../lib/turn-summary'
import { buildVisionFeedback } from '../api/vision-feedback'
-import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'
+import { getModelMaxTokens, estimateTokens } from '../lib/context-compaction'
+import { buildRequestMessages, trimWorkingHistory } from '../lib/context-decay'
+import { effectiveSendWindow } from '../lib/send-window'
+import { useSendSizeStore } from '../stores/sendSizeStore'
import { resolveAgentNumCtx } from '../lib/agent-num-ctx'
import { useMemoryStore } from '../stores/memoryStore'
import { useVoiceStore } from '../stores/voiceStore'
@@ -46,7 +49,7 @@ import { markToolsUnsupported } from '../api/tool-capability'
import { buildExtractionPrompt, parseExtractionResponse } from '../lib/memory-extraction'
import { useAgentWorkflowStore } from '../stores/agentWorkflowStore'
import { WorkflowEngine } from '../lib/workflow-engine'
-import type { AgentBlock, AgentToolCall, OllamaChatMessage } from '../types/agent-mode'
+import type { AgentBlock, AgentToolCall } from '../types/agent-mode'
import { selectRelevantToolsAsync, ALWAYS_INCLUDE, SMALL_MODEL_MAX_TOOLS } from '../lib/tool-selection'
import { renderToolRoster, renderToolNames } from '../lib/tool-roster'
import { MUTATING_TOOLS, allowedInReadOnlyTurn } from '../lib/mutating-tools'
@@ -69,7 +72,7 @@ import { openPlanGap, planReconcileSteer, PLAN_RECONCILE_BUDGET } from '../lib/p
import { PlanStaleness, planStalenessSteer } from '../lib/plan-staleness'
import { reasoningOnlyRound, REASONING_CONTINUE_BUDGET, REASONING_CONTINUE_STEER } from '../lib/reasoning-round'
import { useTodoStore } from '../stores/todoStore'
-import { hostEnvironmentBlock } from '../lib/host-platform'
+import { platformPromptLine, hostClockLine } from '../lib/host-platform'
import { httpStatusOf, isTerminalModelError, retryDelayMs } from '../lib/http-status'
import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'
@@ -415,6 +418,7 @@ export function useAgentChat() {
let systemPrompt = conv.personaEnabled === true ? conv.systemPrompt : ''
const ragState = useRAGStore.getState()
const ragEnabled = ragState.ragEnabled[convId] ?? false
+ let ragSuffix = ''
if (ragEnabled) {
// Guard the lock: a throw here (before the main try/finally below) would
@@ -429,7 +433,12 @@ export function useAgentChat() {
const contextBlock = ragContext.chunks
.map((c: any, i: number) => `[Source ${i + 1}]\n${c.content}`)
.join('\n\n')
- systemPrompt = `Use the following document context to help answer the user's question. If the context is not relevant, ignore it and answer normally.\n\n---\n${contextBlock}\n---\n\n${systemPrompt || ''}`
+ // Retrieval is the most volatile thing in the whole prompt:
+ // every turn pulls different chunks. In front of the persona it
+ // put a fresh byte at offset 0 and made the upstream prefix cache
+ // miss the ENTIRE prompt on every RAG turn, so it rides at the end
+ // now, behind persona and memory (plan A5).
+ ragSuffix = `\n\nUse the following document context to help answer the user's question. If the context is not relevant, ignore it and answer normally.\n\n---\n${contextBlock}\n---`
}
} catch (err) {
log.error('RAG retrieval failed', { err })
@@ -527,6 +536,13 @@ export function useAgentChat() {
log.warn('agent.caveman_load_failed', { e: String(e) })
}
+ // Everything volatile goes LAST (plan A5): the retrieval chunks that
+ // change every turn and the clock that changes every minute. A prefix
+ // cache matches from byte 0 and stops at the first difference, so one
+ // early timestamp re-prices the whole prompt.
+ agentSystemPrompt += ragSuffix
+ agentSystemPrompt += `\n\n${hostClockLine()}`
+
// Build messages array
let agentMessages: ChatMessage[] = [
...(agentSystemPrompt ? [{ role: 'system' as const, content: agentSystemPrompt }] : []),
@@ -647,10 +663,22 @@ export function useAgentChat() {
// rightly weakened. Windowed batch repeats, per-epoch identical reads and
// repeated narration now watch this loop too.
const loopGuard = new AgentLoopGuard()
-
+ // Which read produced which result message, so the request builder can
+ // tell the guard that a re-read of a CAPPED result is legitimate rather
+ // than a loop (plan A1, LOOP-GUARD). Keyed by the message object, which
+ // works across all three transports.
+ const guardKeyOfResult = new WeakMap<object, string>()
+ const guardKeyFor = (tc: { function: { name: string; arguments?: unknown } }): string =>
+ `${tc.function.name}|${JSON.stringify(tc.function.arguments ?? {})}`
+ const NO_TRIMMED_KEYS: ReadonlySet<string> = new Set<string>()
+
+ // Step number for the decay audit trail. The loop is a while, so it has
+ // no index of its own.
+ let stepNo = 0
try {
// ── Agent Loop ──────────────────────────────────────────
while (runningRef.current && !abort.signal.aborted) {
+ stepNo++
budget.addIteration()
const exceed = budget.exceeded()
if (exceed.kind !== 'none') {
@@ -714,16 +742,77 @@ export function useAgentChat() {
// Keep the compaction budget == the actual num_ctx we send, so we never
// trim to the model's full context (e.g. 128k) while Ollama only has the
// capped num_ctx allocated — that mismatch caused prompt overflow.
- const maxCtx = agentCtx
- // Small-Model Mode (Knob 4): keep the REAL prompt short (the true lever,
- // NOT num_ctx) — tighter ratio + an absolute cap.
- const compactBudget = settings.smallModelMode
- ? Math.floor(Math.min(maxCtx * 0.5, 6000))
- : Math.floor(maxCtx * 0.8)
- agentMessages = compactMessages(
- agentMessages as OllamaChatMessage[],
- compactBudget
- ) as ChatMessage[]
+ // ── Request build (2.6.6, plan A1/A2/A3) ─────────────────────
+ // Age decay, then the send budget, then compaction, in that order:
+ // reversed, the budget counts full results and drops whole messages
+ // to make room the decay would have freed anyway.
+ //
+ // agentMessages itself is never decayed. The store, the transcript
+ // and the next turn keep the complete result; only the copy on the
+ // wire is shortened, which is what makes it reversible from one
+ // settings switch. Small-Model Mode (Knob 4) and the paid-provider
+ // send cap both live in effectiveSendWindow.
+ const decayOn = settings.contextDecay !== false
+ const sendWindow = effectiveSendWindow({
+ providerId,
+ modelWindow: agentCtx,
+ sendWindowTokens: settings.codexSendWindowTokens,
+ capEnabled: decayOn,
+ smallModelMode: settings.smallModelMode,
+ })
+ let sendMessages: ChatMessage[] = agentMessages.slice()
+ let trimmedReadKeys: ReadonlySet<string> = NO_TRIMMED_KEYS
+ try {
+ // Bound the carried history FIRST, in whole blocks and measured on
+ // the decayed sizes. Trimming to the exact budget inside the builder
+ // would move the window start every single step, and a window that
+ // moves every step is a prompt prefix that is never the same twice.
+ // Whole messages are dropped here, never shortened: decay stays on
+ // the send copy alone, so the store keeps every result complete.
+ agentMessages = trimWorkingHistory(agentMessages, sendWindow, { enabled: decayOn }).messages
+ const built = buildRequestMessages(agentMessages, {
+ budgetTokens: sendWindow,
+ enabled: decayOn,
+ hysteresis: decayOn,
+ keyOf: (m) => guardKeyOfResult.get(m as unknown as object),
+ })
+ sendMessages = built.messages
+ trimmedReadKeys = new Set(built.trimmedKeys)
+ if (convId) {
+ useSendSizeStore.getState().report(convId, {
+ tokens: built.promptTokens,
+ window: sendWindow,
+ atMessageCount:
+ useChatStore.getState().conversations.find((c) => c.id === convId)?.messages.length ?? 0,
+ trimmedResults: built.trimmedCount,
+ savedChars: built.savedChars,
+ })
+ if (built.trimmedCount > 0 || built.prunedPlans > 0) {
+ const auditId = useToolAuditStore.getState().record({
+ convId,
+ toolCallId: `decay-${stepNo}`,
+ toolName: 'context_decay',
+ args: {
+ step: stepNo,
+ trimmedResults: built.trimmedCount,
+ savedChars: built.savedChars,
+ prunedPlanMessages: built.prunedPlans,
+ sendWindow,
+ },
+ })
+ useToolAuditStore.getState().complete(auditId, {
+ status: 'completed',
+ completedAt: Date.now(),
+ resultPreview:
+ `Shortened ${built.trimmedCount} aged tool result${built.trimmedCount === 1 ? '' : 's'} ` +
+ `and dropped ${built.prunedPlans} superseded plan message${built.prunedPlans === 1 ? '' : 's'}, ` +
+ `saving ${built.savedChars} characters. Request: ~${built.promptTokens} of ${sendWindow} tokens.`,
+ })
+ }
+ }
+ } catch {
+ sendMessages = agentMessages.slice()
+ }
// Honouring a long `retry-after` means the run goes quiet for up to a
// minute, and a silent gap reads as a freeze (which is exactly the
@@ -785,7 +874,7 @@ export function useAgentChat() {
.find((c) => c.id === convId)?.messages.find((m) => m.id === assistantMessage.id)?.usage
if (!existingUsage || existingUsage.estimated) {
const estPrompt =
- estimateTokens(agentMessages.map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content))).join('\n')) +
+ estimateTokens(sendMessages.map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content))).join('\n')) +
estimateTokens(JSON.stringify(tools))
useChatStore.getState().updateMessageUsage(convId!, assistantMessage.id, {
promptTokens: estPrompt, completionTokens: 0, totalTokens: estPrompt, estimated: true,
@@ -819,7 +908,7 @@ export function useAgentChat() {
try {
turn = await streamOllamaChatWithTools(
modelToUse,
- agentMessages,
+ sendMessages,
tools,
{
temperature: chatOptions.temperature,
@@ -848,6 +937,9 @@ export function useAgentChat() {
// it to its text fallback and retry — the run must survive a
// wrong vision guess. A user-attached image stays untouched.
if (isMultimodalUnsupportedError(String(thinkErr?.message ?? '')) && stripVisionFeedbackMessages(agentMessages)) {
+ // The send copy carries the same attachment; strip it there
+ // too or the retry resends exactly what just failed.
+ stripVisionFeedbackMessages(sendMessages)
visionRefused = true
log.warn('agent.vision_feedback_healed', { model: modelToUse })
continue
@@ -861,7 +953,7 @@ export function useAgentChat() {
&& (thinkErr?.message?.includes('does not support thinking') || httpStatusOf(thinkErr) === 400)) {
turn = await streamOllamaChatWithTools(
modelToUse,
- agentMessages,
+ sendMessages,
tools,
{
temperature: chatOptions.temperature,
@@ -932,13 +1024,14 @@ export function useAgentChat() {
let connRetries = 0
for (;;) {
try {
- turn = await streamProviderTurn(provider, modelToUse, agentMessages, streamOpts, onLiveContent, onLiveThinking)
+ turn = await streamProviderTurn(provider, modelToUse, sendMessages, streamOpts, onLiveContent, onLiveThinking)
break
} catch (thinkErr: any) {
// G22 parity with the Ollama branch: heal a wrong vision
// guess instead of ending the run (R20 witness: LM Studio,
// gemma-3-4b-it-abliterated, text-only conversion).
if (isMultimodalUnsupportedError(String(thinkErr?.message ?? '')) && stripVisionFeedbackMessages(agentMessages)) {
+ stripVisionFeedbackMessages(sendMessages)
visionRefused = true
log.warn('agent.vision_feedback_healed', { model: modelToUse, provider: providerId })
continue
@@ -950,7 +1043,7 @@ export function useAgentChat() {
// 400 twice (review 2026-08-14).
if (streamOpts.thinking !== undefined
&& (thinkErr?.message?.includes('does not support thinking') || httpStatusOf(thinkErr) === 400)) {
- turn = await streamProviderTurn(provider, modelToUse, agentMessages, { ...streamOpts, thinking: undefined as unknown as boolean }, onLiveContent, () => {})
+ turn = await streamProviderTurn(provider, modelToUse, sendMessages, { ...streamOpts, thinking: undefined as unknown as boolean }, onLiveContent, () => {})
break
}
const transient = thinkErr?.name !== 'AbortError' && !isTerminalModelError(thinkErr)
@@ -1017,7 +1110,7 @@ export function useAgentChat() {
const hermesTurn = await streamProviderTurn(
provider,
modelToUse,
- agentMessages.map(m => ({ role: m.role, content: m.content })),
+ sendMessages.map(m => ({ role: m.role, content: m.content })),
{ ...chatOptions, thinking: undefined as unknown as boolean },
(_full, delta) => feedUI(splitter.feed(display.feed(delta))),
)
@@ -1376,15 +1469,32 @@ export function useAgentChat() {
? narrationVerdict
: loopGuard.recordBatch(
toolCalls.map((tc) => ({ name: tc.function.name, args: JSON.stringify(tc.function.arguments ?? {}) })),
+ // Reads the builder just sent capped: re-reading those is the
+ // decay working as designed, not a loop (plan A1, LOOP-GUARD).
+ { trimmedReadKeys },
)
if (batchVerdict.action === 'halt') {
contentRef.current =
(contentRef.current ? contentRef.current + '\n\n' : '') +
`_(halted: ${batchVerdict.reason}. The model is looping. Try a stronger model for multi-step tasks, or rephrase the instruction.)_`
scheduleUIUpdate()
+ addBlock(convId!, assistantMessage.id, {
+ id: uuid(),
+ phase: 'reflection',
+ content: `⛔ Loop guard halted the run: ${batchVerdict.reason}.`,
+ timestamp: Date.now(),
+ })
break
}
const pendingSteer = batchVerdict.action === 'steer' ? batchVerdict.message : null
+ if (pendingSteer) {
+ addBlock(convId!, assistantMessage.id, {
+ id: uuid(),
+ phase: 'reflection',
+ content: `↻ Loop guard steered the model: ${pendingSteer}`,
+ timestamp: Date.now(),
+ })
+ }
type BatchEntry = { tc: typeof toolCalls[number]; ac: AgentToolCall; blockId: string }
const batch: BatchEntry[] = []
@@ -1610,6 +1720,14 @@ export function useAgentChat() {
// branch (not the id-less `native` one below) — otherwise DeepInfra 422s
// "ChatCompletionToolMessage.tool_call_id: Field required" and every
// follow-up turn fails. Ollama/LM-Studio are lenient; only cloud bit.
+ // Remember which read produced which result message, so a later step
+ // that sends that result capped can tell the loop guard the re-read is
+ // legitimate. Registered on the pushed OBJECT, so it works for all
+ // three transports even though only one of them carries call ids.
+ const rememberResult = (msg: ChatMessage, tc: { function: { name: string; arguments?: unknown } }) => {
+ guardKeyOfResult.set(msg as unknown as object, guardKeyFor(tc))
+ return msg
+ }
if (providerId === 'openai' || providerId === 'anthropic' || providerId === 'lu-cloud') {
agentMessages.push({
role: 'assistant',
@@ -1618,11 +1736,11 @@ export function useAgentChat() {
})
for (const { tc } of batch) {
const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!
- agentMessages.push({
+ agentMessages.push(rememberResult({
role: 'tool',
content: resultTextFor(result) + mediaNote(tc.function.name, result),
tool_call_id: tc.id,
- })
+ }, tc))
}
} else if (strategy === 'native') {
agentMessages.push({
@@ -1634,10 +1752,10 @@ export function useAgentChat() {
})
for (const { tc } of batch) {
const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!
- agentMessages.push({
+ agentMessages.push(rememberResult({
role: 'tool',
content: resultTextFor(result) + mediaNote(tc.function.name, result),
- })
+ }, tc))
}
} else {
for (const { tc } of batch) {
@@ -1646,10 +1764,10 @@ export function useAgentChat() {
role: 'assistant',
content: `<tool_call>\n{"name": "${tc.function.name}", "arguments": ${JSON.stringify(tc.function.arguments)}}\n</tool_call>`,
})
- agentMessages.push({
+ agentMessages.push(rememberResult({
role: 'user',
content: buildHermesToolResult(tc.function.name, resultTextFor(result) + mediaNote(tc.function.name, result)),
- })
+ }, tc))
}
}
@@ -1661,6 +1779,12 @@ export function useAgentChat() {
results.map((r) => ({ name: r.toolName, failed: r.status === 'failed', error: r.error, args: r.dispatchedArgs })),
)
if (failVerdict.action === 'halt') {
+ addBlock(convId!, assistantMessage.id, {
+ id: uuid(),
+ phase: 'reflection',
+ content: `⛔ Loop guard halted the run: ${failVerdict.reason}.`,
+ timestamp: Date.now(),
+ })
contentRef.current =
(contentRef.current ? contentRef.current + '\n\n' : '') +
`_(halted: ${failVerdict.reason}. The model is looping. Try a stronger model for multi-step tasks, or rephrase the instruction.)_`
@@ -2014,7 +2138,7 @@ export function extractMediaPrompt(text: string): string {
function buildAgentSystemPrompt(basePrompt: string, roster: string): string {
const agentInstructions = `You are an autonomous AI agent inside LU with full access to this computer. You execute tasks end-to-end by using tools, you do NOT just describe what to do.
-${hostEnvironmentBlock()}
+${platformPromptLine()}
Available tools:
${roster}
@@ -2050,7 +2174,7 @@ Other rules:
- PATHS: use paths relative to your working directory (e.g. \`package.json\`, \`src/app.ts\`, \`.\` for the current folder). Never start a path with \`/\` or a drive letter (\`C:\\\`), that escapes your workspace and fails. To list the current folder, use file_list with path \`.\`.
- For filesystem READ tasks: file_list first if needed, then file_read.
- For web tasks: web_search → web_fetch on the best URL → answer based on real data. web_search returns ONLY short snippets, ALWAYS call web_fetch to read the page.
-- OS, clock and timezone are stated above, so do not spend a call finding them out. For hardware details or running processes, use shell_execute (macOS/Linux: \`uname -a\`, \`ps aux\`; Windows: \`Get-ComputerInfo\`, \`Get-Process\`).
+- OS, clock and timezone are stated in this prompt (platform up top, clock at the very end, where a volatile line cannot spoil the prompt cache), so do not spend a call finding them out. For hardware details or running processes, use shell_execute (macOS/Linux: \`uname -a\`, \`ps aux\`; Windows: \`Get-ComputerInfo\`, \`Get-Process\`).
- Chain multiple tools as needed. If a tool fails, try a different approach.
- Be concise in text. All the work happens in tool calls.
- Respond in the same language the user uses.`
@@ -2069,7 +2193,7 @@ Other rules:
function buildAgentSystemPromptLean(basePrompt: string, alwaysThere: string): string {
const lean = `You are an autonomous agent in LU with tools on this computer. Do tasks by CALLING tools, do not just describe them.
-${hostEnvironmentBlock()}
+${platformPromptLine()}
You always have: ${alwaysThere}. Your request carries the other tools that fit the task. Read their names there, do not guess.
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index 951bd9cc..b3a129ef 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -389,6 +389,7 @@ export function useChat() {
let systemPrompt = conv.personaEnabled === true ? conv.systemPrompt : ''
const ragState = useRAGStore.getState()
const ragEnabled = ragState.ragEnabled[convId] ?? false
+ let ragSuffix = ''
if (ragEnabled) {
// Ensure chunks are loaded from IndexedDB before retrieval
@@ -410,8 +411,13 @@ export function useChat() {
const contextBlock = ragContext.chunks
.map((c, i) => `[Source ${i + 1}]\n${c.content}`)
.join("\n\n")
- const ragPrefix = `Use the following document context to help answer the user's question. If the context is not relevant, ignore it and answer normally.\n\n---\n${contextBlock}\n---\n\n`
- systemPrompt = ragPrefix + (systemPrompt || "")
+ // The retrieval block is the most volatile thing in the prompt:
+ // every turn pulls different chunks. It used to sit at byte 0,
+ // ahead of the persona, so an upstream prefix cache, which
+ // matches from the first byte and stops at the first difference,
+ // missed the ENTIRE prompt on every RAG turn. It moves to the very
+ // end, behind persona and memory, and is appended below (plan A5).
+ ragSuffix = `\n\nUse the following document context to help answer the user's question. If the context is not relevant, ignore it and answer normally.\n\n---\n${contextBlock}\n---`
}
} catch (err) {
log.error("RAG retrieval failed, continuing without context", { err })
@@ -471,6 +477,11 @@ export function useChat() {
? (await import('../lib/constants')).CAVEMAN_REMINDERS?.[settings.cavemanMode as 'lite' | 'full' | 'ultra'] || ''
: ''
+ // Volatile last (plan A5): the retrieval block goes behind persona,
+ // memory, thinking and caveman, so everything a prefix cache could match
+ // stays byte-identical from turn to turn.
+ if (ragSuffix) systemPrompt = (systemPrompt || '') + ragSuffix
+
// Count cap (web parity, MAX_SEND_MESSAGES): plain chat sends the whole
// history verbatim, and a long chat of many short turns stays under every
// token budget while the count climbs past the LU Cloud proxy's
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 578f3142..bfb5905f 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -56,15 +56,17 @@ import { selectRelevantTools, selectRelevantToolsAsync, SMALL_MODEL_MAX_TOOLS, g
import { generateEmbeddings } from '../api/rag'
import { truncateToolResult } from '../lib/truncate-tool-result'
import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'
-import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'
+import { getModelMaxTokens, estimateTokens } from '../lib/context-compaction'
+import { buildRequestMessages, trimWorkingHistory, decayRestoredToolResult, isToolResult } from '../lib/context-decay'
+import { effectiveSendWindow } from '../lib/send-window'
+import { useSendSizeStore } from '../stores/sendSizeStore'
import { resolveAgentNumCtx } from '../lib/agent-num-ctx'
-import { hostEnvironmentBlock } from '../lib/host-platform'
+import { platformPromptLine, hostClockLine } from '../lib/host-platform'
import { AgentLoopGuard } from '../lib/agent-loop-guard'
import { findStagedForPath, stagedReadResult, stagedListingNote } from '../lib/staged-overlay'
import { applyAllStagedChanges } from '../lib/staged-apply'
import { useMemoryStore } from '../stores/memoryStore'
import { extractMemoriesFromPair } from './useMemory'
-import type { OllamaChatMessage } from '../types/agent-mode'
import { useCodexConfirmStore } from '../stores/codexConfirmStore'
// No-op diagnostic hook. Kept as a call site so future debugging can swap
@@ -504,7 +506,11 @@ export function useCodex() {
// Environment block (2.6.6, plan E3): OS, shell, clock, timezone. Codex
// never had the platform sentence; it paid for it with system_info and
// get_current_time round trips instead, and those tools are gone now.
- let systemPrompt = `${baseCodexPrompt}${assetLine}\n\n${hostEnvironmentBlock()}\n${workDirLine}`
+ // Only the STABLE half lives here (plan A5): the platform sentence reads
+ // the same on every turn, while the clock changes every minute and now
+ // rides at the very end of the prompt, behind everything a prefix cache
+ // could otherwise have matched.
+ let systemPrompt = `${baseCodexPrompt}${assetLine}\n\n${platformPromptLine()}\n${workDirLine}`
// Standing goal (/goal) — ahead of the rules and the repo map so it frames
// everything that follows instead of reading as an afterthought.
systemPrompt += renderGoalSection(useAgentGoalStore.getState().getGoal(convId))
@@ -583,6 +589,15 @@ export function useCodex() {
systemPromptHead: systemPrompt.slice(0, 500),
cavemanReminder: cavemanReminder.slice(0, 120),
})
+ // Session restore (2.6.6, plan A1): the hidden tool chain of PREVIOUS turns
+ // is the cheapest thing in the whole history to shrink. Its job is to tell
+ // the model what it already did, and a 60k build log from three turns ago
+ // does that no better than its head and tail, and it is paid for on every
+ // single step of this turn. A result the run already sent capped
+ // comes back at exactly those bytes (decayRestoredToolResult is a pure
+ // function of the stored text), so a restore never re-cuts with a second
+ // budget and never moves the prefix.
+ const decayRestored = settings.contextDecay !== false
let messages: ChatMessage[] = [
{ role: 'system', content: systemPrompt },
...conv.messages
@@ -594,6 +609,9 @@ export function useCodex() {
? `${cavemanReminder}\n${m.content}`
: m.content,
}
+ if (decayRestored && m.hidden && isToolResult(msg)) {
+ msg.content = decayRestoredToolResult(msg.content)
+ }
// Carry over tool_calls from hidden assistant messages so the
// model sees the full tool-call chain from previous turns
// (continue capability, parity with original Codex CLI).
@@ -711,6 +729,13 @@ export function useCodex() {
}
}
+ // LAST, after architect and repo map (plan A5): the one line that changes
+ // every minute closes the prompt instead of opening it. A prefix cache
+ // matches from byte 0 and stops at the first difference, so a clock near
+ // the top re-prices the whole prompt on every new turn.
+ systemPrompt += `\n\n${hostClockLine()}`
+ messages[0] = { role: 'system', content: systemPrompt }
+
let fullContent = ''
// Phase 6: pin turn start so in-turn cache scopes to this user prompt.
@@ -755,6 +780,16 @@ export function useCodex() {
// it forever while the budget allowed 200 iterations of the loop
// (Morgan's 5-minute file_read loop, 2026-07-26).
const loopGuard = new AgentLoopGuard()
+ // Which read produced which result message. The request builder reports
+ // back the results it sent CAPPED, and this map turns those messages
+ // into the loop-guard keys that must not be counted as a repeat (plan
+ // A1, LOOP-GUARD). Keyed by message object, so it survives every
+ // transport shape and every reordering the builder does; a WeakMap so a
+ // dropped message takes its entry with it.
+ const guardKeyOfResult = new WeakMap<object, string>()
+ const guardKeyFor = (tc: { function: { name: string; arguments: unknown } }): string =>
+ `${tc.function.name}|${JSON.stringify(tc.function.arguments)}`
+ const NO_TRIMMED_KEYS: ReadonlySet<string> = new Set<string>()
// Echo guard — small models occasionally re-emit the system prompt
// ("Hello, I am the Coding Agent, an autonomous coding agent…") after a
// tool error. The user asked to silence those silently rather than
@@ -825,24 +860,87 @@ export function useCodex() {
signal: abort.signal,
}
- // Context compaction — keep recent N messages intact, summarise older.
- // Without this the conversation grows unbounded across iterations;
- // 8K-context local models blow past their window after a few tool
- // calls and Ollama starts silently truncating or errors out.
+ // ── Request build (2.6.6, plan A1/A2/A3) ─────────────────────────
+ // Age decay, then the send budget, then compaction, in that order.
+ // The other way round the budget counts full results, drops whole
+ // messages to make room, and the decay that would have made them fit
+ // never happens.
+ //
+ // The working array is never decayed. What the store keeps, what the
+ // transcript shows and what the next turn restores stays complete;
+ // only the copy that goes on the wire is shortened, which is what
+ // makes the whole thing reversible from one settings switch.
+ //
+ // Small-Model Mode (Knob 4) keeps the REAL prompt short, which is the
+ // actual lever for small models, NOT num_ctx (the num_ctx-as-ceiling
+ // fear is largely a myth). effectiveSendWindow carries that profile,
+ // and on a paid provider it also carries the send cap.
+ const decayOn = settings.contextDecay !== false
+ const sendWindow = effectiveSendWindow({
+ providerId,
+ modelWindow: numCtx,
+ sendWindowTokens: settings.codexSendWindowTokens,
+ capEnabled: decayOn,
+ smallModelMode: settings.smallModelMode,
+ })
+ let sendMessages: ChatMessage[] = messages.slice()
+ let trimmedReadKeys: ReadonlySet<string> = NO_TRIMMED_KEYS
try {
- // Small-Model Mode (Knob 4): keep the REAL prompt short — that is the
- // actual lever for small models, NOT num_ctx (research found the
- // num_ctx-as-ceiling fear is largely a myth). Tighter ratio + an
- // absolute cap so history stays small regardless of the allocation.
- const compactBudget = settings.smallModelMode
- ? Math.floor(Math.min(numCtx * 0.5, 6000))
- : Math.floor(numCtx * 0.8)
- messages = compactMessages(
- messages as unknown as OllamaChatMessage[],
- compactBudget,
- ) as unknown as ChatMessage[]
+ // Bound the carried history FIRST, in whole blocks and measured on
+ // the decayed sizes. Trimming to the exact budget inside the builder
+ // would move the window start every single step, and a window that
+ // moves every step is a prompt prefix that is never the same twice.
+ // Whole messages are dropped here, never shortened: decay stays on
+ // the send copy alone, so the store keeps every result complete.
+ messages = trimWorkingHistory(messages, sendWindow, { enabled: decayOn }).messages
+ const built = buildRequestMessages(messages, {
+ budgetTokens: sendWindow,
+ enabled: decayOn,
+ hysteresis: decayOn,
+ keyOf: (m) => guardKeyOfResult.get(m as unknown as object),
+ })
+ sendMessages = built.messages
+ trimmedReadKeys = new Set(built.trimmedKeys)
+ if (convId) {
+ useSendSizeStore.getState().report(convId, {
+ tokens: built.promptTokens,
+ window: sendWindow,
+ atMessageCount:
+ useChatStore.getState().conversations.find((c) => c.id === convId)?.messages.length ?? 0,
+ trimmedResults: built.trimmedCount,
+ savedChars: built.savedChars,
+ })
+ // Without a trace, support cannot tell decay apart from model
+ // flakiness: a run that re-reads a file looks identical either
+ // way. One audit row per step that actually shortened something
+ // is the cheapest possible answer to "why did it read that again"
+ // (plan A1, SICHTBARKEIT).
+ if (built.trimmedCount > 0 || built.prunedPlans > 0) {
+ const auditId = useToolAuditStore.getState().record({
+ convId,
+ toolCallId: `decay-${i}`,
+ toolName: 'context_decay',
+ args: {
+ step: i + 1,
+ trimmedResults: built.trimmedCount,
+ savedChars: built.savedChars,
+ prunedPlanMessages: built.prunedPlans,
+ sendWindow,
+ },
+ })
+ useToolAuditStore.getState().complete(auditId, {
+ status: 'completed',
+ completedAt: Date.now(),
+ resultPreview:
+ `Shortened ${built.trimmedCount} aged tool result${built.trimmedCount === 1 ? '' : 's'} ` +
+ `and dropped ${built.prunedPlans} superseded plan message${built.prunedPlans === 1 ? '' : 's'}, ` +
+ `saving ${built.savedChars} characters. Request: ~${built.promptTokens} of ${sendWindow} tokens.`,
+ })
+ }
+ }
} catch {
- // Compaction is best-effort; fall through with raw history.
+ // Building is best-effort; fall through with the raw history.
+ sendMessages = messages.slice()
}
// Live paint for EVERY transport branch below (Ollama, openai-compat
@@ -961,7 +1059,7 @@ export function useCodex() {
codexTools: codexTools.map(t => t.name),
relevantDefs: relevantDefs.map(t => t.name),
toolsSentCount: tools.length,
- messagesLen: messages.length,
+ messagesLen: sendMessages.length,
lastUserMsg: lastUserMsg.slice(0, 120),
})
@@ -986,7 +1084,7 @@ export function useCodex() {
.find((c) => c.id === convId)?.messages.find((m) => m.id === assistantMsg.id)?.usage
if (!existingUsage || existingUsage.estimated) {
const estPrompt =
- estimateTokens(messages.map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content))).join('\n')) +
+ estimateTokens(sendMessages.map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content))).join('\n')) +
estimateTokens(JSON.stringify(tools))
useChatStore.getState().updateMessageUsage(convId!, assistantMsg.id, {
promptTokens: estPrompt, completionTokens: 0, totalTokens: estPrompt, estimated: true,
@@ -994,9 +1092,9 @@ export function useCodex() {
}
}
try {
- void diagLog('streamWithTools-enter', { iter: i, messagesLen: messages.length, toolsCount: tools.length, thinking: chatOptions.thinking })
+ void diagLog('streamWithTools-enter', { iter: i, messagesLen: sendMessages.length, toolsCount: tools.length, thinking: chatOptions.thinking })
turn = await streamWithTools(
- modelToUse, messages, tools,
+ modelToUse, sendMessages, tools,
{ temperature: 0.1, thinking: chatOptions.thinking, maxTokens: chatOptions.maxTokens, contextWindow: numCtx, signal: abort.signal },
liveContent,
(t) => {
@@ -1016,7 +1114,7 @@ export function useCodex() {
})
if (httpStatusOf(thinkErr) === 400 || thinkErr?.message?.includes('does not support thinking')) {
turn = await streamWithTools(
- modelToUse, messages, tools,
+ modelToUse, sendMessages, tools,
{ temperature: 0.1, thinking: undefined, maxTokens: chatOptions.maxTokens, contextWindow: numCtx, signal: abort.signal },
liveContent,
() => {},
@@ -1114,10 +1212,10 @@ export function useCodex() {
}
}
try {
- turn = await streamProviderTurn(provider, modelToUse, messages, streamOpts, liveContent, liveThinking)
+ turn = await streamProviderTurn(provider, modelToUse, sendMessages, streamOpts, liveContent, liveThinking)
} catch (thinkErr: any) {
if (thinkErr?.message?.includes('does not support thinking') || httpStatusOf(thinkErr) === 400) {
- turn = await streamProviderTurn(provider, modelToUse, messages, { ...streamOpts, thinking: undefined as unknown as boolean }, liveContent, () => {})
+ turn = await streamProviderTurn(provider, modelToUse, sendMessages, { ...streamOpts, thinking: undefined as unknown as boolean }, liveContent, () => {})
} else {
throw thinkErr
}
@@ -1159,7 +1257,11 @@ export function useCodex() {
},
)
const hermesSystem = buildHermesToolPrompt(hermesTools) + `\n\n${systemPrompt}`
+ // Both arrays: the working one so the NEXT step's budget still
+ // counts the hermes tool prompt, the send one because that is what
+ // actually goes out.
messages[0] = { role: 'system', content: hermesSystem }
+ sendMessages[0] = messages[0]
// Streamed prompt-transport turn (David 2026-07-31): prose renders
// token by token while the display filter keeps <tool_call> XML
// from ever flashing into the bubble. The parse below still runs
@@ -1172,7 +1274,7 @@ export function useCodex() {
const hermesTurn = await streamProviderTurn(
provider,
modelToUse,
- messages.map(m => ({ role: m.role, content: m.content })),
+ sendMessages.map(m => ({ role: m.role, content: m.content })),
{ ...chatOptions, thinking: undefined as unknown as boolean, contextWindow: numCtx },
(_full, delta) => {
shown += display.feed(delta)
@@ -1452,11 +1554,25 @@ export function useCodex() {
? narrationVerdict
: loopGuard.recordBatch(
toolCalls.map((tc) => ({ name: tc.function.name, args: JSON.stringify(tc.function.arguments) })),
+ // Reads whose newest result the builder just sent capped. Those
+ // re-reads are the decay working as designed: the bytes are gone
+ // from the prompt, so fetching them again is the correct move,
+ // not a loop (plan A1, LOOP-GUARD).
+ { trimmedReadKeys },
)
if (batchVerdict.action === 'halt') {
void diagLog('loop-guard-halt', { iter: i, reason: batchVerdict.reason })
const msg = `\n\n_(halted: ${batchVerdict.reason}. The model is looping. Try a stronger model for multi-step code tasks, or rephrase the instruction.)_`
useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + msg)
+ // A halt has to be visible in the thread itself, not only as a
+ // suffix on the answer: support cannot otherwise tell a loop halt
+ // apart from a model that simply stopped (plan A1, SICHTBARKEIT).
+ addBlock({
+ id: uuid(),
+ phase: 'reflection',
+ content: `⛔ Loop guard halted the run: ${batchVerdict.reason}.`,
+ timestamp: Date.now(),
+ })
break
}
// Steer is appended AFTER this iteration's assistant+tool messages
@@ -1469,6 +1585,12 @@ export function useCodex() {
// but put the anti-repeat instruction in front of the NEXT turn.
void diagLog('loop-guard-steer', { iter: i })
pendingSteer = batchVerdict.message
+ addBlock({
+ id: uuid(),
+ phase: 'reflection',
+ content: `↻ Loop guard steered the model: ${batchVerdict.message}`,
+ timestamp: Date.now(),
+ })
}
type BatchEntry = { tc: typeof toolCalls[number]; ac: AgentToolCall; blockId: string; injectedArgs: Record<string, any> }
@@ -1881,11 +2003,19 @@ export function useCodex() {
// "messages.N…ChatCompletionToolMessage.tool_call_id: Field required"
// and every follow-up turn in the conversation fails. Ollama/LM-Studio
// are lenient, which is why this only bit the cloud path.
+ // Remember which read produced which result message, so a later step
+ // that sends that result capped can tell the loop guard the re-read is
+ // legitimate. Registered on the pushed OBJECT, which is why it works
+ // for all three transports even though only one of them carries ids.
+ const rememberResult = (msg: ChatMessage, tc: { function: { name: string; arguments: unknown } }) => {
+ guardKeyOfResult.set(msg as unknown as object, guardKeyFor(tc))
+ return msg
+ }
if (providerId === 'openai' || providerId === 'anthropic' || providerId === 'lu-cloud') {
messages.push({ role: 'assistant', content: turnContent || '', tool_calls: toolCalls })
for (const { tc } of batch) {
const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!
- messages.push({ role: 'tool', content: resultTextFor(result), tool_call_id: tc.id })
+ messages.push(rememberResult({ role: 'tool', content: resultTextFor(result), tool_call_id: tc.id }, tc))
}
} else if (strategy === 'native') {
messages.push({
@@ -1897,7 +2027,7 @@ export function useCodex() {
})
for (const { tc } of batch) {
const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!
- messages.push({ role: 'tool', content: resultTextFor(result) })
+ messages.push(rememberResult({ role: 'tool', content: resultTextFor(result) }, tc))
}
} else {
for (const entry of batch) {
@@ -1906,7 +2036,10 @@ export function useCodex() {
role: 'assistant',
content: `<tool_call>\n{"name": "${entry.ac.toolName}", "arguments": ${JSON.stringify(entry.injectedArgs)}}\n</tool_call>`,
})
- messages.push({ role: 'user', content: buildHermesToolResult(entry.ac.toolName, resultTextFor(result)) })
+ messages.push(rememberResult(
+ { role: 'user', content: buildHermesToolResult(entry.ac.toolName, resultTextFor(result)) },
+ entry.tc,
+ ))
}
}
@@ -1920,6 +2053,12 @@ export function useCodex() {
if (failVerdict.action === 'halt') {
const msg = `\n\n_(halted: ${failVerdict.reason}. The model is looping. Try a stronger model for multi-step code tasks, or rephrase the instruction.)_`
useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + msg)
+ addBlock({
+ id: uuid(),
+ phase: 'reflection',
+ content: `⛔ Loop guard halted the run: ${failVerdict.reason}.`,
+ timestamp: Date.now(),
+ })
break
}
diff --git a/src/lib/__tests__/host-platform.test.ts b/src/lib/__tests__/host-platform.test.ts
index e8a3b15e..354f5742 100644
--- a/src/lib/__tests__/host-platform.test.ts
+++ b/src/lib/__tests__/host-platform.test.ts
@@ -115,12 +115,18 @@ describe('the tools really are gone', () => {
it('the agent prompt states the platform instead of spending a call on it', () => {
// There is no render harness in this repo, so the prompt is guarded at the
// source, like DownloadBadge-autoclose.test.ts does.
+ // 2.6.6 plan A5 split the block in two: the platform sentence is stable
+ // and stays where it was, the clock is volatile and moved to the very end
+ // of the prompt so a prefix cache can still match everything in front of
+ // it. Both halves still have to be there.
const agent = read('hooks', 'useAgentChat.ts')
- expect(agent).toMatch(/hostEnvironmentBlock\(\)/)
- expect(agent).toMatch(/OS, clock and timezone are stated above/)
+ expect(agent).toMatch(/platformPromptLine\(\)/)
+ expect(agent).toMatch(/hostClockLine\(\)/)
+ expect(agent).toMatch(/OS, clock and timezone are stated in this prompt/)
// Codex pays for the block too now (it never had the platform sentence).
const codex = read('hooks', 'useCodex.ts')
- expect(codex).toMatch(/hostEnvironmentBlock\(\)/)
+ expect(codex).toMatch(/platformPromptLine\(\)/)
+ expect(codex).toMatch(/hostClockLine\(\)/)
})
})
diff --git a/src/lib/__tests__/prefix-stability.test.ts b/src/lib/__tests__/prefix-stability.test.ts
new file mode 100644
index 00000000..50c7c5eb
--- /dev/null
+++ b/src/lib/__tests__/prefix-stability.test.ts
@@ -0,0 +1,157 @@
+/**
+ * A5: prefix stability and plan pruning (2.6.6 plan).
+ *
+ * An upstream prefix cache matches from byte 0 and stops at the first
+ * difference, so anything volatile near the front of the prompt costs the whole
+ * prompt. Three things were sitting there:
+ *
+ * 1. the clock, which changes every minute,
+ * 2. the RAG block, which changes every turn,
+ * 3. twenty near-identical copies of the same todo list, which change every
+ * step and are read past by the model anyway.
+ */
+
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+import { hostClockLine, hostEnvironmentBlock, platformPromptLine } from '../host-platform'
+import { pruneSupersededPlans, buildRequestMessages, SUPERSEDED_PLAN_NOTE, type DecayMessage } from '../context-decay'
+
+const src = (...p: string[]) => readFileSync(resolve(__dirname, '..', '..', ...p), 'utf8')
+
+describe('A5.1: the clock is its own line and it goes last', () => {
+ it('two prompts two minutes apart share an identical stable half', () => {
+ const stable = platformPromptLine('macos')
+ const a = `${stable}\n\n${hostClockLine(new Date('2026-08-21T12:00:00Z'))}`
+ const b = `${stable}\n\n${hostClockLine(new Date('2026-08-21T12:02:00Z'))}`
+ expect(a).not.toBe(b)
+ // Everything up to the clock is byte-identical, and the clock is at the end.
+ expect(a.slice(0, stable.length)).toBe(b.slice(0, stable.length))
+ expect(a.indexOf(stable)).toBe(0)
+ })
+
+ it('the clock line still names the date, so the retired clock tool is covered', () => {
+ const line = hostClockLine(new Date('2026-08-21T12:00:00Z'))
+ expect(line).toMatch(/August 2026/)
+ expect(line).toMatch(/Trust this line/)
+ })
+
+ it('the combined block is still the two halves joined, for callers that want it', () => {
+ const now = new Date('2026-08-21T12:00:00Z')
+ expect(hostEnvironmentBlock('linux', now))
+ .toBe(`${platformPromptLine('linux')}\n${hostClockLine(now)}`)
+ })
+
+ it('the coding loop appends the clock AFTER architect and repo map', () => {
+ const codex = src('hooks', 'useCodex.ts')
+ const clockAt = codex.indexOf('systemPrompt += `\\n\\n${hostClockLine()}`')
+ const repoMapAt = codex.indexOf('renderRepoMapSection(repoMap)')
+ const memoryAt = codex.indexOf('remembered context from previous conversations')
+ expect(clockAt).toBeGreaterThan(-1)
+ expect(clockAt).toBeGreaterThan(repoMapAt)
+ expect(clockAt).toBeGreaterThan(memoryAt)
+ })
+
+ it('the agent loop appends the clock after persona, memory and caveman', () => {
+ const agent = src('hooks', 'useAgentChat.ts')
+ const clockAt = agent.indexOf('agentSystemPrompt += `\\n\\n${hostClockLine()}`')
+ const cavemanAt = agent.indexOf('agent.caveman_load_failed')
+ expect(clockAt).toBeGreaterThan(-1)
+ expect(clockAt).toBeGreaterThan(cavemanAt)
+ })
+})
+
+describe('A5.3: the RAG block moved from byte 0 to the end', () => {
+ it('the plain chat appends retrieval instead of prepending it', () => {
+ const chat = src('hooks', 'useChat.ts')
+ expect(chat).not.toMatch(/systemPrompt = ragPrefix \+/)
+ expect(chat).toMatch(/ragSuffix = /)
+ expect(chat).toMatch(/if \(ragSuffix\) systemPrompt = \(systemPrompt \|\| ''\) \+ ragSuffix/)
+ })
+
+ it('the append lands after the memory block, not before it', () => {
+ const chat = src('hooks', 'useChat.ts')
+ const memoryAt = chat.indexOf('remembered context from previous conversations')
+ const appendAt = chat.indexOf("if (ragSuffix) systemPrompt = (systemPrompt || '') + ragSuffix")
+ expect(memoryAt).toBeGreaterThan(-1)
+ expect(appendAt).toBeGreaterThan(memoryAt)
+ })
+
+ it('the agent surface got the same treatment', () => {
+ const agent = src('hooks', 'useAgentChat.ts')
+ expect(agent).toMatch(/ragSuffix = /)
+ expect(agent).toMatch(/agentSystemPrompt \+= ragSuffix/)
+ })
+})
+
+/** A history with `n` plan updates, each one a complete rewrite of the list. */
+function planHistory(n: number, mixed = false): DecayMessage[] {
+ const out: DecayMessage[] = [
+ { role: 'system', content: 'SYSTEM' },
+ { role: 'user', content: 'build it' },
+ ]
+ for (let i = 1; i <= n; i++) {
+ const calls: any[] = [{ id: `t${i}`, function: { name: 'todo_write', arguments: { todos: [`step ${i}`] } } }]
+ if (mixed) calls.push({ id: `r${i}`, function: { name: 'file_read', arguments: { path: 'a.ts' } } })
+ out.push({ role: 'assistant', content: '', tool_calls: calls })
+ out.push({ role: 'tool', content: `plan v${i}: ${'item '.repeat(200)}`, tool_call_id: `t${i}` })
+ if (mixed) out.push({ role: 'tool', content: `file body ${i}`, tool_call_id: `r${i}` })
+ }
+ return out
+}
+
+describe('A5.2: only the newest plan state survives', () => {
+ it('five plan updates leave exactly one todo_write pair', () => {
+ const { messages, prunedCount } = pruneSupersededPlans(planHistory(5))
+ const remaining = messages.filter(
+ (m) => Array.isArray(m.tool_calls) && JSON.stringify(m.tool_calls).includes('todo_write'),
+ )
+ expect(remaining).toHaveLength(1)
+ expect(prunedCount).toBe(8) // four pairs
+ })
+
+ it('the survivor is the NEWEST plan, not the first', () => {
+ const { messages } = pruneSupersededPlans(planHistory(5))
+ const results = messages.filter((m) => m.role === 'tool')
+ expect(String(results[results.length - 1].content)).toContain('plan v5')
+ expect(messages.some((m) => String(m.content ?? '').includes('plan v1'))).toBe(false)
+ })
+
+ it('a single plan update is left completely alone', () => {
+ const history = planHistory(1)
+ const { messages, prunedCount } = pruneSupersededPlans(history)
+ expect(prunedCount).toBe(0)
+ expect(messages.map((m) => m.content)).toEqual(history.map((m) => m.content))
+ })
+
+ it('in a mixed batch the call stays and only the result text is replaced', () => {
+ // Dropping half a batch would leave a tool_call with no result, which
+ // strict OpenAI-compatible providers reject outright.
+ const history = planHistory(3, true)
+ const { messages } = pruneSupersededPlans(history)
+ expect(messages).toHaveLength(history.length)
+ const superseded = messages.filter((m) => m.content === SUPERSEDED_PLAN_NOTE)
+ expect(superseded).toHaveLength(2)
+ // The file results in the same batches are untouched.
+ expect(messages.some((m) => m.content === 'file body 1')).toBe(true)
+ })
+
+ it('saves real tokens on a long run', () => {
+ const history = planHistory(10)
+ const pruned = buildRequestMessages(history, { budgetTokens: 100000 })
+ const raw = buildRequestMessages(history, { budgetTokens: 100000, prunePlans: false })
+ expect(pruned.prunedPlans).toBe(18)
+ expect(pruned.promptTokens).toBeLessThan(raw.promptTokens / 2)
+ })
+
+ it('negative control: with pruning off every copy still rides along', () => {
+ const raw = buildRequestMessages(planHistory(5), { budgetTokens: 100000, prunePlans: false })
+ const plans = raw.messages.filter((m) => String(m.content ?? '').startsWith('plan v'))
+ expect(plans).toHaveLength(5)
+ })
+
+ it('the notaus switches plan pruning off with the decay', () => {
+ const off = buildRequestMessages(planHistory(5), { budgetTokens: 100000, enabled: false })
+ expect(off.prunedPlans).toBe(0)
+ })
+})
diff --git a/src/lib/host-platform.ts b/src/lib/host-platform.ts
index f62b271e..a4eb98e1 100644
--- a/src/lib/host-platform.ts
+++ b/src/lib/host-platform.ts
@@ -75,6 +75,24 @@ export function hostEnvironmentBlock(
p: HostPlatform = hostPlatform(),
now: Date = new Date(),
): string {
+ return [platformPromptLine(p), hostClockLine(now)].join('\n')
+}
+
+/**
+ * The clock half of the environment block, on its own.
+ *
+ * This one line is the single most expensive character sequence in the whole
+ * system prompt (2.6.6, plan A5). It changes every minute, and it used to sit
+ * near the TOP of the prompt, ahead of the persona, the rules and the repo
+ * map. An upstream prefix cache matches from byte 0 and stops at the first
+ * difference, so a timestamp up there means every new turn re-prices the ENTIRE
+ * prompt as a cache miss. Everything volatile now goes last, and the stable
+ * head in front of it is byte-identical from turn to turn.
+ *
+ * The wording is unchanged, only the position: it still replaces the retired
+ * clock tool, so it still has to name the date of the run.
+ */
+export function hostClockLine(now: Date = new Date()): string {
let tz = ''
try {
tz = Intl.DateTimeFormat().resolvedOptions().timeZone ?? ''
@@ -82,8 +100,5 @@ export function hostEnvironmentBlock(
// No timezone is better than a wrong one.
}
const stamp = now.toLocaleString('en-GB', { dateStyle: 'full', timeStyle: 'short' })
- return [
- platformPromptLine(p),
- `Date and time at the start of this run: ${stamp}${tz ? ` (${tz})` : ''}. Trust this line; there is no clock tool.`,
- ].join('\n')
+ return `Date and time at the start of this run: ${stamp}${tz ? ` (${tz})` : ''}. Trust this line; there is no clock tool.`
}