feat(FN-4393): complete Step 1 — add memory inclusion mode settings and resolver

Fusion-Task-Id: FN-4393
Fusion-Task-Lineage: 3615215d-9caa-4402-9258-a5a5de137dd6
This commit is contained in:
Fusion
2026-05-13 22:56:52 -07:00
committed by gsxdsm
parent db618bd380
commit 283fcea6ee
7 changed files with 132 additions and 2 deletions

View File

@@ -0,0 +1,58 @@
import { describe, expect, it } from "vitest";
import type { Agent, GlobalSettings, ProjectSettings } from "../types.js";
import { resolveAgentMemoryInclusionMode } from "../agent-memory-mode.js";
function makeAgent(mode?: unknown): Agent {
return {
id: "agent-1",
name: "Agent 1",
role: "executor",
state: "idle",
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
metadata: {},
runtimeConfig: mode === undefined ? {} : { agentMemoryInclusionMode: mode },
};
}
describe("resolveAgentMemoryInclusionMode", () => {
it("prefers per-agent override over project and global", () => {
const result = resolveAgentMemoryInclusionMode({
agent: makeAgent("off"),
projectSettings: { agentMemoryInclusionMode: "index" } as ProjectSettings,
globalSettings: { agentMemoryInclusionMode: "full" } as GlobalSettings,
});
expect(result).toEqual({ mode: "off", source: "agent" });
});
it("prefers project over global", () => {
const result = resolveAgentMemoryInclusionMode({
agent: makeAgent(),
projectSettings: { agentMemoryInclusionMode: "index" } as ProjectSettings,
globalSettings: { agentMemoryInclusionMode: "off" } as GlobalSettings,
});
expect(result).toEqual({ mode: "index", source: "project" });
});
it("prefers global over default", () => {
const result = resolveAgentMemoryInclusionMode({
agent: makeAgent(),
globalSettings: { agentMemoryInclusionMode: "off" } as GlobalSettings,
});
expect(result).toEqual({ mode: "off", source: "global" });
});
it("falls back to full default", () => {
const result = resolveAgentMemoryInclusionMode({ agent: makeAgent() });
expect(result).toEqual({ mode: "full", source: "default" });
});
it("ignores invalid values and falls through", () => {
const result = resolveAgentMemoryInclusionMode({
agent: makeAgent("bad"),
projectSettings: { agentMemoryInclusionMode: "nope" as never } as ProjectSettings,
globalSettings: { agentMemoryInclusionMode: "index" } as GlobalSettings,
});
expect(result).toEqual({ mode: "index", source: "global" });
});
});

View File

