@powerhousedao/switchboard 6.2.3-dev.70 → 6.2.3-dev.72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/.tsbuild/test/default-drive-slug.test.d.ts +2 -0
  2. package/.tsbuild/test/default-drive-slug.test.d.ts.map +1 -0
  3. package/.tsbuild/test/plugin-config-schemas.test.d.ts +2 -0
  4. package/.tsbuild/test/plugin-config-schemas.test.d.ts.map +1 -0
  5. package/.tsbuild/test/port-probe.test.d.ts +2 -0
  6. package/.tsbuild/test/port-probe.test.d.ts.map +1 -0
  7. package/.tsbuild/test/shutdown.test.d.ts +2 -0
  8. package/.tsbuild/test/shutdown.test.d.ts.map +1 -0
  9. package/.tsbuild/test/store-lock.test.d.ts +2 -0
  10. package/.tsbuild/test/store-lock.test.d.ts.map +1 -0
  11. package/.tsbuild/test/workflows-plugin-config.test.d.ts +2 -0
  12. package/.tsbuild/test/workflows-plugin-config.test.d.ts.map +1 -0
  13. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  14. package/CHANGELOG.md +44 -0
  15. package/dist/index.mjs +1 -1
  16. package/dist/{mcp-cNWW82NH.mjs → mcp-SsBK14Jm.mjs} +10 -5
  17. package/dist/mcp-SsBK14Jm.mjs.map +1 -0
  18. package/dist/plugins/attachments.d.mts +10 -0
  19. package/dist/plugins/attachments.d.mts.map +1 -1
  20. package/dist/plugins/attachments.mjs +4 -4
  21. package/dist/plugins/mcp.d.mts +10 -0
  22. package/dist/plugins/mcp.d.mts.map +1 -1
  23. package/dist/plugins/mcp.mjs +4 -4
  24. package/dist/plugins/privacy.d.mts +10 -0
  25. package/dist/plugins/privacy.d.mts.map +1 -1
  26. package/dist/plugins/privacy.mjs +4 -4
  27. package/dist/plugins/workflows.d.mts +46 -3
  28. package/dist/plugins/workflows.d.mts.map +1 -1
  29. package/dist/plugins/workflows.mjs +4 -4
  30. package/dist/{privacy-C8KVimKF.mjs → privacy-BsFl7GzK.mjs} +9 -4
  31. package/dist/{privacy-C8KVimKF.mjs.map → privacy-BsFl7GzK.mjs.map} +1 -1
  32. package/dist/{server-CF_mjyJi.mjs → server-CrWPtMG6.mjs} +114 -29
  33. package/dist/server-CrWPtMG6.mjs.map +1 -0
  34. package/dist/server.d.mts +18 -15
  35. package/dist/server.d.mts.map +1 -1
  36. package/dist/server.mjs +3 -3
  37. package/dist/{utils-uaBlzyjS.mjs → utils-Dh845exv.mjs} +42 -9
  38. package/dist/utils-Dh845exv.mjs.map +1 -0
  39. package/dist/utils.d.mts +8 -2
  40. package/dist/utils.d.mts.map +1 -1
  41. package/dist/utils.mjs +3 -3
  42. package/dist/{workflows-qKtqZhn3.mjs → workflows-fsBcElEi.mjs} +111 -67
  43. package/dist/{workflows-qKtqZhn3.mjs.map → workflows-fsBcElEi.mjs.map} +1 -1
  44. package/package.json +18 -17
  45. package/test/attachments/routes.test.ts +26 -11
  46. package/test/default-drive-slug.test.ts +97 -0
  47. package/test/plugin-config-schemas.test.ts +83 -0
  48. package/test/port-probe.test.ts +45 -0
  49. package/test/shutdown.test.ts +278 -0
  50. package/test/store-lock.test.ts +65 -0
  51. package/test/workflows-plugin-config.test.ts +77 -0
  52. package/dist/mcp-cNWW82NH.mjs.map +0 -1
  53. package/dist/server-CF_mjyJi.mjs.map +0 -1
  54. package/dist/utils-uaBlzyjS.mjs.map +0 -1
