-
Notifications
You must be signed in to change notification settings - Fork 3k
fix(compaction): recover agent config after session compaction #2378
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
90be61b
fix(compaction): add checkpoint store for session agent config
code-yeongyu 67a30cd
fix(compaction): resolve prompt config from recent session context
code-yeongyu b7170b2
fix(compaction): recover checkpointed agent config after compaction
code-yeongyu c789baf
fix(background-agent): merge prompt context across compaction gaps
code-yeongyu 2b5dec5
fix(background-agent): use compaction-aware prompt context in manager
code-yeongyu 65eddda
fix(plugin): wire compaction context hook creation
code-yeongyu df36efa
fix(plugin): dispatch compaction context hook events
code-yeongyu 719a35e
fix(plugin): capture compaction context during compaction
code-yeongyu e99e638
fix(compaction): validate recovered agent config state
code-yeongyu 0e093af
refactor: split oversized hook.ts to respect 200 LOC limit
code-yeongyu 3550305
Merge branch 'dev' into fix/issue-2232
code-yeongyu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,21 @@ | ||
| import { readdirSync, readFileSync } from "node:fs" | ||
| import { join } from "node:path" | ||
| import type { StoredMessage } from "../hook-message-injector" | ||
| import { getCompactionAgentConfigCheckpoint } from "../../shared/compaction-agent-config-checkpoint" | ||
|
|
||
| type SessionMessage = { | ||
| info?: { | ||
| agent?: string | ||
| model?: { | ||
| providerID?: string | ||
| modelID?: string | ||
| variant?: string | ||
| } | ||
| providerID?: string | ||
| modelID?: string | ||
| tools?: StoredMessage["tools"] | ||
| } | ||
| } | ||
|
|
||
| export function isCompactionAgent(agent: string | undefined): boolean { | ||
| return agent?.trim().toLowerCase() === "compaction" | ||
|
|
@@ -16,42 +31,121 @@ function hasFullAgentAndModel(message: StoredMessage): boolean { | |
| function hasPartialAgentOrModel(message: StoredMessage): boolean { | ||
| const hasAgent = !!message.agent && !isCompactionAgent(message.agent) | ||
| const hasModel = !!message.model?.providerID && !!message.model?.modelID | ||
| return hasAgent || hasModel | ||
| return hasAgent || hasModel || !!message.tools | ||
| } | ||
|
|
||
| export function findNearestMessageExcludingCompaction(messageDir: string): StoredMessage | null { | ||
| function convertSessionMessageToStoredMessage(message: SessionMessage): StoredMessage | null { | ||
| const info = message.info | ||
| if (!info) { | ||
| return null | ||
| } | ||
|
|
||
| const providerID = info.model?.providerID ?? info.providerID | ||
| const modelID = info.model?.modelID ?? info.modelID | ||
|
|
||
| return { | ||
| ...(info.agent ? { agent: info.agent } : {}), | ||
| ...(providerID && modelID | ||
| ? { | ||
| model: { | ||
| providerID, | ||
| modelID, | ||
| ...(info.model?.variant ? { variant: info.model.variant } : {}), | ||
| }, | ||
| } | ||
| : {}), | ||
| ...(info.tools ? { tools: info.tools } : {}), | ||
| } | ||
| } | ||
|
|
||
| function mergeStoredMessages( | ||
| messages: Array<StoredMessage | null>, | ||
| sessionID?: string, | ||
| ): StoredMessage | null { | ||
| const merged: StoredMessage = {} | ||
|
|
||
| for (const message of messages) { | ||
| if (!message || isCompactionAgent(message.agent)) { | ||
| continue | ||
| } | ||
|
|
||
| if (!merged.agent && message.agent) { | ||
| merged.agent = message.agent | ||
| } | ||
|
|
||
| if (!merged.model?.providerID && message.model?.providerID && message.model.modelID) { | ||
| merged.model = { | ||
| providerID: message.model.providerID, | ||
| modelID: message.model.modelID, | ||
| ...(message.model.variant ? { variant: message.model.variant } : {}), | ||
| } | ||
| } | ||
|
|
||
| if (!merged.tools && message.tools) { | ||
| merged.tools = message.tools | ||
| } | ||
|
|
||
| if (hasFullAgentAndModel(merged) && merged.tools) { | ||
| break | ||
| } | ||
| } | ||
|
|
||
| const checkpoint = sessionID | ||
| ? getCompactionAgentConfigCheckpoint(sessionID) | ||
| : undefined | ||
|
|
||
| if (!merged.agent && checkpoint?.agent) { | ||
| merged.agent = checkpoint.agent | ||
| } | ||
|
|
||
| if (!merged.model && checkpoint?.model) { | ||
| merged.model = { | ||
| providerID: checkpoint.model.providerID, | ||
| modelID: checkpoint.model.modelID, | ||
| } | ||
| } | ||
|
|
||
| if (!merged.tools && checkpoint?.tools) { | ||
| merged.tools = checkpoint.tools | ||
| } | ||
|
|
||
| return hasPartialAgentOrModel(merged) ? merged : null | ||
| } | ||
|
|
||
| export function resolvePromptContextFromSessionMessages( | ||
| messages: SessionMessage[], | ||
| sessionID?: string, | ||
| ): StoredMessage | null { | ||
| const convertedMessages = messages | ||
| .map(convertSessionMessageToStoredMessage) | ||
| .reverse() | ||
|
|
||
| return mergeStoredMessages(convertedMessages, sessionID) | ||
| } | ||
|
|
||
| export function findNearestMessageExcludingCompaction( | ||
| messageDir: string, | ||
| sessionID?: string, | ||
| ): StoredMessage | null { | ||
| try { | ||
| const files = readdirSync(messageDir) | ||
| .filter((name) => name.endsWith(".json")) | ||
| .filter((name: string) => name.endsWith(".json")) | ||
| .sort() | ||
| .reverse() | ||
|
|
||
| for (const file of files) { | ||
| try { | ||
| const content = readFileSync(join(messageDir, file), "utf-8") | ||
| const parsed = JSON.parse(content) as StoredMessage | ||
| if (hasFullAgentAndModel(parsed)) { | ||
| return parsed | ||
| } | ||
| } catch { | ||
| continue | ||
| } | ||
| } | ||
| const messages: Array<StoredMessage | null> = [] | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: Synchronously reading and parsing all message files before merging blocks the event loop and degrades performance for long sessions. Prompt for AI agents |
||
|
|
||
| for (const file of files) { | ||
| try { | ||
| const content = readFileSync(join(messageDir, file), "utf-8") | ||
| const parsed = JSON.parse(content) as StoredMessage | ||
| if (hasPartialAgentOrModel(parsed)) { | ||
| return parsed | ||
| } | ||
| messages.push(JSON.parse(content) as StoredMessage) | ||
| } catch { | ||
| continue | ||
| } | ||
| } | ||
|
|
||
| return mergeStoredMessages(messages, sessionID) | ||
| } catch { | ||
| return null | ||
| } | ||
|
|
||
| return null | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
56 changes: 56 additions & 0 deletions
56
src/hooks/compaction-context-injector/compaction-context-prompt.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| import { | ||
| createSystemDirective, | ||
| SystemDirectiveTypes, | ||
| } from "../../shared/system-directive" | ||
|
|
||
| export const COMPACTION_CONTEXT_PROMPT = `${createSystemDirective(SystemDirectiveTypes.COMPACTION_CONTEXT)} | ||
|
|
||
| When summarizing this session, you MUST include the following sections in your summary: | ||
|
|
||
| ## 1. User Requests (As-Is) | ||
| - List all original user requests exactly as they were stated | ||
| - Preserve the user's exact wording and intent | ||
|
|
||
| ## 2. Final Goal | ||
| - What the user ultimately wanted to achieve | ||
| - The end result or deliverable expected | ||
|
|
||
| ## 3. Work Completed | ||
| - What has been done so far | ||
| - Files created/modified | ||
| - Features implemented | ||
| - Problems solved | ||
|
|
||
| ## 4. Remaining Tasks | ||
| - What still needs to be done | ||
| - Pending items from the original request | ||
| - Follow-up tasks identified during the work | ||
|
|
||
| ## 5. Active Working Context (For Seamless Continuation) | ||
| - **Files**: Paths of files currently being edited or frequently referenced | ||
| - **Code in Progress**: Key code snippets, function signatures, or data structures under active development | ||
| - **External References**: Documentation URLs, library APIs, or external resources being consulted | ||
| - **State & Variables**: Important variable names, configuration values, or runtime state relevant to ongoing work | ||
|
|
||
| ## 6. Explicit Constraints (Verbatim Only) | ||
| - Include ONLY constraints explicitly stated by the user or in existing AGENTS.md context | ||
| - Quote constraints verbatim (do not paraphrase) | ||
| - Do NOT invent, add, or modify constraints | ||
| - If no explicit constraints exist, write "None" | ||
|
|
||
| ## 7. Agent Verification State (Critical for Reviewers) | ||
| - **Current Agent**: What agent is running (momus, oracle, etc.) | ||
| - **Verification Progress**: Files already verified/validated | ||
| - **Pending Verifications**: Files still needing verification | ||
| - **Previous Rejections**: If reviewer agent, what was rejected and why | ||
| - **Acceptance Status**: Current state of review process | ||
|
|
||
| This section is CRITICAL for reviewer agents (momus, oracle) to maintain continuity. | ||
|
|
||
| ## 8. Delegated Agent Sessions | ||
| - List ALL background agent tasks spawned during this session | ||
| - For each: agent name, category, status, description, and **session_id** | ||
| - **RESUME, DON'T RESTART.** Each listed session retains full context. After compaction, use \`session_id\` to continue existing agent sessions instead of spawning new ones. This saves tokens, preserves learned context, and prevents duplicate work. | ||
|
|
||
| This context is critical for maintaining continuity after compaction. | ||
| ` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| export const HOOK_NAME = "compaction-context-injector" | ||
| export const AGENT_RECOVERY_PROMPT = "[restore checkpointed session agent configuration after compaction]" | ||
| export const NO_TEXT_TAIL_THRESHOLD = 5 | ||
| export const RECOVERY_COOLDOWN_MS = 60_000 | ||
| export const RECENT_COMPACTION_WINDOW_MS = 10 * 60 * 1000 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P1: Custom agent: Opencode Compatibility
The
variantproperty in the OpenCode SDK is located at the root of the message object (info.variant), not withinmodel. Readinginfo.model?.variantwill silently fail to recover the agent variant from OpenCode message responses. Update theSessionMessagetype and this mapping logic to extractvariantdirectly frominfo.Prompt for AI agents