feat(FN-3722): route plugin store to configured global directory

Merges centralized plugin installation (FN-3722): TaskStore plugin store is now routed to a configured global directory with legacy migration hardening, and CLI plugin commands are aligned accordingly, backed by comprehensive integration and regression tests. Also includes a dashboard fix to return

Fusion-Task-Id: FN-3722
This commit is contained in:
Fusion
2026-05-08 08:03:39 -07:00
committed by gsxdsm
parent 68eff4418c
commit 45fe41c075
17 changed files with 351 additions and 42 deletions

View File

@@ -0,0 +1,5 @@
---
"@runfusion/fusion": patch
---
Fix plugin installation persistence so user-installed plugins are always recorded in the shared central `plugin_installs` registry (with per-project state in `project_plugin_states`) instead of project-local legacy plugin rows. This ensures installs are visible across projects and processes as intended.

View File

@@ -327,6 +327,8 @@ Hybrid evaluator pipeline (FN-3389/FN-3391):
- **Global install metadata** in central DB table `plugin_installs` (`~/.fusion/fusion-central.db`) including manifest/path/settings/schema/dependencies
- **Per-project runtime state** in central DB table `project_plugin_states` keyed by normalized project path (`enabled`, `state`, `error`)
- Legacy project-local `plugins` rows in `.fusion/fusion.db` are migrated lazily on plugin-store init/read; migration is idempotent and keeps newest `updatedAt` install metadata as global canonical data while preserving per-project enablement rows
- Post-FN-3722, the project-local `plugins` table is legacy read-only migration input; any new install writer targeting it is a bug
- `TaskStore.getPluginStore()` now propagates the configured `globalSettingsDir`/central directory so all CLI and dashboard install paths resolve the same central DB
- `PluginLoader` (`plugin-loader.ts`) loads/unloads plugin modules using the effective per-project plugin state
- Plugin contributions now include both embedded `uiSlots` and top-level `dashboardViews`
- Discovery endpoints:

View File

@@ -86,6 +86,7 @@ Plugin persistence is split across global and project scopes:
- Global installation metadata is shared across projects in `~/.fusion/fusion-central.db` (`plugin_installs`)
- Per-project activation/runtime state is tracked separately per normalized project path (`project_plugin_states`)
- Project-local `.fusion/fusion.db` `plugins` rows are legacy migration-only input and are no longer a write target for installs
Operationally:
- `install` / `uninstall` are global actions

View File