@@ -0,0 +1,97 @@
1
+ import {
2
+ ReactorBuilder,
3
+ ReactorClientBuilder,
4
+ type InProcessReactorClientModule,
5
+ } from "@powerhousedao/reactor";
6
+ import { driveDocumentModelModule } from "@powerhousedao/shared/document-drive";
7
+ import type { DriveInput } from "@powerhousedao/shared/document-drive";
8
+ import {
9
+ withSignaturePolicy,
10
+ type DocumentModelModule,
11
+ } from "@powerhousedao/shared/document-model";
12
+ import { documentModelDocumentModelModule } from "document-model";
13
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
14
+ import { addDefaultDrive } from "../src/utils.mjs";
15
+
16
+ const PORT = 4001;
17
+
18
+ const workflows = (id: string): DriveInput =>
19
+ ({
20
+ id,
21
+ slug: "workflows",
22
+ global: { name: "Workflows" },
23
+ local: {
24
+ availableOffline: true,
25
+ listeners: [],
26
+ sharingType: "public",
27
+ triggers: [],
28
+ },
29
+ }) as DriveInput;
30
+
31
+ describe("addDefaultDrive with a slug another document holds", () => {
32
+ let module: InProcessReactorClientModule;
33
+ const logger = { error: vi.fn() };
34
+
35
+ beforeEach(async () => {
36
+ logger.error.mockClear();
37
+ module = await new ReactorClientBuilder()
38
+ .withReactorBuilder(
39
+ new ReactorBuilder().withDocumentModelSources([
40
+ driveDocumentModelModule as unknown as DocumentModelModule,
41
+ documentModelDocumentModelModule as unknown as DocumentModelModule,
42
+ ]),
43
+ )
44
+ .buildModule();
45
+ });
46
+
47
+ afterEach(() => {
48
+ module.reactor.kill();
49
+ });
50
+
51
+ const isCreated = (id: string) =>
52
+ module.client.get(id).then(
53
+ () => true,
54
+ () => false,
55
+ );
56
+
57
+ it("creates the drive when the slug is free", async () => {
58
+ await expect(
59
+ addDefaultDrive(module.client, workflows("workflows-a"), PORT, logger),
60
+ ).resolves.toBe(`http://localhost:${PORT}/d/workflows-a`);
61
+ await expect(module.client.resolveIdOrSlug("workflows")).resolves.toBe(
62
+ "workflows-a",
63
+ );
64
+ });
65
+
66
+ // A project moved to another folder hashes its drive ids anew.
67
+ it("serves the drive that holds the slug instead of creating a twin", async () => {
68
+ await addDefaultDrive(
69
+ module.client,
70
+ workflows("workflows-a"),
71
+ PORT,
72
+ logger,
73
+ );
74
+ await expect(
75
+ addDefaultDrive(module.client, workflows("workflows-b"), PORT, logger),
76
+ ).resolves.toBe(`http://localhost:${PORT}/d/workflows-a`);
77
+ expect(await isCreated("workflows-b")).toBe(false);
78
+ expect(logger.error).not.toHaveBeenCalled();
79
+ });
80
+
81
+ it("logs an error and creates nothing when another kind of document holds it", async () => {
82
+ const other = withSignaturePolicy(
83
+ documentModelDocumentModelModule.utils.createDocument(),
84
+ "legacy",
85
+ );
86
+ other.header.slug = "workflows";
87
+ await module.client.create(other);
88
+
89
+ await expect(
90
+ addDefaultDrive(module.client, workflows("workflows-c"), PORT, logger),
91
+ ).resolves.toBeUndefined();
92
+ expect(await isCreated("workflows-c")).toBe(false);
93
+ expect(logger.error).toHaveBeenCalledWith(
94
+ `The default drive "workflows" was not created: the slug belongs to powerhouse/document-model document ${other.header.id}.`,
95
+ );
96
+ });
97
+ });
@@ -0,0 +1,83 @@
1
+ import type { PluginEntry } from "@powerhousedao/host-core";
2
+ import { describe, expect, it } from "vitest";
3
+ import { attachmentsPlugin } from "../src/plugins/attachments.mjs";
4
+ import { mcpPlugin } from "../src/plugins/mcp.mjs";
5
+ import { privacyPlugin } from "../src/plugins/privacy.mjs";
6
+ import { workflowsPlugin } from "../src/plugins/workflows.mjs";
7
+
8
+ // typed-host-configs 1.4 / T2 lane C: every built-in switchboard plugin
9
+ // declares a zod configSchema, and its module augments PHPluginConfigs so a
10
+ // host.js entry's config is typed by specifier.
11
+
12
+ /** The typed object form of a known specifier's entry. (The bare-string form
13
+ * and the untyped `{ module: string }` fallback do not narrow by specifier.) */
14
+ type EntryFor<M extends string> = Extract<PluginEntry, { module: M }>;
15
+
16
+ describe("switchboard plugin configSchemas", () => {
17
+ it.each([
18
+ ["mcp", mcpPlugin],
19
+ ["attachments", attachmentsPlugin],
20
+ ["privacy", privacyPlugin],
21
+ ])("%s takes no config: {} passes, any key is a typo", (_, plugin) => {
22
+ expect(plugin.configSchema?.safeParse({}).success).toBe(true);
23
+ expect(plugin.configSchema?.safeParse({ enabled: true }).success).toBe(
24
+ false,
25
+ );
26
+ });
27
+
28
+ it("workflows rejects a typo'd key and accepts drive: false", () => {
29
+ expect(
30
+ workflowsPlugin.configSchema?.safeParse({ drive: false }).success,
31
+ ).toBe(true);
32
+ expect(
33
+ workflowsPlugin.configSchema?.safeParse({ drives: false }).success,
34
+ ).toBe(false);
35
+ });
36
+ });
37
+
38
+ describe("PHPluginConfigs augmentation (type level)", () => {
39
+ it("types the switchboard workflows entry: drive is { slug, name, … } | false", () => {
40
+ const entries: PluginEntry[] = [
41
+ "@powerhousedao/switchboard/plugins/mcp",
42
+ {
43
+ module: "@powerhousedao/switchboard/plugins/workflows",
44
+ config: { drive: { slug: "workflows", name: "Workflows" } },
45
+ },
46
+ {
47
+ module: "@powerhousedao/switchboard/plugins/workflows",
48
+ config: { drive: false },
49
+ },
50
+ ];
51
+ // Positive cases pin that the entry type exists (not `never`), so the
52
+ // expect-errors below fail for the right reason.
53
+ const declared: EntryFor<"@powerhousedao/switchboard/plugins/workflows"> = {
54
+ module: "@powerhousedao/switchboard/plugins/workflows",
55
+ config: { drive: { slug: "flows", name: "Flows" } },
56
+ };
57
+ const off: PHPluginConfigs["@powerhousedao/switchboard/plugins/workflows"] =
58
+ { drive: false };
59
+ const urlDrive: EntryFor<"@powerhousedao/switchboard/plugins/workflows"> = {
60
+ module: "@powerhousedao/switchboard/plugins/workflows",
61
+ // @ts-expect-error -- the switchboard workflows drive is a declaration, not a URL (that is Connect's)
62
+ config: { drive: "http://localhost:4001/d/workflows" },
63
+ };
64
+ const typo: EntryFor<"@powerhousedao/switchboard/plugins/workflows"> = {
65
+ module: "@powerhousedao/switchboard/plugins/workflows",
66
+ // @ts-expect-error -- `drives` is not a workflows config key
67
+ config: { drives: false },
68
+ };
69
+ expect([entries, declared, off, urlDrive, typo]).toBeDefined();
70
+ });
71
+
72
+ it("types the no-config plugins as taking no keys", () => {
73
+ const mcp: PHPluginConfigs["@powerhousedao/switchboard/plugins/mcp"] = {
74
+ // @ts-expect-error -- mcp takes no config
75
+ enabled: true,
76
+ };
77
+ const none: PHPluginConfigs["@powerhousedao/switchboard/plugins/privacy"] =
78
+ {};
79
+ const attachments: EntryFor<"@powerhousedao/switchboard/plugins/attachments"> =
80
+ { module: "@powerhousedao/switchboard/plugins/attachments", config: {} };
81
+ expect([mcp, none, attachments]).toBeDefined();
82
+ });
83
+ });
@@ -0,0 +1,45 @@
1
+ import net from "node:net";
2
+ import { afterEach, describe, expect, it, vi } from "vitest";
3
+ import { isPortAvailable } from "../src/server.mjs";
4
+
5
+ // A host without IPv6, e.g. a container: binding `::` fails before the port is tried.
6
+ function withoutIpv6() {
7
+ const { listen } = net.Server.prototype as unknown as {
8
+ listen: (this: net.Server, ...args: unknown[]) => net.Server;
9
+ };
10
+ return vi.spyOn(net.Server.prototype, "listen").mockImplementation(function (
11
+ this: net.Server,
12
+ ...args: unknown[]
13
+ ) {
14
+ const [options] = args as [{ host?: string } | undefined];
15
+ if (options?.host === "::") {
16
+ const error = Object.assign(new Error("address family not supported"), {
17
+ code: "EAFNOSUPPORT",
18
+ });
19
+ queueMicrotask(() => this.emit("error", error));
20
+ return this;
21
+ }
22
+ return listen.apply(this, args);
23
+ });
24
+ }
25
+
26
+ afterEach(() => {
27
+ vi.restoreAllMocks();
28
+ });
29
+
30
+ describe("isPortAvailable", () => {
31
+ it("probes IPv4 on a host without IPv6", async () => {
32
+ withoutIpv6();
33
+ const busy = net.createServer();
34
+ await new Promise<void>((resolve) =>
35
+ busy.listen({ port: 0, host: "0.0.0.0" }, resolve),
36
+ );
37
+ const { port } = busy.address() as net.AddressInfo;
38
+ try {
39
+ await expect(isPortAvailable(port)).resolves.toBe(false);
40
+ } finally {
41
+ await new Promise((resolve) => busy.close(resolve));
42
+ }
43
+ await expect(isPortAvailable(port)).resolves.toBe(true);
44
+ });
45
+ });
@@ -0,0 +1,278 @@
1
+ import { PGlite } from "@electric-sql/pglite";
2
+ import {
3
+ ReactorBuilder,
4
+ ReactorClientBuilder,
5
+ type Database,
6
+ type InProcessReactorClientModule,
7
+ } from "@powerhousedao/reactor";
8
+ import type { ILogger } from "document-model";
9
+ import { Kysely } from "kysely";
10
+ import { PGliteDialect } from "kysely-pglite-dialect";
11
+ import { mkdtemp, rm } from "node:fs/promises";
12
+ import { createServer } from "node:net";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ import {
16
+ afterEach,
17
+ beforeEach,
18
+ describe,
19
+ expect,
20
+ it,
21
+ vi,
22
+ type MockInstance,
23
+ } from "vitest";
24
+ import { applySwitchboardReactorDefaults } from "../src/builder-defaults.mjs";
25
+ import { startSwitchboard } from "../src/server.mjs";
26
+
27
+ type Switchboard = Awaited<ReturnType<typeof startSwitchboard>>;
28
+
29
+ async function freePort(): Promise<number> {
30
+ const server = createServer();
31
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
32
+ const address = server.address();
33
+ await new Promise<void>((resolve) => server.close(() => resolve()));
34
+ if (!address || typeof address === "string") throw new Error("no port");
35
+ return address.port;
36
+ }
37
+
38
+ /** True when nothing holds `port` any more. */
39
+ async function portIsFree(port: number): Promise<boolean> {
40
+ const server = createServer();
41
+ return new Promise((resolve) => {
42
+ server.once("error", () => resolve(false));
43
+ server.listen(port, () => server.close(() => resolve(true)));
44
+ });
45
+ }
46
+
47
+ /** initServer returns the reactor-api handle too; SwitchboardReactor does not
48
+ * type it. Spying on its dispose shows how often the api was drained. */
49
+ function apiOf(sb: object): { dispose: () => Promise<void> } {
50
+ const api: unknown = Reflect.get(sb, "api");
51
+ if (
52
+ typeof api !== "object" ||
53
+ api === null ||
54
+ typeof Reflect.get(api, "dispose") !== "function"
55
+ ) {
56
+ throw new Error("switchboard returned no api handle");
57
+ }
58
+ return api as { dispose: () => Promise<void> };
59
+ }
60
+
61
+ function stubLogger(): ILogger {
62
+ const logger = {
63
+ verbose: vi.fn(),
64
+ debug: vi.fn(),
65
+ info: vi.fn(),
66
+ warn: vi.fn(),
67
+ error: vi.fn(),
68
+ child: vi.fn(),
69
+ };
70
+ logger.child.mockReturnValue(logger);
71
+ return logger as unknown as ILogger;
72
+ }
73
+
74
+ describe("SwitchboardReactor.shutdown", () => {
75
+ let tempRoot: string;
76
+ let previousReactorDb: string | undefined;
77
+ let switchboard: Switchboard | undefined;
78
+ const signalsBefore = {
79
+ SIGINT: new Set<NodeJS.SignalsListener>(),
80
+ SIGTERM: new Set<NodeJS.SignalsListener>(),
81
+ };
82
+ const addedListeners = (signal: "SIGINT" | "SIGTERM") =>
83
+ (process.listeners(signal) as NodeJS.SignalsListener[]).filter(
84
+ (listener) => !signalsBefore[signal].has(listener),
85
+ );
86
+
87
+ beforeEach(async () => {
88
+ tempRoot = await mkdtemp(join(tmpdir(), "switchboard-shutdown-"));
89
+ previousReactorDb = process.env.PH_REACTOR_DATABASE_URL;
90
+ process.env.PH_REACTOR_DATABASE_URL = join(tempRoot, "reactor-storage");
91
+ for (const signal of ["SIGINT", "SIGTERM"] as const) {
92
+ signalsBefore[signal] = new Set(
93
+ process.listeners(signal) as NodeJS.SignalsListener[],
94
+ );
95
+ }
96
+ });
97
+
98
+ afterEach(async () => {
99
+ await switchboard?.shutdown().catch(() => undefined);
100
+ switchboard = undefined;
101
+ vi.restoreAllMocks();
102
+ // The owned reactor's withSignalHandlers() listeners outlive the test.
103
+ for (const signal of ["SIGINT", "SIGTERM"] as const) {
104
+ for (const listener of addedListeners(signal)) {
105
+ process.removeListener(signal, listener);
106
+ }
107
+ }
108
+ if (previousReactorDb === undefined) {
109
+ delete process.env.PH_REACTOR_DATABASE_URL;
110
+ } else {
111
+ process.env.PH_REACTOR_DATABASE_URL = previousReactorDb;
112
+ }
113
+ await rm(tempRoot, { recursive: true, force: true });
114
+ });
115
+
116
+ async function start(
117
+ reactor?: InProcessReactorClientModule,
118
+ ): Promise<Switchboard> {
119
+ switchboard = await startSwitchboard({
120
+ reactor,
121
+ workflows: { enabled: false },
122
+ dbPath: join(tempRoot, "read-model"),
123
+ port: await freePort(),
124
+ strictPort: true,
125
+ mcp: false,
126
+ disableLocalPackages: true,
127
+ identity: { keypairPath: join(tempRoot, "identity.json") },
128
+ logger: stubLogger(),
129
+ });
130
+ return switchboard;
131
+ }
132
+
133
+ /**
134
+ * Spies on the reactor module the switchboard builds for itself, from the
135
+ * moment it is built (an aborted boot tears it down before returning).
136
+ */
137
+ function watchOwnedReactor() {
138
+ const realBuild = Object.getOwnPropertyDescriptor(
139
+ ReactorClientBuilder.prototype,
140
+ "buildModule",
141
+ )?.value as (
142
+ this: ReactorClientBuilder,
143
+ ) => Promise<InProcessReactorClientModule>;
144
+ const watched: {
145
+ kill?: MockInstance<() => unknown>;
146
+ destroy?: MockInstance<() => Promise<void>>;
147
+ } = {};
148
+ vi.spyOn(ReactorClientBuilder.prototype, "buildModule").mockImplementation(
149
+ async function (this: ReactorClientBuilder) {
150
+ const built = await realBuild.call(this);
151
+ if (!built.reactorModule) throw new Error("no reactor module built");
152
+ watched.kill = vi.spyOn(built.reactorModule.reactor, "kill");
153
+ watched.destroy = vi.spyOn(built.reactorModule.database, "destroy");
154
+ return built;
155
+ },
156
+ );
157
+ return watched;
158
+ }
159
+
160
+ /** Stubbed before boot: the signal handler binds process.exit when the
161
+ * reactor is built. */
162
+ function stubExit() {
163
+ const codes: Array<number | undefined> = [];
164
+ let resolveExit: (code: number | undefined) => void = () => undefined;
165
+ const exited = new Promise<number | undefined>((resolve) => {
166
+ resolveExit = resolve;
167
+ });
168
+ vi.spyOn(process, "exit").mockImplementation((code) => {
169
+ const value = code === undefined ? undefined : Number(code);
170
+ codes.push(value);
171
+ resolveExit(value);
172
+ return undefined as never;
173
+ });
174
+ return { codes, exited };
175
+ }
176
+
177
+ function raiseSigint(): void {
178
+ const sigint = addedListeners("SIGINT");
179
+ expect(sigint).toHaveLength(1);
180
+ sigint[0]!("SIGINT");
181
+ }
182
+
183
+ it("stops an owned reactor and frees the port once, however often it is called", async () => {
184
+ const reactor = watchOwnedReactor();
185
+ const exit = stubExit();
186
+
187
+ const sb = await start();
188
+ const dispose = vi.spyOn(apiOf(sb), "dispose");
189
+ expect(await portIsFree(sb.port)).toBe(false);
190
+
191
+ await Promise.all([sb.shutdown(), sb.shutdown()]);
192
+ await sb.shutdown();
193
+
194
+ expect(reactor.kill).toHaveBeenCalledTimes(1);
195
+ expect(dispose).toHaveBeenCalledTimes(1);
196
+ expect(reactor.destroy).toHaveBeenCalledTimes(1);
197
+ expect(await portIsFree(sb.port)).toBe(true);
198
+ expect(exit.codes).toEqual([]);
199
+
200
+ // A later SIGINT joins the finished teardown and only exits.
201
+ raiseSigint();
202
+ expect(await exit.exited).toBe(0);
203
+ expect(exit.codes).toEqual([0]);
204
+ expect(reactor.kill).toHaveBeenCalledTimes(1);
205
+ expect(dispose).toHaveBeenCalledTimes(1);
206
+ expect(reactor.destroy).toHaveBeenCalledTimes(1);
207
+ }, 60_000);
208
+
209
+ it("an aborted boot tears the owned reactor down once, through its shutdown", async () => {
210
+ const reactor = watchOwnedReactor();
211
+ const exit = stubExit();
212
+ const previousSource = process.env.RENOWN_SOURCE;
213
+ // No loaded package serves the renown read model: the boot aborts after
214
+ // the reactor and the api are up.
215
+ process.env.RENOWN_SOURCE = "self";
216
+ const port = await freePort();
217
+
218
+ try {
219
+ await expect(
220
+ startSwitchboard({
221
+ workflows: { enabled: false },
222
+ dbPath: join(tempRoot, "read-model"),
223
+ port,
224
+ strictPort: true,
225
+ mcp: false,
226
+ disableLocalPackages: true,
227
+ identity: { keypairPath: join(tempRoot, "identity.json") },
228
+ logger: stubLogger(),
229
+ }),
230
+ ).rejects.toThrow(/no loaded package serves/);
231
+ } finally {
232
+ if (previousSource === undefined) {
233
+ delete process.env.RENOWN_SOURCE;
234
+ } else {
235
+ process.env.RENOWN_SOURCE = previousSource;
236
+ }
237
+ }
238
+
239
+ expect(reactor.kill).toHaveBeenCalledTimes(1);
240
+ expect(reactor.destroy).toHaveBeenCalledTimes(1);
241
+ expect(await portIsFree(port)).toBe(true);
242
+
243
+ raiseSigint();
244
+ expect(await exit.exited).toBe(0);
245
+ expect(reactor.kill).toHaveBeenCalledTimes(1);
246
+ expect(reactor.destroy).toHaveBeenCalledTimes(1);
247
+ }, 60_000);
248
+
249
+ it("drains the api once and leaves a caller-provided reactor running", async () => {
250
+ const database = new Kysely<Database>({
251
+ dialect: new PGliteDialect(new PGlite()),
252
+ });
253
+ const reactorBuilder = new ReactorBuilder().withKysely(database);
254
+ const clientBuilder = new ReactorClientBuilder().withReactorBuilder(
255
+ reactorBuilder,
256
+ );
257
+ applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, {
258
+ signalHandlers: false,
259
+ });
260
+ const caller = await clientBuilder.buildModule();
261
+ const callerModule = caller.reactorModule;
262
+ if (!callerModule) throw new Error("caller built no reactor module");
263
+
264
+ try {
265
+ const sb = await start(caller);
266
+ const kill = vi.spyOn(callerModule.reactor, "kill");
267
+ const dispose = vi.spyOn(apiOf(sb), "dispose");
268
+
269
+ await Promise.all([sb.shutdown(), sb.shutdown()]);
270
+
271
+ expect(dispose).toHaveBeenCalledTimes(1);
272
+ expect(kill).not.toHaveBeenCalled();
273
+ expect(await portIsFree(sb.port)).toBe(true);
274
+ } finally {
275
+ await callerModule.shutdown();
276
+ }
277
+ }, 60_000);
278
+ });
@@ -0,0 +1,65 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { afterEach, describe, expect, it } from "vitest";
5
+ import {
6
+ acquireStoreLocks,
7
+ releaseStoreLocks,
8
+ StoreInUseError,
9
+ } from "../src/store-lock.mjs";
10
+
11
+ const dirs: string[] = [];
12
+ function store(): string {
13
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "ph-store-lock-"));
14
+ dirs.push(root);
15
+ return path.join(root, "reactor-storage");
16
+ }
17
+ afterEach(() => {
18
+ releaseStoreLocks();
19
+ for (const d of dirs.splice(0))
20
+ fs.rmSync(d, { recursive: true, force: true });
21
+ });
22
+
23
+ const lockOf = (dir: string) => `${path.resolve(dir)}.lock`;
24
+ const lockPid = (dir: string) =>
25
+ (JSON.parse(fs.readFileSync(lockOf(dir), "utf8")) as { pid: number }).pid;
26
+ const claim = (dir: string, pid: number) =>
27
+ fs.writeFileSync(
28
+ lockOf(dir),
29
+ JSON.stringify({ pid, startedAt: "earlier", command: "ph run vetra" }),
30
+ );
31
+
32
+ describe("acquireStoreLocks", () => {
33
+ it("writes a sibling lock (never inside the data dir) and releases it", () => {
34
+ const dir = store();
35
+ acquireStoreLocks([dir]);
36
+ expect(lockPid(dir)).toBe(process.pid);
37
+ expect(fs.existsSync(dir)).toBe(false); // initdb still gets an empty dir
38
+ releaseStoreLocks();
39
+ expect(fs.existsSync(lockOf(dir))).toBe(false);
40
+ });
41
+
42
+ it("refuses a store held by another live process, naming it", () => {
43
+ const dir = store();
44
+ claim(dir, 4242);
45
+ expect(() => acquireStoreLocks([dir], (pid) => pid === 4242)).toThrow(
46
+ StoreInUseError,
47
+ );
48
+ expect(() => acquireStoreLocks([dir], (pid) => pid === 4242)).toThrow(
49
+ /pid 4242.*ph run vetra/,
50
+ );
51
+ });
52
+
53
+ it("takes over a stale lock from a dead (hard-killed) process", () => {
54
+ const dir = store();
55
+ claim(dir, 4242);
56
+ acquireStoreLocks([dir], () => false);
57
+ expect(lockPid(dir)).toBe(process.pid);
58
+ });
59
+
60
+ it("is re-entrant for the owning process (in-process restarts)", () => {
61
+ const dir = store();
62
+ acquireStoreLocks([dir]);
63
+ expect(() => acquireStoreLocks([dir])).not.toThrow();
64
+ });
65
+ });
@@ -0,0 +1,77 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import createWorkflowsPlugin, {
3
+ workflowsDriveDeclaration,
4
+ workflowsPlugin,
5
+ } from "../src/plugins/workflows.mjs";
6
+
7
+ // The workflows plugin DECLARES the drive it serves (workflow-plugins plan):
8
+ // a drive contribution the switchboard runner merges into the host's plan.
9
+ describe("workflows plugin — drive contribution from entry config", () => {
10
+ it("contributes the classic Workflows drive by default (project-hashed id, Workflow Studio)", () => {
11
+ expect(workflowsPlugin.contributions?.drives).toEqual([
12
+ {
13
+ slug: "workflows",
14
+ name: "Workflows",
15
+ preferredEditor: "workflow-studio",
16
+ projectHash: "id",
17
+ },
18
+ ]);
19
+ // the default export is the factory resolveHostPlugins calls with the
20
+ // entry config; no config = the built-in instance's declaration
21
+ expect(createWorkflowsPlugin({}).contributions).toEqual(
22
+ workflowsPlugin.contributions,
23
+ );
24
+ });
25
+
26
+ it("names the drive from the entry: slug, name, icon; a fixed id drops the hash", () => {
27
+ const plugin = createWorkflowsPlugin({
28
+ drive: { slug: "automations", name: "Automations", id: "automations" },
29
+ });
30
+ expect(plugin.contributions?.drives).toEqual([
31
+ {
32
+ slug: "automations",
33
+ name: "Automations",
34
+ id: "automations",
35
+ preferredEditor: "workflow-studio",
36
+ },
37
+ ]);
38
+ expect(
39
+ workflowsDriveDeclaration({ drive: { icon: "./icons/flows.png" } }),
40
+ ).toEqual({
41
+ slug: "workflows",
42
+ name: "Workflows",
43
+ preferredEditor: "workflow-studio",
44
+ projectHash: "id",
45
+ icon: "./icons/flows.png",
46
+ });
47
+ // the vetra-style hashed slug stays available on request
48
+ expect(
49
+ workflowsDriveDeclaration({ drive: { projectHash: true } }),
50
+ ).toMatchObject({ projectHash: true });
51
+ });
52
+
53
+ it("drive: false serves the runtime without seeding a drive", () => {
54
+ expect(
55
+ createWorkflowsPlugin({ drive: false }).contributions?.drives,
56
+ ).toEqual([]);
57
+ });
58
+
59
+ it("rejects config it does not know (the entry's typo fails boot, not silently)", () => {
60
+ expect(() => createWorkflowsPlugin({ drives: {} })).toThrow();
61
+ expect(() => createWorkflowsPlugin({ drive: { slugg: "x" } })).toThrow();
62
+ expect(
63
+ workflowsPlugin.configSchema?.safeParse({ drive: { slug: "" } }).success,
64
+ ).toBe(false);
65
+ });
66
+
67
+ it("keeps the transformServerOptions behaviour: presence forces workflows on unless explicitly off", () => {
68
+ const hooks = createWorkflowsPlugin({ drive: false }).hooks!;
69
+ const transform = hooks.transformServerOptions!;
70
+ expect(transform({}, {} as never)).toEqual({
71
+ workflows: { enabled: true },
72
+ });
73
+ expect(transform({ workflows: { enabled: false } }, {} as never)).toEqual({
74
+ workflows: { enabled: false },
75
+ });
76
+ });
77
+ });
@@ -1 +0,0 @@
1
- {"version":3,"file":"mcp-cNWW82NH.mjs","sources":["../src/plugins/mcp.mts"],"sourcesContent":["import type { HostPlugin } from \"@powerhousedao/host-core\";\nimport type { SwitchboardHostContext } from \"../plugin-host.mjs\";\n\n/**\n * R2.2 — the MCP subsystem as a built-in plugin. Flag-on semantics: PRESENCE\n * IS ACTIVATION — listed (built-in default) means the /mcp endpoint mounts;\n * removed from the composition means it does not exist. The MCP_ENABLED env\n * flag governs the classic/flag-off path only (resolveMcpEnabled, which\n * still runs and whose result this transform overrides flag-on).\n *\n * The mount itself lives inside reactor-api's initializeAndStartAPI (carve\n * map: reactor-api server.ts:1282-1294) and is driven by options.mcp — the\n * plugin's whole job is owning that option.\n */\nexport const mcpPlugin: HostPlugin<{\n transformServerOptions: (\n options: Record<string, unknown>,\n ctx: SwitchboardHostContext,\n ) => Record<string, unknown>;\n}> = {\n name: \"switchboard-mcp\",\n appliesTo: \"switchboard\",\n hooks: {\n // An explicit caller/host `mcp: false` option keeps winning (the same\n // short-circuit resolveMcpEnabled has); only the ENV flag loses its\n // meaning flag-on — presence in the composition is the switch.\n transformServerOptions: (options) =>\n options.mcp === false ? options : { ...options, mcp: true },\n },\n};\n\n// resolveHostPlugins consumes the DEFAULT export (plugin object or factory).\nexport default mcpPlugin;\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,YAKR;CACH,MAAM;CACN,WAAW;CACX,OAAO,EAIL,yBAAyB,YACvB,QAAQ,QAAQ,QAAQ,UAAU;EAAE,GAAG;EAAS,KAAK;CAAK,EAC9D;AACF","debug_id":"d0d8adf1-591a-51b6-9fdb-e71751e66fca"}