@powerhousedao/switchboard 6.2.3-dev.6 → 6.2.3-dev.60

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 (177) hide show
  1. package/.tsbuild/test/attachments/byte-grants.test.d.ts +2 -0
  2. package/.tsbuild/test/attachments/byte-grants.test.d.ts.map +1 -0
  3. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts +2 -0
  4. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts.map +1 -0
  5. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts +2 -0
  6. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts.map +1 -0
  7. package/.tsbuild/test/attachments/url-signer.test.d.ts +2 -0
  8. package/.tsbuild/test/attachments/url-signer.test.d.ts.map +1 -0
  9. package/.tsbuild/test/boot-create-signature-policy.test.d.ts +2 -0
  10. package/.tsbuild/test/boot-create-signature-policy.test.d.ts.map +1 -0
  11. package/.tsbuild/test/boot-inspection-enabled.test.d.ts +2 -0
  12. package/.tsbuild/test/boot-inspection-enabled.test.d.ts.map +1 -0
  13. package/.tsbuild/test/boot-mcp-enabled.test.d.ts +2 -0
  14. package/.tsbuild/test/boot-mcp-enabled.test.d.ts.map +1 -0
  15. package/.tsbuild/test/boot-privacy.test.d.ts +2 -0
  16. package/.tsbuild/test/boot-privacy.test.d.ts.map +1 -0
  17. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts +2 -0
  18. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts.map +1 -0
  19. package/.tsbuild/test/boot-without-renown.test.d.ts +2 -0
  20. package/.tsbuild/test/boot-without-renown.test.d.ts.map +1 -0
  21. package/.tsbuild/test/boot-without-require-signatures.test.d.ts +2 -0
  22. package/.tsbuild/test/boot-without-require-signatures.test.d.ts.map +1 -0
  23. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts +2 -0
  24. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts.map +1 -0
  25. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts +2 -0
  26. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts.map +1 -0
  27. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts +2 -0
  28. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts.map +1 -0
  29. package/.tsbuild/test/builder-defaults.test.d.ts +2 -0
  30. package/.tsbuild/test/builder-defaults.test.d.ts.map +1 -0
  31. package/.tsbuild/test/create-signature-policy.test.d.ts +2 -0
  32. package/.tsbuild/test/create-signature-policy.test.d.ts.map +1 -0
  33. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts +2 -0
  34. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
  35. package/.tsbuild/test/fatal-shutdown.test.d.ts +2 -0
  36. package/.tsbuild/test/fatal-shutdown.test.d.ts.map +1 -0
  37. package/.tsbuild/test/inspection-flag.test.d.ts +2 -0
  38. package/.tsbuild/test/inspection-flag.test.d.ts.map +1 -0
  39. package/.tsbuild/test/inspection-throttle.test.d.ts +2 -0
  40. package/.tsbuild/test/inspection-throttle.test.d.ts.map +1 -0
  41. package/.tsbuild/test/mcp-flag.test.d.ts +2 -0
  42. package/.tsbuild/test/mcp-flag.test.d.ts.map +1 -0
  43. package/.tsbuild/test/observability-signals.test.d.ts +2 -0
  44. package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
  45. package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
  46. package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
  47. package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
  48. package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
  49. package/.tsbuild/test/renown-trust-policy.test.d.ts +2 -0
  50. package/.tsbuild/test/renown-trust-policy.test.d.ts.map +1 -0
  51. package/.tsbuild/test/snapshot-writer.d.ts +18 -0
  52. package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
  53. package/.tsbuild/test/unsupported-stored-documents.test.d.ts +2 -0
  54. package/.tsbuild/test/unsupported-stored-documents.test.d.ts.map +1 -0
  55. package/.tsbuild/test/workflow/harness.d.ts +56 -0
  56. package/.tsbuild/test/workflow/harness.d.ts.map +1 -0
  57. package/.tsbuild/test/workflow/oauth.test.d.ts +2 -0
  58. package/.tsbuild/test/workflow/oauth.test.d.ts.map +1 -0
  59. package/.tsbuild/test/workflow/resolvers.test.d.ts +2 -0
  60. package/.tsbuild/test/workflow/resolvers.test.d.ts.map +1 -0
  61. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts +2 -0
  62. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts.map +1 -0
  63. package/.tsbuild/test/workflow/webhook-signed.test.d.ts +2 -0
  64. package/.tsbuild/test/workflow/webhook-signed.test.d.ts.map +1 -0
  65. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts +2 -0
  66. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts.map +1 -0
  67. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts +2 -0
  68. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts.map +1 -0
  69. package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
  70. package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
  71. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
  72. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
  73. package/.tsbuild/test/workflow-read-gate.test.d.ts +2 -0
  74. package/.tsbuild/test/workflow-read-gate.test.d.ts.map +1 -0
  75. package/.tsbuild/test/workflow-runtime.test.d.ts +2 -0
  76. package/.tsbuild/test/workflow-runtime.test.d.ts.map +1 -0
  77. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  78. package/.tsbuild/tsdown.config.d.ts.map +1 -1
  79. package/.tsbuild/vitest.config.d.ts.map +1 -1
  80. package/Auth.md +144 -2
  81. package/CHANGELOG.md +736 -0
  82. package/README.md +47 -10
  83. package/dist/index.d.mts +2 -1
  84. package/dist/index.mjs +50 -50
  85. package/dist/index.mjs.map +1 -1
  86. package/dist/install-packages.d.mts +2 -1
  87. package/dist/install-packages.mjs +2 -2
  88. package/dist/install-packages.mjs.map +1 -1
  89. package/dist/mcp-cNWW82NH.mjs +27 -0
  90. package/dist/mcp-cNWW82NH.mjs.map +1 -0
  91. package/dist/migrate.d.mts +2 -1
  92. package/dist/migrate.mjs +4 -3
  93. package/dist/migrate.mjs.map +1 -1
  94. package/dist/plugin-host-CGO4XZzK.d.mts +38 -0
  95. package/dist/plugin-host-CGO4XZzK.d.mts.map +1 -0
  96. package/dist/plugins/attachments.d.mts +23 -0
  97. package/dist/plugins/attachments.d.mts.map +1 -0
  98. package/dist/plugins/attachments.mjs +4 -0
  99. package/dist/plugins/mcp.d.mts +21 -0
  100. package/dist/plugins/mcp.d.mts.map +1 -0
  101. package/dist/plugins/mcp.mjs +4 -0
  102. package/dist/plugins/privacy.d.mts +12 -0
  103. package/dist/plugins/privacy.d.mts.map +1 -0
  104. package/dist/plugins/privacy.mjs +4 -0
  105. package/dist/plugins/workflows.d.mts +36 -0
  106. package/dist/plugins/workflows.d.mts.map +1 -0
  107. package/dist/plugins/workflows.mjs +4 -0
  108. package/dist/privacy-C8KVimKF.mjs +113 -0
  109. package/dist/privacy-C8KVimKF.mjs.map +1 -0
  110. package/dist/{server-CiKkVE6g.mjs → server-C9RQTWTA.mjs} +1132 -222
  111. package/dist/server-C9RQTWTA.mjs.map +1 -0
  112. package/dist/server.d.mts +158 -30
  113. package/dist/server.d.mts.map +1 -1
  114. package/dist/server.mjs +4 -5
  115. package/dist/{utils-Baw7rThP.mjs → utils-uaBlzyjS.mjs} +15 -9
  116. package/dist/utils-uaBlzyjS.mjs.map +1 -0
  117. package/dist/utils.d.mts +4 -5
  118. package/dist/utils.d.mts.map +1 -1
  119. package/dist/utils.mjs +3 -3
  120. package/dist/workflow-runtime-7GaJ13c9.d.mts +30 -0
  121. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +1 -0
  122. package/dist/workflows-qKtqZhn3.mjs +1338 -0
  123. package/dist/workflows-qKtqZhn3.mjs.map +1 -0
  124. package/package.json +49 -20
  125. package/scripts/install-packages.sh +0 -0
  126. package/test/attachment-reference-read-model.test.ts +6 -1
  127. package/test/attachments/auth.test.ts +85 -0
  128. package/test/attachments/byte-grants.test.ts +290 -0
  129. package/test/attachments/byte-routes-read-gate.integration.test.ts +314 -0
  130. package/test/attachments/download-target.test.ts +201 -32
  131. package/test/attachments/index.test.ts +47 -4
  132. package/test/attachments/reserve-metadata-parity.test.ts +96 -0
  133. package/test/attachments/routes-integration.test.ts +60 -4
  134. package/test/attachments/routes.test.ts +271 -24
  135. package/test/attachments/service-config.test.ts +13 -3
  136. package/test/attachments/url-signer.test.ts +105 -0
  137. package/test/boot-create-signature-policy.test.ts +108 -0
  138. package/test/boot-inspection-enabled.test.ts +150 -0
  139. package/test/boot-mcp-enabled.test.ts +130 -0
  140. package/test/boot-privacy.test.ts +243 -0
  141. package/test/boot-unsupported-stored-documents.test.ts +213 -0
  142. package/test/boot-without-renown.test.ts +81 -0
  143. package/test/boot-without-require-signatures.test.ts +74 -0
  144. package/test/boot-worker-trust-policy.test.ts +90 -0
  145. package/test/boot-workflow-singleton-conflict.test.ts +107 -0
  146. package/test/boot-workflow-singleton-retry.test.ts +133 -0
  147. package/test/builder-defaults.test.ts +80 -0
  148. package/test/create-signature-policy.test.ts +69 -0
  149. package/test/durable-node-fs-pg16.test.ts +80 -0
  150. package/test/fatal-shutdown.test.ts +165 -0
  151. package/test/inspection-flag.test.ts +62 -0
  152. package/test/inspection-throttle.test.ts +23 -0
  153. package/test/mcp-flag.test.ts +56 -0
  154. package/test/observability-signals.test.ts +131 -0
  155. package/test/pglite-dialect.test.ts +217 -2
  156. package/test/pglite-preflight.test.ts +313 -0
  157. package/test/pglite-version.test.ts +9 -1
  158. package/test/plugin-presence.test.ts +269 -0
  159. package/test/renown-trust-policy.test.ts +315 -0
  160. package/test/snapshot-writer.ts +94 -0
  161. package/test/unsupported-stored-documents.test.ts +72 -0
  162. package/test/worker-pool.test.ts +27 -1
  163. package/test/workflow/harness.ts +289 -0
  164. package/test/workflow/oauth.test.ts +214 -0
  165. package/test/workflow/resolvers.test.ts +357 -0
  166. package/test/workflow/webhook-dedupe.test.ts +295 -0
  167. package/test/workflow/webhook-signed.test.ts +509 -0
  168. package/test/workflow/webhook-trigger-test.test.ts +82 -0
  169. package/test/workflow/webhook-unsigned.test.ts +345 -0
  170. package/test/workflow-reactor-access.test.ts +384 -0
  171. package/test/workflow-reactor-enforcement.test.ts +808 -0
  172. package/test/workflow-read-gate.test.ts +213 -0
  173. package/test/workflow-runtime.test.ts +1122 -0
  174. package/tsconfig.json +11 -2
  175. package/tsdown.config.ts +9 -1
  176. package/dist/server-CiKkVE6g.mjs.map +0 -1
  177. package/dist/utils-Baw7rThP.mjs.map +0 -1
