Files
fusion/packages/core/src/memory-compaction.ts
gsxdsm cca13737b6 FN-8603: reduce steady-state diagnostic log noise
Route routine core, engine, and dashboard diagnostics through debug-gated shared loggers.

- Demote steady-state diagnostic sites while preserving warnings and errors for actionable failures.
- Add cross-package severity contracts and manifest coverage for demoted log sites.
- Document logging severity guidance and add a patch changeset.

Files changed:
 .changeset/fn-8603-log-severity.md                 |  7 ++
 docs/diagnostics.md                                | 20 ++++--
 .../__tests__/log-severity-spam-contract.test.ts   | 71 ++++++++++++++++++
 packages/core/src/activity-analytics.ts            |  5 +-
 packages/core/src/ai-summarize.ts                  | 61 +++++++---------
 packages/core/src/async-mission-store.ts           |  5 +-
 packages/core/src/async-secrets-store.ts           |  7 +-
 packages/core/src/central-core.ts                  | 17 ++---
 packages/core/src/docker-provisioning.ts           | 13 ++--
 packages/core/src/index.ts                         |  1 +
 packages/core/src/master-key.ts                    |  9 ++-
 packages/core/src/memory-compaction.ts             | 29 ++++----
 packages/core/src/memory-insights.ts               |  7 +-
 packages/core/src/migration-orchestrator.ts        |  7 +-
 packages/core/src/mission-store.ts                 |  5 +-
 packages/core/src/node-discovery.ts                |  7 +-
 packages/core/src/notification/dispatcher.ts       |  9 ++-
 .../core/src/plugins/bundled-plugin-install.ts     | 11 +--
 packages/core/src/reflection-store.ts              |  5 +-
 packages/core/src/secrets-store.ts                 |  7 +-
 packages/core/src/task-store/agent-logs.ts         | 21 +++---
 packages/core/src/task-store/async-events.ts       |  5 +-
 packages/core/src/task-store/async-maintenance.ts  |  7 +-
 packages/core/src/task-store/comments-ops.ts       |  7 +-
 packages/core/src/task-store/task-mutation-ops.ts  | 11 +--
 packages/core/src/task-store/workflow-integrity.ts |  9 ++-
 packages/core/src/types/merge-policy.ts            |  5 +-
 packages/core/src/usage-events.ts                  |  5 +-
 .../__tests__/log-severity-spam-contract.test.ts   | 48 +++++++++++++
 packages/dashboard/src/ai-refine.ts                |  5 +-
 packages/dashboard/src/ai-session-diagnostics.ts   | 10 +--
 packages/dashboard/src/chat.ts                     |  8 ++-
 packages/dashboard/src/devserver-manager.ts        |  9 ++-
 packages/dashboard/src/file-service.ts             |  5 +-
 packages/dashboard/src/github-tracking-comments.ts |  7 +-
 .../dashboard/src/github-tracking-reconciler.ts    |  5 +-
 packages/dashboard/src/github-tracking-state.ts    |  5 +-
 packages/dashboard/src/gitlab-lifecycle.ts         |  5 +-
 packages/dashboard/src/insights-routes.ts          |  9 ++-
 packages/dashboard/src/issue-image-attachments.ts  |  5 +-
 packages/dashboard/src/knowledge-index.ts          |  5 +-
 packages/dashboard/src/plugin-routes.ts            |  7 +-
 packages/dashboard/src/routes/board-workflows.ts   |  5 +-
 packages/dashboard/src/routes/context.ts           |  5 +-
 .../dashboard/src/routes/register-auth-routes.ts   | 13 ++--
 .../routes/register-docker-provisioning-routes.ts  |  7 +-
 .../dashboard/src/routes/register-git-github.ts    | 21 +++---
 packages/dashboard/src/routes/register-gitlab.ts   |  7 +-
 .../src/routes/register-session-diff-routes.ts     |  9 ++-
 .../src/routes/register-settings-memory-routes.ts  |  7 +-
 .../src/routes/register-setup-activity-routes.ts   |  7 +-
 .../dashboard/src/routes/register-signal-routes.ts |  5 +-
 .../src/routes/register-task-workflow-routes.ts    | 11 +--
 packages/dashboard/src/runtime-logger.ts           | 11 +--
 packages/dashboard/src/server.ts                   |  7 +-
 packages/dashboard/src/sse.ts                      |  8 ++-
 packages/dashboard/src/terminal-service.ts         | 34 ++++-----
 packages/dashboard/src/view-chunk-manifest.ts      |  5 +-
 .../engine/src/__tests__/log-severity-manifest.ts  | 83 ++++++++++++++++++++++
 .../__tests__/log-severity-spam-contract.test.ts   | 40 ++++++++++-
 .../src/__tests__/logger-debug-gating.test.ts      |  7 +-
 packages/engine/src/goal-anchoring-audit.ts        |  5 +-
 packages/engine/src/plugin-runner.ts               | 44 ++++++------
 packages/engine/src/pty-native.ts                  |  9 ++-
 .../engine/src/runtimes/child-process-worker.ts    |  4 +-
 packages/engine/src/self-healing.ts                | 12 ++--
 packages/engine/src/worktree-hooks.ts              | 10 ++-
 67 files changed, 632 insertions(+), 250 deletions(-)

Fusion-Task-Id: FN-8603

Fusion-Task-Lineage: 53901db6-1af2-4bd7-b5ea-49507e048ef2

Co-authored-by: Fusion (runfusion.ai) <noreply@runfusion.ai>
2026-07-26 12:01:19 -07:00

338 lines
13 KiB
TypeScript