@@ -55,6 +55,7 @@ const mocks = vi.hoisted(() => {
const missionStore = {
listMissions: vi.fn().mockResolvedValue([]),
};
const pluginStore = pluginStoreCtor();
return {
init: vi.fn().mockResolvedValue(undefined),
@@ -63,6 +64,7 @@ const mocks = vi.hoisted(() => {
getFusionDir: vi.fn().mockReturnValue("/repo/.fusion"),
getRootDir: vi.fn().mockReturnValue("/repo"),
getMissionStore: vi.fn().mockReturnValue(missionStore),
getPluginStore: vi.fn().mockReturnValue(pluginStore),
getSettings: vi.fn().mockResolvedValue({
maxConcurrent: 2,
recycleWorktrees: false,

View File

@@ -75,6 +75,17 @@ function makeMockStore() {
listMilestones: vi.fn().mockReturnValue([]),
listFeatures: vi.fn().mockReturnValue([]),
};
const mockPluginStore = {
init: vi.fn().mockResolvedValue(undefined),
listPlugins: vi.fn().mockResolvedValue([]),
getPlugin: vi.fn(),
registerPlugin: vi.fn(),
enablePlugin: vi.fn(),
disablePlugin: vi.fn(),
updatePluginSettings: vi.fn(),
unregisterPlugin: vi.fn(),
updatePluginState: vi.fn(),
};
return {
init: vi.fn().mockResolvedValue(undefined),
watch: vi.fn().mockResolvedValue(undefined),
@@ -101,6 +112,7 @@ function makeMockStore() {
})),
getActiveMergingTask: vi.fn().mockReturnValue(undefined),
getMissionStore: vi.fn().mockReturnValue(mockMissionStore),
getPluginStore: vi.fn().mockReturnValue(mockPluginStore),
close: vi.fn(),
on: vi.fn((event: string, handler: (...args: unknown[]) => void) => {
emitter.on(event, handler);

View File

@@ -68,6 +68,7 @@ vi.mock("@fusion/core", () => ({
PluginStore: mocks.PluginStore,
PluginLoader: mocks.PluginLoader,
validatePluginManifest: vi.fn().mockReturnValue({ valid: true, errors: [] }),
resolveGlobalDir: vi.fn().mockReturnValue("/tmp/fusion-global"),
}));
vi.mock("../../project-context.js", () => ({
@@ -132,6 +133,100 @@ describe("plugin commands", () => {
await expect(resolvePluginEntryFile(pluginDir)).resolves.toBe(resolve(pluginDir, "dist/index.js"));
});
it("uses resolved TaskStore plugin store when available", async () => {
const contextStore = {
getPluginStore: vi.fn().mockReturnValue({
init: vi.fn().mockResolvedValue(undefined),
registerPlugin: vi.fn().mockResolvedValue({ id: "paperclip-runtime", enabled: true }),
listPlugins: vi.fn().mockResolvedValue([]),
getPlugin: vi.fn(),
updatePluginSettings: vi.fn().mockResolvedValue(undefined),
}),
};
vi.mocked(resolveProject).mockResolvedValue({
projectPath: "/tmp/fn-project",
store: contextStore,
} as never);
const pluginDir = await createTempPluginFixture([
{
path: "manifest.json",
content: JSON.stringify({ id: "paperclip-runtime", name: "Paperclip Runtime", version: "1.0.0" }),
},
{
path: "package.json",
content: JSON.stringify({ exports: { ".": { import: "./dist/index.js" } } }),
},
{
path: "dist/index.js",
content:
"export default { manifest: { id: 'paperclip-runtime', name: 'Paperclip Runtime', version: '1.0.0' }, async onLoad() {}, async onUnload() {} };",
},
]);
tempDirs.push(pluginDir);
await expect(runPluginInstall(pluginDir)).resolves.toBeUndefined();
expect(contextStore.getPluginStore).toHaveBeenCalledTimes(1);
expect(mocks.PluginStore).not.toHaveBeenCalled();
});
it("writes runPluginInstall metadata to central tables only", async () => {
const actualCore = await vi.importActual<typeof import("@fusion/core")>("@fusion/core");
const projectDir = await mkdtemp(join(tmpdir(), "fn-plugin-project-"));
const centralDir = await mkdtemp(join(tmpdir(), "fn-plugin-central-"));
tempDirs.push(projectDir, centralDir);
const realStore = new actualCore.PluginStore(projectDir, { centralGlobalDir: centralDir });
await realStore.init();
vi.mocked(resolveProject).mockResolvedValue({
projectPath: projectDir,
store: { getPluginStore: () => realStore },
} as never);
const pluginDir = await createTempPluginFixture([
{
path: "manifest.json",
content: JSON.stringify({ id: "paperclip-runtime", name: "Paperclip Runtime", version: "1.0.0" }),
},
{
path: "package.json",
content: JSON.stringify({ exports: { ".": { import: "./dist/index.js" } } }),
},
{
path: "dist/index.js",
content:
"export default { manifest: { id: 'paperclip-runtime', name: 'Paperclip Runtime', version: '1.0.0' }, async onLoad() {}, async onUnload() {} };",
},
]);
tempDirs.push(pluginDir);
await expect(runPluginInstall(pluginDir)).resolves.toBeUndefined();
const centralDb = new actualCore.CentralDatabase(centralDir);
centralDb.init();
const installCount = centralDb
.prepare("SELECT COUNT(*) as count FROM plugin_installs WHERE id = ?")
.get("paperclip-runtime") as { count: number };
const stateCount = centralDb
.prepare("SELECT COUNT(*) as count FROM project_plugin_states WHERE pluginId = ? AND projectPath = ?")
.get("paperclip-runtime", projectDir) as { count: number };
const localDb = new actualCore.Database(join(projectDir, ".fusion"));
localDb.init();
const legacyCount = localDb
.prepare("SELECT COUNT(*) as count FROM plugins WHERE id = ?")
.get("paperclip-runtime") as { count: number };
expect(installCount.count).toBe(1);
expect(stateCount.count).toBe(1);
expect(legacyCount.count).toBe(0);
centralDb.close();
localDb.close();
});
it("includes getRootDir on the plugin loader taskStore mock (FN-2687)", async () => {
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
throw new Error(`exit:${code}`);

View File

@@ -75,6 +75,7 @@ const mocks = vi.hoisted(() => {
const missionStore = {
listMissions: vi.fn().mockResolvedValue([]),
};
const pluginStore = pluginStoreCtor();
return {
init: vi.fn().mockResolvedValue(undefined),
@@ -86,6 +87,7 @@ const mocks = vi.hoisted(() => {
getSettings: vi.fn().mockResolvedValue({}),
})),
getMissionStore: vi.fn().mockReturnValue(missionStore),
getPluginStore: vi.fn().mockReturnValue(pluginStore),
getSettings: vi.fn().mockResolvedValue({
maxConcurrent: 2,
recycleWorktrees: false,
@@ -907,13 +909,14 @@ describe("runServe — Plugin wiring", () => {
process.exit = originalExit;
});
it("creates PluginStore and PluginLoader instances", async () => {
it("gets PluginStore from TaskStore and creates PluginLoader", async () => {
const { PluginStore, PluginLoader } = await import("@fusion/core");
await runServe(4040, {});
expect(PluginStore).toHaveBeenCalledTimes(1);
expect(mocks.taskStores[0].getPluginStore).toHaveBeenCalledTimes(1);
expect(PluginLoader).toHaveBeenCalledTimes(1);
expect(PluginStore).toHaveBeenCalled();
await triggerSignal("SIGINT");
});
@@ -933,12 +936,12 @@ describe("runServe — Plugin wiring", () => {
await triggerSignal("SIGINT");
});
it("initializes PluginStore with the task store's project root", async () => {
const { PluginStore } = await import("@fusion/core");
it("initializes the TaskStore-provided PluginStore", async () => {
await runServe(4040, {});
expect(PluginStore).toHaveBeenCalledWith("/repo");
expect(mocks.taskStores[0].getPluginStore).toHaveBeenCalledTimes(1);
const taskStorePluginStore = mocks.taskStores[0].getPluginStore.mock.results[0]?.value as { init: ReturnType<typeof vi.fn> };
expect(taskStorePluginStore?.init).toHaveBeenCalledTimes(1);
await triggerSignal("SIGINT");
});

View File

@@ -12,7 +12,6 @@ import type { AddressInfo } from "node:net";
import { join } from "node:path";
import {
CentralCore,
PluginStore,
PluginLoader,
getTaskMergeBlocker,
INSIGHT_EXTRACTION_SCHEDULE_NAME,
@@ -367,12 +366,7 @@ export async function runDaemon(opts: DaemonOptions = {}) {
}
// ── PluginStore: plugin installation management ─────────────────────
// Some mocked stores used in tests may not implement getRootDir(); fall
// back to the resolved runtime cwd in that case.
const storeRootDir = typeof (store as { getRootDir?: () => string }).getRootDir === "function"
? (store as { getRootDir: () => string }).getRootDir()
: cwd;
const pluginStore = new PluginStore(storeRootDir);
const pluginStore = store.getPluginStore();
await pluginStore.init();
// ── PluginLoader: plugin lifecycle management ───────────────────────

View File

@@ -1,5 +1,5 @@
import type { AddressInfo } from "node:net";
import { dirname, join, resolve as pathResolve } from "node:path";
import { join, resolve as pathResolve } from "node:path";
import { execFile as execFileCb } from "node:child_process";
import { promisify } from "node:util";
import { stat, readdir, readFile as fsReadFile } from "node:fs/promises";
@@ -8,7 +8,6 @@ import {
AutomationStore,
CentralCore,
AgentStore,
PluginStore,
PluginLoader,
getTaskMergeBlocker,
getEnabledPiExtensionPaths,
@@ -1067,11 +1066,7 @@ export async function runDashboard(port: number, opts: { paused?: boolean; dev?:
// Enables the PluginManager UI to list, install, enable, disable, and
// configure plugins via the /api/plugins REST endpoints.
//
const pluginStoreRootDir =
typeof (store as { getRootDir?: () => string }).getRootDir === "function"
? store.getRootDir()
: dirname(store.getFusionDir());
const pluginStore = new PluginStore(pluginStoreRootDir);
const pluginStore = store.getPluginStore();
await pluginStore.init();
// ── PluginLoader: plugin lifecycle management ───────────────────────

View File

@@ -13,7 +13,7 @@ import { existsSync } from "node:fs";
import { dirname, extname, join, resolve } from "node:path";
import { readFile, stat } from "node:fs/promises";
import * as readline from "node:readline";
import { PluginStore, PluginLoader, validatePluginManifest } from "@fusion/core";
import { PluginStore, PluginLoader, validatePluginManifest, resolveGlobalDir } from "@fusion/core";
import { resolveProject } from "../project-context.js";
export interface BuiltinPluginCatalogEntry {
@@ -92,11 +92,23 @@ async function getProjectPath(projectName?: string): Promise<string> {
/**
* Create a PluginStore for the given project.
*/
async function createPluginStore(projectName?: string): Promise<PluginStore> {
const projectPath = await getProjectPath(projectName);
const pluginStore = new PluginStore(projectPath);
await pluginStore.init();
return pluginStore;
async function createPluginStore(
projectName?: string,
options?: { centralGlobalDir?: string },
): Promise<PluginStore> {
try {
const context = await resolveProject(projectName, process.cwd(), options?.centralGlobalDir);
const pluginStore = context.store.getPluginStore();
await pluginStore.init();
return pluginStore;
} catch {
const projectPath = await getProjectPath(projectName);
const pluginStore = new PluginStore(projectPath, {
centralGlobalDir: options?.centralGlobalDir ?? resolveGlobalDir(),
});
await pluginStore.init();
return pluginStore;
}
}
/**

View File

@@ -10,10 +10,9 @@
*/
import type { AddressInfo } from "node:net";
import { dirname, join } from "node:path";
import { join } from "node:path";
import {
CentralCore,
PluginStore,
PluginLoader,
getTaskMergeBlocker,
INSIGHT_EXTRACTION_SCHEDULE_NAME,
@@ -425,11 +424,7 @@ export async function runServe(
// internally for task-execution plugin hooks. These instances here serve the
// HTTP plugin-management API routes and are intentionally separate.
//
const pluginStoreRootDir =
typeof (store as { getRootDir?: () => string }).getRootDir === "function"
? store.getRootDir()
: dirname(store.getFusionDir());
const pluginStore = new PluginStore(pluginStoreRootDir);
const pluginStore = store.getPluginStore();
await pluginStore.init();
// ── PluginLoader: plugin lifecycle management ───────────────────────

View File

@@ -1,6 +1,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { PluginStore } from "../plugin-store.js";
import { Database, toJson } from "../db.js";
import { CentralDatabase } from "../central-db.js";
import { rm } from "node:fs/promises";
import { join } from "node:path";
import { mkdtempSync } from "node:fs";
@@ -142,7 +143,7 @@ describe("PluginStore", () => {
}
});
it("is idempotent when init runs multiple times", async () => {
it("is idempotent across repeated init and store rehydration", async () => {
const migrationProject = makeTmpDir();
const migrationCentral = makeTmpDir();
try {
@@ -157,14 +158,59 @@ describe("PluginStore", () => {
await migrationStore.init();
await migrationStore.init();
const plugins = await migrationStore.listPlugins();
const reopenedStore = new PluginStore(migrationProject, { centralGlobalDir: migrationCentral });
await reopenedStore.init();
const plugins = await reopenedStore.listPlugins();
expect(plugins.filter((plugin) => plugin.id === "legacy-idempotent")).toHaveLength(1);
const centralDb = new CentralDatabase(migrationCentral);
centralDb.init();
const installCount = centralDb
.prepare("SELECT COUNT(*) as count FROM plugin_installs WHERE id = ?")
.get("legacy-idempotent") as { count: number };
expect(installCount.count).toBe(1);
const localDb = new Database(join(migrationProject, ".fusion"));
localDb.init();
const marker = localDb
.prepare("SELECT value FROM __meta WHERE key = 'pluginCentralMigrationV1'")
.get() as { value: string } | undefined;
expect(marker?.value).toBe("done");
} finally {
await rm(migrationProject, { recursive: true, force: true });
await rm(migrationCentral, { recursive: true, force: true });
}
});
it("shows globally installed plugin in another project as disabled until explicitly enabled", async () => {
const projectA = makeTmpDir();
const projectB = makeTmpDir();
const sharedCentral = makeTmpDir();
try {
const storeA = new PluginStore(projectA, { centralGlobalDir: sharedCentral });
const storeB = new PluginStore(projectB, { centralGlobalDir: sharedCentral });
await storeA.init();
await storeB.init();
await storeA.registerPlugin({
manifest: makeManifest({ id: "shared-global", name: "Shared Global" }),
path: "/plugins/shared-global",
});
const inProjectB = await storeB.getPlugin("shared-global");
expect(inProjectB.enabled).toBe(false);
await storeB.enablePlugin("shared-global");
const enabledInProjectB = await storeB.getPlugin("shared-global");
expect(enabledInProjectB.enabled).toBe(true);
} finally {
await rm(projectA, { recursive: true, force: true });
await rm(projectB, { recursive: true, force: true });
await rm(sharedCentral, { recursive: true, force: true });
}
});
it("keeps latest updatedAt install metadata across projects while preserving per-project enablement", async () => {
const projectA = makeTmpDir();
const projectB = makeTmpDir();

View File

@@ -25,6 +25,7 @@ const mockedRunCommandAsync = vi.mocked(runCommandAsync);
import { TaskStore, TaskHasDependentsError } from "../store.js";
import { AgentStore } from "../agent-store.js";
import { CentralDatabase } from "../central-db.js";
import { appendFile, readFile, writeFile, mkdir, rm, readdir, unlink } from "node:fs/promises";
import { join } from "node:path";
import { mkdtempSync, existsSync } from "node:fs";
@@ -134,6 +135,37 @@ describe("TaskStore", () => {
`).run(taskId, timestamp, text, type, detail ?? null, agent ?? null);
}
describe("plugin store routing", () => {
it("routes plugin writes to the configured central global dir", async () => {
const pluginStore = store.getPluginStore();
await pluginStore.init();
await pluginStore.registerPlugin({
manifest: {
id: "taskstore-plugin",
name: "TaskStore Plugin",
version: "1.0.0",
},
path: "/tmp/taskstore-plugin",
});
const centralDb = new CentralDatabase(globalDir);
centralDb.init();
const installCount = centralDb
.prepare("SELECT COUNT(*) as count FROM plugin_installs WHERE id = ?")
.get("taskstore-plugin") as { count: number };
expect(installCount.count).toBe(1);
const localCount = store
.getDatabase()
.prepare("SELECT COUNT(*) as count FROM plugins WHERE id = ?")
.get("taskstore-plugin") as { count: number };
expect(localCount.count).toBe(0);
centralDb.close();
});
});
// ── Prompt generation (no duplicate description) ───────────────
describe("prompt generation", () => {

View File

@@ -1635,6 +1635,10 @@ export class Database {
if (version < 24) {
this.applyMigration(24, () => {
// Legacy project-local plugin table (introduced in v24) is retained for
// one-shot migration reads by PluginStore.migrateLegacyProjectRows().
// Post-FN-3722 all new plugin install writes must go to central
// plugin_installs + project_plugin_states tables; writes here are a bug.
this.db.exec(`
CREATE TABLE IF NOT EXISTS plugins (
id TEXT PRIMARY KEY,

View File

@@ -342,11 +342,11 @@ export class PluginStore extends EventEmitter<PluginStoreEvents> {
row.updatedAt,
);
}
this.localDb
.prepare("INSERT INTO __meta (key, value) VALUES ('pluginCentralMigrationV1', 'done') ON CONFLICT(key) DO UPDATE SET value = excluded.value")
.run();
});
this.localDb
.prepare("INSERT INTO __meta (key, value) VALUES ('pluginCentralMigrationV1', 'done') ON CONFLICT(key) DO UPDATE SET value = excluded.value")
.run();
}
async registerPlugin(input: PluginRegistrationInput): Promise<PluginInstallation> {

View File

@@ -550,6 +550,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
// Tests that need cross-instance persistence (open store A, close,
// open store B on the same dir, expect data) must leave this false.
private readonly inMemoryDb: boolean;
private readonly globalSettingsDir?: string;
constructor(
private rootDir: string,
@@ -565,6 +566,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
this.inMemoryDb = options?.inMemoryDb === true;
const resolvedGlobalSettingsDir = globalSettingsDir
?? (process.env.VITEST === "true" ? join(rootDir, ".fusion-global-settings") : undefined);
this.globalSettingsDir = resolvedGlobalSettingsDir;
this.globalSettingsStore = new GlobalSettingsStore(resolvedGlobalSettingsDir);
}
@@ -6804,7 +6806,9 @@ ${notificationsSection}`;
*/
getPluginStore(): PluginStore {
if (!this.pluginStore) {
this.pluginStore = new PluginStore(this.rootDir);
// PluginStore persists install/state rows in central DB, so it must use
// the same resolved global settings directory as TaskStore.
this.pluginStore = new PluginStore(this.rootDir, { centralGlobalDir: this.globalSettingsDir });
}
return this.pluginStore;
}

View File

@@ -13,9 +13,13 @@
// @vitest-environment node
import { describe, it, expect, vi, beforeEach } from "vitest";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import express from "express";
import type { TaskStore, PluginStore, PluginLoader, PluginInstallation } from "@fusion/core";
import { mkdtempSync } from "node:fs";
import { rm } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { Database, CentralDatabase, type TaskStore, type PluginStore, type PluginLoader, type PluginInstallation } from "@fusion/core";
import * as fusionCore from "@fusion/core";
import { createApiRoutes } from "../routes.js";
import { createPluginRouter } from "../plugin-routes.js";
@@ -343,6 +347,109 @@ describe("POST /api/plugins mode:install — package root path", () => {
});
// ══════════════════════════════════════════════════════════════════
describe("POST /api/plugins central persistence integration", () => {
let projectDir: string;
let centralDir: string;
beforeEach(() => {
projectDir = mkdtempSync(join(tmpdir(), "plugin-route-project-"));
centralDir = mkdtempSync(join(tmpdir(), "plugin-route-central-"));
});
afterEach(async () => {
await rm(projectDir, { recursive: true, force: true });
await rm(centralDir, { recursive: true, force: true });
});
function buildRealApp(pluginStore: PluginStore) {
const pluginLoader = createMockPluginLoader();
const store = createMockTaskStore({
getRootDir: vi.fn().mockReturnValue(projectDir),
getPluginStore: vi.fn().mockReturnValue(pluginStore),
});
const app = express();
app.use(express.json());
app.use("/api", createApiRoutes(store, { pluginStore, pluginLoader }));
return app;
}
it("writes register mode installs to central tables and not project-local plugins", async () => {
const pluginStore = new fusionCore.PluginStore(projectDir, { centralGlobalDir: centralDir });
await pluginStore.init();
const app = buildRealApp(pluginStore);
const res = await REQUEST(app, "POST", "/api/plugins", {
mode: "register",
id: "central-register",
name: "Central Register",
version: "1.0.0",
path: "/tmp/central-register.js",
});
expect(res.status).toBe(201);
const centralDb = new CentralDatabase(centralDir);
centralDb.init();
const installCount = centralDb
.prepare("SELECT COUNT(*) as count FROM plugin_installs WHERE id = ?")
.get("central-register") as { count: number };
const stateCount = centralDb
.prepare("SELECT COUNT(*) as count FROM project_plugin_states WHERE pluginId = ?")
.get("central-register") as { count: number };
const localDb = new Database(join(projectDir, ".fusion"));
localDb.init();
const legacyCount = localDb
.prepare("SELECT COUNT(*) as count FROM plugins WHERE id = ?")
.get("central-register") as { count: number };
expect(installCount.count).toBe(1);
expect(stateCount.count).toBe(1);
expect(legacyCount.count).toBe(0);
centralDb.close();
localDb.close();
});
it("writes install mode installs to central tables and not project-local plugins", async () => {
const pluginStore = new fusionCore.PluginStore(projectDir, { centralGlobalDir: centralDir });
await pluginStore.init();
const pluginPath = "/tmp/my-plugin";
mockAccess.mockImplementation((p: string) => {
if (p === pluginPath || p === `${pluginPath}/manifest.json`) return Promise.resolve();
return Promise.reject(new Error("not found"));
});
mockReadFile.mockResolvedValueOnce(JSON.stringify(VALID_MANIFEST));
const app = buildRealApp(pluginStore);
const res = await REQUEST(app, "POST", "/api/plugins", {
mode: "install",
path: pluginPath,
});
expect(res.status).toBe(201);
const centralDb = new CentralDatabase(centralDir);
centralDb.init();
const installCount = centralDb
.prepare("SELECT COUNT(*) as count FROM plugin_installs WHERE id = ?")
.get("my-plugin") as { count: number };
const localDb = new Database(join(projectDir, ".fusion"));
localDb.init();
const legacyCount = localDb
.prepare("SELECT COUNT(*) as count FROM plugins WHERE id = ?")
.get("my-plugin") as { count: number };
expect(installCount.count).toBe(1);
expect(legacyCount.count).toBe(0);
centralDb.close();
localDb.close();
});
});
describe("POST /api/plugins mode:install — negative paths", () => {
let pluginStore: PluginStore;
let pluginLoader: PluginLoader;