@@ -0,0 +1,313 @@
1
+ import { createDurableNodeFs } from "@powerhousedao/reactor-api/pglite-node";
2
+ import type { ILogger } from "document-model";
3
+ import { promises as fs } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import {
7
+ afterAll,
8
+ afterEach,
9
+ beforeAll,
10
+ beforeEach,
11
+ describe,
12
+ expect,
13
+ it,
14
+ vi,
15
+ } from "vitest";
16
+ import { runPglitePreflight } from "../src/pglite-preflight.js";
17
+ import { loadNodeFsClass, loadPGliteModule } from "../src/pglite-version.js";
18
+ import { writeSnapshotFromDir } from "./snapshot-writer.js";
19
+
20
+ // PGlite initdb and pg_dump are several times slower on the Windows runner.
21
+ const BOOT_TIMEOUT = 120_000;
22
+ const RM = { recursive: true, force: true, maxRetries: 10 } as const;
23
+ const ROWS = 10;
24
+ const CONVERTED_LINE =
25
+ /^Converted PGlite snapshot at (.+): snapshot (\d+) bytes -> (\d+) bytes on disk, (\d+) entries, (\d+) ms$/;
26
+
27
+ type StubLogger = ILogger & {
28
+ debug: ReturnType<typeof vi.fn>;
29
+ info: ReturnType<typeof vi.fn>;
30
+ warn: ReturnType<typeof vi.fn>;
31
+ };
32
+
33
+ function stubLogger(): StubLogger {
34
+ const logger = {
35
+ verbose: vi.fn(),
36
+ debug: vi.fn(),
37
+ info: vi.fn(),
38
+ warn: vi.fn(),
39
+ error: vi.fn(),
40
+ child: vi.fn(),
41
+ };
42
+ logger.child.mockReturnValue(logger);
43
+ return logger as unknown as StubLogger;
44
+ }
45
+
46
+ async function exists(p: string): Promise<boolean> {
47
+ try {
48
+ await fs.lstat(p);
49
+ return true;
50
+ } catch {
51
+ return false;
52
+ }
53
+ }
54
+
55
+ async function pgVersion(dir: string): Promise<string> {
56
+ return (await fs.readFile(path.join(dir, "PG_VERSION"), "utf8")).trim();
57
+ }
58
+
59
+ /** Opens `dir` the way the server does and counts the seeded rows. */
60
+ async function countRows(dir: string, major: 16 | 17): Promise<number> {
61
+ const [{ PGlite: Pg }, Base] = await Promise.all([
62
+ loadPGliteModule(major),
63
+ loadNodeFsClass(major),
64
+ ]);
65
+ const pg = new Pg({
66
+ fs: createDurableNodeFs(Base, dir, {
67
+ fsync: false,
68
+ maintenanceIntervalMs: 0,
69
+ }),
70
+ });
71
+ try {
72
+ await pg.waitReady;
73
+ const { rows } = await pg.query<{ n: number }>(
74
+ 'SELECT count(*)::int AS n FROM "Rows"',
75
+ );
76
+ return rows[0].n;
77
+ } finally {
78
+ await pg.close();
79
+ }
80
+ }
81
+
82
+ function convertedLines(logger: StubLogger): string[] {
83
+ return logger.info.mock.calls
84
+ .map((call) => String(call[0]))
85
+ .filter((line) => CONVERTED_LINE.test(line));
86
+ }
87
+
88
+ describe("runPglitePreflight", () => {
89
+ // A pure-snapshot PG16 store: snapshot.bin and nothing else, the layout
90
+ // AtomicNodeFs left for a store it created itself.
91
+ let template: string;
92
+ let root: string;
93
+ let logger: StubLogger;
94
+
95
+ beforeAll(async () => {
96
+ template = await fs.mkdtemp(path.join(os.tmpdir(), "preflight-template-"));
97
+ const loose = path.join(template, "loose");
98
+ const { PGlite: LegacyPGlite } = await loadPGliteModule(16);
99
+ const LegacyNodeFS = await loadNodeFsClass(16);
100
+ const pg = new LegacyPGlite({ fs: new LegacyNodeFS(loose) });
101
+ await pg.waitReady;
102
+ await pg.exec('CREATE TABLE "Rows" (id int PRIMARY KEY, payload text)');
103
+ await pg.exec(
104
+ `INSERT INTO "Rows" SELECT g, repeat('x', 100) FROM generate_series(1, ${ROWS}) g`,
105
+ );
106
+ await pg.close();
107
+ await fs.rm(path.join(loose, "postmaster.pid"), { force: true });
108
+ expect(await pgVersion(loose)).toBe("16");
109
+
110
+ const store = path.join(template, "store");
111
+ await fs.mkdir(store);
112
+ await writeSnapshotFromDir(loose, path.join(store, "snapshot.bin"));
113
+ await fs.rm(loose, RM);
114
+ }, BOOT_TIMEOUT);
115
+
116
+ afterAll(async () => {
117
+ await fs.rm(template, RM);
118
+ }, BOOT_TIMEOUT);
119
+
120
+ beforeEach(async () => {
121
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "preflight-"));
122
+ logger = stubLogger();
123
+ });
124
+
125
+ afterEach(async () => {
126
+ await fs.rm(root, RM);
127
+ }, BOOT_TIMEOUT);
128
+
129
+ async function snapshotDir(name: string): Promise<string> {
130
+ const dir = path.join(root, name);
131
+ await fs.cp(path.join(template, "store"), dir, { recursive: true });
132
+ return dir;
133
+ }
134
+
135
+ async function looseDir(name: string, major = 17): Promise<string> {
136
+ const dir = path.join(root, name);
137
+ await fs.mkdir(path.join(dir, "pg_wal"), { recursive: true });
138
+ await fs.writeFile(path.join(dir, "PG_VERSION"), `${major}\n`);
139
+ return dir;
140
+ }
141
+
142
+ it(
143
+ "converts before detecting the major, so a PG16 snapshot is migrated",
144
+ async () => {
145
+ const dir = await snapshotDir("reactor-storage");
146
+
147
+ const detected = await runPglitePreflight({
148
+ dirs: [dir],
149
+ migratePglite: true,
150
+ inMemory: false,
151
+ logger,
152
+ });
153
+
154
+ expect(detected.get(dir)).toBe(17);
155
+ expect(await pgVersion(dir)).toBe("17");
156
+ expect(await exists(path.join(dir, "snapshot.bin"))).toBe(false);
157
+ expect(await exists(`${dir}.converting`)).toBe(false);
158
+ expect(await exists(`${dir}.old`)).toBe(false);
159
+ expect(convertedLines(logger)).toHaveLength(1);
160
+ expect(logger.info).toHaveBeenCalledWith(
161
+ expect.stringContaining("Migrating"),
162
+ );
163
+ expect(await countRows(dir, 17)).toBe(ROWS);
164
+ },
165
+ BOOT_TIMEOUT,
166
+ );
167
+
168
+ // Pins the order alone: before this change a pure-snapshot dir had no loose
169
+ // PG_VERSION and the migration logged "No PG_VERSION; skipping". The case
170
+ // above also needs the legacy pg_dump to work.
171
+ it(
172
+ "attempts the migration of a PG16 snapshot instead of skipping it",
173
+ async () => {
174
+ const dir = await snapshotDir("reactor-storage");
175
+
176
+ await runPglitePreflight({
177
+ dirs: [dir],
178
+ migratePglite: true,
179
+ inMemory: false,
180
+ logger,
181
+ }).catch(() => undefined);
182
+
183
+ expect(convertedLines(logger)).toHaveLength(1);
184
+ expect(logger.info).not.toHaveBeenCalledWith(
185
+ expect.stringContaining("No PG_VERSION"),
186
+ );
187
+ expect(logger.info).toHaveBeenCalledWith(
188
+ expect.stringContaining(`Migrating ${dir} from PG16 to PG17`),
189
+ );
190
+ },
191
+ BOOT_TIMEOUT,
192
+ );
193
+
194
+ it(
195
+ "boots a converted dir on the second start without converting",
196
+ async () => {
197
+ const dir = await snapshotDir("reactor-storage");
198
+ const first = { dirs: [dir], inMemory: false, logger };
199
+ await runPglitePreflight(first);
200
+ expect(convertedLines(logger)).toHaveLength(1);
201
+ expect(await pgVersion(dir)).toBe("16");
202
+
203
+ const second = stubLogger();
204
+ const detected = await runPglitePreflight({ ...first, logger: second });
205
+
206
+ expect(detected.get(dir)).toBe(16);
207
+ expect(convertedLines(second)).toHaveLength(0);
208
+ expect(await exists(`${dir}.converting`)).toBe(false);
209
+ expect(await exists(`${dir}.old`)).toBe(false);
210
+ expect(await countRows(dir, 16)).toBe(ROWS);
211
+ },
212
+ BOOT_TIMEOUT,
213
+ );
214
+
215
+ it("removes pg_wal/xlogtemp.*", async () => {
216
+ const dir = await looseDir("read-storage");
217
+ const segment = path.join(dir, "pg_wal", "000000010000000000000001");
218
+ await fs.writeFile(segment, "wal");
219
+ await fs.writeFile(path.join(dir, "pg_wal", "xlogtemp.42"), "");
220
+ await fs.writeFile(path.join(dir, "pg_wal", "xlogtemp.7"), "");
221
+
222
+ const detected = await runPglitePreflight({
223
+ dirs: [dir],
224
+ inMemory: false,
225
+ logger,
226
+ });
227
+
228
+ expect(detected.get(dir)).toBe(17);
229
+ expect(await fs.readdir(path.join(dir, "pg_wal"))).toEqual([
230
+ "000000010000000000000001",
231
+ ]);
232
+ expect(await exists(segment)).toBe(true);
233
+ });
234
+
235
+ it("removes postmaster.pid without a warn call", async () => {
236
+ const dir = await looseDir("read-storage");
237
+ const lockfile = path.join(dir, "postmaster.pid");
238
+ await fs.writeFile(lockfile, "42\n");
239
+
240
+ await runPglitePreflight({ dirs: [dir], inMemory: false, logger });
241
+
242
+ expect(await exists(lockfile)).toBe(false);
243
+ expect(logger.warn).not.toHaveBeenCalled();
244
+ expect(logger.debug).toHaveBeenCalledWith(
245
+ expect.stringContaining(lockfile),
246
+ );
247
+ });
248
+
249
+ it(
250
+ "logs one info line per converted dir with sizes and duration",
251
+ async () => {
252
+ const reactor = await snapshotDir("reactor-storage");
253
+ const readModel = await snapshotDir("read-storage");
254
+
255
+ await runPglitePreflight({
256
+ dirs: [reactor, readModel],
257
+ inMemory: false,
258
+ logger,
259
+ });
260
+
261
+ const lines = convertedLines(logger);
262
+ expect(lines).toHaveLength(2);
263
+ const byDir = new Map(
264
+ lines.map((line) => {
265
+ const match = CONVERTED_LINE.exec(line)!;
266
+ return [match[1], match.slice(2).map(Number)] as const;
267
+ }),
268
+ );
269
+ for (const dir of [reactor, readModel]) {
270
+ const [snapshotBytes, convertedBytes, entries] = byDir.get(dir)!;
271
+ expect(snapshotBytes).toBeGreaterThan(0);
272
+ expect(convertedBytes).toBeGreaterThan(0);
273
+ expect(entries).toBeGreaterThan(0);
274
+ }
275
+ },
276
+ BOOT_TIMEOUT,
277
+ );
278
+
279
+ it("touches nothing in memory", async () => {
280
+ const dir = await snapshotDir("reactor-storage");
281
+
282
+ const detected = await runPglitePreflight({
283
+ dirs: [dir],
284
+ inMemory: true,
285
+ logger,
286
+ });
287
+
288
+ expect(detected.size).toBe(0);
289
+ expect(await exists(path.join(dir, "snapshot.bin"))).toBe(true);
290
+ });
291
+
292
+ it("wipes the dirs and their conversion siblings under forcePgVersion", async () => {
293
+ const dir = await snapshotDir("reactor-storage");
294
+ await fs.mkdir(`${dir}.old`);
295
+ await fs.mkdir(`${dir}.converting`);
296
+
297
+ const detected = await runPglitePreflight({
298
+ dirs: [dir],
299
+ forcePgVersion: 17,
300
+ migratePglite: true,
301
+ inMemory: false,
302
+ logger,
303
+ });
304
+
305
+ expect(detected.size).toBe(0);
306
+ expect(await exists(dir)).toBe(false);
307
+ expect(await exists(`${dir}.old`)).toBe(false);
308
+ expect(await exists(`${dir}.converting`)).toBe(false);
309
+ expect(logger.warn).toHaveBeenCalledWith(
310
+ expect.stringContaining("ignoring --migrate-pglite"),
311
+ );
312
+ });
313
+ });
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from "vitest";
2
- import { parseForcePgVersion } from "../src/pglite-version.js";
2
+ import { openForVerify, parseForcePgVersion } from "../src/pglite-version.js";
3
3
 
