feat(KB-504): add migration and first-run experience for multi-project support

- Add MigrationOrchestrator with filesystem scanning and auto-registration

- Add FirstRunExperience with setup wizard state management

- CLI integration with automatic migration hook on first run

- Backward-compatible single-project mode support

- \"--project\" flag support for CLI multi-project targeting

- KB_SKIP_MIGRATION environment variable for recovery

- Graceful fallback when central database unavailable

- New fn init command to initialize kb projects

- Interactive first-run setup wizard API in dashboard
This commit is contained in:
gsxdsm
2026-04-01 08:17:30 -07:00
parent 5681c354e2
commit 017c1bb8d5
9 changed files with 286 additions and 441 deletions

View File

@@ -123,26 +123,26 @@ export type {
ProjectStatus,
ProjectHealth,
CentralActivityLogEntry,
GlobalConcurrencyState
} from "./types.js";
// ── Migration and First-Run Experience ────────────────────────────────
export {
FirstRunDetector,
MigrationCoordinator,
BackwardCompat,
ProjectRequiredError,
} from "./migration.js";
export type {
FirstRunState,
GlobalConcurrencyState,
DetectedProject,
MigrationOptions,
MigrationResult,
ProjectSetupInput,
ResolvedContext,
} from "./migration.js";
SetupState,
SetupCompletionResult,
} from "./types.js";
// ── Migration & First-Run (Multi-Project Support) ───────────────────────────
export {
needsCentralMigration,
detectExistingProjects,
autoMigrateToCentral,
} from "./db-migrate.js";
MigrationOrchestrator,
createMigrationOrchestrator,
MAX_AUTO_REGISTER_PROJECTS,
DEFAULT_MAX_DEPTH,
EXCLUDED_DIRS,
} from "./migration-orchestrator.js";
export {
FirstRunExperience,
createFirstRunExperience,
} from "./first-run.js";

View File

@@ -178,12 +178,12 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
worktree, blockedBy, paused, baseBranch, baseCommitSha, modelPresetId, modelProvider,
modelId, validatorModelProvider, validatorModelId, mergeRetries, error,
summary, thinkingLevel, createdAt, updatedAt, columnMovedAt,
dependencies, steps, log, attachments,
dependencies, steps, log, attachments, steeringComments,
comments, workflowStepResults, prInfo, issueInfo, mergeDetails,
breakIntoSubtasks, enabledWorkflowSteps, modifiedFiles, sliceId
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)
`).run(
task.id,
@@ -215,7 +215,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
toJson(task.steps || []),
toJson(task.log || []),
toJson(task.attachments || []),
"[]", // steeringComments column - no longer used, write empty array
toJson(task.steeringComments || []),
toJson(task.comments || []),
toJson(task.workflowStepResults || []),
toJsonNullable(task.prInfo),
@@ -2707,4 +2707,97 @@ ${notificationsSection}`;
}
return this.missionStore;
}
// ── Backward Compatibility (Multi-Project Support) ────────────────────────
/**
* Get or create a TaskStore for a project, supporting backward-compatible
* single-project mode and multi-project resolution.
*
* Resolution logic:
* - If `projectId` provided: look up in central registry, create store for that path
* - If no `projectId` and single project registered: use that project
* - If no `projectId` and multiple projects: throw requiring explicit selection
* - If no central DB available: fall back to legacy behavior (current directory)
*
* @param projectId — Optional project ID to resolve
* @param centralCore — Optional CentralCore instance (creates new if not provided)
* @returns TaskStore initialized for the resolved project
* @throws Error if project resolution fails or multiple projects require explicit selection
*/
static async getOrCreateForProject(
projectId?: string,
centralCore?: import("./central-core.js").CentralCore
): Promise<TaskStore> {
// If no centralCore provided, try to create one
let core = centralCore;
let shouldCleanupCore = false;
if (!core) {
try {
const { CentralCore } = await import("./central-core.js");
core = new CentralCore();
await core.init();
shouldCleanupCore = true;
} catch {
// Central core not available - fall back to legacy mode
}
}
// Legacy mode: no central core available
if (!core) {
const store = new TaskStore(process.cwd());
await store.init();
return store;
}
try {
// If projectId provided, look it up directly
if (projectId) {
const project = await core.getProject(projectId);
if (!project) {
// Try to find by name
const allProjects = await core.listProjects();
const byName = allProjects.find(p => p.name === projectId);
if (!byName) {
throw new Error(`Project "${projectId}" not found`);
}
const store = new TaskStore(byName.path);
await store.init();
return store;
}
const store = new TaskStore(project.path);
await store.init();
return store;
}
// No projectId provided - check registered projects
const projects = await core.listProjects();
if (projects.length === 0) {
// No projects registered - fall back to legacy mode (current directory)
const store = new TaskStore(process.cwd());
await store.init();
return store;
}
if (projects.length === 1) {
// Exactly one project - use it
const store = new TaskStore(projects[0].path);
await store.init();
return store;
}
// Multiple projects - require explicit selection
const projectList = projects.map(p => ` - ${p.name}: ${p.path}`).join("\n");
throw new Error(
`Multiple projects registered. Use --project <name> to specify one.\n\nAvailable projects:\n${projectList}`
);
} finally {
// Clean up the central core if we created it
if (shouldCleanupCore && core) {
await core.close();
}
}
}
}