import { createLogger } from "./logger.js";
const severityAuditLog = createLogger("core-memory-compaction");
/**
* AI Memory Compaction Service
*
* Provides AI-powered memory compaction for project memory files.
* Uses an AI agent to distill memory content down to the most important
* architectural conventions, pitfalls, and decisions.
*
* Features:
* - Dynamic import of @fusion/engine for AI agent creation
* - 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";
import { getFnAgent, type AgentMessage } from "./ai-engine-loader.js";
// ── Constants ───────────────────────────────────────────────────────────────
/** System prompt for memory compaction */
export const COMPACT_MEMORY_SYSTEM_PROMPT = `You are a memory distillation assistant for a software development project.
Your job is to compress the provided project memory markdown into a shorter version that preserves only the most important information.
## Guidelines
- Preserve only the most important architectural conventions and patterns
- Preserve critical pitfalls and anti-patterns to avoid
- Preserve significant decisions and their rationale
- Remove redundant examples, outdated information, and trivial details
- Maintain the markdown format and structure
- Output ONLY the compacted markdown - no explanations or commentary
- Be aggressive in trimming while keeping essential knowledge
## What to KEEP:
- Key architectural patterns and their rationale
- Important conventions that agents must follow
- Critical pitfalls and how to avoid them
- Major project decisions and their context
- Security-sensitive patterns
## What to REMOVE:
- Verbose examples that can be inferred
- Minor implementation details
- Outdated or superseded information
- Repetitive explanations
- Trivial gotchas that aren't critical
Return only the compacted markdown content.`;
/** Debug flag for AI operations */
// ── Custom Errors ───────────────────────────────────────────────────────────
export class AiServiceError extends Error {
constructor(message: string) {
super(message);
this.name = "AiServiceError";
}
}
// ── AI Integration ───────────────────────────────────────────────────────────
/**
* Compact memory content using AI to distill it down to the most important insights.
*
* @param content - The current memory content to compact
* @param rootDir - Project root directory for AI agent context
* @param provider - Optional AI model provider (e.g., "anthropic")
* @param modelId - Optional AI model ID (e.g., "claude-sonnet-4-5")
* @returns The compacted memory content
* @throws AiServiceError if AI processing fails
*/
export async function compactMemoryWithAi(
content: string,
rootDir: string,
provider?: string,
modelId?: string
): Promise<string> {
const createFnAgent = await getFnAgent();
if (!createFnAgent) {
severityAuditLog.debug("[memory-compaction] AI engine not available");
throw new AiServiceError("AI engine not available");
}
const agentOptions: {
cwd: string;
systemPrompt: string;
tools: "readonly";
defaultProvider?: string;
defaultModelId?: string;
} = {
cwd: rootDir,
systemPrompt: COMPACT_MEMORY_SYSTEM_PROMPT,
tools: "readonly",
};
// Add model selection if both provider and modelId are provided
if (provider && modelId) {
agentOptions.defaultProvider = provider;
agentOptions.defaultModelId = modelId;
}
severityAuditLog.debug("[memory-compaction] Creating agent session...");
/*
* FNXC:McpConfig 2026-06-26-00:00:
* Memory compaction lives in @fusion/core and cannot import engine MCP resolution without introducing a core→engine cycle. This readonly session intentionally runs without configured MCP servers until a neutral store/secrets seam exists in core.
*/
const agentResult = await createFnAgent(agentOptions);
if (!agentResult?.session) {
severityAuditLog.debug("[memory-compaction] Failed to initialize AI agent - no session");
throw new AiServiceError("Failed to initialize AI agent");
}
severityAuditLog.debug("[memory-compaction] Agent session created, sending prompt...");
try {
// Send the memory content to the agent
await agentResult.session.prompt(content);
// Check for session errors (pi SDK stores errors in state.error, does not throw)
if (agentResult.session.state?.error) {
const errorMsg = agentResult.session.state.error;
severityAuditLog.debug(`[memory-compaction] Session error: ${errorMsg}`);
throw new AiServiceError(`AI session error: ${errorMsg}`);
}
severityAuditLog.debug("[memory-compaction] Prompt sent, extracting response from messages...");
const messages: AgentMessage[] = agentResult.session.state?.messages ?? [];
const assistantMessages = messages.filter((m: AgentMessage) => m.role === "assistant");
severityAuditLog.debug(`[memory-compaction] Total messages: ${messages.length}, Assistant messages: ${assistantMessages.length}`);
const lastMessage = assistantMessages.pop();
let compacted = "";
if (lastMessage?.content) {
// Handle both string and array content types
if (typeof lastMessage.content === "string") {
compacted = lastMessage.content.trim();
} else if (Array.isArray(lastMessage.content)) {
// Extract text from content blocks
compacted = lastMessage.content
.filter((c: { type: string; text: string }): c is { type: "text"; text: string } => c.type === "text")
.map((c: { type: string; text: string }) => c.text)
.join("")
.trim();
}
}
severityAuditLog.debug(`[memory-compaction] Extracted compacted content length: ${compacted.length}`);
if (!compacted) {
severityAuditLog.debug("[memory-compaction] AI returned empty response");
throw new AiServiceError("AI returned empty response");
}
severityAuditLog.debug("[memory-compaction] Memory compaction successful");
return compacted;
} catch (err) {
if (err instanceof AiServiceError) {
throw err;
}
const message = err instanceof Error ? err.message : "AI processing failed";
severityAuditLog.debug(`[memory-compaction] Unexpected error: ${message}`);
throw new AiServiceError(message);
} finally {
// Ensure session is disposed even on error
try {
agentResult.session.dispose?.();
} catch {
// Ignore disposal errors
}
}
}
// ── Test Helpers ───────────────────────────────────────────────────────────
/**
* Reset all compaction state. Used for testing only.
* Currently a no-op since there are no caches, but available for future use.
*/
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/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/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/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);
}
}