@@ -69,6 +69,8 @@ describe("settings key parity", () => {
expect(isProjectSettingsKey("persistAgentThinkingLogEphemeral")).toBe(false);
expect(isGlobalOnlySettingsKey("persistAgentThinkingLogEphemeral")).toBe(true);
expect(isGlobalSettingsKey("researchSettings")).toBe(false);
expect(isGlobalSettingsKey("agentMemoryInclusionMode")).toBe(true);
expect(isProjectSettingsKey("agentMemoryInclusionMode")).toBe(true);
});
it("defaults persisted thinking logs to disabled", () => {
@@ -162,7 +164,7 @@ describe("settings key parity", () => {
it("only intentional shared keys appear in both global and project scopes", () => {
const projectKeySet = new Set(PROJECT_SETTINGS_KEYS as readonly string[]);
const overlap = (GLOBAL_SETTINGS_KEYS as readonly string[]).filter((key) => projectKeySet.has(key));
expect(overlap).toEqual(["githubTrackingDefaultRepo"]);
expect(overlap).toEqual(["githubTrackingDefaultRepo", "agentMemoryInclusionMode"]);
});
});

View File

@@ -0,0 +1,43 @@
import type { Agent, AgentMemoryInclusionMode, GlobalSettings, ProjectSettings } from "./types.js";
export type AgentMemoryInclusionModeSource = "agent" | "project" | "global" | "default";
export interface ResolveAgentMemoryInclusionModeInput {
agent?: Agent | null;
projectSettings?: ProjectSettings | null;
globalSettings?: GlobalSettings | null;
}
export interface ResolvedAgentMemoryInclusionMode {
mode: AgentMemoryInclusionMode;
source: AgentMemoryInclusionModeSource;
}
function isAgentMemoryInclusionMode(value: unknown): value is AgentMemoryInclusionMode {
return value === "full" || value === "index" || value === "off";
}
export function resolveAgentMemoryInclusionMode({
agent,
projectSettings,
globalSettings,
}: ResolveAgentMemoryInclusionModeInput): ResolvedAgentMemoryInclusionMode {
const agentMode = agent?.runtimeConfig && typeof agent.runtimeConfig === "object"
? (agent.runtimeConfig as Record<string, unknown>).agentMemoryInclusionMode
: undefined;
if (isAgentMemoryInclusionMode(agentMode)) {
return { mode: agentMode, source: "agent" };
}
const projectMode = projectSettings?.agentMemoryInclusionMode;
if (isAgentMemoryInclusionMode(projectMode)) {
return { mode: projectMode, source: "project" };
}
const globalMode = globalSettings?.agentMemoryInclusionMode;
if (isAgentMemoryInclusionMode(globalMode)) {
return { mode: globalMode, source: "global" };
}
return { mode: "full", source: "default" };
}

View File

@@ -1,6 +1,12 @@
export { COLUMNS, DEFAULT_COLUMN, isColumn, normalizeColumn, COLUMN_LABELS, COLUMN_DESCRIPTIONS, VALID_TRANSITIONS, DEFAULT_SETTINGS, DEFAULT_GLOBAL_SETTINGS, DEFAULT_PROJECT_SETTINGS, GLOBAL_SETTINGS_KEYS, PROJECT_SETTINGS_KEYS, isGlobalSettingsKey, isProjectSettingsKey, resolvePersistAgentThinkingLog, THINKING_LEVELS, THEME_MODES, COLOR_THEMES, WORKFLOW_STEP_TEMPLATES, AGENT_PERMISSIONS, PERMANENT_AGENT_ACTION_CATEGORIES, AGENT_PERMISSION_POLICY_ACTION_CATEGORIES, AGENT_PROVISIONING_APPROVAL_MODES, AGENT_PERMISSION_POLICY_PRESET_IDS, LEGACY_AGENT_PERMISSION_POLICY_ACTION_CATEGORY_ALIASES, APPROVAL_REQUEST_STATUSES, APPROVAL_REQUEST_AUDIT_EVENT_TYPES, normalizeApprovalRequestActionCategory, isValidApprovalRequestTransition, agentToConfigSnapshot, diffConfigSnapshots, isEphemeralAgent, hasAgentIdentity, CheckoutConflictError, DEFAULT_HEARTBEAT_PROCEDURE_PATH, getDefaultHeartbeatProcedurePath, EXECUTION_MODES, DEFAULT_EXECUTION_MODE, TASK_PRIORITIES, DEFAULT_TASK_PRIORITY, HIGH_FANOUT_BLOCKER_TODO_THRESHOLD, STALE_HIGH_FANOUT_BLOCKER_AGE_THRESHOLD_MS, DASHBOARD_USER_ID, normalizeMessageParticipant, validateMessageMetadata, validateDockerNodeConfig, sanitizeDockerNodeConfigForResponse, normalizeMergeConflictStrategy, normalizeMergeStrategyOverlapBehavior, normalizePostMergeAuditMode, POST_MERGE_AUDIT_MODES, normalizeMergeAuditAutoRecovery, MERGE_AUDIT_AUTO_RECOVERY_MODES, buildResearchDocumentKey, REPO_OVERRIDE_RE, SHARED_STATE_SNAPSHOT_VERSION } from "./types.js";
export type { Column, IssueInfo, IssueState, TaskSourceIssue, PrInfo, PrStatus, Task, TaskTokenUsage, TaskAttachment, TaskComment, TaskCommentInput, TaskDocument, TaskDocumentRevision, TaskDocumentCreateInput, TaskDocumentWithTask, TaskCreateInput, MeshReplicatedTaskCreatePayload, MeshReplicatedTaskApplyResult, TaskSource, SourceType, TaskDetail, InboxTask, TodoList, TodoItem, TodoListCreateInput, TodoListUpdateInput, TodoItemCreateInput, TodoItemUpdateInput, TodoListWithItems, AgentLogEntry, AgentLogType, AgentRole, BoardConfig, DistributedTaskIdReserveInput, DistributedTaskIdReserveResult, DistributedTaskIdCommitInput, DistributedTaskIdCommitResult, DistributedTaskIdAbortInput, DistributedTaskIdAbortResult, DistributedTaskIdStateInput, DistributedTaskIdStateResult, AutostashOrphanRecord, AutostashOutcome, MergeDetails, MergeResult, MergeConflictStrategy, CanonicalMergeConflictStrategy, MergeStrategyOverlapBehavior, PostMergeAuditMode, MergeAuditAutoRecoveryMode, DirectMergeCommitStrategy, Settings, GlobalSettings, ProjectSettings, WebSearchBackend, ResearchEnabledSources, ResearchGlobalDefaults, ResearchProjectLimits, ResearchProjectSettings, EvalFollowUpPolicy, EvalProjectSettings, ResolvedEvalSettings, SettingsScope, DaemonTokenSettings, TaskStep, StepStatus, TaskLogEntry, RunMutationContext, ActivityLogEntry, ActivityEventType, ThinkingLevel, ThemeMode, ColorTheme, ExecutionMode, TaskPriority, UnavailableNodePolicy, PlanningQuestion, PlanningSummary, PlanningResponse, PlanningQuestionType, ArchivedTaskEntry, BatchStatusRequest, BatchStatusResponse, BatchStatusEntry, BatchStatusResult, GithubIssueAction, ModelPreset, WorkflowStep, WorkflowStepMode, WorkflowStepPhase, WorkflowStepInput, WorkflowStepResult, WorkflowStepTemplate, Agent, OrgTreeNode, AgentState, AgentDetail, AgentCreateInput, AgentUpdateInput, AgentApiKey, AgentApiKeyCreateResult, AgentCapability, AgentPromptTemplate, AgentPromptsConfig, AgentPermission, PermanentAgentActionCategory, PermanentAgentSensitiveActionCategory, PermanentAgentGatingContext, AgentPermissionPolicy, AgentPermissionPolicyRules, AgentPermissionPolicyActionCategory, AgentProvisioningApprovalMode, LegacyAgentPermissionPolicyActionCategory, ApprovalRequestActionCategoryInput, ApprovalRequestActionCategory, AgentPermissionPolicyDisposition, AgentPermissionPolicyPresetId, ApprovalRequestStatus, ApprovalRequestAuditEventType, ApprovalRequestActorSnapshot, ApprovalRequestTargetAction, ApprovalRequestAuditEvent, ApprovalRequest, ApprovalRequestCreateInput, ApprovalRequestDecisionInput, ApprovalRequestCompletionInput, ApprovalRequestListInput, TaskAssignSource, AgentAccessState, AgentHeartbeatConfig, AgentBudgetConfig, AgentBudgetStatus, InstructionsBundleConfig, MessageResponseMode, AgentHeartbeatEvent, AgentHeartbeatRun, BlockedStateSnapshot, HeartbeatInvocationSource, AgentTaskSession, AgentRating, AgentRatingSummary, AgentRatingInput, AgentConfigSnapshot, RevisionFieldDiff, AgentConfigRevision, AgentStats, ReflectionTrigger, ReflectionMetrics, AgentReflection, AgentPerformanceSummary, NtfyNotificationEvent, NotificationEvent, NotificationPayload, NotificationProviderConfig, CustomProvider, SteeringComment, ParticipantType, MessageType, Message, MessageCreateInput, MessageFilter, MessageMetadata, MessageReplyReference, Mailbox, CheckoutLease, RunAuditDomain, RunAuditEvent, RunAuditEventInput, RunAuditEventFilter } from "./types.js";
export type { Column, IssueInfo, IssueState, TaskSourceIssue, PrInfo, PrStatus, Task, TaskTokenUsage, TaskAttachment, TaskComment, TaskCommentInput, TaskDocument, TaskDocumentRevision, TaskDocumentCreateInput, TaskDocumentWithTask, TaskCreateInput, MeshReplicatedTaskCreatePayload, MeshReplicatedTaskApplyResult, TaskSource, SourceType, TaskDetail, InboxTask, TodoList, TodoItem, TodoListCreateInput, TodoListUpdateInput, TodoItemCreateInput, TodoItemUpdateInput, TodoListWithItems, AgentLogEntry, AgentLogType, AgentRole, BoardConfig, DistributedTaskIdReserveInput, DistributedTaskIdReserveResult, DistributedTaskIdCommitInput, DistributedTaskIdCommitResult, DistributedTaskIdAbortInput, DistributedTaskIdAbortResult, DistributedTaskIdStateInput, DistributedTaskIdStateResult, AutostashOrphanRecord, AutostashOutcome, MergeDetails, MergeResult, MergeConflictStrategy, CanonicalMergeConflictStrategy, MergeStrategyOverlapBehavior, PostMergeAuditMode, MergeAuditAutoRecoveryMode, DirectMergeCommitStrategy, Settings, GlobalSettings, ProjectSettings, WebSearchBackend, ResearchEnabledSources, ResearchGlobalDefaults, ResearchProjectLimits, ResearchProjectSettings, EvalFollowUpPolicy, EvalProjectSettings, ResolvedEvalSettings, SettingsScope, DaemonTokenSettings, TaskStep, StepStatus, TaskLogEntry, RunMutationContext, ActivityLogEntry, ActivityEventType, ThinkingLevel, ThemeMode, ColorTheme, ExecutionMode, TaskPriority, UnavailableNodePolicy, PlanningQuestion, PlanningSummary, PlanningResponse, PlanningQuestionType, ArchivedTaskEntry, BatchStatusRequest, BatchStatusResponse, BatchStatusEntry, BatchStatusResult, GithubIssueAction, ModelPreset, WorkflowStep, WorkflowStepMode, WorkflowStepPhase, WorkflowStepInput, WorkflowStepResult, WorkflowStepTemplate, Agent, OrgTreeNode, AgentState, AgentDetail, AgentCreateInput, AgentUpdateInput, AgentApiKey, AgentApiKeyCreateResult, AgentCapability, AgentPromptTemplate, AgentPromptsConfig, AgentPermission, PermanentAgentActionCategory, PermanentAgentSensitiveActionCategory, PermanentAgentGatingContext, AgentPermissionPolicy, AgentPermissionPolicyRules, AgentPermissionPolicyActionCategory, AgentProvisioningApprovalMode, LegacyAgentPermissionPolicyActionCategory, ApprovalRequestActionCategoryInput, ApprovalRequestActionCategory, AgentPermissionPolicyDisposition, AgentPermissionPolicyPresetId, ApprovalRequestStatus, ApprovalRequestAuditEventType, ApprovalRequestActorSnapshot, ApprovalRequestTargetAction, ApprovalRequestAuditEvent, ApprovalRequest, ApprovalRequestCreateInput, ApprovalRequestDecisionInput, ApprovalRequestCompletionInput, ApprovalRequestListInput, TaskAssignSource, AgentAccessState, AgentHeartbeatConfig, AgentBudgetConfig, AgentBudgetStatus, InstructionsBundleConfig, MessageResponseMode, AgentHeartbeatEvent, AgentHeartbeatRun, BlockedStateSnapshot, HeartbeatInvocationSource, AgentTaskSession, AgentRating, AgentRatingSummary, AgentRatingInput, AgentConfigSnapshot, RevisionFieldDiff, AgentConfigRevision, AgentStats, ReflectionTrigger, ReflectionMetrics, AgentReflection, AgentPerformanceSummary, NtfyNotificationEvent, NotificationEvent, NotificationPayload, NotificationProviderConfig, CustomProvider, SteeringComment, ParticipantType, MessageType, Message, MessageCreateInput, MessageFilter, MessageMetadata, MessageReplyReference, Mailbox, CheckoutLease, RunAuditDomain, RunAuditEvent, RunAuditEventInput, RunAuditEventFilter, AgentMemoryInclusionMode } from "./types.js";
export { AGENT_VALID_TRANSITIONS } from "./types.js";
export {
resolveAgentMemoryInclusionMode,
type AgentMemoryInclusionModeSource,
type ResolveAgentMemoryInclusionModeInput,
type ResolvedAgentMemoryInclusionMode,
} from "./agent-memory-mode.js";
export type { TaskReviewData, TaskReviewSummary, TaskReviewItem } from "./types.js";
export type {
TaskCommitAssociation,

View File

@@ -94,6 +94,7 @@ export async function ensureMemoryFile(rootDir: string): Promise<boolean> {
type MemorySettings = {
memoryEnabled?: boolean;
memoryBackendType?: string;
agentMemoryInclusionMode?: "full" | "index" | "off";
[key: string]: unknown;
};

View File

@@ -92,6 +92,7 @@ export const DEFAULT_GLOBAL_SETTINGS = {
persistAgentThinkingLogPermanent: false,
persistAgentThinkingLogEphemeral: false,
persistAgentThinkingLog: false,
agentMemoryInclusionMode: "full",
researchGlobalDefaults: {
searchProvider: undefined,
synthesisProvider: undefined,
@@ -287,6 +288,7 @@ export const DEFAULT_PROJECT_SETTINGS = {
taskEvaluationFollowUpPolicy: "off",
taskEvaluationRetention: undefined,
memoryEnabled: true,
agentMemoryInclusionMode: undefined,
memoryBackendType: "qmd",
memoryAutoSummarizeEnabled: false,
memoryAutoSummarizeThresholdChars: 50_000,

View File

@@ -1664,6 +1664,8 @@ export interface ResolvedEvalSettings {
retentionDays: number;
}
export type AgentMemoryInclusionMode = "full" | "index" | "off";
export interface GlobalSettings {
/** Theme mode preference: dark, light, or system (follows OS). Default: "dark". */
themeMode?: ThemeMode;
@@ -2515,6 +2517,12 @@ export interface ProjectSettings {
/** Reference to a named script in the scripts map that runs before task execution.
* Used for pre-task setup like environment preparation. */
setupScript?: string;
/** Agent memory prompt inclusion mode baseline for all projects/agents.
* - "full": inline full curated memory content into prompts (default)
* - "index": include only a compact memory index, then fetch on demand via memory tools
* - "off": omit agent-memory prompt sections entirely
*/
agentMemoryInclusionMode?: AgentMemoryInclusionMode;
/** When true, enables periodic AI-powered extraction of insights from working memory
* into a distilled long-term memory file. Creates an automation schedule that reads
* `.fusion/memory/MEMORY.md`, identifies patterns/principles/pitfalls, and writes to
@@ -2533,6 +2541,12 @@ export interface ProjectSettings {
* in their prompts and will not read or write to .fusion/memory/ files.
* Default: true (enabled for backward compatibility). */
memoryEnabled?: boolean;
/** Agent memory prompt inclusion mode for this project.
* - "full": inline full curated memory content into prompts
* - "index": include only a compact memory index and fetch details via tools
* - "off": omit agent-memory prompt sections entirely
*/
agentMemoryInclusionMode?: AgentMemoryInclusionMode;
/** Memory backend type for pluggable memory storage.
* Available built-in backends:
* - "qmd": QMD (Quantized Memory Distillation) backend using the qmd CLI tool (default)
@@ -4669,6 +4683,10 @@ export interface AgentHeartbeatConfig {
messageResponseMode?: MessageResponseMode;
/** Per-agent budget governance configuration. When set, enables budget tracking and enforcement. */
budgetConfig?: AgentBudgetConfig;
/** Per-agent override for memory prompt inclusion mode. */
agentMemoryInclusionMode?: AgentMemoryInclusionMode;
/** Last resolved memory inclusion mode recorded by engine for transition logging. */
lastAgentMemoryInclusionMode?: AgentMemoryInclusionMode;
/**
* When true, the engine fires a catch-up heartbeat at server startup if the
* agent's last heartbeat is older than its interval — i.e., the server was