feat(FN-1892): merge fusion/fn-1892

This commit is contained in:
Fusion
2026-04-16 12:53:06 -07:00
committed by gsxdsm
parent 8705cb08cf
commit 11f84151ce
14 changed files with 503 additions and 72 deletions

View File

@@ -175,6 +175,10 @@ export {
export {
compactMemoryWithAi,
COMPACT_MEMORY_SYSTEM_PROMPT,
createAutoSummarizeAutomation,
syncAutoSummarizeAutomation,
AUTO_SUMMARIZE_SCHEDULE_NAME,
DEFAULT_AUTO_SUMMARIZE_SCHEDULE,
__resetCompactionState,
} from "./memory-compaction.js";
// Note: AiServiceError is shared with ai-summarize.ts and re-exported from there

View File

@@ -1,7 +1,11 @@
import { describe, it, expect, beforeEach } from "vitest";
import { describe, it, expect, beforeEach, vi } from "vitest";
import {
compactMemoryWithAi,
COMPACT_MEMORY_SYSTEM_PROMPT,
createAutoSummarizeAutomation,
syncAutoSummarizeAutomation,
AUTO_SUMMARIZE_SCHEDULE_NAME,
DEFAULT_AUTO_SUMMARIZE_SCHEDULE,
AiServiceError,
__resetCompactionState,
} from "./memory-compaction.js";
@@ -29,6 +33,196 @@ describe("memory-compaction", () => {
expect(COMPACT_MEMORY_SYSTEM_PROMPT).toContain("Remove");
expect(COMPACT_MEMORY_SYSTEM_PROMPT).toContain("redundant");
});
it("should have correct auto-summarize schedule name", () => {
expect(AUTO_SUMMARIZE_SCHEDULE_NAME).toBe("Memory Auto-Summarize");
});
it("should have correct default schedule", () => {
expect(DEFAULT_AUTO_SUMMARIZE_SCHEDULE).toBe("0 3 * * *");
});
});
// ── createAutoSummarizeAutomation ───────────────────────────────────────────
describe("createAutoSummarizeAutomation", () => {
it("should create automation with default settings", () => {
const automation = createAutoSummarizeAutomation({});
expect(automation.name).toBe(AUTO_SUMMARIZE_SCHEDULE_NAME);
expect(automation.scheduleType).toBe("custom");
expect(automation.cronExpression).toBe(DEFAULT_AUTO_SUMMARIZE_SCHEDULE);
expect(automation.enabled).toBe(true);
expect(automation.steps!).toHaveLength(1);
expect(automation.steps![0].type).toBe("ai-prompt");
expect(automation.steps![0].id).toBe("memory-auto-summarize");
});
it("should use custom schedule when provided", () => {
const automation = createAutoSummarizeAutomation({
memoryAutoSummarizeSchedule: "0 */6 * * *",
});
expect(automation.cronExpression).toBe("0 */6 * * *");
});
it("should include threshold in prompt", () => {
const automation = createAutoSummarizeAutomation({
memoryAutoSummarizeThresholdChars: 75000,
});
expect(automation.steps![0].prompt).toContain("75000");
});
it("should include model provider in step when provided", () => {
const automation = createAutoSummarizeAutomation(
{},
"anthropic",
"claude-sonnet-4-5"
);
expect(automation.steps![0].modelProvider).toBe("anthropic");
expect(automation.steps![0].modelId).toBe("claude-sonnet-4-5");
});
it("should not include model fields when not provided", () => {
const automation = createAutoSummarizeAutomation({});
expect(automation.steps![0]).not.toHaveProperty("modelProvider");
expect(automation.steps![0]).not.toHaveProperty("modelId");
});
it("should set correct timeout", () => {
const automation = createAutoSummarizeAutomation({});
expect(automation.steps![0].timeoutMs).toBe(120_000);
});
it("should prompt to preserve core sections", () => {
const automation = createAutoSummarizeAutomation({});
expect(automation.steps![0].prompt).toContain("Architecture");
expect(automation.steps![0].prompt).toContain("Conventions");
expect(automation.steps![0].prompt).toContain("Pitfalls");
});
it("should prompt to check threshold and skip when below", () => {
const automation = createAutoSummarizeAutomation({});
expect(automation.steps![0].prompt).toContain("Below threshold");
expect(automation.steps![0].prompt).toContain("skipped");
});
it("should prompt to write compacted content to file", () => {
const automation = createAutoSummarizeAutomation({});
expect(automation.steps![0].prompt).toContain(".fusion/memory.md");
});
});
// ── syncAutoSummarizeAutomation ─────────────────────────────────────────────
describe("syncAutoSummarizeAutomation", () => {
it("should delete schedule when auto-summarize is disabled", async () => {
const mockStore = {
listSchedules: vi.fn().mockResolvedValue([
{ id: "sched-1", name: AUTO_SUMMARIZE_SCHEDULE_NAME },
]),
deleteSchedule: vi.fn().mockResolvedValue(undefined),
};
await syncAutoSummarizeAutomation(mockStore as any, {
memoryAutoSummarizeEnabled: false,
});
expect(mockStore.deleteSchedule).toHaveBeenCalledWith("sched-1");
});
it("should not delete schedule when auto-summarize is disabled but no schedule exists", async () => {
const mockStore = {
listSchedules: vi.fn().mockResolvedValue([]),
deleteSchedule: vi.fn().mockResolvedValue(undefined),
};
await syncAutoSummarizeAutomation(mockStore as any, {
memoryAutoSummarizeEnabled: false,
});
expect(mockStore.deleteSchedule).not.toHaveBeenCalled();
});
it("should create new schedule when auto-summarize is enabled and no schedule exists", async () => {
const mockStore = {
listSchedules: vi.fn().mockResolvedValue([]),
createSchedule: vi.fn().mockResolvedValue({ id: "new-sched-1" }),
};
const result = await syncAutoSummarizeAutomation(mockStore as any, {
memoryAutoSummarizeEnabled: true,
});
expect(mockStore.createSchedule).toHaveBeenCalledWith(
expect.objectContaining({
name: AUTO_SUMMARIZE_SCHEDULE_NAME,
scheduleType: "custom",
enabled: true,
})
);
expect(result).toEqual({ id: "new-sched-1" });
});
it("should update existing schedule when auto-summarize is enabled", async () => {
const mockStore = {
listSchedules: vi.fn().mockResolvedValue([
{ id: "existing-sched", name: AUTO_SUMMARIZE_SCHEDULE_NAME },
]),
updateSchedule: vi.fn().mockResolvedValue({ id: "existing-sched" }),
};
await syncAutoSummarizeAutomation(mockStore as any, {
memoryAutoSummarizeEnabled: true,
memoryAutoSummarizeSchedule: "0 3 * * 1",
});
expect(mockStore.updateSchedule).toHaveBeenCalledWith(
"existing-sched",
expect.objectContaining({
scheduleType: "custom",
cronExpression: "0 3 * * 1",
enabled: true,
})
);
});
it("should use default schedule when not specified", async () => {
const mockStore = {
listSchedules: vi.fn().mockResolvedValue([]),
createSchedule: vi.fn().mockResolvedValue({ id: "new-sched" }),
};
await syncAutoSummarizeAutomation(mockStore as any, {
memoryAutoSummarizeEnabled: true,
});
expect(mockStore.createSchedule).toHaveBeenCalledWith(
expect.objectContaining({
cronExpression: DEFAULT_AUTO_SUMMARIZE_SCHEDULE,
})
);
});
it("should throw error for invalid cron expression", async () => {
const mockStore = {
listSchedules: vi.fn().mockResolvedValue([]),
};
await expect(
syncAutoSummarizeAutomation(mockStore as any, {
memoryAutoSummarizeEnabled: true,
memoryAutoSummarizeSchedule: "not-a-cron",
})
).rejects.toThrow("Invalid auto-summarize schedule");
});
});
// ── compactMemoryWithAi ────────────────────────────────────────────────────