View File

@@ -386,6 +386,8 @@ export interface Task {
baseCommitSha?: string;
attachments?: TaskAttachment[];
comments?: TaskComment[];
/** Steering comments injected during task execution for real-time guidance */
steeringComments?: TaskComment[];
/** PR information for tasks linked to GitHub pull requests */
prInfo?: PrInfo;
mergeDetails?: MergeDetails;
@@ -531,7 +533,8 @@ export interface GlobalSettings {
* and ntfyTopic, notifications include a Click URL that opens the dashboard
* directly to the task. Example: "http://localhost:3000" or "https://fusion.example.com" */
ntfyDashboardHost?: string;
/** Whether the first-run setup wizard has been completed. */
/** When true, indicates the first-run setup wizard has been completed.
* Set by FirstRunExperience.completeSetup() after successful migration. */
setupComplete?: boolean;
}
@@ -1151,3 +1154,75 @@ export interface AgentUpdateInput {
role?: AgentCapability;
metadata?: Record<string, unknown>;
}
// ── Migration & First-Run Types (Multi-Project Support) ───────────────────
/** A project detected during filesystem scanning for auto-migration */
export interface DetectedProject {
/** Absolute path to the project directory */
path: string;
/** Project name (derived from directory basename) */
name: string;
/** Whether the project has a valid kb database */
hasDb: boolean;
}
/** Options for migration orchestration */
export interface MigrationOptions {
/** Starting path for project detection (default: process.cwd()) */
startPath?: string;
/** Whether to auto-register detected projects (default: false) */
autoRegister?: boolean;
/** Whether to perform a dry run (detect only, don't register) */
dryRun?: boolean;
/** Maximum depth to scan (default: 5) */
maxDepth?: number;
/** Progress callback for UI feedback */
onProgress?: (current: number, total: number, projectPath: string) => void;
}
/** Result of migration execution */
export interface MigrationResult {
/** Projects detected during scan */
projectsDetected: DetectedProject[];
/** Projects successfully registered */
projectsRegistered: RegisteredProject[];
/** Projects skipped (already registered or invalid) */
projectsSkipped: Array<{ path: string; reason: string }>;
/** Errors encountered during migration */
errors: Array<{ path: string; error: string }>;
}
/** Input for setting up a project during first-run wizard */
export interface ProjectSetupInput {
/** Absolute path to project directory */
path: string;
/** Display name for the project */
name: string;
/** Execution isolation mode (default: 'in-process') */
isolationMode?: IsolationMode;
}
/** Complete setup state for first-run experience */
export interface SetupState {
/** Whether this is a fresh installation (no projects registered) */
isFirstRun: boolean;
/** Whether any projects were detected during scan */
hasDetectedProjects: boolean;
/** Projects detected but not yet registered */
detectedProjects: DetectedProject[];
/** Projects already registered in the system */
registeredProjects: RegisteredProject[];
/** Recommended action based on current state */
recommendedAction: 'auto-detect' | 'manual-setup' | 'create-new';
}
/** Result of completing the setup wizard */
export interface SetupCompletionResult {
/** Whether setup completed successfully */
success: boolean;
/** Projects that were registered */
projects: RegisteredProject[];
/** Suggested next steps for the user */
nextSteps: string[];
}