4
4
  describe("parseForcePgVersion", () => {
5
5
  it("returns null for undefined", () => {
@@ -35,3 +35,11 @@ describe("parseForcePgVersion", () => {
35
35
  expect(() => parseForcePgVersion("16.5")).toThrow(/PH_FORCE_PG_VERSION/);
36
36
  });
37
37
  });
38
+
39
+ describe("openForVerify", () => {
40
+ it("throws on an unsupported major before touching disk", async () => {
41
+ await expect(openForVerify(15, "/nonexistent/pglite-dir")).rejects.toThrow(
42
+ /PG_VERSION=15 is not supported/,
43
+ );
44
+ });
45
+ });
@@ -0,0 +1,269 @@
1
+ import { mkdtemp, rm } from "node:fs/promises";
2
+ import { createServer } from "node:net";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { HostPlugin, ResolvedPlugin } from "@powerhousedao/host-core";
6
+ import type { ILogger } from "document-model";
7
+ import { describe, expect, it, vi } from "vitest";
8
+ import {
9
+ builtinSwitchboardPlugins,
10
+ createSwitchboardPluginHost,
11
+ } from "../src/plugin-host.mjs";
12
+ import { startSwitchboard, type StartServerOptions } from "../src/server.mjs";
13
+
14
+ // `port: 0` would bind a random port the switchboard does not report back, so
15
+ // the test picks a free one and pins it.
16
+ async function freePort(): Promise<number> {
17
+ const server = createServer();
18
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
19
+ const address = server.address();
20
+ await new Promise<void>((resolve) => server.close(() => resolve()));
21
+ if (!address || typeof address === "string") throw new Error("no port");
22
+ return address.port;
23
+ }
24
+
25
+ function stubLogger(): ILogger {
26
+ const logger = {
27
+ verbose: vi.fn(),
28
+ debug: vi.fn(),
29
+ info: vi.fn(),
30
+ warn: vi.fn(),
31
+ error: vi.fn(),
32
+ child: vi.fn(),
33
+ };
34
+ logger.child.mockReturnValue(logger);
35
+ return logger as unknown as ILogger;
36
+ }
37
+
38
+ /**
39
+ * Boots with FEATURE_PLUGIN_HOST_ENABLED=1, sandboxing the env exactly like
40
+ * boot-mcp-enabled.test.ts: temp PH_REACTOR_DATABASE_URL, MCP_ENABLED cleared
41
+ * so it never leaks into the plugin-host composition under test, and every
42
+ * touched env var restored in `finally`. Workflows stay off by default here
43
+ * — case 5 below covers workflow presence on its own, lighter path.
44
+ */
45
+ async function withPluginHostSwitchboard(
46
+ optionsOverride: Partial<StartServerOptions>,
47
+ run: (
48
+ switchboard: Awaited<ReturnType<typeof startSwitchboard>>,
49
+ ) => Promise<void>,
50
+ ): Promise<void> {
51
+ const tempRoot = await mkdtemp(
52
+ join(tmpdir(), "switchboard-plugin-presence-"),
53
+ );
54
+ const names = [
55
+ "PH_REACTOR_DATABASE_URL",
56
+ "MCP_ENABLED",
57
+ "FEATURE_PLUGIN_HOST_ENABLED",
58
+ ];
59
+ const previous = names.map((name) => [name, process.env[name]] as const);
60
+ process.env.PH_REACTOR_DATABASE_URL = join(tempRoot, "reactor-storage");
61
+ delete process.env.MCP_ENABLED;
62
+ process.env.FEATURE_PLUGIN_HOST_ENABLED = "1";
63
+ let switchboard: Awaited<ReturnType<typeof startSwitchboard>> | undefined;
64
+
65
+ try {
66
+ switchboard = await startSwitchboard({
67
+ workflows: { enabled: false },
68
+ dbPath: join(tempRoot, "read-model"),
69
+ port: await freePort(),
70
+ strictPort: true,
71
+ disableLocalPackages: true,
72
+ identity: { keypairPath: join(tempRoot, "identity.json") },
73
+ drive: {
74
+ slug: "default-drive",
75
+ global: { name: "Default Drive" },
76
+ },
77
+ logger: stubLogger(),
78
+ ...optionsOverride,
79
+ });
80
+ await run(switchboard);
81
+ await switchboard.shutdown();
82
+ switchboard = undefined;
83
+ } finally {
84
+ await switchboard?.shutdown();
85
+ for (const [name, value] of previous) {
86
+ if (value === undefined) {
87
+ delete process.env[name];
88
+ } else {
89
+ process.env[name] = value;
90
+ }
91
+ }
92
+ await rm(tempRoot, { recursive: true, force: true });
93
+ }
94
+ }
95
+
96
+ async function postMcp(port: number): Promise<number> {
97
+ const response = await fetch(`http://127.0.0.1:${port}/mcp`, {
98
+ method: "POST",
99
+ headers: {
100
+ "content-type": "application/json",
101
+ accept: "application/json, text/event-stream",
102
+ },
103
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }),
104
+ });
105
+ await response.body?.cancel();
106
+ return response.status;
107
+ }
108
+
109
+ async function getReservation(port: number): Promise<number> {
110
+ const response = await fetch(
111
+ `http://127.0.0.1:${port}/attachments/reservations/does-not-matter`,
112
+ );
113
+ await response.body?.cancel();
114
+ return response.status;
115
+ }
116
+
117
+ describe("plugin-host composition presence (FEATURE_PLUGIN_HOST_ENABLED)", () => {
118
+ it("DEFAULT composition: mcp mounted, attachments present", async () => {
119
+ await withPluginHostSwitchboard({}, async (switchboard) => {
120
+ expect(switchboard.mcpEnabled).toBe(true);
121
+ expect(await postMcp(switchboard.port)).not.toBe(404);
122
+ expect(switchboard.attachmentService).toBeDefined();
123
+ });
124
+ }, 60_000);
125
+
126
+ it("EMPTY composition ([]): attachments absent", async () => {
127
+ await withPluginHostSwitchboard(
128
+ { pluginComposition: [] },
129
+ async (switchboard) => {
130
+ expect(switchboard.attachmentService).toBeUndefined();
131
+ expect(await getReservation(switchboard.port)).toBe(404);
132
+ },
133
+ );
134
+ }, 60_000);
135
+
136
+ // Presence is activation (R2.6c fix): flag-on, startSwitchboard skips the
137
+ // classic mcp/workflows resolvers and initServer normalizes unset values to
138
+ // OFF after transformServerOptions — an absent plugin actually deactivates
139
+ // its subsystem.
140
+ it("EMPTY composition ([]): /mcp does not mount — presence is activation", async () => {
141
+ await withPluginHostSwitchboard(
142
+ { pluginComposition: [] },
143
+ async (switchboard) => {
144
+ expect(switchboard.mcpEnabled).toBe(false);
145
+ expect(await postMcp(switchboard.port)).toBe(404);
146
+ },
147
+ );
148
+ }, 60_000);
149
+
150
+ it("SUBSET composition (mcp only): mcp mounted, attachments absent", async () => {
151
+ const mcpOnly = builtinSwitchboardPlugins().filter((resolved) =>
152
+ resolved.entry.module.includes("/plugins/mcp"),
153
+ );
154
+ expect(mcpOnly).toHaveLength(1);
155
+ await withPluginHostSwitchboard(
156
+ { pluginComposition: mcpOnly },
157
+ async (switchboard) => {
158
+ expect(switchboard.mcpEnabled).toBe(true);
159
+ expect(await postMcp(switchboard.port)).not.toBe(404);
160
+ expect(switchboard.attachmentService).toBeUndefined();
161
+ expect(await getReservation(switchboard.port)).toBe(404);
162
+ },
163
+ );
164
+ }, 60_000);
165
+
166
+ it("an explicit mcp: false option still wins over the default composition", async () => {
167
+ await withPluginHostSwitchboard({ mcp: false }, async (switchboard) => {
168
+ expect(switchboard.mcpEnabled).toBe(false);
169
+ expect(await postMcp(switchboard.port)).toBe(404);
170
+ });
171
+ }, 60_000);
172
+ });
173
+
174
+ describe("plugin-host workflows presence (transformServerOptions)", () => {
175
+ // A real boot's workflows.enabled is resolved classically (env/config,
176
+ // default OFF) in startSwitchboard BEFORE the plugin host is even
177
+ // constructed (server.mts resolveWorkflowsEnabled ~line 1545, pluginHost
178
+ // gate at ~line 407) — by the time the workflows plugin's
179
+ // transformServerOptions hook runs, options.workflows.enabled is already a
180
+ // definite boolean, so its "unless explicit false" short-circuit can never
181
+ // observe an "unset" value through that path. Exercising the hook directly
182
+ // against createSwitchboardPluginHost, as suggested as a fallback, is the
183
+ // only way to observe the plugin's own force-true behavior in isolation —
184
+ // see the suspected-bug note in the final report.
185
+ it("forces workflows.enabled true when the plugin is present, leaves it alone when absent", async () => {
186
+ const withWorkflowsPlugin = createSwitchboardPluginHost(
187
+ { logger: stubLogger(), options: {}, renown: null },
188
+ builtinSwitchboardPlugins(),
189
+ );
190
+ const resolvedWith = await withWorkflowsPlugin.transformOptions<
191
+ Record<string, unknown>
192
+ >({});
193
+ expect(
194
+ (resolvedWith.workflows as { enabled?: boolean } | undefined)?.enabled,
195
+ ).toBe(true);
196
+
197
+ const withoutAnyPlugin = createSwitchboardPluginHost(
198
+ { logger: stubLogger(), options: {}, renown: null },
199
+ [],
200
+ );
201
+ const resolvedWithout = await withoutAnyPlugin.transformOptions<
202
+ Record<string, unknown>
203
+ >({});
204
+ expect(resolvedWithout.workflows).toBeUndefined();
205
+ });
206
+
207
+ it("still honors an explicit workflows.enabled: false even with the plugin present", async () => {
208
+ const host = createSwitchboardPluginHost(
209
+ { logger: stubLogger(), options: {}, renown: null },
210
+ builtinSwitchboardPlugins(),
211
+ );
212
+ const resolved = await host.transformOptions<Record<string, unknown>>({
213
+ workflows: { enabled: false },
214
+ });
215
+ expect(
216
+ (resolved.workflows as { enabled?: boolean } | undefined)?.enabled,
217
+ ).toBe(false);
218
+ });
219
+ });
220
+
221
+ describe("plugin-host onShutdown ordering (runObserveHookSequential)", () => {
222
+ it("runs onShutdown sequentially, in registration order — not by whichever finishes first", async () => {
223
+ const order: string[] = [];
224
+
225
+ function fakePlugin(name: string, delayMs: number): HostPlugin {
226
+ return {
227
+ name,
228
+ appliesTo: "switchboard",
229
+ hooks: {
230
+ onShutdown: async () => {
231
+ if (delayMs > 0) {
232
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
233
+ }
234
+ order.push(name);
235
+ },
236
+ },
237
+ };
238
+ }
239
+
240
+ function resolvedFake(plugin: HostPlugin): ResolvedPlugin {
241
+ return {
242
+ plugin,
243
+ provenance: "local",
244
+ entry: {
245
+ module: `fake:${plugin.name}`,
246
+ enabled: true,
247
+ verbs: "*",
248
+ config: {},
249
+ },
250
+ };
251
+ }
252
+
253
+ // Registered first but slower: if onShutdown ran in parallel (the way
254
+ // the other hook moments do, via Promise.all in runObserveHook), "b"
255
+ // would resolve first and the recorded order would be ["b", "a"].
256
+ // Sequential execution must still record registration order, ["a", "b"].
257
+ const first = fakePlugin("a", 50);
258
+ const second = fakePlugin("b", 0);
259
+
260
+ const host = createSwitchboardPluginHost(
261
+ { logger: stubLogger(), options: {}, renown: null },
262
+ [resolvedFake(first), resolvedFake(second)],
263
+ );
264
+
265
+ await host.observe("onShutdown");
266
+
267
+ expect(order).toEqual(["a", "b"]);
268
+ });
269
+ });