View File

@@ -10,8 +10,12 @@
* - Read-only tool access (prevents accidental memory modification during compaction)
* - Session disposal in finally block to prevent leaks
* - AiServiceError for AI-related failures
* - Auto-summarize automation integration for scheduled compaction
*/
import type { ProjectSettings } from "./types.js";
import type { ScheduledTaskCreateInput } from "./automation.js";
// Dynamic import for @fusion/engine to avoid resolution issues in test environment
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type AgentResult = any;
@@ -212,3 +216,150 @@ export async function compactMemoryWithAi(
export function __resetCompactionState(): void {
// No-op: no caches to reset in current implementation
}
// ── Automation Integration ───────────────────────────────────────────────
/** Constant name for the auto-summarize automation schedule. */
export const AUTO_SUMMARIZE_SCHEDULE_NAME = "Memory Auto-Summarize";
/** Default schedule for auto-summarize: daily at 3 AM. */
export const DEFAULT_AUTO_SUMMARIZE_SCHEDULE = "0 3 * * *";
/**
* Create the automation config for auto-summarize memory compaction.
*
* Returns a `ScheduledTaskCreateInput` ready for `AutomationStore.createSchedule()`.
* The automation uses a single `ai-prompt` step that checks memory size and
* compacts it if it exceeds the configured threshold.
*
* The AI model provider and ID are optional — when not specified, the
* automation system falls back to the project's default model.
*
* @param settings - Project settings for schedule and threshold configuration.
* @param modelProvider - Optional AI model provider override.
* @param modelId - Optional AI model ID override.
* @returns The automation creation input.
*/
export function createAutoSummarizeAutomation(
settings: Partial<ProjectSettings>,
modelProvider?: string,
modelId?: string,
): ScheduledTaskCreateInput {
const schedule = settings.memoryAutoSummarizeSchedule ?? DEFAULT_AUTO_SUMMARIZE_SCHEDULE;
const threshold = settings.memoryAutoSummarizeThresholdChars ?? 50_000;
// Build the prompt that reads working memory, checks size, and compacts if needed.
// Note: At automation execution time, the AI agent has access to the filesystem.
const prompt = `You are the Memory Auto-Summarization agent. Your job is to check the project's working memory file size and compress it when it exceeds the configured threshold.
## Your Task
1. Read the working memory file at \`.fusion/memory.md\` using your file reading tools
2. Check if the file size exceeds the threshold of ${threshold} characters
3. If the file is BELOW the threshold: output JSON indicating no compaction needed:
\`\`\`json
{"skipped": true, "reason": "Below threshold", "currentSize": <actual_size>}
\`\`\`
4. If the file is AT OR ABOVE the threshold:
a) Distill the memory to ONLY the most important insights
b) Preserve at least 2 of these 3 core sections: Architecture, Conventions, Pitfalls
c) Write the compacted content back to \`.fusion/memory.md\`
d) Output JSON indicating compaction was done:
\`\`\`json
{"skipped": false, "originalSize": <size_before>, "newSize": <size_after>, "reduction": "<percentage>%"}
\`\`\`
## Compaction Guidelines
**MUST PRESERVE (durable items):**
- Architecture: Project structure, key abstractions, major components
- Conventions: Coding standards, naming patterns, established practices
- Pitfalls: Known issues to avoid, anti-patterns to watch for
- Any section header (## <name>) should stay if it contains durable content
**SHOULD REMOVE (transient items):**
- One-time observations from completed tasks
- Task-specific implementation notes
- Verbose explanations that can be condensed
- Outdated or superseded entries
- Trivial gotchas that aren't critical
**CRITICAL REQUIREMENTS:**
- You MUST preserve at least 2 of these 3 core sections: Architecture, Conventions, Pitfalls
- Output ONLY valid JSON — no markdown fences, no extra text
- Use your file writing tools to update \`.fusion/memory.md\` with the compacted content`;
return {
name: AUTO_SUMMARIZE_SCHEDULE_NAME,
description: "Automatically compresses working memory when it exceeds the configured size threshold",
scheduleType: "custom",
cronExpression: schedule,
command: "", // Required by type but unused when steps are present
enabled: true,
steps: [
{
id: "memory-auto-summarize",
type: "ai-prompt",
name: "Auto-Summarize Memory",
prompt,
...(modelProvider && modelId ? { modelProvider, modelId } : {}),
timeoutMs: 120_000, // 2 minutes
},
],
};
}
/**
* Synchronize the auto-summarize automation with project settings.
*
* Creates, updates, or deletes the automation schedule based on whether
* auto-summarize is enabled in the project settings. Follows the same
* pattern as `syncInsightExtractionAutomation()`.
*
* @param automationStore - The AutomationStore instance.
* @param settings - Current project settings.
* @returns The created/updated schedule, or undefined if deleted/disabled.
*/
export async function syncAutoSummarizeAutomation(
automationStore: import("./automation-store.js").AutomationStore,
settings: Partial<ProjectSettings>,
): Promise<import("./automation.js").ScheduledTask | undefined> {
const { AutomationStore } = await import("./automation-store.js");
// Find existing auto-summarize schedule by name
const schedules = await automationStore.listSchedules();
const existingSchedule = schedules.find(
(s) => s.name === AUTO_SUMMARIZE_SCHEDULE_NAME,
);
// If auto-summarize is disabled, delete existing schedule if present
if (!settings.memoryAutoSummarizeEnabled) {
if (existingSchedule) {
await automationStore.deleteSchedule(existingSchedule.id);
}
return undefined;
}
// Validate the cron schedule
const schedule = settings.memoryAutoSummarizeSchedule ?? DEFAULT_AUTO_SUMMARIZE_SCHEDULE;
if (!AutomationStore.isValidCron(schedule)) {
throw new Error(`Invalid auto-summarize schedule: ${schedule}`);
}
// Build the automation input
const input = createAutoSummarizeAutomation(settings);
if (existingSchedule) {
// Update existing schedule
return await automationStore.updateSchedule(existingSchedule.id, {
scheduleType: "custom",
cronExpression: schedule,
command: input.command,
steps: input.steps,
enabled: true,
});
} else {
// Create new schedule
return await automationStore.createSchedule(input);
}
}

View File

@@ -124,6 +124,9 @@ export const DEFAULT_PROJECT_SETTINGS = {
insightExtractionMinIntervalMs: 86_400_000,
memoryEnabled: true,
memoryBackendType: "file",
memoryAutoSummarizeEnabled: false,
memoryAutoSummarizeThresholdChars: 50_000,
memoryAutoSummarizeSchedule: "0 3 * * *",
tokenCap: undefined,
runStepsInNewSessions: false,
maxParallelSteps: 2,

View File

@@ -1259,6 +1259,20 @@ export interface ProjectSettings {
* - Any registered custom backend type
* Default: "file" */
memoryBackendType?: string;
/** When true, enables automatic AI-powered summarization and compression of the
* working memory file when it exceeds the configured size threshold.
* Creates an automation schedule that checks memory size and compacts when needed.
* Default: false. */
memoryAutoSummarizeEnabled?: boolean;
/** Character count threshold that triggers automatic memory summarization.
* When working memory exceeds this size, the auto-summarize automation will
* compress it. Only used when memoryAutoSummarizeEnabled is true.
* Default: 50000. */
memoryAutoSummarizeThresholdChars?: number;
/** Cron expression for the auto-summarize check schedule. Only used when
* memoryAutoSummarizeEnabled is true.
* Default: "0 3 * * *" (daily at 3 AM, offset from insight extraction at 2 AM). */
memoryAutoSummarizeSchedule?: string;
/** Maximum token count before auto-compact triggers. When undefined, compact
* only on overflow errors. When set, the engine monitors token usage after
* each prompt and proactively compacts context when the token count reaches