diff --git a/packages/coding-agent/docs/compaction.md b/packages/coding-agent/docs/compaction.md index fb6b3929..0f8a63be 100644 --- a/packages/coding-agent/docs/compaction.md +++ b/packages/coding-agent/docs/compaction.md @@ -43,6 +43,19 @@ Non-cancelled failures append a versioned `step-compaction-failure` custom entry A `length` response remains an incomplete summary and is never saved as a successful checkpoint. Check model output limits and input headroom rather than assuming increasing `reserveTokens` increases the output cap. Transient transport failures use the existing bounded retry policy; deterministic malformed responses and cancellations do not become network retries. +A `length` response is not immediately fatal: reasoning shares the model's output cap with the summary body, so a request that thinks too much can truncate a summary that would otherwise fit. Two recovery steps run in order and are recorded in `degradations`: + +1. `thinking-off` — resend the unchanged input with reasoning removed. +2. `tight-target` — resend with a tightened length budget appended to the prompt. + +When both are spent the truncated response is reported as a failure with the steps already applied. This is a deterministic failure: an identical request, model and cap cannot succeed on retry, so automatic threshold compaction pauses on the first occurrence instead of after the transient-failure limit. + +### Summarization Request Policy + +Reasoning and the summary body share one output cap. The session's thinking level is therefore only a ceiling: `compaction.thinkingLevel` (default `low`) caps it, `"inherit"` restores the old behavior of passing the session level through, and the result is clamped to what the model accepts. + +`compaction.summaryTargetTokens` (default 16000) gives the prompt an explicit budget, capped at half the model's output limit so reasoning has room. The update prompt consolidates rather than copies the previous summary forward, so the summary converges instead of growing monotonically across compactions. + ## Compaction ### When It Triggers @@ -440,6 +453,8 @@ Configure compaction in `~/.stepcode/config.toml` or trusted `/.ste enabled = true triggerRatio = 0.9 keepRecentTokens = 20000 +thinkingLevel = "low" +summaryTargetTokens = 16000 [compaction.modelTriggerRatios] "my-provider/small-window-model" = 0.8 @@ -454,6 +469,8 @@ keepRecentTokens = 20000 | `triggerPolicy` | `"v2"` | `"legacy"` restores the previous threshold and checkpoints | | `reserveTokens` | `16384` | Legacy trigger headroom; when set explicitly, also caps the v2 trigger at `contextWindow - reserveTokens` | | `keepRecentTokens` | `20000` | Recent tokens to keep (not summarized) | +| `thinkingLevel` | `"low"` | Thinking-level ceiling for summarization requests; the session level is an upper bound, `"inherit"` keeps it | +| `summaryTargetTokens` | `16000` | Token target for the summary; capped at half the model's output limit | Invalid trigger values fall back to their defaults and are reported as settings warnings at startup. diff --git a/packages/coding-agent/docs/settings.md b/packages/coding-agent/docs/settings.md index fb8ca6b2..72e8ad53 100644 --- a/packages/coding-agent/docs/settings.md +++ b/packages/coding-agent/docs/settings.md @@ -128,6 +128,8 @@ anthropicExtraUsage = false | `compaction.triggerPolicy` | string | `"v2"` | `"legacy"` restores the previous `contextWindow - reserveTokens` trigger and checkpoints | | `compaction.reserveTokens` | number | `16384` | Legacy trigger headroom; under v2 an explicit value also caps the trigger at `contextWindow - reserveTokens` | | `compaction.keepRecentTokens` | number | `20000` | Recent tokens to keep (not summarized) | +| `compaction.thinkingLevel` | string | `"low"` | Thinking-level ceiling for summarization requests; the session level is an upper bound, `"inherit"` keeps it | +| `compaction.summaryTargetTokens` | number | `16000` | Token target for the summary; capped at half the model's output limit | | `compaction.contextProjection` | string | `"off"` | `off` selects native compaction, `lightweight-v1` selects deterministic projection, `clm-v1` opts into CLM | | `compaction.autoClm.enabled` | boolean | `true` | Attempt bounded CLM maintenance before native compaction | @@ -136,11 +138,18 @@ anthropicExtraUsage = false enabled = true triggerRatio = 0.9 keepRecentTokens = 20000 +thinkingLevel = "low" +summaryTargetTokens = 16000 ``` Compaction summaries use the provider's normal model/output and remaining-context budget. `compaction.reserveTokens` does not set a separate summary output cap. +Reasoning shares that output cap with the summary body, so the session's thinking +level is capped by `compaction.thinkingLevel` rather than passed through. A summary +that still hits the output limit is retried once with reasoning removed and once +with a tightened budget before it fails. + ### Branch Summary | Setting | Type | Default | Description | diff --git a/packages/coding-agent/schema/config.schema.json b/packages/coding-agent/schema/config.schema.json index 5e80a488..fb5a1cef 100644 --- a/packages/coding-agent/schema/config.schema.json +++ b/packages/coding-agent/schema/config.schema.json @@ -229,6 +229,48 @@ ], "description": "Context projection mode: `off` (default, native compaction), `lightweight-v1`, or `clm-v1`." }, + "thinkingLevel": { + "anyOf": [ + { + "type": "string", + "const": "inherit" + }, + { + "type": "string", + "const": "off" + }, + { + "type": "string", + "const": "minimal" + }, + { + "type": "string", + "const": "low" + }, + { + "type": "string", + "const": "medium" + }, + { + "type": "string", + "const": "high" + }, + { + "type": "string", + "const": "xhigh" + }, + { + "type": "string", + "const": "max" + } + ], + "description": "Thinking level ceiling for summarization requests (default `low`). The session level is an upper bound; `inherit` keeps it. Reasoning shares the output cap with the summary, so an uncapped level truncates the summary on adaptive-thinking models." + }, + "summaryTargetTokens": { + "type": "integer", + "minimum": 1, + "description": "Token target for the generated summary (default 16000). Capped at half the model's output limit; an invalid value is ignored." + }, "autoClm": { "type": "object", "properties": { diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts index fe7fa8cb..4e27a3f0 100644 --- a/packages/coding-agent/src/core/agent-session.ts +++ b/packages/coding-agent/src/core/agent-session.ts @@ -88,6 +88,7 @@ import { type ProjectionByRuleStats, prepareCompaction, projectContextForRequest, + resolveCompactionThinkingLevel, resolveCompactionThreshold, shouldCompact, } from "./compaction/index.ts"; @@ -99,7 +100,12 @@ import { type LiveContextStatus, } from "./compaction/live-context/manager.ts"; import { StableContextNotices } from "./compaction/live-context/stable-notices.ts"; -import { formatRetryPolicy, formatSummaryDiagnostics, SummaryFailure } from "./compaction/summary-diagnostics.ts"; +import { + formatRetryPolicy, + formatSummaryDiagnostics, + isTruncatedSummaryFailure, + SummaryFailure, +} from "./compaction/summary-diagnostics.ts"; import { DEFAULT_THINKING_LEVEL, THINKING_LEVEL_OPTIONS } from "./defaults.ts"; import { SessionExecutionTrace } from "./execution-trace.ts"; import { exportSessionToHtml, type ToolHtmlRenderer } from "./export-html/index.ts"; @@ -526,8 +532,13 @@ export class AgentSession { private _autoClmAbortController?: AbortController; private _manualClm = false; private _nativeThresholdBoundary?: string; - /** Consecutive failed automatic threshold compactions; v2 pauses automatic compaction at the limit. */ - private _thresholdCompactionFailures = 0; + /** + * Consecutive failed automatic threshold compactions, keyed by the identity of the + * attempt that failed. A different summarizer, output cap, context window or + * thinking level is a genuinely new attempt, so its failures start from zero; the + * same key keeps counting until a compaction succeeds. + */ + private _thresholdCompactionFailure: { fingerprint: string; count: number } | undefined; /** * What `_runAgentPrompt` measured for the prompt's first request. The before-request hook skips its * check only when the outgoing request still matches, so input added afterwards is measured again. @@ -865,10 +876,11 @@ export class AgentSession { // While paused, skip measurement too: a persistent estimator fault must stop being retried. if (this._thresholdCompactionPaused()) return context; const previousCompaction = getLatestCompactionEntry(this.sessionManager.getBranch())?.id; + // The model the request will use; a maintenance fault is counted against it. + const model = this.model; try { const automatic = await this._runAutomaticClm(context, signal); if (!automatic?.attempted) { - const model = this.model; if ( model && model.contextWindow > 0 && @@ -885,7 +897,7 @@ export class AgentSession { } catch (error) { // Maintenance is optional for this request: send it as-is, and let overflow recovery cover a // request that does not fit. _runAutoCompaction reports its own failures. - if (!signal?.aborted) this._recordMaintenanceFault(error); + if (!signal?.aborted) this._recordMaintenanceFault(error, model); } // Only native compaction rebuilds canonical state. Otherwise keep the loop context // while CLM overlays its existing prefix. @@ -937,15 +949,61 @@ export class AgentSession { /** Automatic threshold maintenance pauses after repeated failures until a compaction succeeds. */ private _thresholdCompactionPaused(): boolean { - return this._usesTriggerPolicyV2() && this._thresholdCompactionFailures >= AUTO_COMPACTION_FAILURE_LIMIT; + if (!this._usesTriggerPolicyV2() || !this.model) return false; + const failure = this._thresholdCompactionFailure; + // Only the attempt that failed is paused. A different summarizer, output cap, + // window or thinking level gets its own chance, so the pause must not follow it. + return ( + failure?.fingerprint === this._thresholdCompactionFingerprint(this.model) && + failure.count >= AUTO_COMPACTION_FAILURE_LIMIT + ); + } + + /** + * Identity of the next automatic threshold compaction. Everything that decides + * whether the same request can succeed again is part of it: the summarizer, its + * output cap, the context window that sets the trigger, and the thinking level the + * summary request will use. Switching models to another key restarts the count; + * switching back resumes it. + */ + private _thresholdCompactionFingerprint(model: Model): string { + const thinkingLevel = resolveCompactionThinkingLevel( + model, + this.thinkingLevel, + this.settingsManager.getCompactionThinkingLevel(), + ); + return [ + `${model.provider}/${model.id}`, + `maxTokens=${model.maxTokens}`, + `window=${model.contextWindow}`, + `thinking=${thinkingLevel}`, + ].join("|"); + } + + /** Record a threshold-compaction failure against the attempt's fingerprint. */ + private _recordThresholdCompactionFailure(model: Model, deterministic = false): void { + const fingerprint = this._thresholdCompactionFingerprint(model); + const previous = + this._thresholdCompactionFailure?.fingerprint === fingerprint ? this._thresholdCompactionFailure.count : 0; + // A deterministic failure (the recovery ladder is spent) cannot succeed on an + // identical retry, so it saturates the budget instead of spending it one by one. + this._thresholdCompactionFailure = { + fingerprint, + count: deterministic ? AUTO_COMPACTION_FAILURE_LIMIT : previous + 1, + }; + } + + /** Clear the failure count after a compaction or CLM edit succeeded. */ + private _clearThresholdCompactionFailures(): void { + this._thresholdCompactionFailure = undefined; } /** * Record an unexpected throw while measuring or preparing automatic maintenance. It is persisted as a * compaction failure diagnostic and counts toward the pause, so a persistent fault stops being retried. */ - private _recordMaintenanceFault(error: unknown): void { - this._thresholdCompactionFailures++; + private _recordMaintenanceFault(error: unknown, model: Model | undefined = this.model): void { + if (model) this._recordThresholdCompactionFailure(model); try { this._recordCompactionFailure(error, "threshold"); } catch { @@ -1173,7 +1231,7 @@ export class AgentSession { } if (!result.attempted) return result; // An accepted CLM edit is a successful automatic maintenance; it ends a failure streak. - if (result.accepted) this._thresholdCompactionFailures = 0; + if (result.accepted) this._clearThresholdCompactionFailures(); if (result.outcome) this._emit({ type: "live_context", outcome: result.outcome }); this._emit({ type: "auto_clm_end", result }); if (result.fallback && !signal?.aborted && !interrupted()) { @@ -1620,7 +1678,7 @@ export class AgentSession { this.agent.state.messages, signal ?? this._agentRunAbortController?.signal, ); - if (outcome?.accepted) this._thresholdCompactionFailures = 0; + if (outcome?.accepted) this._clearThresholdCompactionFailures(); if (outcome) this._emit({ type: "live_context", outcome }); } }; @@ -3187,8 +3245,6 @@ export class AgentSession { source: "set" | "cycle" | "restore", ): Promise { if (modelsAreEqual(previousModel, nextModel)) return; - // A different model has its own window and summarizer behavior; give automatic compaction a fresh start. - this._thresholdCompactionFailures = 0; await this._extensionRunner.emit({ type: "model_select", model: nextModel, @@ -3455,6 +3511,13 @@ export class AgentSession { env: Record | undefined, reason: "manual" | "threshold" | "overflow", ): Promise { + // Reasoning shares the output cap with the summary body, so the session level + // is capped by `compaction.thinkingLevel` instead of being inherited as-is. + const thinkingLevel = resolveCompactionThinkingLevel( + requestModel, + this.thinkingLevel, + this.settingsManager.getCompactionThinkingLevel(), + ); return this._trace.withSummaryPurpose("compaction", () => compact( preparation, @@ -3463,7 +3526,7 @@ export class AgentSession { headers, customInstructions, signal, - this.thinkingLevel, + thinkingLevel, this.agent.streamFunction, env, this.settingsManager.getRetrySettings(), @@ -3592,7 +3655,7 @@ export class AgentSession { usage, ); this._trace.recordSummary("compaction", compactionEntryId); - this._thresholdCompactionFailures = 0; + this._clearThresholdCompactionFailures(); const newEntries = this.sessionManager.getEntries(); const sessionContext = this.sessionManager.buildSessionContext(); this.agent.state.messages = sessionContext.messages; @@ -4027,7 +4090,7 @@ export class AgentSession { ); this._trace.recordSummary("compaction", compactionEntryId); committed = true; - this._thresholdCompactionFailures = 0; + this._clearThresholdCompactionFailures(); const newEntries = this.sessionManager.getEntries(); const sessionContext = this.sessionManager.buildSessionContext(); this.agent.state.messages = sessionContext.messages; @@ -4089,9 +4152,15 @@ export class AgentSession { // A throw after the compaction was persisted (for example from a session_compact // handler) is not a failed compaction, so it does not count toward the pause. if (!aborted && !committed && reason === "threshold") { - this._thresholdCompactionFailures++; + // A summary the degradation ladder could not rescue is deterministic: the + // same request, model and cap fail again, so pause immediately instead of + // repeating it for the remaining transient-failure budget. + const deterministic = error instanceof SummaryFailure && isTruncatedSummaryFailure(error); + if (this.model) this._recordThresholdCompactionFailure(this.model, deterministic); if (this._thresholdCompactionPaused()) { - formattedErrorMessage += `\nAutomatic compaction is paused for this session after ${AUTO_COMPACTION_FAILURE_LIMIT} consecutive failures. Run /compact to retry; a successful compaction resumes it.`; + formattedErrorMessage += deterministic + ? `\nAutomatic compaction is paused: the summary hit the output limit even after dropping reasoning and tightening the target. Run /compact to retry; a successful compaction resumes it.` + : `\nAutomatic compaction is paused for this session after ${AUTO_COMPACTION_FAILURE_LIMIT} consecutive failures. Run /compact to retry; a successful compaction resumes it.`; } } this._emit({ @@ -4233,8 +4302,7 @@ export class AgentSession { } this.agent.state.model = refreshedModel; - // A changed window moves the trigger, like a model switch; give automatic compaction a fresh start. - if (refreshedModel.contextWindow !== currentModel.contextWindow) this._thresholdCompactionFailures = 0; + // A changed window moves the trigger; the failure fingerprint already covers it. } private _bindExtensionCore(runner: ExtensionRunner): void { diff --git a/packages/coding-agent/src/core/compaction/compaction.ts b/packages/coding-agent/src/core/compaction/compaction.ts index 630c201a..bfcf5e29 100644 --- a/packages/coding-agent/src/core/compaction/compaction.ts +++ b/packages/coding-agent/src/core/compaction/compaction.ts @@ -43,6 +43,11 @@ import { summaryFailure, } from "./summary-diagnostics.ts"; import { createSummarySourceReducer } from "./summary-overflow.ts"; +import { + DEFAULT_COMPACTION_SUMMARY_TARGET_TOKENS, + resolveSummaryLengthBudget, + type SummaryLengthBudget, +} from "./summary-policy.ts"; import { computeFileLists, createFileOps, @@ -53,7 +58,6 @@ import { safeJsonStringify, serializeConversation, } from "./utils.ts"; - // ============================================================================ // File Operation Tracking // ============================================================================ @@ -157,6 +161,12 @@ export interface CompactionSettings { enabled: boolean; reserveTokens: number; keepRecentTokens: number; + /** + * Token target for the generated summary. Undefined uses + * {@link DEFAULT_COMPACTION_SUMMARY_TARGET_TOKENS}; the model's output cap + * still caps it. + */ + summaryTargetTokens?: number; } export const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = { @@ -165,6 +175,7 @@ export const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = { // Summary output is sized separately by the provider. reserveTokens: 24576, keepRecentTokens: 20000, + summaryTargetTokens: DEFAULT_COMPACTION_SUMMARY_TARGET_TOKENS, }; // ============================================================================ @@ -532,34 +543,87 @@ const SUMMARY_DETAIL_RULES = `Detail requirements: 3. Keep negative information: failures, dead ends, and disproven hypotheses are as important as successes — they stop the next model from repeating them. 4. Separate facts from inference: if something was not directly observed in the conversation, label it as inferred or unverified. 5. No empty statements: "fixed the bug" or "made progress" is useless — every item must say what changed, where, and what evidence supports it. -6. If you must shorten, first cut repetition, rhetoric, and background that is closed or superseded; cut the active User Goal, Verification results, and Next Actions last. +6. If you must shorten, first cut repetition, rhetoric, and background that is closed or superseded; cut the active User Goal, Verification results, and Next Actions last.`; -Be thorough. A complete handoff matters more than brevity, but every line must carry information the next model can act on.`; +const SUMMARIZATION_PROMPT_HEAD = `The messages above are a conversation to summarize. Produce a structured handoff summary that the next model instance will use to continue the work. The summarized messages will be discarded: your summary replaces them entirely. -const SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Produce a structured handoff summary that the next model instance will use to continue the work. The summarized messages will be discarded: your summary replaces them entirely. +Use this EXACT format:`; -Use this EXACT format: - -${SUMMARY_FORMAT} - -${SUMMARY_DETAIL_RULES}`; - -const UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing handoff summary provided in tags. +const UPDATE_SUMMARIZATION_PROMPT_HEAD = `The messages above are NEW conversation messages to incorporate into the existing handoff summary provided in tags. Update the summary so it remains a complete handoff for the next model instance. RULES: -- PRESERVE Done items from the previous summary together with their recorded results; do not drop or dilute them. +- PRESERVE the User Goal, Verification results and Next Actions that are still active. - Move items from "In Progress" to "Done" ONLY when the new messages provide concrete evidence of completion; otherwise update where they stand. +- CONSOLIDATE the previous summary instead of copying it forward: a Done item whose result is no longer referenced by any active goal or Next Action collapses to one line (path or identifier plus outcome), and duplicates merge. +- Drop facts, references and failed approaches that newer messages have superseded. - Do NOT repeat or re-expand Failed Approaches already recorded; keep each recorded once and add newly failed approaches. -- REMOVE Next Actions that were completed or are now obsolete; add new ones reflecting the current state. - ADD new files, verification results, decisions, and constraints from the new messages. - PRESERVE exact file paths, function names, commands, exit codes, and error lines. -- Remove other content only when it is clearly superseded or no longer relevant to any active goal. -Use this EXACT format: +Use this EXACT format:`; + +const TURN_PREFIX_SUMMARIZATION_PROMPT_HEAD = `The messages above are the PREFIX of a single turn that was too large to keep in context. The most recent part of the turn (the suffix) is retained verbatim; your summary replaces only this prefix and is read together with the retained suffix. + +Produce a structured handoff summary of the prefix so the next model instance can understand the retained suffix and finish the turn. Scope every section to this turn's prefix; use "(none)" where the prefix has nothing to report. + +Use this EXACT format:`; + +/** Budget rule appended to {@link SUMMARY_DETAIL_RULES} with concrete token numbers. */ +const summaryLengthRule = (targetTokens: number, hardCapTokens: number): string => + [ + ` Length budget: aim for at most ${targetTokens} tokens and never exceed ${hardCapTokens}.`, + ` The budget is a hard output limit, not a preference: a summary that runs past it is truncated and discarded, and the whole compaction has to be retried.`, + ` When you are over budget, cut in the order of rule 6. Every line must carry information the next model can act on.`, + ].join(""); +/** + * Build the prompt for a first-time summary. + * + * @param budget - token budget resolved from the summarization model's output cap + */ +function buildSummarizationPrompt(budget: SummaryLengthBudget): string { + return `${SUMMARIZATION_PROMPT_HEAD} + +${SUMMARY_FORMAT} + +${SUMMARY_DETAIL_RULES} + +${summaryLengthRule(budget.targetTokens, budget.hardCapTokens)}`; +} + +/** + * Build the prompt that folds new messages into an existing summary. + * + * @param budget - token budget resolved from the summarization model's output cap + */ +function buildUpdateSummarizationPrompt(budget: SummaryLengthBudget): string { + return `${UPDATE_SUMMARIZATION_PROMPT_HEAD} + +${SUMMARY_FORMAT} + +${SUMMARY_DETAIL_RULES} + +${summaryLengthRule(budget.targetTokens, budget.hardCapTokens)}`; +} + +/** + * Build the prompt for the prefix of a split turn. + * + * @param budget - token budget resolved from the summarization model's output cap + */ +function buildTurnPrefixPrompt(budget: SummaryLengthBudget): string { + return `${TURN_PREFIX_SUMMARIZATION_PROMPT_HEAD} ${SUMMARY_FORMAT} -${SUMMARY_DETAIL_RULES}`; +${SUMMARY_DETAIL_RULES} + +${summaryLengthRule(budget.targetTokens, budget.hardCapTokens)}`; +} + +/** Tighten the budget after a summary still hit the output cap. */ +function buildTightTargetSuffix(budget: SummaryLengthBudget): string { + return `\n\nThe previous attempt was cut off by the output limit. Rewrite the summary at half the length: aim for at most ${Math.max(1, Math.floor(budget.targetTokens / 2))} tokens. Merge related items into single lines, drop the least load-bearing detail first, and never leave a section truncated.`; +} /** * Returns an error message when a summarization response cannot safely be persisted. @@ -659,6 +723,8 @@ export async function completeSummarization( /** * Generate a summary of the conversation using the LLM. * If previousSummary is provided, uses the update prompt to merge. + * + * @param summaryTargetTokens - token target for the summary; undefined uses the default */ export async function generateSummary( currentMessages: AgentMessage[], @@ -676,6 +742,7 @@ export async function generateSummary( retry?: RetryPolicy, callbacks?: RetryCallbacks, sessionId?: string, + summaryTargetTokens?: number, ): Promise { return ( await generateSummaryWithUsage( @@ -693,6 +760,7 @@ export async function generateSummary( retry, callbacks, sessionId, + summaryTargetTokens, ) ).text; } @@ -714,11 +782,21 @@ function buildSummarizationContext(promptText: string): Context { /** Shares of the first rejected request's estimate, never compounded across retries. */ const SUMMARY_OVERFLOW_TARGETS = [0.7, 0.5, 0.35] as const; +/** + * Steps applied when a summary is cut off by the output cap, in order. The first + * step recovers the common case, where reasoning ate most of the output budget; + * the second targets a summary whose body alone is too long. Once both are spent + * the truncated response is returned so the caller fails with the diagnostics. + */ +const TRUNCATION_DEGRADATIONS = ["thinking-off", "tight-target"] as const; + /** * Keep the initial summary payload intact, reducing only its source history after an * explicit context-overflow error. The outer transient policy retains one retry budget * across reductions; completeSummarization performs each individual request with the * usual cache/routing behavior. Branch summaries keep their existing independent path. + * + * @param tightPromptSuffix - appended to the prompt on the last truncation step */ async function completeSummaryWithOverflowRecovery( messages: AgentMessage[], @@ -729,6 +807,7 @@ async function completeSummaryWithOverflowRecovery( streamFn?: StreamFn, retry?: RetryPolicy, callbacks?: RetryCallbacks, + tightPromptSuffix?: string, ): Promise { let conversation = serializeConversation(convertToLlm(messages)); let context = buildSummarizationContext(buildPrompt(conversation)); @@ -742,6 +821,7 @@ async function completeSummaryWithOverflowRecovery( let usage: Usage | undefined; let lastResponse: AssistantMessage | undefined; let attempts = 0; + const appliedDegradations: string[] = []; const startedAt = Date.now(); const requestOptions = { ...options, sessionId: options.sessionId ?? uuidv7() }; @@ -775,6 +855,23 @@ async function completeSummaryWithOverflowRecovery( inputTokens: estimateRequestTokens(textUtf8ByteLength(conversation)), maxTokens: requestOptions.maxTokens ?? model.maxTokens ?? 0, }); + // Output truncation is recoverable: reasoning shares the output cap with the + // summary body, so dropping it (and then tightening the target) usually + // fits. When the ladder is spent the truncated response is returned and the + // caller reports the failure with the steps already applied. + if (response.stopReason === "length") { + const step = TRUNCATION_DEGRADATIONS[appliedDegradations.length]; + if (step === undefined) return response; + appliedDegradations.push(step); + if (step === "thinking-off") { + // Delete rather than assign undefined: a present key with an undefined + // value still reaches the provider as an explicit reasoning setting. + delete requestOptions.reasoning; + } else { + context = buildSummarizationContext(buildPrompt(conversation) + (tightPromptSuffix ?? "")); + } + continue; + } if ( response.stopReason !== "error" || (!isContextOverflow(response, model.contextWindow) && @@ -808,7 +905,12 @@ async function completeSummaryWithOverflowRecovery( const result = { ...response, usage: usage ?? response.usage }; const diagnostics = getSummaryDiagnostics(response); if (diagnostics) { - saveSummaryDiagnostics(result, { ...diagnostics, attempts, durationMs: Date.now() - startedAt }); + saveSummaryDiagnostics(result, { + ...diagnostics, + attempts, + degradations: appliedDegradations, + durationMs: Date.now() - startedAt, + }); } return result; } catch (error) { @@ -824,7 +926,12 @@ async function completeSummaryWithOverflowRecovery( if (lastResponse && !options.signal?.aborted) { const diagnostics = getSummaryDiagnostics(lastResponse); if (diagnostics) { - saveSummaryDiagnostics(lastResponse, { ...diagnostics, attempts, durationMs: Date.now() - startedAt }); + saveSummaryDiagnostics(lastResponse, { + ...diagnostics, + attempts, + degradations: appliedDegradations, + durationMs: Date.now() - startedAt, + }); throw summaryFailure(error instanceof Error ? error.message : String(error), lastResponse); } } @@ -849,9 +956,11 @@ export async function generateSummaryWithUsage( retry?: RetryPolicy, callbacks?: RetryCallbacks, sessionId?: string, + summaryTargetTokens?: number, ): Promise<{ text: string; usage: Usage }> { + const budget = resolveSummaryLengthBudget(model, summaryTargetTokens); // Use update prompt if we have a previous summary, otherwise initial prompt - let basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT; + let basePrompt = previousSummary ? buildUpdateSummarizationPrompt(budget) : buildSummarizationPrompt(budget); if (customInstructions) { basePrompt = `${basePrompt}\n\nAdditional focus: ${customInstructions}`; } @@ -876,6 +985,7 @@ export async function generateSummaryWithUsage( streamFn, retry, callbacks, + buildTightTargetSuffix(budget), ); if (response.stopReason === "aborted") { @@ -1021,16 +1131,6 @@ export function prepareCompaction( // Main compaction function // ============================================================================ -const TURN_PREFIX_SUMMARIZATION_PROMPT = `The messages above are the PREFIX of a single turn that was too large to keep in context. The most recent part of the turn (the suffix) is retained verbatim; your summary replaces only this prefix and is read together with the retained suffix. - -Produce a structured handoff summary of the prefix so the next model instance can understand the retained suffix and finish the turn. Scope every section to this turn's prefix; use "(none)" where the prefix has nothing to report. - -Use this EXACT format: - -${SUMMARY_FORMAT} - -${SUMMARY_DETAIL_RULES}`; - /** * Generate summaries for compaction using prepared data. * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving. @@ -1062,7 +1162,9 @@ export async function compact( previousSummary, fileOps, activeSkills = [], + settings, } = preparation; + const summaryTargetTokens = settings.summaryTargetTokens; // Generate summaries and merge into one let summary: string; @@ -1088,6 +1190,7 @@ export async function compact( retry, callbacks, sessionId, + summaryTargetTokens, ); historyText = historyResult.text; historyUsage = historyResult.usage; @@ -1104,6 +1207,7 @@ export async function compact( retry, callbacks, sessionId, + summaryTargetTokens, ); // Merge into single summary summary = `${historyText}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixResult.text}`; @@ -1125,6 +1229,7 @@ export async function compact( retry, callbacks, sessionId, + summaryTargetTokens, ); summary = result.text; summaryUsage = result.usage; @@ -1167,18 +1272,21 @@ async function generateTurnPrefixSummary( retry?: RetryPolicy, callbacks?: RetryCallbacks, sessionId?: string, + summaryTargetTokens?: number, ): Promise<{ text: string; usage: Usage }> { + const budget = resolveSummaryLengthBudget(model, summaryTargetTokens); // The suffix of the turn is retained verbatim, so the summary only needs // to describe the prefix. const response = await completeSummaryWithOverflowRecovery( messages, - (conversation) => `\n${conversation}\n\n\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`, + (conversation) => `\n${conversation}\n\n\n${buildTurnPrefixPrompt(budget)}`, model, createSummarizationOptions(model, apiKey, headers, env, signal, thinkingLevel, sessionId), "Turn prefix summarization", streamFn, retry, callbacks, + buildTightTargetSuffix(budget), ); if (response.stopReason === "aborted") { diff --git a/packages/coding-agent/src/core/compaction/index.ts b/packages/coding-agent/src/core/compaction/index.ts index 66241fad..22fd5445 100644 --- a/packages/coding-agent/src/core/compaction/index.ts +++ b/packages/coding-agent/src/core/compaction/index.ts @@ -5,5 +5,6 @@ export * from "./branch-summarization.ts"; export * from "./compaction.ts"; export * from "./projection.ts"; +export * from "./summary-policy.ts"; export * from "./trigger-policy.ts"; export * from "./utils.ts"; diff --git a/packages/coding-agent/src/core/compaction/summary-diagnostics.ts b/packages/coding-agent/src/core/compaction/summary-diagnostics.ts index 89755cb4..bda2a038 100644 --- a/packages/coding-agent/src/core/compaction/summary-diagnostics.ts +++ b/packages/coding-agent/src/core/compaction/summary-diagnostics.ts @@ -19,6 +19,8 @@ export interface SummaryRequestDiagnostics { errorKind?: string; rawStopReason?: string; usage?: AssistantMessage["usage"]; + /** Output-truncation recovery steps already applied, oldest first. */ + degradations?: string[]; } const responses = new WeakMap(); @@ -76,8 +78,20 @@ export function summaryFailure(message: string, response: AssistantMessage): Err return diagnostics ? new SummaryFailure(message, diagnostics) : new Error(redactSecretString(message)); } +/** + * Whether a summary failure is deterministic rather than transient. + * + * A length stop whose recovery ladder already ran out cannot succeed on an + * identical retry, so the caller can stop repeating it. The check is on the + * recorded stop reason, never on the message text. + */ +export function isTruncatedSummaryFailure(error: unknown): boolean { + if (!(error instanceof SummaryFailure)) return false; + return error.diagnostics.stopReason === "length"; +} + export function formatSummaryDiagnostics(d: SummaryRequestDiagnostics): string { - return `Summary request: stage=${d.stage ?? "unknown"}, provider=${d.provider}, model=${d.model}, api=${d.api}; contextWindow=${d.contextWindow}, model.maxTokens=${d.modelMaxTokens}, selectedMaxTokens=${d.selectedMaxTokens ?? "unknown"}, observedPayloadMaxTokens=${d.observedMaxTokens ?? "unknown"}, inputTokensEstimated=${d.inputTokensEstimated}, reasoning=${d.reasoning}; attempts=${d.attempts}, durationMs=${d.durationMs}, stopReason=${d.stopReason ?? "unknown"}, errorKind=${d.errorKind ?? "unknown"}.`; + return `Summary request: stage=${d.stage ?? "unknown"}, provider=${d.provider}, model=${d.model}, api=${d.api}; contextWindow=${d.contextWindow}, model.maxTokens=${d.modelMaxTokens}, selectedMaxTokens=${d.selectedMaxTokens ?? "unknown"}, observedPayloadMaxTokens=${d.observedMaxTokens ?? "unknown"}, inputTokensEstimated=${d.inputTokensEstimated}, reasoning=${d.reasoning}, degradations=${d.degradations?.join(">") ?? "none"}; attempts=${d.attempts}, durationMs=${d.durationMs}, stopReason=${d.stopReason ?? "unknown"}, errorKind=${d.errorKind ?? "unknown"}.`; } export function formatRetryPolicy(retry: RetryPolicy): string { diff --git a/packages/coding-agent/src/core/compaction/summary-policy.ts b/packages/coding-agent/src/core/compaction/summary-policy.ts new file mode 100644 index 00000000..187312dc --- /dev/null +++ b/packages/coding-agent/src/core/compaction/summary-policy.ts @@ -0,0 +1,89 @@ +/** + * Summarization request policy shared by compaction and branch summaries. + * + * A summarization request shares the model's output cap with its own reasoning + * tokens. Inheriting the session's thinking level lets reasoning consume most of + * that budget (observed 40k-47k of a 64k cap), which truncates the summary body. + * {@link resolveCompactionThinkingLevel} caps it, and + * {@link resolveSummaryLengthBudget} gives the prompt an explicit target. + * + * @module summary-policy + */ + +import { clampThinkingLevel, type Model, type ModelThinkingLevel } from "@step-harness/providers"; + +/** `"inherit"` keeps the session level; any other value is a ceiling on it. */ +export type CompactionThinkingLevelSetting = ModelThinkingLevel | "inherit"; + +/** Summaries aim for this many tokens unless the model's output cap is smaller. */ +export const DEFAULT_COMPACTION_SUMMARY_TARGET_TOKENS = 16_000; + +/** Default ceiling for summarization requests. */ +export const DEFAULT_COMPACTION_THINKING_LEVEL: CompactionThinkingLevelSetting = "low"; + +/** + * Share of the output cap a summary targets. Reasoning must fit in the rest, so a + * target above half the cap truncates whenever the model thinks at its default + * effort. + */ +const SUMMARY_TARGET_FRACTION = 0.5; + +/** A summary never asks for more than this share of the output cap. */ +const SUMMARY_HARD_CAP_FRACTION = 0.75; + +/** Thinking levels ordered from cheapest to most expensive. */ +const THINKING_LEVEL_ORDER: ModelThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"]; + +const COMPACTION_THINKING_LEVEL_SETTINGS: ReadonlySet = new Set([ + ...THINKING_LEVEL_ORDER, + "inherit", +]); + +/** Whether a value is a valid `compaction.thinkingLevel`, for settings that skipped schema validation. */ +export function isCompactionThinkingLevelSetting(value: unknown): value is CompactionThinkingLevelSetting { + return typeof value === "string" && COMPACTION_THINKING_LEVEL_SETTINGS.has(value); +} +/** + * Resolve the thinking level a summarization request uses. + * + * The session level is an upper bound: a session on `low` keeps `low` even when + * the setting asks for more, and `"inherit"` preserves the previous behavior. + * The result is clamped to what the model accepts, so a level the endpoint would + * reject is never sent. + * + * @param model - model that will receive the summarization request + * @param sessionLevel - level the session is currently using + * @param setting - `compaction.thinkingLevel`; `"inherit"` means the session level + */ +export function resolveCompactionThinkingLevel( + model: Model, + sessionLevel: ModelThinkingLevel, + setting: CompactionThinkingLevelSetting | undefined, +): ModelThinkingLevel { + if (setting === undefined || setting === "inherit") return sessionLevel; + const capped = Math.min(THINKING_LEVEL_ORDER.indexOf(sessionLevel), THINKING_LEVEL_ORDER.indexOf(setting)); + if (capped < 0) return clampThinkingLevel(model, setting); + return clampThinkingLevel(model, THINKING_LEVEL_ORDER[Math.max(capped, 0)] ?? setting); +} + +/** Token budget handed to the summary prompt. */ +export interface SummaryLengthBudget { + /** Tokens the summary should stay under. */ + targetTokens: number; + /** Tokens the summary must not exceed; over budget is reported, never truncated locally. */ + hardCapTokens: number; +} + +/** + * Resolve the summary length budget from the model's output cap. + * + * @param model - model that will receive the summarization request + * @param setting - `compaction.summaryTargetTokens`; the default applies when unset + */ +export function resolveSummaryLengthBudget(model: Model, setting: number | undefined): SummaryLengthBudget { + const outputCap = model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY; + const requested = setting ?? DEFAULT_COMPACTION_SUMMARY_TARGET_TOKENS; + const target = Math.max(1, Math.min(requested, Math.floor(outputCap * SUMMARY_TARGET_FRACTION))); + const hardCap = Math.max(target, Math.min(Math.floor(outputCap * SUMMARY_HARD_CAP_FRACTION), target * 2)); + return { targetTokens: target, hardCapTokens: hardCap }; +} diff --git a/packages/coding-agent/src/core/settings-manager.ts b/packages/coding-agent/src/core/settings-manager.ts index 849ed92c..7200ee78 100644 --- a/packages/coding-agent/src/core/settings-manager.ts +++ b/packages/coding-agent/src/core/settings-manager.ts @@ -11,6 +11,12 @@ import { normalizePath, resolvePath } from "../utils/paths.ts"; import { stripBom } from "../utils/text.ts"; import { type AutoClmSettings, resolveAutoClmSettings } from "./compaction/live-context/auto-options.ts"; import type { ContextProjectionMode } from "./compaction/projection.ts"; +import { + type CompactionThinkingLevelSetting, + DEFAULT_COMPACTION_SUMMARY_TARGET_TOKENS, + DEFAULT_COMPACTION_THINKING_LEVEL, + isCompactionThinkingLevelSetting, +} from "./compaction/summary-policy.ts"; import { type CompactionTriggerSettings, resolveCompactionTriggerSettings } from "./compaction/trigger-policy.ts"; import { DEFAULT_HTTP_IDLE_TIMEOUT_MS, parseHttpIdleTimeoutMs } from "./http-dispatcher.ts"; import type { @@ -25,6 +31,7 @@ import type { WarningSettings, } from "./settings-schema.ts"; +export type { CompactionThinkingLevelSetting } from "./compaction/summary-policy.ts"; export type { BranchSummarySettings, CompactionSettings, @@ -830,17 +837,43 @@ export class SettingsManager { return resolveAutoClmSettings(this.settings.compaction?.autoClm); } + /** + * Thinking level ceiling for summarization requests. `inherit` keeps the + * session level, which is the pre-P0-1 behavior. Reasoning shares the model's + * output cap with the summary body, so an uncapped level truncates the + * summary on adaptive-thinking models; the default is `low`. Invalid values + * were reported when settings loaded and fall back to the default. + */ + getCompactionThinkingLevel(): CompactionThinkingLevelSetting { + const setting = this.settings.compaction?.thinkingLevel; + // Fail closed on anything the schema would have rejected, so a value that + // bypassed load-time validation cannot reach the request as-is. + return isCompactionThinkingLevelSetting(setting) ? setting : DEFAULT_COMPACTION_THINKING_LEVEL; + } + + /** Token target for the generated summary; the provider still caps it. */ + getCompactionSummaryTargetTokens(): number { + const setting = this.settings.compaction?.summaryTargetTokens; + return typeof setting === "number" && Number.isInteger(setting) && setting > 0 + ? setting + : DEFAULT_COMPACTION_SUMMARY_TARGET_TOKENS; + } + getCompactionSettings(): { enabled: boolean; reserveTokens: number; keepRecentTokens: number; contextProjection: ContextProjectionMode; + thinkingLevel: CompactionThinkingLevelSetting; + summaryTargetTokens: number; } { return { enabled: this.getCompactionEnabled(), reserveTokens: this.getCompactionReserveTokens(), keepRecentTokens: this.getCompactionKeepRecentTokens(), contextProjection: this.getContextProjectionMode(), + thinkingLevel: this.getCompactionThinkingLevel(), + summaryTargetTokens: this.getCompactionSummaryTargetTokens(), }; } diff --git a/packages/coding-agent/src/core/settings-schema.ts b/packages/coding-agent/src/core/settings-schema.ts index 1e63440a..213ef1ba 100644 --- a/packages/coding-agent/src/core/settings-schema.ts +++ b/packages/coding-agent/src/core/settings-schema.ts @@ -170,6 +170,31 @@ const CompactionSettingsSchema = Type.Object( description: "Context projection mode: `off` (default, native compaction), `lightweight-v1`, or `clm-v1`.", }), ), + thinkingLevel: Type.Optional( + Type.Union( + [ + Type.Literal("inherit"), + Type.Literal("off"), + Type.Literal("minimal"), + Type.Literal("low"), + Type.Literal("medium"), + Type.Literal("high"), + Type.Literal("xhigh"), + Type.Literal("max"), + ], + { + description: + "Thinking level ceiling for summarization requests (default `low`). The session level is an upper bound; `inherit` keeps it. Reasoning shares the output cap with the summary, so an uncapped level truncates the summary on adaptive-thinking models.", + }, + ), + ), + summaryTargetTokens: Type.Optional( + Type.Integer({ + minimum: 1, + description: + "Token target for the generated summary (default 16000). Capped at half the model's output limit; an invalid value is ignored.", + }), + ), autoClm: Type.Optional(AutoClmSettingsSchema), }, { additionalProperties: false, description: "Automatic context compaction." }, diff --git a/packages/coding-agent/test/compaction-overflow-recovery.test.ts b/packages/coding-agent/test/compaction-overflow-recovery.test.ts index 492b05d2..6b501094 100644 --- a/packages/coding-agent/test/compaction-overflow-recovery.test.ts +++ b/packages/coding-agent/test/compaction-overflow-recovery.test.ts @@ -368,11 +368,16 @@ describe.each(["history", "prefix"])("%s summary context overflow r }, }, ])("does not discard more input for $name output", async ({ response }) => { - const { streamFn, requests } = scriptedStream([response, reply()]); + const { streamFn, requests } = scriptedStream([response, reply(), reply()]); // Output integrity has separate coverage; here acceptance/rejection must never cause source reduction. + // A length stop does run the truncation ladder (drop reasoning, then tighten the target), but that + // ladder only rewrites the request's options and prompt tail — the summarized source is untouched. await summarize(path, streamFn, { retry: retryPolicy }).catch(() => undefined); - expect(requests).toHaveLength(1); - expect(prompt(requests[0]!)).toContain(serializeConversation(convertToLlm(history(path)))); + expect(requests.length).toBeGreaterThanOrEqual(1); + const conversation = serializeConversation(convertToLlm(history(path))); + for (const request of requests) { + expect(prompt(request!)).toContain(conversation); + } }); it("sends the unchanged standalone request when the first attempt succeeds", async () => { diff --git a/packages/coding-agent/test/compaction-summary-reasoning.test.ts b/packages/coding-agent/test/compaction-summary-reasoning.test.ts index 81c8879e..62b786b3 100644 --- a/packages/coding-agent/test/compaction-summary-reasoning.test.ts +++ b/packages/coding-agent/test/compaction-summary-reasoning.test.ts @@ -184,24 +184,53 @@ describe("generateSummary reasoning options", () => { ); }); - it("rejects a length-limited history summary", async () => { - completeSimpleMock.mockResolvedValueOnce({ + it("rejects a length-limited history summary after the truncation ladder is spent", async () => { + completeSimpleMock.mockImplementation(async () => ({ ...mockSummaryResponse, stopReason: "length", content: [{ type: "text", text: "partial" }], - }); + })); await expect(generateSummaryWithUsage(messages, createModel(false), 2000, "test-key")).rejects.toThrow( "generation hit the token cap", ); + // Drop reasoning, then tighten the target: three requests before giving up. + expect(completeSimpleMock).toHaveBeenCalledTimes(3); }); - it("rejects a length-limited split-turn summary", async () => { - completeSimpleMock.mockResolvedValueOnce({ + it("recovers a length-limited history summary by dropping reasoning", async () => { + completeSimpleMock.mockImplementationOnce(async () => ({ ...mockSummaryResponse, stopReason: "length", content: [{ type: "text", text: "partial" }], - }); + usage: { ...mockSummaryResponse.usage, reasoning: 40000 }, + })); + + const result = await generateSummaryWithUsage( + messages, + createModel(true), + 2000, + "test-key", + undefined, + undefined, + undefined, + undefined, + "medium", + ); + + expect(result.text).toBe("## Goal\nTest summary"); + expect(completeSimpleMock).toHaveBeenCalledTimes(2); + // The retry must not send reasoning, or it hits the same cap. + expect(completeSimpleMock.mock.calls[0]![2]).toMatchObject({ reasoning: "medium" }); + expect(completeSimpleMock.mock.calls[1]![2]).not.toHaveProperty("reasoning"); + }); + + it("rejects a length-limited split-turn summary after the truncation ladder is spent", async () => { + completeSimpleMock.mockImplementation(async () => ({ + ...mockSummaryResponse, + stopReason: "length", + content: [{ type: "text", text: "partial" }], + })); const preparation: CompactionPreparation = { firstKeptEntryId: "entry-keep", messagesToSummarize: [], @@ -215,6 +244,7 @@ describe("generateSummary reasoning options", () => { await expect(compact(preparation, createModel(false), "test-key")).rejects.toThrow( "generation hit the token cap", ); + expect(completeSimpleMock).toHaveBeenCalledTimes(3); }); it("does not set reasoning when thinking is off", async () => { diff --git a/packages/coding-agent/test/compaction-thinking-level.test.ts b/packages/coding-agent/test/compaction-thinking-level.test.ts new file mode 100644 index 00000000..cf796ace --- /dev/null +++ b/packages/coding-agent/test/compaction-thinking-level.test.ts @@ -0,0 +1,161 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { Model } from "@step-harness/providers"; +import { afterEach, describe, expect, it } from "vitest"; +import { resolveCompactionThinkingLevel, resolveSummaryLengthBudget } from "../src/core/compaction/index.ts"; +import { SettingsManager } from "../src/core/settings-manager.ts"; + +/** The model from the reported incident: adaptive thinking, 64k output cap, 1M window. */ +function createOpusModel(): Model<"anthropic-messages"> { + return { + id: "claude-opus-5-5-working", + name: "Claude Opus 5.5", + api: "anthropic-messages", + provider: "stepcode-anthropic", + baseUrl: "https://example.invalid", + reasoning: true, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 1000000, + maxTokens: 64000, + thinkingLevelMap: { off: "off", low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, + compat: { forceAdaptiveThinking: true }, + }; +} + +/** A budget-thinking model with no `max` level at all. */ +function createLimitedModel(): Model<"anthropic-messages"> { + return { + id: "limited-thinking-model", + name: "Limited thinking model", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://example.invalid", + reasoning: true, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 200000, + maxTokens: 32000, + thinkingLevelMap: { off: "off", low: "low", medium: "medium" }, + }; +} + +describe("resolveCompactionThinkingLevel", () => { + const model = createOpusModel(); + + it("caps the session level at the configured ceiling", () => { + expect(resolveCompactionThinkingLevel(model, "max", "low")).toBe("low"); + expect(resolveCompactionThinkingLevel(model, "max", "medium")).toBe("medium"); + expect(resolveCompactionThinkingLevel(model, "xhigh", "low")).toBe("low"); + }); + + it("keeps the session level when it is already below the ceiling", () => { + expect(resolveCompactionThinkingLevel(model, "low", "max")).toBe("low"); + expect(resolveCompactionThinkingLevel(model, "medium", "high")).toBe("medium"); + }); + + it("inherits the session level when unset or explicitly inherited", () => { + expect(resolveCompactionThinkingLevel(model, "max", "inherit")).toBe("max"); + expect(resolveCompactionThinkingLevel(model, "max", undefined)).toBe("max"); + }); + + it("can turn reasoning off for the summary request", () => { + expect(resolveCompactionThinkingLevel(model, "max", "off")).toBe("off"); + }); + + it("clamps to a level the model accepts instead of sending an unsupported one", () => { + const limited = createLimitedModel(); + // `max` is not in this model's map; clamping must not send it. + expect(resolveCompactionThinkingLevel(limited, "max", "max")).not.toBe("max"); + expect(resolveCompactionThinkingLevel(limited, "max", "low")).toBe("low"); + }); +}); + +describe("resolveSummaryLengthBudget", () => { + it("targets half the output cap and leaves headroom for reasoning", () => { + const budget = resolveSummaryLengthBudget(createOpusModel(), undefined); + + expect(budget.targetTokens).toBe(16000); + expect(budget.hardCapTokens).toBe(32000); + expect(budget.hardCapTokens).toBeLessThan(createOpusModel().maxTokens); + }); + + it("honors an explicit smaller target", () => { + expect(resolveSummaryLengthBudget(createOpusModel(), 4000).targetTokens).toBe(4000); + }); + + it("caps the target at half the output cap even when configured higher", () => { + const budget = resolveSummaryLengthBudget(createLimitedModel(), 30000); + + expect(budget.targetTokens).toBe(16000); + expect(budget.hardCapTokens).toBeLessThanOrEqual(createLimitedModel().maxTokens); + }); + + it("never produces a zero or negative budget", () => { + const budget = resolveSummaryLengthBudget(createLimitedModel(), 0); + + expect(budget.targetTokens).toBeGreaterThan(0); + expect(budget.hardCapTokens).toBeGreaterThanOrEqual(budget.targetTokens); + }); +}); + +const settingsCleanups: Array<() => void> = []; +afterEach(() => { + while (settingsCleanups.length > 0) settingsCleanups.pop()?.(); +}); + +describe("compaction thinking level settings", () => { + function createSettingsManager(): SettingsManager { + const tempDir = mkdtempSync(join(tmpdir(), "compaction-thinking-settings-")); + settingsCleanups.push(() => rmSync(tempDir, { recursive: true, force: true })); + return SettingsManager.create(tempDir, tempDir); + } + + it("defaults to a low ceiling and the default summary target", () => { + const settings = createSettingsManager(); + + expect(settings.getCompactionThinkingLevel()).toBe("low"); + expect(settings.getCompactionSummaryTargetTokens()).toBe(16000); + expect(settings.getCompactionSettings()).toMatchObject({ + thinkingLevel: "low", + summaryTargetTokens: 16000, + }); + }); + + it("reads an explicit ceiling and target", () => { + const settings = createSettingsManager(); + settings.applyOverrides({ compaction: { thinkingLevel: "medium", summaryTargetTokens: 8000 } }); + + expect(settings.getCompactionThinkingLevel()).toBe("medium"); + expect(settings.getCompactionSummaryTargetTokens()).toBe(8000); + }); + + it("keeps `inherit` for the previous behavior", () => { + const settings = createSettingsManager(); + settings.applyOverrides({ compaction: { thinkingLevel: "inherit" } }); + + expect(settings.getCompactionThinkingLevel()).toBe("inherit"); + }); + + it.each([ + { name: "an unknown level", thinkingLevel: "turbo" as never }, + { name: "a non-string level", thinkingLevel: 3 as never }, + ])("falls back to the default for $name", ({ thinkingLevel }) => { + const settings = createSettingsManager(); + settings.applyOverrides({ compaction: { thinkingLevel } }); + + expect(settings.getCompactionThinkingLevel()).toBe("low"); + }); + + it.each([ + { name: "zero", summaryTargetTokens: 0 }, + { name: "a negative value", summaryTargetTokens: -5 }, + { name: "a fraction", summaryTargetTokens: 1.5 }, + ])("falls back to the default summary target for $name", ({ summaryTargetTokens }) => { + const settings = createSettingsManager(); + settings.applyOverrides({ compaction: { summaryTargetTokens } }); + + expect(settings.getCompactionSummaryTargetTokens()).toBe(16000); + }); +}); diff --git a/packages/coding-agent/test/suite/agent-session-auto-clm.test.ts b/packages/coding-agent/test/suite/agent-session-auto-clm.test.ts index ff309013..8f549b2c 100644 --- a/packages/coding-agent/test/suite/agent-session-auto-clm.test.ts +++ b/packages/coding-agent/test/suite/agent-session-auto-clm.test.ts @@ -145,11 +145,14 @@ describe("automatic CLM maintenance", () => { it("treats an accepted automatic CLM edit as a success that ends a native failure streak", async () => { const h = await setup({ alignNativeThreshold: true }); seed(h, "old completed observation\n".repeat(8800)); - (h.session as unknown as { _thresholdCompactionFailures: number })._thresholdCompactionFailures = 2; + const internals = h.session as unknown as { + _thresholdCompactionFailure?: { fingerprint: string; count: number }; + }; + internals._thresholdCompactionFailure = { fingerprint: "seeded", count: 2 }; h.setResponses([(context) => automaticEdit(context), fauxAssistantMessage("done")]); await h.session.prompt("NEW REQUIREMENT: preserve output order"); expect(h.session.getLiveContextStatus()!.revision).toBe(1); - expect((h.session as unknown as { _thresholdCompactionFailures: number })._thresholdCompactionFailures).toBe(0); + expect(internals._thresholdCompactionFailure).toBeUndefined(); }); it("uses the same native threshold after a complete parallel tool turn", async () => { let completed = 0; diff --git a/packages/coding-agent/test/suite/agent-session-compaction-trigger.test.ts b/packages/coding-agent/test/suite/agent-session-compaction-trigger.test.ts index d7a10b9c..f5496769 100644 --- a/packages/coding-agent/test/suite/agent-session-compaction-trigger.test.ts +++ b/packages/coding-agent/test/suite/agent-session-compaction-trigger.test.ts @@ -2,8 +2,9 @@ import type { AgentMessage, AgentTool } from "@step-harness/agent-core"; import { type Context, fauxAssistantMessage, fauxToolCall } from "@step-harness/providers"; import { Type } from "typebox"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { SummaryFailure } from "../../src/core/compaction/summary-diagnostics.ts"; import { SUMMARIZATION_SYSTEM_PROMPT } from "../../src/core/compaction/utils.ts"; -import { createHarness, type Harness } from "./harness.ts"; +import { createHarness, type Harness, type HarnessOptions } from "./harness.ts"; const SUMMARY = "## Goal\nTask in progress. Preserve the bulk evidence result."; @@ -20,10 +21,13 @@ async function setup( contextWindow?: number; keepRecentTokens?: number; contextProjection?: "off" | "clm-v1"; + models?: HarnessOptions["models"]; } = {}, ): Promise { const h = await createHarness({ - models: [{ id: "trigger-model", contextWindow: options.contextWindow ?? 16_000, maxTokens: 2_048 }], + models: options.models ?? [ + { id: "trigger-model", contextWindow: options.contextWindow ?? 16_000, maxTokens: 2_048 }, + ], settings: { compaction: { contextProjection: options.contextProjection ?? "off", @@ -38,6 +42,13 @@ async function setup( return h; } +function thresholdFailureCount(h: Harness): number { + return ( + (h.session as unknown as { _thresholdCompactionFailure?: { count: number } })._thresholdCompactionFailure + ?.count ?? 0 + ); +} + function seed(h: Harness, text: string): void { const messages: AgentMessage[] = [ { role: "user", content: "Investigate the parser", timestamp: 1 }, @@ -125,6 +136,103 @@ describe("compaction trigger policy v2", () => { expect(ends.map((event) => event.errorMessage?.includes("paused"))).toEqual([false, false, true]); }); + it("keeps counting failures when the user switches away and back to the same model", async () => { + const h = await setup({ + models: [ + { id: "trigger-model", contextWindow: 16_000, maxTokens: 2_048 }, + { id: "other-model", contextWindow: 16_000, maxTokens: 2_048 }, + ], + }); + seed(h, "prior observation ".repeat(3_300)); + const internals = h.session as unknown as { _runDefaultCompaction: () => Promise }; + const failing = vi + .spyOn(internals, "_runDefaultCompaction") + .mockRejectedValue(new Error("summary model unavailable")); + + h.setResponses([fauxAssistantMessage("answer 0")]); + await h.session.prompt("prompt 0"); + expect(thresholdFailureCount(h)).toBe(1); + + // Switching models used to clear the count, so the breaker never tripped. + await h.session.setModel(h.getModel("other-model")!); + await h.session.setModel(h.getModel("trigger-model")!); + + h.setResponses([fauxAssistantMessage("answer 1")]); + await h.session.prompt("prompt 1"); + expect(thresholdFailureCount(h)).toBe(2); + + h.setResponses([fauxAssistantMessage("answer 2")]); + await h.session.prompt("prompt 2"); + expect(thresholdFailureCount(h)).toBe(3); + expect(failing).toHaveBeenCalledTimes(3); + expect(h.eventsOfType("compaction_end").at(-1)?.errorMessage).toContain("paused"); + }); + + it("pauses immediately when the truncation ladder is exhausted", async () => { + const h = await setup(); + seed(h, "prior observation ".repeat(3_300)); + const truncated = new SummaryFailure("Summarization failed: generation hit the token cap", { + provider: "faux", + model: "trigger-model", + api: "faux", + contextWindow: 16_000, + modelMaxTokens: 2_048, + inputTokensEstimated: 100, + reasoning: "off", + attempts: 3, + durationMs: 1, + stopReason: "length", + degradations: ["thinking-off", "tight-target"], + }); + const internals = h.session as unknown as { _runDefaultCompaction: () => Promise }; + const failing = vi.spyOn(internals, "_runDefaultCompaction").mockRejectedValue(truncated); + + h.setResponses([fauxAssistantMessage("answer 0")]); + await h.session.prompt("prompt 0"); + + // A summary that survives the whole ladder fails deterministically: retrying the + // identical request costs another full round trip, so the first failure pauses. + expect(failing).toHaveBeenCalledTimes(1); + // Saturated at the limit (AUTO_COMPACTION_FAILURE_LIMIT), not counted one by one. + expect(thresholdFailureCount(h)).toBe(3); + expect(h.eventsOfType("compaction_end").at(-1)?.errorMessage).toContain("paused"); + + h.setResponses([fauxAssistantMessage("answer 1")]); + await h.session.prompt("prompt 1"); + expect(failing).toHaveBeenCalledTimes(1); + }); + + it("gives a different summarizer a fresh failure count", async () => { + const h = await setup({ + models: [ + { id: "trigger-model", contextWindow: 16_000, maxTokens: 2_048 }, + { id: "bigger-model", contextWindow: 16_000, maxTokens: 4_096 }, + ], + }); + seed(h, "prior observation ".repeat(3_300)); + const internals = h.session as unknown as { _runDefaultCompaction: () => Promise }; + vi.spyOn(internals, "_runDefaultCompaction").mockRejectedValue(new Error("summary model unavailable")); + + h.setResponses([fauxAssistantMessage("answer 0")]); + await h.session.prompt("prompt 0"); + h.setResponses([fauxAssistantMessage("answer 1")]); + await h.session.prompt("prompt 1"); + expect(thresholdFailureCount(h)).toBe(2); + + // A different output cap is a different attempt: the pause does not follow it, + // and its own failures start from zero. + await h.session.setModel(h.getModel("bigger-model")!); + expect(thresholdFailureCount(h)).toBe(2); + expect((h.session as unknown as { _thresholdCompactionPaused: () => boolean })._thresholdCompactionPaused()).toBe( + false, + ); + + h.setResponses([fauxAssistantMessage("answer 2")]); + await h.session.prompt("prompt 2"); + expect(thresholdFailureCount(h)).toBe(1); + expect(h.eventsOfType("compaction_end").at(-1)?.errorMessage).not.toContain("paused"); + }); + it("resumes automatic compaction after a successful manual compaction", async () => { const h = await setup(); seed(h, "prior observation ".repeat(3_300)); @@ -189,7 +297,7 @@ describe("compaction trigger policy v2", () => { expect(ends.map((event) => event.errorMessage === undefined)).toEqual([false, false, false, false]); expect(ends.some((event) => event.errorMessage?.includes("paused"))).toBe(false); // Each attempt persisted a compaction, so none of them may count as a failure. - expect((h.session as unknown as { _thresholdCompactionFailures: number })._thresholdCompactionFailures).toBe(0); + expect(thresholdFailureCount(h)).toBe(0); }); it("keeps the compacted context when a chained request hook returns only a thinking update", async () => { diff --git a/packages/coding-agent/test/suite/regressions/6647-compaction-retries-transient-stream-drop.test.ts b/packages/coding-agent/test/suite/regressions/6647-compaction-retries-transient-stream-drop.test.ts index b8447ef5..f834738c 100644 --- a/packages/coding-agent/test/suite/regressions/6647-compaction-retries-transient-stream-drop.test.ts +++ b/packages/coding-agent/test/suite/regressions/6647-compaction-retries-transient-stream-drop.test.ts @@ -231,7 +231,8 @@ describe("#6647 compaction retries transient summarization failures", () => { contextWindow: harness.getModel().contextWindow, modelMaxTokens: harness.getModel().maxTokens, observedMaxTokens: 16, - attempts: 1, + attempts: 3, + degradations: ["thinking-off", "tight-target"], stopReason: "length", }, }, diff --git a/packages/coding-agent/test/suite/regressions/7048-compaction-truncated-summary.test.ts b/packages/coding-agent/test/suite/regressions/7048-compaction-truncated-summary.test.ts index 396c462e..f7a82918 100644 --- a/packages/coding-agent/test/suite/regressions/7048-compaction-truncated-summary.test.ts +++ b/packages/coding-agent/test/suite/regressions/7048-compaction-truncated-summary.test.ts @@ -40,7 +40,11 @@ describe("#7048 truncated compaction summaries", () => { it("does not persist a length-limited summary", async () => { harness = await createHarness(); seedCompactableSession(harness); - harness.setResponses([fauxAssistantMessage("partial summar", { stopReason: "length" })]); + // Every attempt is truncated: the recovery ladder (drop reasoning, tighten the + // target) is spent and the partial text still must not become a checkpoint. + harness.setResponses( + Array.from({ length: 4 }, () => fauxAssistantMessage("partial summar", { stopReason: "length" })), + ); await expect(harness.session.compact()).rejects.toThrow("generation hit the token cap"); expect(harness.sessionManager.getEntries().filter((entry) => entry.type === "compaction")).toHaveLength(0); diff --git a/packages/coding-agent/test/suite/regressions/compaction-adaptive-wire.test.ts b/packages/coding-agent/test/suite/regressions/compaction-adaptive-wire.test.ts index fa0e4de8..a316c298 100644 --- a/packages/coding-agent/test/suite/regressions/compaction-adaptive-wire.test.ts +++ b/packages/coding-agent/test/suite/regressions/compaction-adaptive-wire.test.ts @@ -12,9 +12,9 @@ import { createHarness, getMessageText, type Harness } from "../harness.ts"; const SYSTEM_SHA256 = "7f4677db342c3991df3ed0ba729c514db1772ef7af4c39155d2a0d87d08b12bb"; const TEMPLATE_SHA256 = { - history: "4379f7f63f9fbd36f3f273e94b9566d78967e2e938e4b483957bf67266490572", - prefix: "0a355395dcd867cb08c3be3229d31475b3a468c51021489fcca4fab6c967cdb6", - update: "90546e9b55c76b8ac2570b98b0d2849cb3808f102097f52f643b00253edbb333", + history: "daed7bdfc7f2c98e9e468b273165ddf1447c1ddee5224bce8845e95c4c663a24", + prefix: "c6792227fc9d2d04816058aad193fca1336f73b84321a09d22800b6eedfef50e", + update: "6c0f7947abad0ed0856715527baed7f30485a472c065ed1be9e3338307b5e4d1", }; const GOAL = "SYNTHETIC_GOAL: preserve the parser API and finish the existing plan."; const ZERO_USAGE = { diff --git a/packages/coding-agent/test/suite/regressions/compaction-integrity.test.ts b/packages/coding-agent/test/suite/regressions/compaction-integrity.test.ts index a69fca5b..359e00c0 100644 --- a/packages/coding-agent/test/suite/regressions/compaction-integrity.test.ts +++ b/packages/coding-agent/test/suite/regressions/compaction-integrity.test.ts @@ -298,12 +298,14 @@ describe("compaction integrity", () => { ])("preserves $name and the original context", async ({ response, error }) => { const harness = await seedSession(layout); const before = captureSession(harness); - harness.setResponses([response]); + // A length stop runs the truncation ladder before it is reported, so the + // faux provider is called once per rung plus the original attempt. + harness.setResponses(Array.from({ length: 4 }, () => response)); await expect(harness.session.compact()).rejects.toThrow(error); expectOnlyFailureDiagnosticAdded(harness, before); - expect(harness.faux.state.callCount).toBe(1); + expect(harness.faux.state.callCount).toBe(response.stopReason === "length" ? 3 : 1); expect(harness.eventsOfType("compaction_end").at(-1)).toMatchObject({ result: undefined, aborted: false,