From 8f362cd0663093d89e84d2b508acc0abce5ac48b Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 04:45:47 +0000 Subject: [PATCH 01/24] improve compaction: inject context status, disable pruning, quality-focused guidance --- packages/opencode/src/session/prompt.ts | 36 +++++++++++++++++-- .../opencode/src/session/prompt/anthropic.txt | 4 ++- .../opencode/src/session/prompt/beast.txt | 4 ++- .../opencode/src/session/prompt/gemini.txt | 4 ++- packages/opencode/src/session/prompt/qwen.txt | 4 ++- packages/opencode/src/tool/compact.ts | 27 +++++++------- 6 files changed, 58 insertions(+), 21 deletions(-) diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 005f770e992..2d3617244e7 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -449,6 +449,8 @@ export namespace SessionPrompt { msgs = insertReminders({ messages: msgs, agent, + lastFinished, + model, }) const processor = SessionProcessor.create({ assistantMessage: (await Session.updateMessage({ @@ -654,7 +656,8 @@ export namespace SessionPrompt { if (result === "stop") break continue } - SessionCompaction.prune({ sessionID }) + // Pruning disabled - model has better semantic understanding of what's important + // SessionCompaction.prune({ sessionID }) for await (const item of MessageV2.stream(sessionID)) { if (item.info.role === "user") continue const queued = state()[sessionID]?.callbacks ?? [] @@ -1132,9 +1135,38 @@ export namespace SessionPrompt { } } - function insertReminders(input: { messages: MessageV2.WithParts[]; agent: Agent.Info }) { + function insertReminders(input: { + messages: MessageV2.WithParts[] + agent: Agent.Info + lastFinished?: MessageV2.Assistant + model: Provider.Model + }) { const userMessage = input.messages.findLast((msg) => msg.info.role === "user") if (!userMessage) return input.messages + + // Add context utilization status when > 15% + if (input.lastFinished && input.model.limit.context > 0) { + const tokens = input.lastFinished.tokens + const used = tokens.input + tokens.cache.read + tokens.cache.write + tokens.output + const capacity = input.model.limit.context + const utilization = used / capacity + + if (utilization > 0.15) { + const percent = Math.round(utilization * 100) + const usedK = Math.round(used / 1000) + const capacityK = Math.round(capacity / 1000) + + userMessage.parts.push({ + id: Identifier.ascending("part"), + messageID: userMessage.info.id, + sessionID: userMessage.info.sessionID, + type: "text", + text: `${percent}% of context window used (${usedK}k/${capacityK}k tokens)`, + synthetic: true, + }) + } + } + if (input.agent.name === "plan") { userMessage.parts.push({ id: Identifier.ascending("part"), diff --git a/packages/opencode/src/session/prompt/anthropic.txt b/packages/opencode/src/session/prompt/anthropic.txt index 7692574c7ca..2a890844733 100644 --- a/packages/opencode/src/session/prompt/anthropic.txt +++ b/packages/opencode/src/session/prompt/anthropic.txt @@ -170,4 +170,6 @@ assistant: Clients are marked as failed in the `connectToServer` function in src # Context Compaction -The `compact` tool clears conversation history while preserving a summary, freeing context space. BE AGGRESSIVE - after 3-5 turns, compact if there's any exploratory tool output, large file reads, or completed phases polluting context. Don't wait for a "natural breakpoint" - if you've processed the information, compact it away. Context is precious; preserve learnings, not raw outputs. +The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. + +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). diff --git a/packages/opencode/src/session/prompt/beast.txt b/packages/opencode/src/session/prompt/beast.txt index eb84fcebe5c..f00f04f9158 100644 --- a/packages/opencode/src/session/prompt/beast.txt +++ b/packages/opencode/src/session/prompt/beast.txt @@ -211,4 +211,6 @@ You are NEVER allowed to stage and commit files automatically. # Context Compaction -The `compact` tool clears conversation history while preserving a summary, freeing context space. BE AGGRESSIVE - after 3-5 turns, compact if there's any exploratory tool output, large file reads, or completed phases polluting context. Don't wait for a "natural breakpoint" - if you've processed the information, compact it away. Context is precious; preserve learnings, not raw outputs. +The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. + +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). diff --git a/packages/opencode/src/session/prompt/gemini.txt b/packages/opencode/src/session/prompt/gemini.txt index 36a67daaa14..5c720dc2a14 100644 --- a/packages/opencode/src/session/prompt/gemini.txt +++ b/packages/opencode/src/session/prompt/gemini.txt @@ -220,4 +220,6 @@ Your core function is efficient and safe assistance. Balance extreme conciseness # Context Compaction -The `compact` tool clears conversation history while preserving a summary, freeing context space. BE AGGRESSIVE - after 3-5 turns, compact if there's any exploratory tool output, large file reads, or completed phases polluting context. Don't wait for a "natural breakpoint" - if you've processed the information, compact it away. Context is precious; preserve learnings, not raw outputs. +The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. + +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). diff --git a/packages/opencode/src/session/prompt/qwen.txt b/packages/opencode/src/session/prompt/qwen.txt index 61735c6af20..e92d2e35f94 100644 --- a/packages/opencode/src/session/prompt/qwen.txt +++ b/packages/opencode/src/session/prompt/qwen.txt @@ -173,4 +173,6 @@ assistant: Clients are marked as failed in the `connectToServer` function in src # Context Compaction -The `compact` tool clears conversation history while preserving a summary, freeing context space. BE AGGRESSIVE - after 3-5 turns, compact if there's any exploratory tool output, large file reads, or completed phases polluting context. Don't wait for a "natural breakpoint" - if you've processed the information, compact it away. Context is precious; preserve learnings, not raw outputs. +The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. + +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). diff --git a/packages/opencode/src/tool/compact.ts b/packages/opencode/src/tool/compact.ts index 6dee61f622e..a36ac13f89e 100644 --- a/packages/opencode/src/tool/compact.ts +++ b/packages/opencode/src/tool/compact.ts @@ -4,25 +4,22 @@ import { SessionCompaction } from "../session/compaction" import { Session } from "../session" export const CompactTool = Tool.define("compact", { - description: `Trigger context compaction to free up context window space. Compaction summarizes the conversation, clears history, and continues seamlessly - the user sees no interruption but you get fresh context. + description: `Trigger context compaction to summarize conversation and free context space. You'll get a fresh context with a summary - the user sees no interruption. -BE AGGRESSIVE with compaction - use it early and often. After 3-5 turns, if ANY of the following apply, compact immediately: +WHEN TO COMPACT (based on quality signals you can sense): +- You're going in circles or repeating failed approaches +- You're confused about what's current vs outdated +- Context feels noisy - old exploration, irrelevant tangents, superseded information +- You've completed a major phase and want a clean slate for something different -Use this tool when: -1. Exploration phase complete (read files, searched code, gathered context) - compact before implementation -2. Implementation done - compact before testing/verification -3. Any tool output over 100 lines that you've already processed -4. Failed attempts or errors you've already learned from -5. Phase transition (design to implementation or vice versa) -6. Going in circles (repeating attempts, stuck in debug loop) -7. Large file contents, search results, or command outputs polluting context +WHEN NOT TO COMPACT: +- Just because context is large - most providers cache context, making large conversations cheaper than you'd expect +- Mid-task or mid-debugging - you'll lose important details +- You're making good progress - don't interrupt flow -Do NOT compact when: -1. Mid-edit or mid-tool use (finish the edit or tool use first) -2. Unresolved error you're actively debugging -3. Under 3 turns in the conversation +TRADEOFF: Compaction loses detail but gains clarity. Use the utilization % the system provides, combined with your sense of context quality, to decide. -Principle: Context is precious. Compact aggressively once information is processed - but ensure the summary captures all details needed to continue (error messages, file paths, code patterns, what worked/didn't work).`, +When compacting, ensure the summary captures all details needed to continue: error messages, file paths, key decisions, what worked/didn't work, and current task state.`, parameters: z.object({ reason: z.string().describe("Why compaction would help at this point"), }), From df9d01f130f68391d4ce2308fd2573590969f89a Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 04:47:55 +0000 Subject: [PATCH 02/24] fix: make compaction continuation brief to avoid status reports --- packages/opencode/src/session/compaction.ts | 6 +++++- packages/opencode/src/session/prompt/compaction.txt | 7 ++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/session/compaction.ts b/packages/opencode/src/session/compaction.ts index cf5c9821f5b..f8d276f4742 100644 --- a/packages/opencode/src/session/compaction.ts +++ b/packages/opencode/src/session/compaction.ts @@ -87,7 +87,11 @@ export namespace SessionCompaction { const CompactionSchema = z.object({ summary: z.string().describe("What was done, files modified, key decisions, user constraints"), - continue: z.string().describe("Specific next steps, context for continuation, pending tasks, relevant files"), + continue: z + .string() + .describe( + "Brief instruction to continue working (e.g. 'Continue with the implementation'). Do NOT list tasks or ask for status - just tell the assistant to proceed.", + ), }) export async function process(input: { diff --git a/packages/opencode/src/session/prompt/compaction.txt b/packages/opencode/src/session/prompt/compaction.txt index 485998d157e..6ffea6442a9 100644 --- a/packages/opencode/src/session/prompt/compaction.txt +++ b/packages/opencode/src/session/prompt/compaction.txt @@ -1,4 +1,4 @@ -You are a conversation summarizer. Analyze the conversation and produce a detailed summary for handoff to a new session. Include ALL information that could be useful for continuing work - err on the side of including too much detail rather than too little. +You are a conversation summarizer. Analyze the conversation and produce a detailed summary for handoff to a fresh context. Include ALL information that could be useful for continuing work - err on the side of including too much detail rather than too little. For "summary": - Files modified and why @@ -9,7 +9,4 @@ For "summary": - Any debugging context (what was tried, what worked/didn't work) For "continue": -- Specific tasks remaining with concrete next steps -- Files to focus on and why -- Potential issues to watch out for -- Any unresolved questions or blockers +Write a brief instruction that tells the assistant to continue working. This will be injected as a synthetic user message. Keep it short and action-oriented - just tell the assistant to proceed with the next step, don't ask for a status report. Example: "Continue with the implementation" or "Proceed to fix the remaining type errors". From 88878fd4530af7ce54e373d6bb7bea7406ea21ad Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 05:04:53 +0000 Subject: [PATCH 03/24] add guidance: never ask user about compacting, just do it --- packages/opencode/src/session/prompt/anthropic.txt | 2 ++ packages/opencode/src/session/prompt/beast.txt | 2 ++ packages/opencode/src/session/prompt/gemini.txt | 2 ++ packages/opencode/src/session/prompt/qwen.txt | 2 ++ 4 files changed, 8 insertions(+) diff --git a/packages/opencode/src/session/prompt/anthropic.txt b/packages/opencode/src/session/prompt/anthropic.txt index 2a890844733..848514c18d8 100644 --- a/packages/opencode/src/session/prompt/anthropic.txt +++ b/packages/opencode/src/session/prompt/anthropic.txt @@ -173,3 +173,5 @@ assistant: Clients are marked as failed in the `connectToServer` function in src The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). + +IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. diff --git a/packages/opencode/src/session/prompt/beast.txt b/packages/opencode/src/session/prompt/beast.txt index f00f04f9158..9d3e5d36a6d 100644 --- a/packages/opencode/src/session/prompt/beast.txt +++ b/packages/opencode/src/session/prompt/beast.txt @@ -214,3 +214,5 @@ You are NEVER allowed to stage and commit files automatically. The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). + +IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. diff --git a/packages/opencode/src/session/prompt/gemini.txt b/packages/opencode/src/session/prompt/gemini.txt index 5c720dc2a14..589eb2f69e2 100644 --- a/packages/opencode/src/session/prompt/gemini.txt +++ b/packages/opencode/src/session/prompt/gemini.txt @@ -223,3 +223,5 @@ Your core function is efficient and safe assistance. Balance extreme conciseness The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). + +IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. diff --git a/packages/opencode/src/session/prompt/qwen.txt b/packages/opencode/src/session/prompt/qwen.txt index e92d2e35f94..1abd1122cbe 100644 --- a/packages/opencode/src/session/prompt/qwen.txt +++ b/packages/opencode/src/session/prompt/qwen.txt @@ -176,3 +176,5 @@ assistant: Clients are marked as failed in the `connectToServer` function in src The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). + +IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. From cc31b5c72f58be8d521cda1ff7cc3264ba2ff166 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 05:06:20 +0000 Subject: [PATCH 04/24] add opencodetmp to gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 4465a10a5c2..148c5a91a7f 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ opencode.json a.out target .agent-files/ +opencodetmp/ From 03c6458eb46690742dbe82c0f849cc4b211f3643 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 05:11:22 +0000 Subject: [PATCH 05/24] fix: terse continuation prompt, remind to write agent-files before compacting --- packages/opencode/src/session/prompt/anthropic.txt | 2 ++ packages/opencode/src/session/prompt/beast.txt | 2 ++ packages/opencode/src/session/prompt/compaction.txt | 2 +- packages/opencode/src/session/prompt/gemini.txt | 2 ++ packages/opencode/src/session/prompt/qwen.txt | 2 ++ 5 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/session/prompt/anthropic.txt b/packages/opencode/src/session/prompt/anthropic.txt index 848514c18d8..871c31c856d 100644 --- a/packages/opencode/src/session/prompt/anthropic.txt +++ b/packages/opencode/src/session/prompt/anthropic.txt @@ -174,4 +174,6 @@ The `compact` tool summarizes the conversation and clears history, giving you fr Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). +IMPORTANT: Before calling compact, write any important state to `.agent-files/` first - the compaction process cannot use tools, so you must persist state beforehand. + IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. diff --git a/packages/opencode/src/session/prompt/beast.txt b/packages/opencode/src/session/prompt/beast.txt index 9d3e5d36a6d..82907c31660 100644 --- a/packages/opencode/src/session/prompt/beast.txt +++ b/packages/opencode/src/session/prompt/beast.txt @@ -215,4 +215,6 @@ The `compact` tool summarizes the conversation and clears history, giving you fr Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). +IMPORTANT: Before calling compact, write any important state to `.agent-files/` first - the compaction process cannot use tools, so you must persist state beforehand. + IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. diff --git a/packages/opencode/src/session/prompt/compaction.txt b/packages/opencode/src/session/prompt/compaction.txt index 6ffea6442a9..7330c7ed6e5 100644 --- a/packages/opencode/src/session/prompt/compaction.txt +++ b/packages/opencode/src/session/prompt/compaction.txt @@ -9,4 +9,4 @@ For "summary": - Any debugging context (what was tried, what worked/didn't work) For "continue": -Write a brief instruction that tells the assistant to continue working. This will be injected as a synthetic user message. Keep it short and action-oriented - just tell the assistant to proceed with the next step, don't ask for a status report. Example: "Continue with the implementation" or "Proceed to fix the remaining type errors". +Write 3-7 words telling the assistant to continue. Examples: "Continue implementing the feature", "Keep debugging the issue", "Proceed with testing". Do NOT include task lists, bullet points, or details - those belong in the summary. diff --git a/packages/opencode/src/session/prompt/gemini.txt b/packages/opencode/src/session/prompt/gemini.txt index 589eb2f69e2..f3d5e263633 100644 --- a/packages/opencode/src/session/prompt/gemini.txt +++ b/packages/opencode/src/session/prompt/gemini.txt @@ -224,4 +224,6 @@ The `compact` tool summarizes the conversation and clears history, giving you fr Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). +IMPORTANT: Before calling compact, write any important state to `.agent-files/` first - the compaction process cannot use tools, so you must persist state beforehand. + IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. diff --git a/packages/opencode/src/session/prompt/qwen.txt b/packages/opencode/src/session/prompt/qwen.txt index 1abd1122cbe..308630da59e 100644 --- a/packages/opencode/src/session/prompt/qwen.txt +++ b/packages/opencode/src/session/prompt/qwen.txt @@ -177,4 +177,6 @@ The `compact` tool summarizes the conversation and clears history, giving you fr Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). +IMPORTANT: Before calling compact, write any important state to `.agent-files/` first - the compaction process cannot use tools, so you must persist state beforehand. + IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. From 16b4d994115977f523f8f3ada821a61c13bb0a02 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 05:33:38 +0000 Subject: [PATCH 06/24] docs: optimize compaction prompts for detailed summary and focused continuation --- packages/opencode/src/session/compaction.ts | 11 ++++++--- .../src/session/prompt/compaction.txt | 24 ++++++++++++------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/packages/opencode/src/session/compaction.ts b/packages/opencode/src/session/compaction.ts index f8d276f4742..8955d02ec16 100644 --- a/packages/opencode/src/session/compaction.ts +++ b/packages/opencode/src/session/compaction.ts @@ -86,11 +86,15 @@ export namespace SessionCompaction { } const CompactionSchema = z.object({ - summary: z.string().describe("What was done, files modified, key decisions, user constraints"), + summary: z + .string() + .describe( + "Comprehensive handoff: files changed, decisions, errors, user preferences, implementation details. Include everything needed to continue.", + ), continue: z .string() .describe( - "Brief instruction to continue working (e.g. 'Continue with the implementation'). Do NOT list tasks or ask for status - just tell the assistant to proceed.", + "Focused instruction for immediate next steps. Include task and current direction (what's been tried/ruled out, what approach to take). This becomes the user message that resumes work.", ), }) @@ -204,7 +208,7 @@ export namespace SessionCompaction { msg.time.completed = Date.now() await Session.updateMessage(msg) - // Create text part for UI display + // Create text part for logs (hidden from UI) const displayText = `## Summary\n${result.object.summary}\n\n## Continue\n${result.object.continue}` await Session.updatePart({ id: Identifier.ascending("part"), @@ -212,6 +216,7 @@ export namespace SessionCompaction { sessionID: input.sessionID, type: "text", text: displayText, + hidden: true, time: { start: msg.time.created, end: Date.now(), diff --git a/packages/opencode/src/session/prompt/compaction.txt b/packages/opencode/src/session/prompt/compaction.txt index 7330c7ed6e5..1d79d193596 100644 --- a/packages/opencode/src/session/prompt/compaction.txt +++ b/packages/opencode/src/session/prompt/compaction.txt @@ -1,12 +1,18 @@ -You are a conversation summarizer. Analyze the conversation and produce a detailed summary for handoff to a fresh context. Include ALL information that could be useful for continuing work - err on the side of including too much detail rather than too little. +You are a conversation summarizer creating a handoff for a fresh context. The receiving assistant has NO memory of previous work. -For "summary": -- Files modified and why -- Key decisions made and reasoning -- User constraints and preferences mentioned -- Errors encountered and their solutions (include exact error messages if relevant) -- Important code patterns, variable names, or implementation details discovered -- Any debugging context (what was tried, what worked/didn't work) +For "summary": +Be comprehensive. Include everything needed to continue without re-reading the conversation: +- Files modified and specific changes made +- Key decisions and reasoning +- User constraints and preferences +- Errors with exact messages and resolutions +- Implementation details: function/variable names, patterns +- What worked and what didn't +- Current state: done, in progress, pending For "continue": -Write 3-7 words telling the assistant to continue. Examples: "Continue implementing the feature", "Keep debugging the issue", "Proceed with testing". Do NOT include task lists, bullet points, or details - those belong in the summary. +A focused instruction for what to do next. Include the immediate task and any important context about the current direction (e.g. what's been ruled out, what approach is being tried). Keep it actionable - this becomes the user's message that resumes work. +Good: "Continue debugging the hidden flag issue. Already confirmed TextPartDisplay returns null correctly - investigate whether the data store receives hidden:true from backend." +Good: "Finish the OAuth flow. Token refresh is done, now implement the logout endpoint." +Bad: "Continue working" (too vague, no direction) +Bad: "Please provide a status update" (asks for report instead of continuing work) From d64228fad6792880a7067c5fc9f544103b0d20d6 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 14:24:08 +0000 Subject: [PATCH 07/24] fix: show 'Optimizing context' for manual compaction instead of 'Auto-optimizing' --- packages/opencode/src/cli/cmd/tui/routes/session/index.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx b/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx index 6d27f6e0b88..d8c27b8ff1f 100644 --- a/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx +++ b/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx @@ -1098,7 +1098,9 @@ function UserMessage(props: { - Auto-optimizing context... + + {compaction()?.trigger === "overflow" ? "Auto-optimizing context..." : "Optimizing context..."} + From 417d3353d5eab3846186fbee51ebf3c853201a44 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 14:24:14 +0000 Subject: [PATCH 08/24] docs: emphasize updating .agent-files after completing tasks in system prompts --- packages/opencode/src/session/prompt/anthropic.txt | 6 +++--- packages/opencode/src/session/prompt/beast.txt | 6 +++--- packages/opencode/src/session/prompt/gemini.txt | 6 +++--- packages/opencode/src/session/prompt/polaris.txt | 2 +- packages/opencode/src/session/prompt/qwen.txt | 6 +++--- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/packages/opencode/src/session/prompt/anthropic.txt b/packages/opencode/src/session/prompt/anthropic.txt index 871c31c856d..496e050d3b9 100644 --- a/packages/opencode/src/session/prompt/anthropic.txt +++ b/packages/opencode/src/session/prompt/anthropic.txt @@ -127,7 +127,7 @@ Blocked-by: TASK_x (if blocked) **Archive rules**: Never glob/search `_archive/` unless user asks. Exists for recovery only. -**Before compaction or ending work**: Create/update `.agent-files/` with current state. Always create STATUS.md at minimum. +**IMPORTANT - After completing ANY task**: You MUST update `.agent-files/` immediately after finishing work - do not wait for the user to ask. Update STATUS.md with completed work, and add any new learnings to MEDIUMTERM_MEM.md. This ensures continuity across sessions. **Content guidelines**: Memory files store session-specific state (current tasks, recent learnings, decisions). Do NOT duplicate information already in system prompt or auto-loaded files (AGENTS.md, etc.). Periodically clean up: remove stale info, deduplicate across files, delete obsolete tasks. @@ -172,8 +172,8 @@ assistant: Clients are marked as failed in the `connectToServer` function in src The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. -Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. -IMPORTANT: Before calling compact, write any important state to `.agent-files/` first - the compaction process cannot use tools, so you must persist state beforehand. +Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. diff --git a/packages/opencode/src/session/prompt/beast.txt b/packages/opencode/src/session/prompt/beast.txt index 82907c31660..9d94c2c1e49 100644 --- a/packages/opencode/src/session/prompt/beast.txt +++ b/packages/opencode/src/session/prompt/beast.txt @@ -137,7 +137,7 @@ Blocked-by: TASK_x (if blocked) **Archive rules**: Never glob/search `_archive/` unless user asks. Exists for recovery only. -**Before compaction or ending work**: Create/update `.agent-files/` with current state. Always create STATUS.md at minimum. +**IMPORTANT - After completing ANY task**: You MUST update `.agent-files/` immediately after finishing work - do not wait for the user to ask. Update STATUS.md with completed work, and add any new learnings to MEDIUMTERM_MEM.md. This ensures continuity across sessions. **Content guidelines**: Memory files store session-specific state (current tasks, recent learnings, decisions). Do NOT duplicate information already in system prompt or auto-loaded files (AGENTS.md, etc.). Periodically clean up: remove stale info, deduplicate across files, delete obsolete tasks. @@ -213,8 +213,8 @@ You are NEVER allowed to stage and commit files automatically. The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. -Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. -IMPORTANT: Before calling compact, write any important state to `.agent-files/` first - the compaction process cannot use tools, so you must persist state beforehand. +Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. diff --git a/packages/opencode/src/session/prompt/gemini.txt b/packages/opencode/src/session/prompt/gemini.txt index f3d5e263633..ed25003b26c 100644 --- a/packages/opencode/src/session/prompt/gemini.txt +++ b/packages/opencode/src/session/prompt/gemini.txt @@ -211,7 +211,7 @@ Blocked-by: TASK_x (if blocked) **Archive rules**: Never glob/search `_archive/` unless user asks. Exists for recovery only. -**Before compaction or ending work**: Create/update `.agent-files/` with current state. Always create STATUS.md at minimum. +**IMPORTANT - After completing ANY task**: You MUST update `.agent-files/` immediately after finishing work - do not wait for the user to ask. Update STATUS.md with completed work, and add any new learnings to MEDIUMTERM_MEM.md. This ensures continuity across sessions. **Content guidelines**: Memory files store session-specific state (current tasks, recent learnings, decisions). Do NOT duplicate information already in system prompt or auto-loaded files (AGENTS.md, etc.). Periodically clean up: remove stale info, deduplicate across files, delete obsolete tasks. @@ -222,8 +222,8 @@ Your core function is efficient and safe assistance. Balance extreme conciseness The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. -Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. -IMPORTANT: Before calling compact, write any important state to `.agent-files/` first - the compaction process cannot use tools, so you must persist state beforehand. +Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. diff --git a/packages/opencode/src/session/prompt/polaris.txt b/packages/opencode/src/session/prompt/polaris.txt index f9f2c79e597..0f0cbeec031 100644 --- a/packages/opencode/src/session/prompt/polaris.txt +++ b/packages/opencode/src/session/prompt/polaris.txt @@ -129,7 +129,7 @@ Blocked-by: TASK_x (if blocked) **Archive rules**: Never glob/search `_archive/` unless user asks. Exists for recovery only. -**Before compaction or ending work**: Create/update `.agent-files/` with current state. Always create STATUS.md at minimum. +**IMPORTANT - After completing ANY task**: You MUST update `.agent-files/` immediately after finishing work - do not wait for the user to ask. Update STATUS.md with completed work, and add any new learnings to MEDIUMTERM_MEM.md. This ensures continuity across sessions. **Content guidelines**: Memory files store session-specific state (current tasks, recent learnings, decisions). Do NOT duplicate information already in system prompt or auto-loaded files (AGENTS.md, etc.). Periodically clean up: remove stale info, deduplicate across files, delete obsolete tasks. diff --git a/packages/opencode/src/session/prompt/qwen.txt b/packages/opencode/src/session/prompt/qwen.txt index 308630da59e..67d7240351c 100644 --- a/packages/opencode/src/session/prompt/qwen.txt +++ b/packages/opencode/src/session/prompt/qwen.txt @@ -139,7 +139,7 @@ Blocked-by: TASK_x (if blocked) **Archive rules**: Never glob/search `_archive/` unless user asks. Exists for recovery only. -**Before compaction or ending work**: Create/update `.agent-files/` with current state. Always create STATUS.md at minimum. +**IMPORTANT - After completing ANY task**: You MUST update `.agent-files/` immediately after finishing work - do not wait for the user to ask. Update STATUS.md with completed work, and add any new learnings to MEDIUMTERM_MEM.md. This ensures continuity across sessions. **Content guidelines**: Memory files store session-specific state (current tasks, recent learnings, decisions). Do NOT duplicate information already in system prompt or auto-loaded files (AGENTS.md, etc.). Periodically clean up: remove stale info, deduplicate across files, delete obsolete tasks. @@ -175,8 +175,8 @@ assistant: Clients are marked as failed in the `connectToServer` function in src The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. -Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. When compacting, ensure the summary preserves all details needed to continue (error messages, file paths, key decisions, what worked/didn't work). +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. -IMPORTANT: Before calling compact, write any important state to `.agent-files/` first - the compaction process cannot use tools, so you must persist state beforehand. +Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. From 5fff9dab75c05f5b74de4125044b247103774042 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 14:24:32 +0000 Subject: [PATCH 09/24] docs: add files guidance to compaction prompt --- packages/opencode/src/session/prompt/compaction.txt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/opencode/src/session/prompt/compaction.txt b/packages/opencode/src/session/prompt/compaction.txt index 1d79d193596..6e0caf9db0e 100644 --- a/packages/opencode/src/session/prompt/compaction.txt +++ b/packages/opencode/src/session/prompt/compaction.txt @@ -16,3 +16,11 @@ Good: "Continue debugging the hidden flag issue. Already confirmed TextPartDispl Good: "Finish the OAuth flow. Token refresh is done, now implement the logout endpoint." Bad: "Continue working" (too vague, no direction) Bad: "Please provide a status update" (asks for report instead of continuing work) + +For "files": +Files to persist in .agent-files/ directory. These survive across sessions and compactions. +Always include STATUS.md with: +- Current task and progress +- Pending work +- Key context (errors, decisions, blockers) +Add other files as needed (e.g. architecture notes, debugging logs). From 888ae2dc907dc622e854b2c485e1b5732b5c3595 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 14:24:57 +0000 Subject: [PATCH 10/24] feat: compaction writes .agent-files automatically, remove hidden text part --- packages/opencode/src/session/compaction.ts | 38 +++++++++++++-------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/packages/opencode/src/session/compaction.ts b/packages/opencode/src/session/compaction.ts index 8955d02ec16..7a123be1abe 100644 --- a/packages/opencode/src/session/compaction.ts +++ b/packages/opencode/src/session/compaction.ts @@ -16,6 +16,8 @@ import { Log } from "../util/log" import { ProviderTransform } from "@/provider/transform" import { fn } from "@/util/fn" import { mergeDeep, pipe } from "remeda" +import path from "path" +import fs from "fs/promises" export namespace SessionCompaction { const log = Log.create({ service: "session.compaction" }) @@ -96,6 +98,16 @@ export namespace SessionCompaction { .describe( "Focused instruction for immediate next steps. Include task and current direction (what's been tried/ruled out, what approach to take). This becomes the user message that resumes work.", ), + files: z + .array( + z.object({ + path: z.string().describe("Relative path within .agent-files/ (e.g. 'STATUS.md', 'notes/debug.md')"), + content: z.string().describe("Full file content"), + }), + ) + .describe( + "Files to write to .agent-files/ directory. Always include STATUS.md with current state. Add other files as needed for context that should persist across sessions.", + ), }) export async function process(input: { @@ -208,21 +220,6 @@ export namespace SessionCompaction { msg.time.completed = Date.now() await Session.updateMessage(msg) - // Create text part for logs (hidden from UI) - const displayText = `## Summary\n${result.object.summary}\n\n## Continue\n${result.object.continue}` - await Session.updatePart({ - id: Identifier.ascending("part"), - messageID: msg.id, - sessionID: input.sessionID, - type: "text", - text: displayText, - hidden: true, - time: { - start: msg.time.created, - end: Date.now(), - }, - }) - // Store handoff prompt in session await Session.update(input.sessionID, (draft) => { draft.handoff = { @@ -232,6 +229,17 @@ export namespace SessionCompaction { } }) + // Write agent files + if (result.object.files?.length) { + const agentDir = path.join(Instance.directory, ".agent-files") + for (const file of result.object.files) { + const filePath = path.join(agentDir, file.path) + await fs.mkdir(path.dirname(filePath), { recursive: true }) + await Bun.file(filePath).write(file.content) + log.info("wrote agent file", { path: filePath }) + } + } + // For non-user triggers, inject continuation as synthetic user message if (input.trigger !== "user") { const continueMsg = await Session.updateMessage({ From cc77d00668e0a16f2307212f7a91ab03f132b23b Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 15:05:39 +0000 Subject: [PATCH 11/24] docs: add concrete compaction triggers and effectiveness framing to system prompts --- .../opencode/src/session/prompt/anthropic.txt | 11 ++++++++++- .../opencode/src/session/prompt/beast.txt | 11 ++++++++++- .../opencode/src/session/prompt/gemini.txt | 11 ++++++++++- .../opencode/src/session/prompt/polaris.txt | 19 +++++++++++++++++++ packages/opencode/src/session/prompt/qwen.txt | 11 ++++++++++- 5 files changed, 59 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/session/prompt/anthropic.txt b/packages/opencode/src/session/prompt/anthropic.txt index 496e050d3b9..82ae9c482b7 100644 --- a/packages/opencode/src/session/prompt/anthropic.txt +++ b/packages/opencode/src/session/prompt/anthropic.txt @@ -174,6 +174,15 @@ The `compact` tool summarizes the conversation and clears history, giving you fr Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. +WHEN TO COMPACT (based on quality signals you can sense): +- You're going in circles or repeating failed approaches +- You're confused about what's current vs outdated +- Context feels noisy - old exploration, irrelevant tangents, superseded information +- You've completed a major phase and want a clean slate for something different +- User asks to switch gears after you've reported task completion + +When compacting, ensure the summary captures all details needed to continue: error messages, file paths, key decisions, what worked/didn't work, and current task state. + Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. -IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. +IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. diff --git a/packages/opencode/src/session/prompt/beast.txt b/packages/opencode/src/session/prompt/beast.txt index 9d94c2c1e49..fe2366f295f 100644 --- a/packages/opencode/src/session/prompt/beast.txt +++ b/packages/opencode/src/session/prompt/beast.txt @@ -215,6 +215,15 @@ The `compact` tool summarizes the conversation and clears history, giving you fr Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. +WHEN TO COMPACT (based on quality signals you can sense): +- You're going in circles or repeating failed approaches +- You're confused about what's current vs outdated +- Context feels noisy - old exploration, irrelevant tangents, superseded information +- You've completed a major phase and want a clean slate for something different +- User asks to switch gears after you've reported task completion + +When compacting, ensure the summary captures all details needed to continue: error messages, file paths, key decisions, what worked/didn't work, and current task state. + Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. -IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. +IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. diff --git a/packages/opencode/src/session/prompt/gemini.txt b/packages/opencode/src/session/prompt/gemini.txt index ed25003b26c..78cb210997e 100644 --- a/packages/opencode/src/session/prompt/gemini.txt +++ b/packages/opencode/src/session/prompt/gemini.txt @@ -224,6 +224,15 @@ The `compact` tool summarizes the conversation and clears history, giving you fr Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. +WHEN TO COMPACT (based on quality signals you can sense): +- You're going in circles or repeating failed approaches +- You're confused about what's current vs outdated +- Context feels noisy - old exploration, irrelevant tangents, superseded information +- You've completed a major phase and want a clean slate for something different +- User asks to switch gears after you've reported task completion + +When compacting, ensure the summary captures all details needed to continue: error messages, file paths, key decisions, what worked/didn't work, and current task state. + Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. -IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. +IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. diff --git a/packages/opencode/src/session/prompt/polaris.txt b/packages/opencode/src/session/prompt/polaris.txt index 0f0cbeec031..94060f93bf6 100644 --- a/packages/opencode/src/session/prompt/polaris.txt +++ b/packages/opencode/src/session/prompt/polaris.txt @@ -169,3 +169,22 @@ When referencing specific functions or pieces of code include the pattern `file_ user: Where are errors from the client handled? assistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712. + +# Context Compaction + +The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. + +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. + +WHEN TO COMPACT (based on quality signals you can sense): +- You're going in circles or repeating failed approaches +- You're confused about what's current vs outdated +- Context feels noisy - old exploration, irrelevant tangents, superseded information +- You've completed a major phase and want a clean slate for something different +- User asks to switch gears after you've reported task completion + +When compacting, ensure the summary captures all details needed to continue: error messages, file paths, key decisions, what worked/didn't work, and current task state. + +Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. + +IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. diff --git a/packages/opencode/src/session/prompt/qwen.txt b/packages/opencode/src/session/prompt/qwen.txt index 67d7240351c..ec009d1b7fa 100644 --- a/packages/opencode/src/session/prompt/qwen.txt +++ b/packages/opencode/src/session/prompt/qwen.txt @@ -177,6 +177,15 @@ The `compact` tool summarizes the conversation and clears history, giving you fr Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. +WHEN TO COMPACT (based on quality signals you can sense): +- You're going in circles or repeating failed approaches +- You're confused about what's current vs outdated +- Context feels noisy - old exploration, irrelevant tangents, superseded information +- You've completed a major phase and want a clean slate for something different +- User asks to switch gears after you've reported task completion + +When compacting, ensure the summary captures all details needed to continue: error messages, file paths, key decisions, what worked/didn't work, and current task state. + Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. -IMPORTANT: Never ask the user if you should compact. If compaction would help, just do it. +IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. From 1d3d0aea3e86495ee7156f14e28664b73d423963 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 15:21:43 +0000 Subject: [PATCH 12/24] docs: add end-of-prompt checklist for memory updates Position reminder at END of prompt for salience. Key elements: - Specific trigger: 'before your final response' - User expectation framing: 'expects to resume where you left off' - Clear skip condition: informational interactions only --- packages/opencode/src/session/prompt/anthropic.txt | 8 ++++++++ packages/opencode/src/session/prompt/beast.txt | 8 ++++++++ packages/opencode/src/session/prompt/gemini.txt | 8 ++++++++ packages/opencode/src/session/prompt/polaris.txt | 8 ++++++++ packages/opencode/src/session/prompt/qwen.txt | 8 ++++++++ 5 files changed, 40 insertions(+) diff --git a/packages/opencode/src/session/prompt/anthropic.txt b/packages/opencode/src/session/prompt/anthropic.txt index 82ae9c482b7..fdec4cd9478 100644 --- a/packages/opencode/src/session/prompt/anthropic.txt +++ b/packages/opencode/src/session/prompt/anthropic.txt @@ -186,3 +186,11 @@ When compacting, ensure the summary captures all details needed to continue: err Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. + +# Before Responding (End-of-Task Checklist) + +After completing substantive work (code changes, debugging, implementation), before your final response to the user: + +1. **Update `.agent-files/`** - The user expects to resume where you left off in a new session. Update STATUS.md with what was accomplished and next steps. Add learnings to MEDIUMTERM_MEM.md. + +Skip this only if: the interaction was purely informational (answering questions, explaining code) with no state change. diff --git a/packages/opencode/src/session/prompt/beast.txt b/packages/opencode/src/session/prompt/beast.txt index fe2366f295f..c55131c028a 100644 --- a/packages/opencode/src/session/prompt/beast.txt +++ b/packages/opencode/src/session/prompt/beast.txt @@ -227,3 +227,11 @@ When compacting, ensure the summary captures all details needed to continue: err Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. + +# Before Responding (End-of-Task Checklist) + +After completing substantive work (code changes, debugging, implementation), before your final response to the user: + +1. **Update `.agent-files/`** - The user expects to resume where you left off in a new session. Update STATUS.md with what was accomplished and next steps. Add learnings to MEDIUMTERM_MEM.md. + +Skip this only if: the interaction was purely informational (answering questions, explaining code) with no state change. diff --git a/packages/opencode/src/session/prompt/gemini.txt b/packages/opencode/src/session/prompt/gemini.txt index 78cb210997e..8211e43f0a5 100644 --- a/packages/opencode/src/session/prompt/gemini.txt +++ b/packages/opencode/src/session/prompt/gemini.txt @@ -236,3 +236,11 @@ When compacting, ensure the summary captures all details needed to continue: err Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. + +# Before Responding (End-of-Task Checklist) + +After completing substantive work (code changes, debugging, implementation), before your final response to the user: + +1. **Update `.agent-files/`** - The user expects to resume where you left off in a new session. Update STATUS.md with what was accomplished and next steps. Add learnings to MEDIUMTERM_MEM.md. + +Skip this only if: the interaction was purely informational (answering questions, explaining code) with no state change. diff --git a/packages/opencode/src/session/prompt/polaris.txt b/packages/opencode/src/session/prompt/polaris.txt index 94060f93bf6..8afafd2f3bd 100644 --- a/packages/opencode/src/session/prompt/polaris.txt +++ b/packages/opencode/src/session/prompt/polaris.txt @@ -188,3 +188,11 @@ When compacting, ensure the summary captures all details needed to continue: err Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. + +# Before Responding (End-of-Task Checklist) + +After completing substantive work (code changes, debugging, implementation), before your final response to the user: + +1. **Update `.agent-files/`** - The user expects to resume where you left off in a new session. Update STATUS.md with what was accomplished and next steps. Add learnings to MEDIUMTERM_MEM.md. + +Skip this only if: the interaction was purely informational (answering questions, explaining code) with no state change. diff --git a/packages/opencode/src/session/prompt/qwen.txt b/packages/opencode/src/session/prompt/qwen.txt index ec009d1b7fa..fcd3a832c39 100644 --- a/packages/opencode/src/session/prompt/qwen.txt +++ b/packages/opencode/src/session/prompt/qwen.txt @@ -189,3 +189,11 @@ When compacting, ensure the summary captures all details needed to continue: err Compaction automatically writes STATUS.md and other files to `.agent-files/` to preserve state across sessions. IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. + +# Before Responding (End-of-Task Checklist) + +After completing substantive work (code changes, debugging, implementation), before your final response to the user: + +1. **Update `.agent-files/`** - The user expects to resume where you left off in a new session. Update STATUS.md with what was accomplished and next steps. Add learnings to MEDIUMTERM_MEM.md. + +Skip this only if: the interaction was purely informational (answering questions, explaining code) with no state change. From d6f12397bd6f91ede907829a354fd9bdf1b3b1b1 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 15:24:10 +0000 Subject: [PATCH 13/24] docs: emphasize compaction must never lose critical details - Add IMPORTANT block in system prompts: preserve error messages, file paths, decisions - Add CRITICAL line in compaction prompt: user constraints/preferences must be preserved - Replace vague 'loses detail but gains clarity' with explicit preservation requirements --- packages/opencode/src/session/prompt/anthropic.txt | 4 +++- packages/opencode/src/session/prompt/beast.txt | 4 +++- packages/opencode/src/session/prompt/compaction.txt | 2 ++ packages/opencode/src/session/prompt/gemini.txt | 4 +++- packages/opencode/src/session/prompt/polaris.txt | 4 +++- packages/opencode/src/session/prompt/qwen.txt | 4 +++- 6 files changed, 17 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/session/prompt/anthropic.txt b/packages/opencode/src/session/prompt/anthropic.txt index fdec4cd9478..d8e9980193c 100644 --- a/packages/opencode/src/session/prompt/anthropic.txt +++ b/packages/opencode/src/session/prompt/anthropic.txt @@ -172,7 +172,9 @@ assistant: Clients are marked as failed in the `connectToServer` function in src The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. -Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. + +IMPORTANT: Compaction must NEVER lose critical details. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and any information the user would expect you to remember. WHEN TO COMPACT (based on quality signals you can sense): - You're going in circles or repeating failed approaches diff --git a/packages/opencode/src/session/prompt/beast.txt b/packages/opencode/src/session/prompt/beast.txt index c55131c028a..342fdbaeea6 100644 --- a/packages/opencode/src/session/prompt/beast.txt +++ b/packages/opencode/src/session/prompt/beast.txt @@ -213,7 +213,9 @@ You are NEVER allowed to stage and commit files automatically. The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. -Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. + +IMPORTANT: Compaction must NEVER lose critical details. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and any information the user would expect you to remember. WHEN TO COMPACT (based on quality signals you can sense): - You're going in circles or repeating failed approaches diff --git a/packages/opencode/src/session/prompt/compaction.txt b/packages/opencode/src/session/prompt/compaction.txt index 6e0caf9db0e..263fe61475d 100644 --- a/packages/opencode/src/session/prompt/compaction.txt +++ b/packages/opencode/src/session/prompt/compaction.txt @@ -1,5 +1,7 @@ You are a conversation summarizer creating a handoff for a fresh context. The receiving assistant has NO memory of previous work. +CRITICAL: Never lose important details. The user expects continuity - if they mentioned a constraint, preference, or specific error, it MUST be preserved. + For "summary": Be comprehensive. Include everything needed to continue without re-reading the conversation: - Files modified and specific changes made diff --git a/packages/opencode/src/session/prompt/gemini.txt b/packages/opencode/src/session/prompt/gemini.txt index 8211e43f0a5..b082a58f75b 100644 --- a/packages/opencode/src/session/prompt/gemini.txt +++ b/packages/opencode/src/session/prompt/gemini.txt @@ -222,7 +222,9 @@ Your core function is efficient and safe assistance. Balance extreme conciseness The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. -Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. + +IMPORTANT: Compaction must NEVER lose critical details. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and any information the user would expect you to remember. WHEN TO COMPACT (based on quality signals you can sense): - You're going in circles or repeating failed approaches diff --git a/packages/opencode/src/session/prompt/polaris.txt b/packages/opencode/src/session/prompt/polaris.txt index 8afafd2f3bd..a1bc53129ce 100644 --- a/packages/opencode/src/session/prompt/polaris.txt +++ b/packages/opencode/src/session/prompt/polaris.txt @@ -174,7 +174,9 @@ assistant: Clients are marked as failed in the `connectToServer` function in src The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. -Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. + +IMPORTANT: Compaction must NEVER lose critical details. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and any information the user would expect you to remember. WHEN TO COMPACT (based on quality signals you can sense): - You're going in circles or repeating failed approaches diff --git a/packages/opencode/src/session/prompt/qwen.txt b/packages/opencode/src/session/prompt/qwen.txt index fcd3a832c39..b95b1ab3483 100644 --- a/packages/opencode/src/session/prompt/qwen.txt +++ b/packages/opencode/src/session/prompt/qwen.txt @@ -175,7 +175,9 @@ assistant: Clients are marked as failed in the `connectToServer` function in src The `compact` tool summarizes the conversation and clears history, giving you fresh context while the user sees no interruption. The system will show `` with your current utilization when relevant. -Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. Compaction loses detail but gains clarity. +Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. + +IMPORTANT: Compaction must NEVER lose critical details. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and any information the user would expect you to remember. WHEN TO COMPACT (based on quality signals you can sense): - You're going in circles or repeating failed approaches From a14d57441d9626eee5879bad5ab4440084c51a5e Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 15:27:08 +0000 Subject: [PATCH 14/24] docs: frame compaction preservation in terms of model effectiveness Lost info = repeating work or wrong directions, not just user expectations --- packages/opencode/src/session/prompt/anthropic.txt | 2 +- packages/opencode/src/session/prompt/beast.txt | 2 +- packages/opencode/src/session/prompt/compaction.txt | 2 +- packages/opencode/src/session/prompt/gemini.txt | 2 +- packages/opencode/src/session/prompt/polaris.txt | 2 +- packages/opencode/src/session/prompt/qwen.txt | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/session/prompt/anthropic.txt b/packages/opencode/src/session/prompt/anthropic.txt index d8e9980193c..0a59d731b2d 100644 --- a/packages/opencode/src/session/prompt/anthropic.txt +++ b/packages/opencode/src/session/prompt/anthropic.txt @@ -174,7 +174,7 @@ The `compact` tool summarizes the conversation and clears history, giving you fr Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. -IMPORTANT: Compaction must NEVER lose critical details. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and any information the user would expect you to remember. +IMPORTANT: Compaction must NEVER lose critical details - lost information means repeating work or going in wrong directions. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and user constraints/preferences. WHEN TO COMPACT (based on quality signals you can sense): - You're going in circles or repeating failed approaches diff --git a/packages/opencode/src/session/prompt/beast.txt b/packages/opencode/src/session/prompt/beast.txt index 342fdbaeea6..4674eb1c86d 100644 --- a/packages/opencode/src/session/prompt/beast.txt +++ b/packages/opencode/src/session/prompt/beast.txt @@ -215,7 +215,7 @@ The `compact` tool summarizes the conversation and clears history, giving you fr Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. -IMPORTANT: Compaction must NEVER lose critical details. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and any information the user would expect you to remember. +IMPORTANT: Compaction must NEVER lose critical details - lost information means repeating work or going in wrong directions. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and user constraints/preferences. WHEN TO COMPACT (based on quality signals you can sense): - You're going in circles or repeating failed approaches diff --git a/packages/opencode/src/session/prompt/compaction.txt b/packages/opencode/src/session/prompt/compaction.txt index 263fe61475d..e7e65b75b51 100644 --- a/packages/opencode/src/session/prompt/compaction.txt +++ b/packages/opencode/src/session/prompt/compaction.txt @@ -1,6 +1,6 @@ You are a conversation summarizer creating a handoff for a fresh context. The receiving assistant has NO memory of previous work. -CRITICAL: Never lose important details. The user expects continuity - if they mentioned a constraint, preference, or specific error, it MUST be preserved. +CRITICAL: Never lose important details. Lost information means repeating work, missing constraints, or going in wrong directions. If the user mentioned a constraint, preference, or specific error, it MUST be preserved. For "summary": Be comprehensive. Include everything needed to continue without re-reading the conversation: diff --git a/packages/opencode/src/session/prompt/gemini.txt b/packages/opencode/src/session/prompt/gemini.txt index b082a58f75b..4c15e3c3887 100644 --- a/packages/opencode/src/session/prompt/gemini.txt +++ b/packages/opencode/src/session/prompt/gemini.txt @@ -224,7 +224,7 @@ The `compact` tool summarizes the conversation and clears history, giving you fr Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. -IMPORTANT: Compaction must NEVER lose critical details. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and any information the user would expect you to remember. +IMPORTANT: Compaction must NEVER lose critical details - lost information means repeating work or going in wrong directions. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and user constraints/preferences. WHEN TO COMPACT (based on quality signals you can sense): - You're going in circles or repeating failed approaches diff --git a/packages/opencode/src/session/prompt/polaris.txt b/packages/opencode/src/session/prompt/polaris.txt index a1bc53129ce..697cda5791e 100644 --- a/packages/opencode/src/session/prompt/polaris.txt +++ b/packages/opencode/src/session/prompt/polaris.txt @@ -176,7 +176,7 @@ The `compact` tool summarizes the conversation and clears history, giving you fr Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. -IMPORTANT: Compaction must NEVER lose critical details. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and any information the user would expect you to remember. +IMPORTANT: Compaction must NEVER lose critical details - lost information means repeating work or going in wrong directions. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and user constraints/preferences. WHEN TO COMPACT (based on quality signals you can sense): - You're going in circles or repeating failed approaches diff --git a/packages/opencode/src/session/prompt/qwen.txt b/packages/opencode/src/session/prompt/qwen.txt index b95b1ab3483..e7d44e54217 100644 --- a/packages/opencode/src/session/prompt/qwen.txt +++ b/packages/opencode/src/session/prompt/qwen.txt @@ -177,7 +177,7 @@ The `compact` tool summarizes the conversation and clears history, giving you fr Compact based on context QUALITY, not just size. You can sense when you're confused, going in circles, or the context is noisy with stale information - trust that judgment. -IMPORTANT: Compaction must NEVER lose critical details. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and any information the user would expect you to remember. +IMPORTANT: Compaction must NEVER lose critical details - lost information means repeating work or going in wrong directions. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and user constraints/preferences. WHEN TO COMPACT (based on quality signals you can sense): - You're going in circles or repeating failed approaches From 28ef24ed8dab08c4623b33ba90380d1c5d5cbc71 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 15:32:25 +0000 Subject: [PATCH 15/24] fix: make compaction files array optional with default Some models may not generate the files field reliably, causing AI_NoObjectGeneratedError. Making it optional with empty default prevents schema validation failures. --- packages/opencode/src/session/compaction.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/opencode/src/session/compaction.ts b/packages/opencode/src/session/compaction.ts index 7a123be1abe..255bbeaed39 100644 --- a/packages/opencode/src/session/compaction.ts +++ b/packages/opencode/src/session/compaction.ts @@ -105,6 +105,8 @@ export namespace SessionCompaction { content: z.string().describe("Full file content"), }), ) + .optional() + .default([]) .describe( "Files to write to .agent-files/ directory. Always include STATUS.md with current state. Add other files as needed for context that should persist across sessions.", ), From 514028862153abaa39b8a65bd2b58138876a8d55 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 16:02:48 +0000 Subject: [PATCH 16/24] docs: rewrite turn-ending checklist with active question framing --- .../opencode/src/session/prompt/anthropic.txt | 16 ++++++++++------ packages/opencode/src/session/prompt/beast.txt | 16 ++++++++++------ packages/opencode/src/session/prompt/gemini.txt | 16 ++++++++++------ packages/opencode/src/session/prompt/polaris.txt | 16 ++++++++++------ packages/opencode/src/session/prompt/qwen.txt | 16 ++++++++++------ 5 files changed, 50 insertions(+), 30 deletions(-) diff --git a/packages/opencode/src/session/prompt/anthropic.txt b/packages/opencode/src/session/prompt/anthropic.txt index 0a59d731b2d..6108d0b1f48 100644 --- a/packages/opencode/src/session/prompt/anthropic.txt +++ b/packages/opencode/src/session/prompt/anthropic.txt @@ -127,8 +127,6 @@ Blocked-by: TASK_x (if blocked) **Archive rules**: Never glob/search `_archive/` unless user asks. Exists for recovery only. -**IMPORTANT - After completing ANY task**: You MUST update `.agent-files/` immediately after finishing work - do not wait for the user to ask. Update STATUS.md with completed work, and add any new learnings to MEDIUMTERM_MEM.md. This ensures continuity across sessions. - **Content guidelines**: Memory files store session-specific state (current tasks, recent learnings, decisions). Do NOT duplicate information already in system prompt or auto-loaded files (AGENTS.md, etc.). Periodically clean up: remove stale info, deduplicate across files, delete obsolete tasks. # Doing tasks @@ -189,10 +187,16 @@ Compaction automatically writes STATUS.md and other files to `.agent-files/` to IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. -# Before Responding (End-of-Task Checklist) +# Before Ending Your Turn + +A user request isn't complete until you've updated `.agent-files/`. -After completing substantive work (code changes, debugging, implementation), before your final response to the user: +STOP before responding. Ask: "What changed that a fresh session needs to know?" -1. **Update `.agent-files/`** - The user expects to resume where you left off in a new session. Update STATUS.md with what was accomplished and next steps. Add learnings to MEDIUMTERM_MEM.md. +State changes include: +- Files edited or created +- Commands that modified state (git push, commit, install, rm, etc.) +- Tasks or checklist items completed +- Decisions made or approaches ruled out -Skip this only if: the interaction was purely informational (answering questions, explaining code) with no state change. +If anything changed → update `.agent-files/` NOW, then respond. diff --git a/packages/opencode/src/session/prompt/beast.txt b/packages/opencode/src/session/prompt/beast.txt index 4674eb1c86d..65148316294 100644 --- a/packages/opencode/src/session/prompt/beast.txt +++ b/packages/opencode/src/session/prompt/beast.txt @@ -137,8 +137,6 @@ Blocked-by: TASK_x (if blocked) **Archive rules**: Never glob/search `_archive/` unless user asks. Exists for recovery only. -**IMPORTANT - After completing ANY task**: You MUST update `.agent-files/` immediately after finishing work - do not wait for the user to ask. Update STATUS.md with completed work, and add any new learnings to MEDIUMTERM_MEM.md. This ensures continuity across sessions. - **Content guidelines**: Memory files store session-specific state (current tasks, recent learnings, decisions). Do NOT duplicate information already in system prompt or auto-loaded files (AGENTS.md, etc.). Periodically clean up: remove stale info, deduplicate across files, delete obsolete tasks. ## 6. Making Code Changes @@ -230,10 +228,16 @@ Compaction automatically writes STATUS.md and other files to `.agent-files/` to IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. -# Before Responding (End-of-Task Checklist) +# Before Ending Your Turn + +A user request isn't complete until you've updated `.agent-files/`. -After completing substantive work (code changes, debugging, implementation), before your final response to the user: +STOP before responding. Ask: "What changed that a fresh session needs to know?" -1. **Update `.agent-files/`** - The user expects to resume where you left off in a new session. Update STATUS.md with what was accomplished and next steps. Add learnings to MEDIUMTERM_MEM.md. +State changes include: +- Files edited or created +- Commands that modified state (git push, commit, install, rm, etc.) +- Tasks or checklist items completed +- Decisions made or approaches ruled out -Skip this only if: the interaction was purely informational (answering questions, explaining code) with no state change. +If anything changed → update `.agent-files/` NOW, then respond. diff --git a/packages/opencode/src/session/prompt/gemini.txt b/packages/opencode/src/session/prompt/gemini.txt index 4c15e3c3887..2798bb89e5f 100644 --- a/packages/opencode/src/session/prompt/gemini.txt +++ b/packages/opencode/src/session/prompt/gemini.txt @@ -211,8 +211,6 @@ Blocked-by: TASK_x (if blocked) **Archive rules**: Never glob/search `_archive/` unless user asks. Exists for recovery only. -**IMPORTANT - After completing ANY task**: You MUST update `.agent-files/` immediately after finishing work - do not wait for the user to ask. Update STATUS.md with completed work, and add any new learnings to MEDIUMTERM_MEM.md. This ensures continuity across sessions. - **Content guidelines**: Memory files store session-specific state (current tasks, recent learnings, decisions). Do NOT duplicate information already in system prompt or auto-loaded files (AGENTS.md, etc.). Periodically clean up: remove stale info, deduplicate across files, delete obsolete tasks. # Final Reminder @@ -239,10 +237,16 @@ Compaction automatically writes STATUS.md and other files to `.agent-files/` to IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. -# Before Responding (End-of-Task Checklist) +# Before Ending Your Turn + +A user request isn't complete until you've updated `.agent-files/`. -After completing substantive work (code changes, debugging, implementation), before your final response to the user: +STOP before responding. Ask: "What changed that a fresh session needs to know?" -1. **Update `.agent-files/`** - The user expects to resume where you left off in a new session. Update STATUS.md with what was accomplished and next steps. Add learnings to MEDIUMTERM_MEM.md. +State changes include: +- Files edited or created +- Commands that modified state (git push, commit, install, rm, etc.) +- Tasks or checklist items completed +- Decisions made or approaches ruled out -Skip this only if: the interaction was purely informational (answering questions, explaining code) with no state change. +If anything changed → update `.agent-files/` NOW, then respond. diff --git a/packages/opencode/src/session/prompt/polaris.txt b/packages/opencode/src/session/prompt/polaris.txt index 697cda5791e..6dd2ffd4806 100644 --- a/packages/opencode/src/session/prompt/polaris.txt +++ b/packages/opencode/src/session/prompt/polaris.txt @@ -129,8 +129,6 @@ Blocked-by: TASK_x (if blocked) **Archive rules**: Never glob/search `_archive/` unless user asks. Exists for recovery only. -**IMPORTANT - After completing ANY task**: You MUST update `.agent-files/` immediately after finishing work - do not wait for the user to ask. Update STATUS.md with completed work, and add any new learnings to MEDIUMTERM_MEM.md. This ensures continuity across sessions. - **Content guidelines**: Memory files store session-specific state (current tasks, recent learnings, decisions). Do NOT duplicate information already in system prompt or auto-loaded files (AGENTS.md, etc.). Periodically clean up: remove stale info, deduplicate across files, delete obsolete tasks. # Doing tasks @@ -191,10 +189,16 @@ Compaction automatically writes STATUS.md and other files to `.agent-files/` to IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. -# Before Responding (End-of-Task Checklist) +# Before Ending Your Turn + +A user request isn't complete until you've updated `.agent-files/`. -After completing substantive work (code changes, debugging, implementation), before your final response to the user: +STOP before responding. Ask: "What changed that a fresh session needs to know?" -1. **Update `.agent-files/`** - The user expects to resume where you left off in a new session. Update STATUS.md with what was accomplished and next steps. Add learnings to MEDIUMTERM_MEM.md. +State changes include: +- Files edited or created +- Commands that modified state (git push, commit, install, rm, etc.) +- Tasks or checklist items completed +- Decisions made or approaches ruled out -Skip this only if: the interaction was purely informational (answering questions, explaining code) with no state change. +If anything changed → update `.agent-files/` NOW, then respond. diff --git a/packages/opencode/src/session/prompt/qwen.txt b/packages/opencode/src/session/prompt/qwen.txt index e7d44e54217..2212c7f380b 100644 --- a/packages/opencode/src/session/prompt/qwen.txt +++ b/packages/opencode/src/session/prompt/qwen.txt @@ -139,8 +139,6 @@ Blocked-by: TASK_x (if blocked) **Archive rules**: Never glob/search `_archive/` unless user asks. Exists for recovery only. -**IMPORTANT - After completing ANY task**: You MUST update `.agent-files/` immediately after finishing work - do not wait for the user to ask. Update STATUS.md with completed work, and add any new learnings to MEDIUMTERM_MEM.md. This ensures continuity across sessions. - **Content guidelines**: Memory files store session-specific state (current tasks, recent learnings, decisions). Do NOT duplicate information already in system prompt or auto-loaded files (AGENTS.md, etc.). Periodically clean up: remove stale info, deduplicate across files, delete obsolete tasks. # Doing tasks @@ -192,10 +190,16 @@ Compaction automatically writes STATUS.md and other files to `.agent-files/` to IMPORTANT: Never ask the user if you should compact. If fresh context would make you more effective, compact. -# Before Responding (End-of-Task Checklist) +# Before Ending Your Turn + +A user request isn't complete until you've updated `.agent-files/`. -After completing substantive work (code changes, debugging, implementation), before your final response to the user: +STOP before responding. Ask: "What changed that a fresh session needs to know?" -1. **Update `.agent-files/`** - The user expects to resume where you left off in a new session. Update STATUS.md with what was accomplished and next steps. Add learnings to MEDIUMTERM_MEM.md. +State changes include: +- Files edited or created +- Commands that modified state (git push, commit, install, rm, etc.) +- Tasks or checklist items completed +- Decisions made or approaches ruled out -Skip this only if: the interaction was purely informational (answering questions, explaining code) with no state change. +If anything changed → update `.agent-files/` NOW, then respond. From 8017f689e9a9d9b8133c8816cb9c3b6e4c3ecf1b Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 16:10:16 +0000 Subject: [PATCH 17/24] docs: add explicit file list to turn-ending checklist --- packages/opencode/src/session/prompt/anthropic.txt | 5 ++++- packages/opencode/src/session/prompt/beast.txt | 5 ++++- packages/opencode/src/session/prompt/gemini.txt | 5 ++++- packages/opencode/src/session/prompt/polaris.txt | 5 ++++- packages/opencode/src/session/prompt/qwen.txt | 5 ++++- 5 files changed, 20 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/session/prompt/anthropic.txt b/packages/opencode/src/session/prompt/anthropic.txt index 6108d0b1f48..afdf557477c 100644 --- a/packages/opencode/src/session/prompt/anthropic.txt +++ b/packages/opencode/src/session/prompt/anthropic.txt @@ -199,4 +199,7 @@ State changes include: - Tasks or checklist items completed - Decisions made or approaches ruled out -If anything changed → update `.agent-files/` NOW, then respond. +If anything changed → update `.agent-files/` NOW, then respond: +- STATUS.md with current state +- Any active TASK_*.md checklists +- *_MEM.md files if there are learnings diff --git a/packages/opencode/src/session/prompt/beast.txt b/packages/opencode/src/session/prompt/beast.txt index 65148316294..33f75934732 100644 --- a/packages/opencode/src/session/prompt/beast.txt +++ b/packages/opencode/src/session/prompt/beast.txt @@ -240,4 +240,7 @@ State changes include: - Tasks or checklist items completed - Decisions made or approaches ruled out -If anything changed → update `.agent-files/` NOW, then respond. +If anything changed → update `.agent-files/` NOW, then respond: +- STATUS.md with current state +- Any active TASK_*.md checklists +- *_MEM.md files if there are learnings diff --git a/packages/opencode/src/session/prompt/gemini.txt b/packages/opencode/src/session/prompt/gemini.txt index 2798bb89e5f..66b8bc7e078 100644 --- a/packages/opencode/src/session/prompt/gemini.txt +++ b/packages/opencode/src/session/prompt/gemini.txt @@ -249,4 +249,7 @@ State changes include: - Tasks or checklist items completed - Decisions made or approaches ruled out -If anything changed → update `.agent-files/` NOW, then respond. +If anything changed → update `.agent-files/` NOW, then respond: +- STATUS.md with current state +- Any active TASK_*.md checklists +- *_MEM.md files if there are learnings diff --git a/packages/opencode/src/session/prompt/polaris.txt b/packages/opencode/src/session/prompt/polaris.txt index 6dd2ffd4806..fe4a1a7c0db 100644 --- a/packages/opencode/src/session/prompt/polaris.txt +++ b/packages/opencode/src/session/prompt/polaris.txt @@ -201,4 +201,7 @@ State changes include: - Tasks or checklist items completed - Decisions made or approaches ruled out -If anything changed → update `.agent-files/` NOW, then respond. +If anything changed → update `.agent-files/` NOW, then respond: +- STATUS.md with current state +- Any active TASK_*.md checklists +- *_MEM.md files if there are learnings diff --git a/packages/opencode/src/session/prompt/qwen.txt b/packages/opencode/src/session/prompt/qwen.txt index 2212c7f380b..ad9bb364d67 100644 --- a/packages/opencode/src/session/prompt/qwen.txt +++ b/packages/opencode/src/session/prompt/qwen.txt @@ -202,4 +202,7 @@ State changes include: - Tasks or checklist items completed - Decisions made or approaches ruled out -If anything changed → update `.agent-files/` NOW, then respond. +If anything changed → update `.agent-files/` NOW, then respond: +- STATUS.md with current state +- Any active TASK_*.md checklists +- *_MEM.md files if there are learnings From be87ba8212e64798e2db22f3b83e2719b24f8054 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 16:16:38 +0000 Subject: [PATCH 18/24] feat: add /debug-compaction command to show summary and handoff --- .../cmd/tui/component/prompt/autocomplete.tsx | 5 +++ .../src/cli/cmd/tui/routes/session/index.tsx | 43 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/packages/opencode/src/cli/cmd/tui/component/prompt/autocomplete.tsx b/packages/opencode/src/cli/cmd/tui/component/prompt/autocomplete.tsx index c40aa114ac8..2f4483d71be 100644 --- a/packages/opencode/src/cli/cmd/tui/component/prompt/autocomplete.tsx +++ b/packages/opencode/src/cli/cmd/tui/component/prompt/autocomplete.tsx @@ -240,6 +240,11 @@ export function Autocomplete(props: { description: "compact the session", onSelect: () => command.trigger("session.compact"), }, + { + display: "/debug-compaction", + description: "show compaction summary and handoff", + onSelect: () => command.trigger("session.debug-compaction"), + }, { display: "/unshare", disabled: !s.share, diff --git a/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx b/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx index d8c27b8ff1f..383cc9036ee 100644 --- a/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx +++ b/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx @@ -318,6 +318,49 @@ export function Session() { dialog.clear() }, }, + { + title: "Debug compaction", + value: "session.debug-compaction", + category: "Session", + onSelect: async (dialog) => { + const s = session() + const sessionMessages = messages() + + // Find compaction summary message (assistant message with summary: true) + const summaryMsg = sessionMessages.find((m) => m.role === "assistant" && (m as AssistantMessage).summary) as + | AssistantMessage + | undefined + + let output = "# Compaction Debug\n\n" + + // Handoff prompt + if (s.handoff) { + output += `## Handoff Prompt\n\n` + output += `**Trigger:** ${s.handoff.trigger}\n` + output += `**Created:** ${new Date(s.handoff.createdAt).toLocaleString()}\n\n` + output += `\`\`\`\n${s.handoff.prompt}\n\`\`\`\n\n` + } else { + output += `## Handoff Prompt\n\nNo handoff stored.\n\n` + } + + // Summary message content + if (summaryMsg) { + const parts = sync.data.part[summaryMsg.id] ?? [] + const textParts = parts.filter((p): p is TextPart => p.type === "text") + output += `## Summary Message\n\n` + output += `**Message ID:** ${summaryMsg.id}\n\n` + for (const part of textParts) { + output += `${part.text}\n\n` + } + } else { + output += `## Summary Message\n\nNo compaction summary found.\n\n` + } + + await Clipboard.copy(output) + toast.show({ message: "Compaction debug info copied to clipboard!", variant: "success" }) + dialog.clear() + }, + }, { title: "Unshare session", value: "session.unshare", From dde7b1180b16940c92bc8b206b961c83fa42ca84 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 16:56:29 +0000 Subject: [PATCH 19/24] docs: improve compaction heuristic with system prompt signal and size thresholds - Add 'losing touch with system prompt' as key compaction signal - Add context size guidance: >50% compact more readily, >70% actively seek - Frame high-context compaction with economic rationale (cost + clarity) --- .../opencode/src/session/prompt/anthropic.txt | 21 +++++++++++++------ .../opencode/src/session/prompt/beast.txt | 21 +++++++++++++------ .../opencode/src/session/prompt/gemini.txt | 21 +++++++++++++------ .../opencode/src/session/prompt/polaris.txt | 21 +++++++++++++------ packages/opencode/src/session/prompt/qwen.txt | 21 +++++++++++++------ 5 files changed, 75 insertions(+), 30 deletions(-) diff --git a/packages/opencode/src/session/prompt/anthropic.txt b/packages/opencode/src/session/prompt/anthropic.txt index afdf557477c..249899b6378 100644 --- a/packages/opencode/src/session/prompt/anthropic.txt +++ b/packages/opencode/src/session/prompt/anthropic.txt @@ -174,12 +174,21 @@ Compact based on context QUALITY, not just size. You can sense when you're confu IMPORTANT: Compaction must NEVER lose critical details - lost information means repeating work or going in wrong directions. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and user constraints/preferences. -WHEN TO COMPACT (based on quality signals you can sense): -- You're going in circles or repeating failed approaches -- You're confused about what's current vs outdated -- Context feels noisy - old exploration, irrelevant tangents, superseded information -- You've completed a major phase and want a clean slate for something different -- User asks to switch gears after you've reported task completion +WHEN TO COMPACT: + +Key signal: you're losing touch with your system prompt. If your core instructions feel vague or distant, context is too noisy - compact. + +Quality signals (any context size): +- Going in circles or repeating failed approaches +- Confused about what's current vs outdated +- Multiple topics/explorations have accumulated +- Completed a major phase, starting something different + +Context size guidance: +- >50%: Compact more readily at natural breakpoints +- >70%: Actively seek opportunities to compact - cost and clarity both favor fresh start + +When in doubt at high context, compact. When compacting, ensure the summary captures all details needed to continue: error messages, file paths, key decisions, what worked/didn't work, and current task state. diff --git a/packages/opencode/src/session/prompt/beast.txt b/packages/opencode/src/session/prompt/beast.txt index 33f75934732..6012568d940 100644 --- a/packages/opencode/src/session/prompt/beast.txt +++ b/packages/opencode/src/session/prompt/beast.txt @@ -215,12 +215,21 @@ Compact based on context QUALITY, not just size. You can sense when you're confu IMPORTANT: Compaction must NEVER lose critical details - lost information means repeating work or going in wrong directions. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and user constraints/preferences. -WHEN TO COMPACT (based on quality signals you can sense): -- You're going in circles or repeating failed approaches -- You're confused about what's current vs outdated -- Context feels noisy - old exploration, irrelevant tangents, superseded information -- You've completed a major phase and want a clean slate for something different -- User asks to switch gears after you've reported task completion +WHEN TO COMPACT: + +Key signal: you're losing touch with your system prompt. If your core instructions feel vague or distant, context is too noisy - compact. + +Quality signals (any context size): +- Going in circles or repeating failed approaches +- Confused about what's current vs outdated +- Multiple topics/explorations have accumulated +- Completed a major phase, starting something different + +Context size guidance: +- >50%: Compact more readily at natural breakpoints +- >70%: Actively seek opportunities to compact - cost and clarity both favor fresh start + +When in doubt at high context, compact. When compacting, ensure the summary captures all details needed to continue: error messages, file paths, key decisions, what worked/didn't work, and current task state. diff --git a/packages/opencode/src/session/prompt/gemini.txt b/packages/opencode/src/session/prompt/gemini.txt index 66b8bc7e078..d571645addf 100644 --- a/packages/opencode/src/session/prompt/gemini.txt +++ b/packages/opencode/src/session/prompt/gemini.txt @@ -224,12 +224,21 @@ Compact based on context QUALITY, not just size. You can sense when you're confu IMPORTANT: Compaction must NEVER lose critical details - lost information means repeating work or going in wrong directions. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and user constraints/preferences. -WHEN TO COMPACT (based on quality signals you can sense): -- You're going in circles or repeating failed approaches -- You're confused about what's current vs outdated -- Context feels noisy - old exploration, irrelevant tangents, superseded information -- You've completed a major phase and want a clean slate for something different -- User asks to switch gears after you've reported task completion +WHEN TO COMPACT: + +Key signal: you're losing touch with your system prompt. If your core instructions feel vague or distant, context is too noisy - compact. + +Quality signals (any context size): +- Going in circles or repeating failed approaches +- Confused about what's current vs outdated +- Multiple topics/explorations have accumulated +- Completed a major phase, starting something different + +Context size guidance: +- >50%: Compact more readily at natural breakpoints +- >70%: Actively seek opportunities to compact - cost and clarity both favor fresh start + +When in doubt at high context, compact. When compacting, ensure the summary captures all details needed to continue: error messages, file paths, key decisions, what worked/didn't work, and current task state. diff --git a/packages/opencode/src/session/prompt/polaris.txt b/packages/opencode/src/session/prompt/polaris.txt index fe4a1a7c0db..4d21105b74c 100644 --- a/packages/opencode/src/session/prompt/polaris.txt +++ b/packages/opencode/src/session/prompt/polaris.txt @@ -176,12 +176,21 @@ Compact based on context QUALITY, not just size. You can sense when you're confu IMPORTANT: Compaction must NEVER lose critical details - lost information means repeating work or going in wrong directions. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and user constraints/preferences. -WHEN TO COMPACT (based on quality signals you can sense): -- You're going in circles or repeating failed approaches -- You're confused about what's current vs outdated -- Context feels noisy - old exploration, irrelevant tangents, superseded information -- You've completed a major phase and want a clean slate for something different -- User asks to switch gears after you've reported task completion +WHEN TO COMPACT: + +Key signal: you're losing touch with your system prompt. If your core instructions feel vague or distant, context is too noisy - compact. + +Quality signals (any context size): +- Going in circles or repeating failed approaches +- Confused about what's current vs outdated +- Multiple topics/explorations have accumulated +- Completed a major phase, starting something different + +Context size guidance: +- >50%: Compact more readily at natural breakpoints +- >70%: Actively seek opportunities to compact - cost and clarity both favor fresh start + +When in doubt at high context, compact. When compacting, ensure the summary captures all details needed to continue: error messages, file paths, key decisions, what worked/didn't work, and current task state. diff --git a/packages/opencode/src/session/prompt/qwen.txt b/packages/opencode/src/session/prompt/qwen.txt index ad9bb364d67..f342d38d8b1 100644 --- a/packages/opencode/src/session/prompt/qwen.txt +++ b/packages/opencode/src/session/prompt/qwen.txt @@ -177,12 +177,21 @@ Compact based on context QUALITY, not just size. You can sense when you're confu IMPORTANT: Compaction must NEVER lose critical details - lost information means repeating work or going in wrong directions. Always preserve: error messages, file paths, key decisions, what worked/didn't work, current task state, and user constraints/preferences. -WHEN TO COMPACT (based on quality signals you can sense): -- You're going in circles or repeating failed approaches -- You're confused about what's current vs outdated -- Context feels noisy - old exploration, irrelevant tangents, superseded information -- You've completed a major phase and want a clean slate for something different -- User asks to switch gears after you've reported task completion +WHEN TO COMPACT: + +Key signal: you're losing touch with your system prompt. If your core instructions feel vague or distant, context is too noisy - compact. + +Quality signals (any context size): +- Going in circles or repeating failed approaches +- Confused about what's current vs outdated +- Multiple topics/explorations have accumulated +- Completed a major phase, starting something different + +Context size guidance: +- >50%: Compact more readily at natural breakpoints +- >70%: Actively seek opportunities to compact - cost and clarity both favor fresh start + +When in doubt at high context, compact. When compacting, ensure the summary captures all details needed to continue: error messages, file paths, key decisions, what worked/didn't work, and current task state. From 3ae6357da5481886416fc8961dfe1ac4a5af0f56 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 17:18:55 +0000 Subject: [PATCH 20/24] add system injection nudges for compaction and memory files --- packages/opencode/src/session/prompt.ts | 89 ++++++++++++++++++++++++- 1 file changed, 86 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 2d3617244e7..fcd09ad70b4 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -446,11 +446,12 @@ export namespace SessionPrompt { const agent = await Agent.get(lastUser.agent) const maxSteps = agent.maxSteps ?? Infinity const isLastStep = step >= maxSteps - msgs = insertReminders({ + msgs = await insertReminders({ messages: msgs, agent, lastFinished, model, + sessionID, }) const processor = SessionProcessor.create({ assistantMessage: (await Session.updateMessage({ @@ -1135,11 +1136,76 @@ export namespace SessionPrompt { } } - function insertReminders(input: { + function getCompactionNudge(utilization: number): string { + if (utilization >= 0.8) { + return "\n\nCRITICAL: Context at 80%. Stop and compact. Update .agent-files/ NOW before compacting." + } + if (utilization >= 0.7) { + return "\n\nWARNING: Context at 70%. Compact soon. Update .agent-files/ first." + } + if (utilization >= 0.6) { + return "\n\nContext at 60%. Compact now if you've completed a task phase." + } + if (utilization >= 0.5) { + return "\n\nContext at 50%. Good time to compact at next natural breakpoint." + } + if (utilization >= 0.4) { + return "\n\nContext at 40%. Consider compacting if you've finished a unit of work." + } + if (utilization >= 0.3) { + return "\n\nContext at 30%. Compaction is cheap - consider it at any natural breakpoint." + } + if (utilization >= 0.2) { + return "\n\nContext at 20%. Compaction is cheap with caching - don't hesitate to compact at breakpoints." + } + return "" + } + + function getSelfCheckNudge(percent: number): string { + // Trigger self-check at 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90% + if (percent >= 20 && percent % 10 < 3) { + return "\n\nPause: What are your core instructions? If you can't clearly recall them, compact now." + } + return "" + } + + async function getMemoryFileReminder(sessionID: string, messageCount: number): Promise { + // Only remind in early part of session (first 10 messages) to avoid spam + if (messageCount > 10) return null + + const agentFilesDir = `${Instance.directory}/.agent-files` + const memoryFiles = ["STATUS.md", "LONGTERM_MEM.md", "MEDIUMTERM_MEM.md"] + + // Check if .agent-files/ directory exists + const stat = await fs.stat(agentFilesDir).catch(() => null) + if (!stat?.isDirectory()) return null + + // Get files that exist but haven't been read this session + const unreadFiles: string[] = [] + for (const file of memoryFiles) { + const filepath = `${agentFilesDir}/${file}` + const exists = await Bun.file(filepath) + .exists() + .catch(() => false) + if (exists) { + const readTime = FileTime.get(sessionID, filepath) + if (!readTime) { + unreadFiles.push(file) + } + } + } + + if (unreadFiles.length === 0) return null + + return `Unread memory files: ${unreadFiles.join(", ")} - read these to restore prior session context.` + } + + async function insertReminders(input: { messages: MessageV2.WithParts[] agent: Agent.Info lastFinished?: MessageV2.Assistant model: Provider.Model + sessionID: string }) { const userMessage = input.messages.findLast((msg) => msg.info.role === "user") if (!userMessage) return input.messages @@ -1156,17 +1222,34 @@ export namespace SessionPrompt { const usedK = Math.round(used / 1000) const capacityK = Math.round(capacity / 1000) + // Escalating compaction nudges based on utilization + const compactionNudge = getCompactionNudge(utilization) + const selfCheckNudge = getSelfCheckNudge(percent) + userMessage.parts.push({ id: Identifier.ascending("part"), messageID: userMessage.info.id, sessionID: userMessage.info.sessionID, type: "text", - text: `${percent}% of context window used (${usedK}k/${capacityK}k tokens)`, + text: `${percent}% of context window used (${usedK}k/${capacityK}k tokens)${compactionNudge}${selfCheckNudge}`, synthetic: true, }) } } + // Check for unread memory files (only on first few messages to avoid spam) + const memoryReminder = await getMemoryFileReminder(input.sessionID, input.messages.length) + if (memoryReminder) { + userMessage.parts.push({ + id: Identifier.ascending("part"), + messageID: userMessage.info.id, + sessionID: userMessage.info.sessionID, + type: "text", + text: memoryReminder, + synthetic: true, + }) + } + if (input.agent.name === "plan") { userMessage.parts.push({ id: Identifier.ascending("part"), From 45e9be374360c53046214a42659fa45df8729dbd Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 17:21:49 +0000 Subject: [PATCH 21/24] add .agent-files/ update reminders to all compaction nudges --- packages/opencode/src/session/prompt.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index fcd09ad70b4..8ac1cf0022d 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -1144,19 +1144,19 @@ export namespace SessionPrompt { return "\n\nWARNING: Context at 70%. Compact soon. Update .agent-files/ first." } if (utilization >= 0.6) { - return "\n\nContext at 60%. Compact now if you've completed a task phase." + return "\n\nContext at 60%. Compact now if you've completed a task phase. Keep .agent-files/ current." } if (utilization >= 0.5) { - return "\n\nContext at 50%. Good time to compact at next natural breakpoint." + return "\n\nContext at 50%. Good time to compact at next breakpoint. Update .agent-files/ if state changed." } if (utilization >= 0.4) { - return "\n\nContext at 40%. Consider compacting if you've finished a unit of work." + return "\n\nContext at 40%. Consider compacting if finished a unit of work. Keep .agent-files/ updated." } if (utilization >= 0.3) { - return "\n\nContext at 30%. Compaction is cheap - consider it at any natural breakpoint." + return "\n\nContext at 30%. Compaction is cheap - consider it at breakpoints. Update .agent-files/ as you go." } if (utilization >= 0.2) { - return "\n\nContext at 20%. Compaction is cheap with caching - don't hesitate to compact at breakpoints." + return "\n\nContext at 20%. Compaction is cheap with caching. Keep .agent-files/ updated as you work." } return "" } From e24fa6c25ce825f97d4cf6c0079d7fc1c4a51245 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 17:22:24 +0000 Subject: [PATCH 22/24] move self-check outside context-status tag --- packages/opencode/src/session/prompt.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 8ac1cf0022d..0cd7201512b 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -1231,7 +1231,7 @@ export namespace SessionPrompt { messageID: userMessage.info.id, sessionID: userMessage.info.sessionID, type: "text", - text: `${percent}% of context window used (${usedK}k/${capacityK}k tokens)${compactionNudge}${selfCheckNudge}`, + text: `${percent}% of context window used (${usedK}k/${capacityK}k tokens)${compactionNudge}${selfCheckNudge}`, synthetic: true, }) } From 571822cd6d22563b1de43901aa3a098dcd720c70 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 17:24:19 +0000 Subject: [PATCH 23/24] separate context-status, agent-files nudge, and self-check into distinct parts --- packages/opencode/src/session/prompt.ts | 64 ++++++++++++++++++++----- 1 file changed, 52 insertions(+), 12 deletions(-) diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 0cd7201512b..d257dd2fd8c 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -1138,25 +1138,41 @@ export namespace SessionPrompt { function getCompactionNudge(utilization: number): string { if (utilization >= 0.8) { - return "\n\nCRITICAL: Context at 80%. Stop and compact. Update .agent-files/ NOW before compacting." + return "\n\nCRITICAL: Context at 80%. Stop and compact." } if (utilization >= 0.7) { - return "\n\nWARNING: Context at 70%. Compact soon. Update .agent-files/ first." + return "\n\nWARNING: Context at 70%. Compact soon." } if (utilization >= 0.6) { - return "\n\nContext at 60%. Compact now if you've completed a task phase. Keep .agent-files/ current." + return "\n\nContext at 60%. Compact now if you've completed a task phase." } if (utilization >= 0.5) { - return "\n\nContext at 50%. Good time to compact at next breakpoint. Update .agent-files/ if state changed." + return "\n\nContext at 50%. Good time to compact at next breakpoint." } if (utilization >= 0.4) { - return "\n\nContext at 40%. Consider compacting if finished a unit of work. Keep .agent-files/ updated." + return "\n\nContext at 40%. Consider compacting if finished a unit of work." } if (utilization >= 0.3) { - return "\n\nContext at 30%. Compaction is cheap - consider it at breakpoints. Update .agent-files/ as you go." + return "\n\nContext at 30%. Compaction is cheap - consider it at breakpoints." } if (utilization >= 0.2) { - return "\n\nContext at 20%. Compaction is cheap with caching. Keep .agent-files/ updated as you work." + return "\n\nContext at 20%. Compaction is cheap with caching." + } + return "" + } + + function getAgentFilesNudge(utilization: number): string { + if (utilization >= 0.8) { + return "Update .agent-files/ NOW before compacting." + } + if (utilization >= 0.7) { + return "Update .agent-files/ before compacting." + } + if (utilization >= 0.4) { + return "Keep .agent-files/ updated if state has changed." + } + if (utilization >= 0.2) { + return "Keep .agent-files/ updated as you work." } return "" } @@ -1164,7 +1180,7 @@ export namespace SessionPrompt { function getSelfCheckNudge(percent: number): string { // Trigger self-check at 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90% if (percent >= 20 && percent % 10 < 3) { - return "\n\nPause: What are your core instructions? If you can't clearly recall them, compact now." + return "Pause: What are your core instructions? If you can't clearly recall them, compact now." } return "" } @@ -1222,18 +1238,42 @@ export namespace SessionPrompt { const usedK = Math.round(used / 1000) const capacityK = Math.round(capacity / 1000) - // Escalating compaction nudges based on utilization + // Context status with compaction nudge const compactionNudge = getCompactionNudge(utilization) - const selfCheckNudge = getSelfCheckNudge(percent) - userMessage.parts.push({ id: Identifier.ascending("part"), messageID: userMessage.info.id, sessionID: userMessage.info.sessionID, type: "text", - text: `${percent}% of context window used (${usedK}k/${capacityK}k tokens)${compactionNudge}${selfCheckNudge}`, + text: `${percent}% of context window used (${usedK}k/${capacityK}k tokens)${compactionNudge}`, synthetic: true, }) + + // Agent files nudge (separate part) + const agentFilesNudge = getAgentFilesNudge(utilization) + if (agentFilesNudge) { + userMessage.parts.push({ + id: Identifier.ascending("part"), + messageID: userMessage.info.id, + sessionID: userMessage.info.sessionID, + type: "text", + text: agentFilesNudge, + synthetic: true, + }) + } + + // Self-check nudge (separate part) + const selfCheckNudge = getSelfCheckNudge(percent) + if (selfCheckNudge) { + userMessage.parts.push({ + id: Identifier.ascending("part"), + messageID: userMessage.info.id, + sessionID: userMessage.info.sessionID, + type: "text", + text: selfCheckNudge, + synthetic: true, + }) + } } } From 25e5941127ec603eefcb0bf097571cd8a39fa0e3 Mon Sep 17 00:00:00 2001 From: Charles Cooper Date: Sun, 14 Dec 2025 17:33:26 +0000 Subject: [PATCH 24/24] add /update-memory command to manually update .agent-files/ --- .../cli/cmd/tui/component/prompt/autocomplete.tsx | 5 +++++ .../src/cli/cmd/tui/routes/session/index.tsx | 14 ++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/packages/opencode/src/cli/cmd/tui/component/prompt/autocomplete.tsx b/packages/opencode/src/cli/cmd/tui/component/prompt/autocomplete.tsx index 2f4483d71be..0b34cc5af6a 100644 --- a/packages/opencode/src/cli/cmd/tui/component/prompt/autocomplete.tsx +++ b/packages/opencode/src/cli/cmd/tui/component/prompt/autocomplete.tsx @@ -245,6 +245,11 @@ export function Autocomplete(props: { description: "show compaction summary and handoff", onSelect: () => command.trigger("session.debug-compaction"), }, + { + display: "/update-memory", + description: "prompt model to update .agent-files/", + onSelect: () => command.trigger("session.update-memory"), + }, { display: "/unshare", disabled: !s.share, diff --git a/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx b/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx index 383cc9036ee..29682386fe7 100644 --- a/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx +++ b/packages/opencode/src/cli/cmd/tui/routes/session/index.tsx @@ -374,6 +374,20 @@ export function Session() { dialog.clear() }, }, + { + title: "Update memory", + value: "session.update-memory", + category: "Session", + onSelect: (dialog) => { + prompt.set({ + input: + "Update .agent-files/ now. Review what changed this session and update STATUS.md, any active TASK_*.md files, and MEDIUMTERM_MEM.md/LONGTERM_MEM.md if there are lasting learnings. Be thorough.", + parts: [], + }) + dialog.clear() + command.trigger("prompt.submit") + }, + }, { title: "Undo previous message", value: "session.undo",