diff --git a/src/auto-reply/reply/agent-runner.ts b/src/auto-reply/reply/agent-runner.ts index 62f8d7b64..eb63ce23d 100644 --- a/src/auto-reply/reply/agent-runner.ts +++ b/src/auto-reply/reply/agent-runner.ts @@ -19,6 +19,7 @@ import { updateSessionStoreEntry, } from "../../config/sessions.js"; import { emitDiagnosticEvent, isDiagnosticsEnabled } from "../../infra/diagnostic-events.js"; +import { enqueueSystemEvent } from "../../infra/system-events.js"; import { defaultRuntime } from "../../runtime.js"; import { estimateUsageCost, resolveModelCostConfig } from "../../utils/usage-format.js"; import { resolveResponseUsageMode, type VerboseLevel } from "../thinking.js"; @@ -36,6 +37,7 @@ import { appendUsageLine, formatResponseUsageLine } from "./agent-runner-utils.j import { createAudioAsVoiceBuffer, createBlockReplyPipeline } from "./block-reply-pipeline.js"; import { resolveBlockStreamingCoalescing } from "./block-streaming.js"; import { createFollowupRunner } from "./followup-runner.js"; +import { readPostCompactionContext } from "./post-compaction-context.js"; import { enqueueFollowupRun, type FollowupRun, type QueueSettings } from "./queue.js"; import { createReplyToModeFilterForChannel, resolveReplyToMode } from "./reply-threading.js"; import { incrementRunCompactionCount, persistRunSessionUsage } from "./session-run-accounting.js"; @@ -547,6 +549,21 @@ export async function runReplyAgent(params: { lastCallUsage: runResult.meta.agentMeta?.lastCallUsage, contextTokensUsed, }); + + // Inject post-compaction workspace context for the next agent turn + if (sessionKey) { + const workspaceDir = process.cwd(); + readPostCompactionContext(workspaceDir) + .then((contextContent) => { + if (contextContent) { + enqueueSystemEvent(contextContent, { sessionKey }); + } + }) + .catch(() => { + // Silent failure โ€” post-compaction context is best-effort + }); + } + if (verboseEnabled) { const suffix = typeof count === "number" ? ` (count ${count})` : ""; finalPayloads = [{ text: `๐Ÿงน Auto-compaction complete${suffix}.` }, ...finalPayloads]; diff --git a/src/auto-reply/reply/post-compaction-context.test.ts b/src/auto-reply/reply/post-compaction-context.test.ts new file mode 100644 index 000000000..726714b33 --- /dev/null +++ b/src/auto-reply/reply/post-compaction-context.test.ts @@ -0,0 +1,99 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; +import { readPostCompactionContext } from "./post-compaction-context.js"; + +describe("readPostCompactionContext", () => { + const tmpDir = path.join("/tmp", "test-post-compaction-" + Date.now()); + + beforeEach(() => { + fs.mkdirSync(tmpDir, { recursive: true }); + }); + + afterEach(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + it("returns null when no AGENTS.md exists", async () => { + const result = await readPostCompactionContext(tmpDir); + expect(result).toBeNull(); + }); + + it("returns null when AGENTS.md has no relevant sections", async () => { + fs.writeFileSync(path.join(tmpDir, "AGENTS.md"), "# My Agent\n\nSome content.\n"); + const result = await readPostCompactionContext(tmpDir); + expect(result).toBeNull(); + }); + + it("extracts Session Startup section", async () => { + const content = `# Agent Rules + +## Session Startup + +Read these files: +1. WORKFLOW_AUTO.md +2. memory/today.md + +## Other Section + +Not relevant. +`; + fs.writeFileSync(path.join(tmpDir, "AGENTS.md"), content); + const result = await readPostCompactionContext(tmpDir); + expect(result).not.toBeNull(); + expect(result).toContain("Session Startup"); + expect(result).toContain("WORKFLOW_AUTO.md"); + expect(result).toContain("Post-compaction context refresh"); + expect(result).not.toContain("Other Section"); + }); + + it("extracts Red Lines section", async () => { + const content = `# Rules + +## Red Lines + +Never do X. +Never do Y. + +## Other + +Stuff. +`; + fs.writeFileSync(path.join(tmpDir, "AGENTS.md"), content); + const result = await readPostCompactionContext(tmpDir); + expect(result).not.toBeNull(); + expect(result).toContain("Red Lines"); + expect(result).toContain("Never do X"); + }); + + it("extracts both sections", async () => { + const content = `# Rules + +## Session Startup + +Do startup things. + +## Red Lines + +Never break things. + +## Other + +Ignore this. +`; + fs.writeFileSync(path.join(tmpDir, "AGENTS.md"), content); + const result = await readPostCompactionContext(tmpDir); + expect(result).not.toBeNull(); + expect(result).toContain("Session Startup"); + expect(result).toContain("Red Lines"); + expect(result).not.toContain("Other"); + }); + + it("truncates when content exceeds limit", async () => { + const longContent = "## Session Startup\n\n" + "A".repeat(4000) + "\n\n## Other\n\nStuff."; + fs.writeFileSync(path.join(tmpDir, "AGENTS.md"), longContent); + const result = await readPostCompactionContext(tmpDir); + expect(result).not.toBeNull(); + expect(result).toContain("[truncated]"); + }); +}); diff --git a/src/auto-reply/reply/post-compaction-context.ts b/src/auto-reply/reply/post-compaction-context.ts new file mode 100644 index 000000000..ec27a2a04 --- /dev/null +++ b/src/auto-reply/reply/post-compaction-context.ts @@ -0,0 +1,86 @@ +import fs from "node:fs"; +import path from "node:path"; + +const MAX_CONTEXT_CHARS = 3000; + +/** + * Read critical sections from workspace AGENTS.md for post-compaction injection. + * Returns formatted system event text, or null if no AGENTS.md or no relevant sections. + */ +export async function readPostCompactionContext(workspaceDir: string): Promise { + const agentsPath = path.join(workspaceDir, "AGENTS.md"); + + try { + if (!fs.existsSync(agentsPath)) { + return null; + } + + const content = await fs.promises.readFile(agentsPath, "utf-8"); + + // Extract "## Session Startup" and "## Red Lines" sections + // Each section ends at the next "## " heading or end of file + const sections = extractSections(content, ["Session Startup", "Red Lines"]); + + if (sections.length === 0) { + return null; + } + + const combined = sections.join("\n\n"); + const safeContent = + combined.length > MAX_CONTEXT_CHARS + ? combined.slice(0, MAX_CONTEXT_CHARS) + "\n...[truncated]..." + : combined; + + return ( + "[Post-compaction context refresh]\n\n" + + "Session was just compacted. The conversation summary above is a hint, NOT a substitute for your startup sequence. " + + "Execute your Session Startup sequence now โ€” read the required files before responding to the user.\n\n" + + "Critical rules from AGENTS.md:\n\n" + + safeContent + ); + } catch { + return null; + } +} + +/** + * Extract named H2 sections from markdown content. + * Matches "## SectionName" and captures until the next "## " or end of string. + */ +function extractSections(content: string, sectionNames: string[]): string[] { + const results: string[] = []; + const lines = content.split("\n"); + + for (const name of sectionNames) { + let sectionLines: string[] = []; + let inSection = false; + + for (const line of lines) { + // Check if this is the start of our target section + if (line.match(new RegExp(`^##\\s+${escapeRegExp(name)}\\s*$`))) { + inSection = true; + sectionLines = [line]; + continue; + } + + // If we're in the section, check if we've hit another H2 heading + if (inSection) { + if (line.match(/^##\s+/)) { + // Hit another H2 heading, stop collecting + break; + } + sectionLines.push(line); + } + } + + if (sectionLines.length > 0) { + results.push(sectionLines.join("\n").trim()); + } + } + + return results; +} + +function escapeRegExp(str: string): string { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +}