@vellumai/assistant 0.10.3-dev.202606271533.7bf4323 → 0.10.3-dev.202606271729.9783ef3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.3-dev.202606271533.7bf4323",
3
+ "version": "0.10.3-dev.202606271729.9783ef3",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Tests for plugin config/data relocation into the plugin directory.
3
+ *
4
+ * Verifies that:
5
+ * - `runInitHook` reads config from `<pluginDir>/config.json` (not global config)
6
+ * - `runInitHook` points `pluginStorageDir` at `<pluginDir>/data/`
7
+ * - Config migrates from the global `config.plugins.<name>` block on first init
8
+ * - Data migrates from `<workspace>/plugins-data/<name>/` on first init
9
+ * - PRESERVED_ENTRIES excludes config.json, data/, and .disabled from fingerprinting
10
+ */
11
+ import {
12
+ existsSync,
13
+ mkdirSync,
14
+ readFileSync,
15
+ rmSync,
16
+ writeFileSync,
17
+ } from "node:fs";
18
+ import { tmpdir } from "node:os";
19
+ import { join } from "node:path";
20
+ import {
21
+ afterAll,
22
+ beforeAll,
23
+ beforeEach,
24
+ describe,
25
+ expect,
26
+ test,
27
+ } from "bun:test";
28
+
29
+ import {
30
+ computeFingerprint,
31
+ PRESERVED_ENTRIES,
32
+ } from "../cli/lib/plugin-fingerprint.js";
33
+ import {
34
+ resetHookCacheForTests,
35
+ } from "../hooks/hook-loader.js";
36
+ import {
37
+ populateCacheAtBoot,
38
+ resetPluginCacheForTests,
39
+ } from "../plugins/mtime-cache.js";
40
+
41
+ const ROOT = join(
42
+ tmpdir(),
43
+ `vellum-plugin-config-migration-${process.pid}-${Date.now()}`,
44
+ );
45
+
46
+ const PLUGINS_DIR = join(ROOT, "plugins");
47
+ const PLUGINS_DATA_DIR = join(ROOT, "plugins-data");
48
+
49
+ const SIMPLE_PKG = {
50
+ version: "1.0.0",
51
+ peerDependencies: { "@vellumai/plugin-api": "*" },
52
+ };
53
+
54
+ function freshPluginDir(name: string): string {
55
+ const dir = join(PLUGINS_DIR, name);
56
+ rmSync(dir, { recursive: true, force: true });
57
+ mkdirSync(dir, { recursive: true });
58
+ return dir;
59
+ }
60
+
61
+ function writePackageJson(dir: string, pkg: Record<string, unknown>): void {
62
+ writeFileSync(join(dir, "package.json"), JSON.stringify(pkg, null, 2));
63
+ }
64
+
65
+ function writeInitHook(dir: string, body: string): void {
66
+ const hooksDir = join(dir, "hooks");
67
+ mkdirSync(hooksDir, { recursive: true });
68
+ writeFileSync(join(hooksDir, "init.ts"), body);
69
+ }
70
+
71
+ beforeAll(() => {
72
+ process.env.VELLUM_WORKSPACE_DIR = ROOT;
73
+ });
74
+
75
+ beforeEach(() => {
76
+ rmSync(ROOT, { recursive: true, force: true });
77
+ mkdirSync(PLUGINS_DIR, { recursive: true });
78
+ mkdirSync(PLUGINS_DATA_DIR, { recursive: true });
79
+ resetHookCacheForTests();
80
+ resetPluginCacheForTests();
81
+ });
82
+
83
+ afterAll(() => {
84
+ rmSync(ROOT, { recursive: true, force: true });
85
+ });
86
+
87
+ describe("PRESERVED_ENTRIES", () => {
88
+ test("includes install-meta.json, config.json, data, and .disabled", () => {
89
+ expect(PRESERVED_ENTRIES).toContain("install-meta.json");
90
+ expect(PRESERVED_ENTRIES).toContain("config.json");
91
+ expect(PRESERVED_ENTRIES).toContain("data");
92
+ expect(PRESERVED_ENTRIES).toContain(".disabled");
93
+ });
94
+ });
95
+
96
+ describe("fingerprint exclusion of preserved entries", () => {
97
+ test("config.json, data/, and .disabled are excluded from fingerprint", () => {
98
+ const dir = join(PLUGINS_DIR, "fingerprint-test");
99
+ mkdirSync(dir, { recursive: true });
100
+ writeFileSync(join(dir, "package.json"), '{"name":"fingerprint-test"}');
101
+ writeFileSync(join(dir, "config.json"), '{"key":"value"}');
102
+ writeFileSync(join(dir, ".disabled"), "");
103
+ mkdirSync(join(dir, "data"), { recursive: true });
104
+ writeFileSync(join(dir, "data", "state.json"), '{"count":1}');
105
+
106
+ const fp = computeFingerprint(dir, PRESERVED_ENTRIES);
107
+
108
+ // Source files are fingerprinted.
109
+ expect(fp.files["package.json"]).toBeDefined();
110
+ // Preserved entries are NOT fingerprinted.
111
+ expect(fp.files["config.json"]).toBeUndefined();
112
+ expect(fp.files["data"]).toBeUndefined();
113
+ expect(fp.files["data/state.json"]).toBeUndefined();
114
+ expect(fp.files[".disabled"]).toBeUndefined();
115
+ });
116
+ });
117
+
118
+ describe("plugin config/data in plugin directory", () => {
119
+ test("init hook receives config from <pluginDir>/config.json", async () => {
120
+ const dir = freshPluginDir("cfg-plugin");
121
+ writePackageJson(dir, { ...SIMPLE_PKG, name: "cfg-plugin" });
122
+ writeFileSync(
123
+ join(dir, "config.json"),
124
+ JSON.stringify({ apiKey: "secret123" }, null, 2),
125
+ );
126
+
127
+ // Write an init hook that writes the received config to a sentinel file
128
+ // so we can inspect it after boot.
129
+ const sentinel = join(ROOT, "cfg-sentinel.json");
130
+ writeInitHook(
131
+ dir,
132
+ [
133
+ 'import { writeFileSync } from "node:fs";',
134
+ 'import type { InitContext } from "../../src/plugin-api/types.js";',
135
+ "export default async (ctx: InitContext) => {",
136
+ ' writeFileSync(' +
137
+ JSON.stringify(sentinel) +
138
+ ', JSON.stringify(ctx.config));',
139
+ "};",
140
+ ].join("\n"),
141
+ );
142
+
143
+ await populateCacheAtBoot();
144
+
145
+ expect(existsSync(sentinel)).toBe(true);
146
+ const received = JSON.parse(readFileSync(sentinel, "utf-8"));
147
+ expect(received).toEqual({ apiKey: "secret123" });
148
+ });
149
+
150
+ test("init hook receives pluginStorageDir at <pluginDir>/data/", async () => {
151
+ const dir = freshPluginDir("data-plugin");
152
+ writePackageJson(dir, { ...SIMPLE_PKG, name: "data-plugin" });
153
+
154
+ const sentinel = join(ROOT, "data-sentinel.txt");
155
+ writeInitHook(
156
+ dir,
157
+ [
158
+ 'import { writeFileSync } from "node:fs";',
159
+ 'import type { InitContext } from "../../src/plugin-api/types.js";',
160
+ "export default async (ctx: InitContext) => {",
161
+ ' writeFileSync(' + JSON.stringify(sentinel) + ', ctx.pluginStorageDir);',
162
+ "};",
163
+ ].join("\n"),
164
+ );
165
+
166
+ await populateCacheAtBoot();
167
+
168
+ expect(existsSync(sentinel)).toBe(true);
169
+ const storageDir = readFileSync(sentinel, "utf-8");
170
+ expect(storageDir).toBe(join(dir, "data"));
171
+ expect(existsSync(storageDir)).toBe(true);
172
+ });
173
+ });
174
+
175
+ describe("config migration from global config block", () => {
176
+ test("migrates config from config.plugins.<name> to <pluginDir>/config.json", async () => {
177
+ const dir = freshPluginDir("migrate-cfg");
178
+ writePackageJson(dir, { ...SIMPLE_PKG, name: "migrate-cfg" });
179
+
180
+ // Write the old config into the workspace config.json.
181
+ const workspaceConfigPath = join(ROOT, "config.json");
182
+ writeFileSync(
183
+ workspaceConfigPath,
184
+ JSON.stringify({
185
+ plugins: {
186
+ "migrate-cfg": { setting: "old-value", nested: { foo: 1 } },
187
+ },
188
+ }),
189
+ );
190
+
191
+ writeInitHook(
192
+ dir,
193
+ [
194
+ 'import { writeFileSync } from "node:fs";',
195
+ 'import type { InitContext } from "../../src/plugin-api/types.js";',
196
+ "export default async (ctx: InitContext) => {",
197
+ ' writeFileSync(' +
198
+ JSON.stringify(join(ROOT, "migrate-cfg-sentinel.json")) +
199
+ ', JSON.stringify(ctx.config));',
200
+ "};",
201
+ ].join("\n"),
202
+ );
203
+
204
+ await populateCacheAtBoot();
205
+
206
+ // The config should have been migrated to the plugin directory.
207
+ const configPath = join(dir, "config.json");
208
+ expect(existsSync(configPath)).toBe(true);
209
+ const migrated = JSON.parse(readFileSync(configPath, "utf-8"));
210
+ expect(migrated).toEqual({ setting: "old-value", nested: { foo: 1 } });
211
+
212
+ // The init hook should have received the migrated config.
213
+ const sentinel = join(ROOT, "migrate-cfg-sentinel.json");
214
+ expect(existsSync(sentinel)).toBe(true);
215
+ const received = JSON.parse(readFileSync(sentinel, "utf-8"));
216
+ expect(received).toEqual({ setting: "old-value", nested: { foo: 1 } });
217
+ });
218
+ });
219
+
220
+ describe("data migration from plugins-data/", () => {
221
+ test("migrates data from <workspace>/plugins-data/<name>/ to <pluginDir>/data/", async () => {
222
+ const dir = freshPluginDir("migrate-data");
223
+ writePackageJson(dir, { ...SIMPLE_PKG, name: "migrate-data" });
224
+
225
+ // Write old data to the legacy location.
226
+ const oldDataDir = join(PLUGINS_DATA_DIR, "migrate-data");
227
+ mkdirSync(oldDataDir, { recursive: true });
228
+ writeFileSync(join(oldDataDir, "state.json"), '{"old":"data"}');
229
+ writeFileSync(join(oldDataDir, "counter.txt"), "42");
230
+
231
+ writeInitHook(
232
+ dir,
233
+ [
234
+ 'import { writeFileSync } from "node:fs";',
235
+ 'import type { InitContext } from "../../src/plugin-api/types.js";',
236
+ "export default async (ctx: InitContext) => {",
237
+ ' writeFileSync(' +
238
+ JSON.stringify(join(ROOT, "migrate-data-sentinel.txt")) +
239
+ ', ctx.pluginStorageDir);',
240
+ "};",
241
+ ].join("\n"),
242
+ );
243
+
244
+ await populateCacheAtBoot();
245
+
246
+ // The data should have been migrated to the plugin directory.
247
+ const newDataDir = join(dir, "data");
248
+ expect(existsSync(newDataDir)).toBe(true);
249
+ expect(existsSync(join(newDataDir, "state.json"))).toBe(true);
250
+ expect(readFileSync(join(newDataDir, "state.json"), "utf-8")).toBe(
251
+ '{"old":"data"}',
252
+ );
253
+ expect(readFileSync(join(newDataDir, "counter.txt"), "utf-8")).toBe("42");
254
+
255
+ // The old directory should be removed.
256
+ expect(existsSync(oldDataDir)).toBe(false);
257
+
258
+ // The init hook should point at the new data directory.
259
+ const sentinel = join(ROOT, "migrate-data-sentinel.txt");
260
+ expect(existsSync(sentinel)).toBe(true);
261
+ expect(readFileSync(sentinel, "utf-8")).toBe(newDataDir);
262
+ });
263
+ });
@@ -43,7 +43,6 @@ import {
43
43
  DEFAULT_PLUGIN_REF,
44
44
  type FetchLike,
45
45
  type GitRunner,
46
- INSTALL_META_FILENAME,
47
46
  materializePluginTree,
48
47
  type PluginFetchSource,
49
48
  PluginNotFoundError,
@@ -56,6 +55,7 @@ import {
56
55
  compareFingerprint,
57
56
  computeFingerprint,
58
57
  type Fingerprint,
58
+ PRESERVED_ENTRIES,
59
59
  } from "./plugin-fingerprint.js";
60
60
  import { PluginNotInstalledError } from "./uninstall-plugin.js";
61
61
 
@@ -232,12 +232,8 @@ function buildFileDiffs(
232
232
  target: string,
233
233
  recorded: Fingerprint,
234
234
  ): PluginFileDiff[] {
235
- const comparison = compareFingerprint(target, recorded, [
236
- INSTALL_META_FILENAME,
237
- ]);
238
- const materialized = computeFingerprint(baselineRoot, [
239
- INSTALL_META_FILENAME,
240
- ]);
235
+ const comparison = compareFingerprint(target, recorded, PRESERVED_ENTRIES);
236
+ const materialized = computeFingerprint(baselineRoot, PRESERVED_ENTRIES);
241
237
 
242
238
  const files: PluginFileDiff[] = [];
243
239
  for (const path of comparison.modified) {
@@ -19,7 +19,6 @@
19
19
  import {
20
20
  DEFAULT_PLUGIN_REF,
21
21
  type FetchLike,
22
- INSTALL_META_FILENAME,
23
22
  type InstallMeta,
24
23
  readInstallMeta,
25
24
  sanitizePluginName,
@@ -31,6 +30,7 @@ import {
31
30
  import {
32
31
  compareFingerprint,
33
32
  type FingerprintComparison,
33
+ PRESERVED_ENTRIES,
34
34
  } from "./plugin-fingerprint.js";
35
35
  import {
36
36
  fetchMarketplaceEntries,
@@ -183,9 +183,7 @@ function readLocal(
183
183
  // Compare the on-disk tree against the install-time baseline, applying the
184
184
  // same exclusion so the sidecar is never counted as a local addition.
185
185
  const localChanges = manifest?.fingerprint
186
- ? compareFingerprint(entry.target, manifest.fingerprint, [
187
- INSTALL_META_FILENAME,
188
- ])
186
+ ? compareFingerprint(entry.target, manifest.fingerprint, PRESERVED_ENTRIES)
189
187
  : null;
190
188
  return {
191
189
  target: entry.target,
@@ -26,6 +26,7 @@
26
26
  import { execFile } from "node:child_process";
27
27
  import {
28
28
  copyFileSync,
29
+ cpSync,
29
30
  existsSync,
30
31
  mkdirSync,
31
32
  readdirSync,
@@ -45,6 +46,7 @@ import {
45
46
  computeFingerprint,
46
47
  type Fingerprint,
47
48
  parseFingerprint,
49
+ PRESERVED_ENTRIES,
48
50
  } from "./plugin-fingerprint.js";
49
51
  import {
50
52
  fetchMarketplaceEntries,
@@ -515,8 +517,8 @@ export function finalizeStagedInstall(
515
517
  // never hashes itself) — the baseline `plugins inspect` uses to detect later
516
518
  // local edits. The per-file fingerprint answers "which files changed"; the
517
519
  // whole-tree content hash is a compact integrity signal mirroring skills.
518
- const fingerprint = computeFingerprint(stagingDir, [INSTALL_META_FILENAME]);
519
- const contentHash = computeContentHash(stagingDir, [INSTALL_META_FILENAME]);
520
+ const fingerprint = computeFingerprint(stagingDir, PRESERVED_ENTRIES);
521
+ const contentHash = computeContentHash(stagingDir, PRESERVED_ENTRIES);
520
522
 
521
523
  // Record install provenance (source coordinates + resolved commit + content
522
524
  // digests) as a sidecar before the swap so it lands atomically with the
@@ -539,7 +541,24 @@ export function finalizeStagedInstall(
539
541
  // it, so the target's parent is no longer created as a side effect.
540
542
  const target = join(pluginsDir, name);
541
543
  mkdirSync(pluginsDir, { recursive: true });
544
+
545
+ // Copy preserved entries (config.json, data/, .disabled) from the existing
546
+ // install into the staging dir before the swap so user-owned state survives
547
+ // upgrades and reinstalls. Without this, the rm+rename below would destroy
548
+ // user config and runtime data.
542
549
  if (existsSync(target)) {
550
+ for (const entry of PRESERVED_ENTRIES) {
551
+ if (entry === INSTALL_META_FILENAME) continue; // sidecar is rewritten above
552
+ const src = join(target, entry);
553
+ if (!existsSync(src)) continue;
554
+ const dest = join(stagingDir, entry);
555
+ const stat = statSync(src);
556
+ if (stat.isDirectory()) {
557
+ cpSync(src, dest, { recursive: true });
558
+ } else {
559
+ copyFileSync(src, dest);
560
+ }
561
+ }
543
562
  rmSync(target, { recursive: true, force: true });
544
563
  }
545
564
  renameSync(stagingDir, target);
@@ -44,8 +44,10 @@ import { tmpdir } from "node:os";
44
44
  import { dirname, join } from "node:path";
45
45
  import { promisify } from "node:util";
46
46
 
47
- import { INSTALL_META_FILENAME } from "./install-from-github.js";
48
- import { computeFingerprint } from "./plugin-fingerprint.js";
47
+ import {
48
+ computeFingerprint,
49
+ PRESERVED_ENTRIES,
50
+ } from "./plugin-fingerprint.js";
49
51
 
50
52
  const execFileAsync = promisify(execFile);
51
53
 
@@ -243,7 +245,7 @@ export async function mergePluginTree({
243
245
  conflictLabels,
244
246
  }: MergePluginTreeOptions): Promise<PluginMergeResult> {
245
247
  const labels = conflictLabels ?? DEFAULT_CONFLICT_LABELS;
246
- const exclude = [INSTALL_META_FILENAME];
248
+ const exclude = PRESERVED_ENTRIES;
247
249
  const base = computeFingerprint(baseDir, exclude).files;
248
250
  const ours = computeFingerprint(oursDir, exclude).files;
249
251
  const theirs = computeFingerprint(theirsDir, exclude).files;
@@ -161,6 +161,28 @@ export function parseFingerprint(value: unknown): Fingerprint | null {
161
161
  return { algorithm: "sha256", files };
162
162
  }
163
163
 
164
+ /**
165
+ * Top-level entries that are preserved across upgrades and excluded from
166
+ * fingerprinting / drift detection / content hashing. These are runtime-owned
167
+ * state, not part of the plugin's source tree at the pinned commit:
168
+ *
169
+ * - `install-meta.json` — provenance sidecar written at install time.
170
+ * - `config.json` — user-editable plugin config (lives in the plugin dir but
171
+ * is not tracked as source content, so user edits don't count as drift).
172
+ * - `data` — runtime data directory (plugin writes whatever it wants here).
173
+ * - `.disabled` — sentinel file created by `assistant plugins disable`.
174
+ *
175
+ * Without these exclusions, a user editing `config.json` or the plugin writing
176
+ * to `data/` would surface as drift against the install-time baseline, and an
177
+ * upgrade would try to overwrite or merge around user-owned state.
178
+ */
179
+ export const PRESERVED_ENTRIES = [
180
+ "install-meta.json",
181
+ "config.json",
182
+ "data",
183
+ ".disabled",
184
+ ] as const;
185
+
164
186
  /**
165
187
  * Aggregate SHA-256 digest over a tree's contents, returned as `v2:<hex>`.
166
188
  *
@@ -45,7 +45,6 @@ import {
45
45
  type FetchLike,
46
46
  finalizeStagedInstall,
47
47
  type GitRunner,
48
- INSTALL_META_FILENAME,
49
48
  installPlugin,
50
49
  materializePluginTree,
51
50
  type PluginFetchSource,
@@ -56,7 +55,11 @@ import {
56
55
  sanitizePluginName,
57
56
  } from "./install-from-github.js";
58
57
  import { type ConflictLabels, mergePluginTree } from "./merge-plugin-tree.js";
59
- import { computeFingerprint, fingerprintsEqual } from "./plugin-fingerprint.js";
58
+ import {
59
+ computeFingerprint,
60
+ fingerprintsEqual,
61
+ PRESERVED_ENTRIES,
62
+ } from "./plugin-fingerprint.js";
60
63
  import { PluginNotInstalledError } from "./uninstall-plugin.js";
61
64
 
62
65
  /**
@@ -459,9 +462,7 @@ async function mergeUpgrade(
459
462
  // otherwise a curated adapter overlay that moved since install would read
460
463
  // as base→ours/theirs edits and corrupt the merge. Verify against the
461
464
  // recorded fingerprint, exactly as `plugins diff` does.
462
- const baseFingerprint = computeFingerprint(baseDir, [
463
- INSTALL_META_FILENAME,
464
- ]);
465
+ const baseFingerprint = computeFingerprint(baseDir, PRESERVED_ENTRIES);
465
466
  if (!fingerprintsEqual(baseFingerprint, recorded)) {
466
467
  throw new PluginMergeBaselineError(
467
468
  name,
@@ -42,6 +42,7 @@ import {
42
42
  } from "./schemas/logging.js";
43
43
  import { McpConfigSchema } from "./schemas/mcp.js";
44
44
  import { MemoryConfigSchema } from "./schemas/memory.js";
45
+ import { MigrationsConfigSchema } from "./schemas/migrations.js";
45
46
  import { NotificationsConfigSchema } from "./schemas/notifications.js";
46
47
  import {
47
48
  DaemonConfigSchema,
@@ -63,6 +64,7 @@ export const AssistantConfigSchema = z
63
64
  .object({
64
65
  services: ServicesSchema.default(ServicesSchema.parse({})),
65
66
  memory: MemoryConfigSchema.default(MemoryConfigSchema.parse({})),
67
+ migrations: MigrationsConfigSchema.default(MigrationsConfigSchema.parse({})),
66
68
  dataDir: z
67
69
  .string({ error: "dataDir must be a string" })
68
70
  .default(getDataDir())
@@ -0,0 +1,25 @@
1
+ import { z } from "zod";
2
+
3
+ export const MigrationsWorkerConfigSchema = z
4
+ .object({
5
+ enabled: z
6
+ .boolean({ error: "migrations.worker.enabled must be a boolean" })
7
+ .default(false)
8
+ .describe(
9
+ "Enable the async migration worker. While false, migrations that are too expensive to run inside the synchronous startup migration runner skip their work and pass, deferring until the async runner is in place.",
10
+ ),
11
+ })
12
+ .describe("Async migration worker configuration");
13
+
14
+ export const MigrationsConfigSchema = z
15
+ .object({
16
+ worker: MigrationsWorkerConfigSchema.default(
17
+ MigrationsWorkerConfigSchema.parse({}),
18
+ ),
19
+ })
20
+ .describe("Workspace/database migration configuration");
21
+
22
+ export type MigrationsWorkerConfig = z.infer<
23
+ typeof MigrationsWorkerConfigSchema
24
+ >;
25
+ export type MigrationsConfig = z.infer<typeof MigrationsConfigSchema>;
@@ -23,8 +23,10 @@
23
23
  * `manifest.config` if the manifest supplies a parser-like validator
24
24
  * (Zod schemas with `.parse()` are supported; anything else is passed
25
25
  * through untouched).
26
- * 5. Creates `<workspaceDir>/plugins-data/<plugin>/` on demand for per-plugin
27
- * writable state and exposes it via {@link InitContext.pluginStorageDir}.
26
+ * 5. Creates a per-plugin writable data directory on demand and exposes it via
27
+ * {@link InitContext.pluginStorageDir}. For user plugins this is
28
+ * `<pluginDir>/data/`; for default plugins it is
29
+ * `<workspaceDir>/plugins-data/<plugin>/`.
28
30
  * 6. For each surviving plugin, registers its contributed tools and routes
29
31
  * into their global registries via {@link registerPluginTools} and
30
32
  * {@link registerSkillRoute}. Contributions land BEFORE `init()` so
@@ -19,7 +19,14 @@
19
19
  * lets it sit below the plugin cache with no import cycle.
20
20
  */
21
21
 
22
- import { mkdirSync } from "node:fs";
22
+ import {
23
+ cpSync,
24
+ existsSync,
25
+ mkdirSync,
26
+ readFileSync,
27
+ rmSync,
28
+ writeFileSync,
29
+ } from "node:fs";
23
30
  import { join } from "node:path";
24
31
 
25
32
  import { getConfig } from "../config/loader.js";
@@ -227,16 +234,34 @@ export async function preImportWorkspaceHooks(): Promise<void> {
227
234
  * Shared by user plugins and standalone workspace hooks so both get the same
228
235
  * init-context shape and per-owner isolation (a thrown `init` is logged and
229
236
  * swallowed, never blocking boot).
237
+ *
238
+ * For user plugins, `pluginDir` is the absolute path to the installed plugin
239
+ * directory (`<workspace>/plugins/<name>/`). Config and data now live inside
240
+ * the plugin directory as preserved entries:
241
+ *
242
+ * - `<pluginDir>/config.json` — user-editable config (replaces the global
243
+ * `config.plugins.<name>` block).
244
+ * - `<pluginDir>/data/` — runtime data directory (replaces
245
+ * `<workspace>/plugins-data/<name>/`).
246
+ *
247
+ * On first encounter after upgrade, any config or data still at the old
248
+ * locations is migrated into the plugin directory so existing setups keep
249
+ * working without manual intervention. For standalone workspace hooks
250
+ * (`WORKSPACE_HOOKS_OWNER`), `pluginDir` is `null` and the old paths are used
251
+ * as-is since workspace hooks have no plugin directory.
230
252
  */
231
- export async function runInitHook(ownerName: string): Promise<void> {
253
+ export async function runInitHook(
254
+ ownerName: string,
255
+ pluginDir: string | null = null,
256
+ ): Promise<void> {
232
257
  const initHookEntry = hookCache.get(hookKey(ownerName, HOOKS.INIT));
233
258
  if (initHookEntry === undefined) return;
234
259
 
235
260
  try {
236
261
  const initContext: InitContext = {
237
- config: getConfig().plugins?.[ownerName],
262
+ config: resolvePluginConfig(ownerName, pluginDir),
238
263
  logger: log.child({ plugin: ownerName }),
239
- pluginStorageDir: ensureHookStorageDir(ownerName),
264
+ pluginStorageDir: resolvePluginStorageDir(ownerName, pluginDir),
240
265
  assistantVersion: APP_VERSION,
241
266
  };
242
267
  await initHookEntry.hook(initContext);
@@ -298,11 +323,121 @@ export function clearPluginHooks(): void {
298
323
  }
299
324
  }
300
325
 
326
+ /**
327
+ * Filename for user-editable plugin config inside the plugin directory.
328
+ */
329
+ const PLUGIN_CONFIG_FILENAME = "config.json";
330
+
331
+ /**
332
+ * Directory name for per-plugin runtime data inside the plugin directory.
333
+ */
334
+ const PLUGIN_DATA_DIRNAME = "data";
335
+
336
+ /**
337
+ * Resolve a plugin's config for the init context. For user plugins with a
338
+ * `pluginDir`, config lives at `<pluginDir>/config.json`. If that file
339
+ * doesn't exist yet but the old global config block (`config.plugins.<name>`)
340
+ * has a value, the value is written to `config.json` as a one-time migration.
341
+ *
342
+ * For standalone workspace hooks (no `pluginDir`), the old global config block
343
+ * is returned as-is since there's no plugin directory to migrate into.
344
+ */
345
+ function resolvePluginConfig(
346
+ ownerName: string,
347
+ pluginDir: string | null,
348
+ ): unknown {
349
+ if (pluginDir === null) {
350
+ return getConfig().plugins?.[ownerName];
351
+ }
352
+
353
+ const configPath = join(pluginDir, PLUGIN_CONFIG_FILENAME);
354
+
355
+ // Migrate: if config.json doesn't exist but the old global config has a
356
+ // value, write it to the new location so the user's config is preserved.
357
+ if (!existsSync(configPath)) {
358
+ const oldConfig = getConfig().plugins?.[ownerName];
359
+ if (oldConfig !== undefined) {
360
+ try {
361
+ writeFileSync(configPath, JSON.stringify(oldConfig, null, 2));
362
+ log.info(
363
+ { plugin: ownerName, configPath },
364
+ "migrated plugin config from global config to plugin directory",
365
+ );
366
+ } catch (err) {
367
+ log.warn(
368
+ { err, plugin: ownerName, configPath },
369
+ "failed to migrate plugin config to plugin directory — using old value",
370
+ );
371
+ return oldConfig;
372
+ }
373
+ }
374
+ return oldConfig;
375
+ }
376
+
377
+ // Config.json exists — read and parse it.
378
+ try {
379
+ const raw = readFileSync(configPath, "utf-8");
380
+ return JSON.parse(raw);
381
+ } catch (err) {
382
+ log.warn(
383
+ { err, plugin: ownerName, configPath },
384
+ "failed to read plugin config.json — returning undefined",
385
+ );
386
+ return undefined;
387
+ }
388
+ }
389
+
390
+ /**
391
+ * Resolve a plugin's runtime data directory for the init context. For user
392
+ * plugins with a `pluginDir`, data lives at `<pluginDir>/data/`. If that
393
+ * directory doesn't exist but the old `<workspace>/plugins-data/<name>/` does,
394
+ * its contents are moved into the new location as a one-time migration.
395
+ *
396
+ * For standalone workspace hooks (no `pluginDir`), the old
397
+ * `<workspace>/plugins-data/<name>/` path is used and created as-is.
398
+ */
399
+ function resolvePluginStorageDir(
400
+ ownerName: string,
401
+ pluginDir: string | null,
402
+ ): string {
403
+ if (pluginDir === null) {
404
+ return ensureLegacyStorageDir(ownerName);
405
+ }
406
+
407
+ const dataDir = join(pluginDir, PLUGIN_DATA_DIRNAME);
408
+
409
+ // Migrate: if data/ doesn't exist but the old plugins-data/<name>/ does,
410
+ // move its contents into the new location.
411
+ if (!existsSync(dataDir)) {
412
+ const oldDir = join(getWorkspaceDir(), "plugins-data", ownerName);
413
+ if (existsSync(oldDir)) {
414
+ try {
415
+ mkdirSync(dataDir, { recursive: true });
416
+ cpSync(oldDir, dataDir, { recursive: true });
417
+ rmSync(oldDir, { recursive: true, force: true });
418
+ log.info(
419
+ { plugin: ownerName, oldDir, dataDir },
420
+ "migrated plugin data from plugins-data to plugin directory",
421
+ );
422
+ } catch (err) {
423
+ log.warn(
424
+ { err, plugin: ownerName, oldDir, dataDir },
425
+ "failed to migrate plugin data to plugin directory — using old location",
426
+ );
427
+ return ensureLegacyStorageDir(ownerName);
428
+ }
429
+ }
430
+ }
431
+
432
+ mkdirSync(dataDir, { recursive: true });
433
+ return dataDir;
434
+ }
435
+
301
436
  /**
302
437
  * Ensure `<workspaceDir>/plugins-data/<name>/` exists and return its path.
303
- * Used as the per-owner storage directory in the hook init context.
438
+ * Used only for standalone workspace hooks and as a fallback during migration.
304
439
  */
305
- function ensureHookStorageDir(ownerName: string): string {
440
+ function ensureLegacyStorageDir(ownerName: string): string {
306
441
  const dir = join(getWorkspaceDir(), "plugins-data", ownerName);
307
442
  mkdirSync(dir, { recursive: true });
308
443
  return dir;
@@ -1,3 +1,4 @@
1
+ import { getConfig } from "../../config/loader.js";
1
2
  import { getLogger } from "../../util/logger.js";
2
3
  import { getDbPath } from "../../util/platform.js";
3
4
  import { runAsyncSqlite } from "../db-async-query.js";
@@ -124,6 +125,19 @@ function windowSql(lo: number, hi: number): string {
124
125
  export async function migrateStripThinkingFromConsolidated(
125
126
  database: DrizzleDb,
126
127
  ): Promise<void> {
128
+ // Gated on the async migration worker. This sweep proved too expensive for
129
+ // the synchronous startup migration runner — on a large `messages` table it
130
+ // can hold the daemon for minutes and trip the startup probe into a restart
131
+ // loop. While `migrations.worker.enabled` is false, skip the work and let the
132
+ // step pass so startup is never blocked; performing the sweep is deferred to
133
+ // the new async migration runner once it takes shape.
134
+ if (!getConfig().migrations.worker.enabled) {
135
+ log.info(
136
+ "Migration 209: skipped — migrations.worker.enabled is false; deferring the strip-thinking sweep to the async migration runner",
137
+ );
138
+ return;
139
+ }
140
+
127
141
  const raw = getSqliteFrom(database);
128
142
  const dbPath = getDbPath();
129
143
 
@@ -1,12 +1,16 @@
1
+ import { getConfig } from "../../config/loader.js";
1
2
  import {
2
3
  PLACEHOLDER_BLOCKS_OMITTED,
3
4
  PLACEHOLDER_EMPTY_TURN,
4
5
  } from "../../providers/placeholder-sentinels.js";
6
+ import { getLogger } from "../../util/logger.js";
5
7
  import { getDbPath } from "../../util/platform.js";
6
8
  import { runAsyncSqlite } from "../db-async-query.js";
7
9
  import type { DrizzleDb } from "../db-connection.js";
8
10
  import { getSqliteFrom } from "../db-connection.js";
9
11
 
12
+ const log = getLogger("db-init");
13
+
10
14
  /**
11
15
  * Number of `rowid` values swept per `runAsyncSqlite` dispatch. Each window is
12
16
  * one off-thread subprocess transaction. Keeping it well below the row count of
@@ -123,6 +127,19 @@ function windowSql(lo: number, hi: number): string {
123
127
  export async function migrateStripPlaceholderSentinelsFromMessages(
124
128
  database: DrizzleDb,
125
129
  ): Promise<void> {
130
+ // Gated on the async migration worker. This full-table sweep proved too
131
+ // expensive for the synchronous startup migration runner — on a large
132
+ // `messages` table it can hold the daemon's event loop and write lock for
133
+ // minutes. While `migrations.worker.enabled` is false, skip the work and let
134
+ // the step pass so startup is never blocked; performing the sweep is deferred
135
+ // to the new async migration runner once it takes shape.
136
+ if (!getConfig().migrations.worker.enabled) {
137
+ log.info(
138
+ "Migration 222: skipped — migrations.worker.enabled is false; deferring the placeholder-sentinel sweep to the async migration runner",
139
+ );
140
+ return;
141
+ }
142
+
126
143
  const raw = getSqliteFrom(database);
127
144
  const dbPath = getDbPath();
128
145
 
@@ -17,9 +17,18 @@ const {
17
17
  ROWID_WINDOW,
18
18
  WINDOW_TIMEOUT_MS,
19
19
  } = await import("../209-strip-thinking-from-consolidated.js");
20
+ const { loadRawConfig, saveRawConfig } =
21
+ await import("../../../config/loader.js");
20
22
 
21
23
  await initializeDb();
22
24
 
25
+ // The sweep is gated behind `migrations.worker.enabled` (default false), under
26
+ // which it short-circuits and passes. Enable it so the migration does its work
27
+ // for these tests.
28
+ const rawConfig = loadRawConfig();
29
+ rawConfig.migrations = { worker: { enabled: true } };
30
+ saveRawConfig(rawConfig);
31
+
23
32
  const CONV = "conv-209";
24
33
  getSqlite()
25
34
  .query(
@@ -283,6 +292,28 @@ describe("migration 209 — strip thinking from consolidated assistant messages"
283
292
  expect(watermark()).toBeNull();
284
293
  });
285
294
 
295
+ test("skips the sweep and passes when migrations.worker.enabled is false", async () => {
296
+ const original = JSON.stringify([
297
+ { type: "thinking", thinking: "secret", signature: "s" },
298
+ { type: "text", text: "gated" },
299
+ ]);
300
+ const { id } = insert("assistant", original);
301
+
302
+ const disabled = loadRawConfig();
303
+ disabled.migrations = { worker: { enabled: false } };
304
+ saveRawConfig(disabled);
305
+ try {
306
+ // Resolves without throwing and leaves the row untouched — the work is
307
+ // deferred to the async migration runner.
308
+ await migrateStripThinkingFromConsolidated(getDb());
309
+ expect(content(id)).toBe(original);
310
+ } finally {
311
+ const enabled = loadRawConfig();
312
+ enabled.migrations = { worker: { enabled: true } };
313
+ saveRawConfig(enabled);
314
+ }
315
+ });
316
+
286
317
  test("keeps the sweep window and timeout bounded so it cannot overrun a whole table", () => {
287
318
  // Regression guard: ROWID_WINDOW was 100_000, larger than a typical
288
319
  // messages table, so the entire table swept in one subprocess that overran
@@ -20,9 +20,18 @@ const {
20
20
  ROWID_WINDOW,
21
21
  WINDOW_TIMEOUT_MS,
22
22
  } = await import("../222-strip-placeholder-sentinels-from-messages.js");
23
+ const { loadRawConfig, saveRawConfig } =
24
+ await import("../../../config/loader.js");
23
25
 
24
26
  await initializeDb();
25
27
 
28
+ // The sweep is gated behind `migrations.worker.enabled` (default false), under
29
+ // which it short-circuits and passes. Enable it so the migration does its work
30
+ // for these tests.
31
+ const rawConfig = loadRawConfig();
32
+ rawConfig.migrations = { worker: { enabled: true } };
33
+ saveRawConfig(rawConfig);
34
+
26
35
  const CONV = "conv-222";
27
36
  getSqlite()
28
37
  .query(
@@ -235,6 +244,28 @@ describe("migration 222 — strip placeholder sentinels from assistant messages"
235
244
  expect(blocks(second.id)).toEqual([{ type: "text", text: "second" }]);
236
245
  });
237
246
 
247
+ test("skips the sweep and passes when migrations.worker.enabled is false", async () => {
248
+ const original = JSON.stringify([
249
+ { type: "text", text: PLACEHOLDER_EMPTY_TURN },
250
+ { type: "text", text: "gated" },
251
+ ]);
252
+ const { id } = insert("assistant", original);
253
+
254
+ const disabled = loadRawConfig();
255
+ disabled.migrations = { worker: { enabled: false } };
256
+ saveRawConfig(disabled);
257
+ try {
258
+ // Resolves without throwing and leaves the row untouched — the work is
259
+ // deferred to the async migration runner.
260
+ await migrateStripPlaceholderSentinelsFromMessages(getDb());
261
+ expect(content(id)).toBe(original);
262
+ } finally {
263
+ const enabled = loadRawConfig();
264
+ enabled.migrations = { worker: { enabled: true } };
265
+ saveRawConfig(enabled);
266
+ }
267
+ });
268
+
238
269
  test("keeps the sweep window and timeout bounded so it cannot overrun a whole table", () => {
239
270
  expect(ROWID_WINDOW).toBeLessThanOrEqual(10_000);
240
271
  expect(WINDOW_TIMEOUT_MS).toBeLessThan(60 * 60 * 1000);
@@ -637,7 +637,7 @@ describe("collapseEdges", () => {
637
637
 
638
638
  describe("enqueueEmbeds", () => {
639
639
  test("enqueues one embed_concept_page job per slug", () => {
640
- expect(enqueueEmbeds(["alice", "bob", "carol"], database)).toBe(3);
640
+ expect(enqueueEmbeds(["alice", "bob", "carol"])).toBe(3);
641
641
  expect(enqueuedJobs).toEqual([
642
642
  { type: "embed_concept_page", payload: { slug: "alice" } },
643
643
  { type: "embed_concept_page", payload: { slug: "bob" } },
@@ -646,7 +646,7 @@ describe("enqueueEmbeds", () => {
646
646
  });
647
647
 
648
648
  test("empty list is a no-op", () => {
649
- expect(enqueueEmbeds([], database)).toBe(0);
649
+ expect(enqueueEmbeds([])).toBe(0);
650
650
  expect(enqueuedJobs).toEqual([]);
651
651
  });
652
652
  });
@@ -465,19 +465,16 @@ export function collapseEdges(
465
465
  * is implemented separately — we just stage the queue here so the embeddings
466
466
  * are ready by the time activation needs them.
467
467
  *
468
- * `database` is threaded through to `enqueueMemoryJob` as the override DB
469
- * handle. Without this, jobs would be written to the global `getDb()` instead
470
- * of the migration's DB — which is wrong for tests, isolated runners, and
471
- * multi-workspace processes that pass an explicit `database`.
468
+ * The `memory_jobs` queue lives in the dedicated memory database
469
+ * (`assistant-memory.db`), not the main DB. `enqueueMemoryJob` targets it by
470
+ * default, so we pass no DB override here: the migration's `database` handle is
471
+ * the *main* DB (the v1 graph source read by `gatherV1State`) and must not
472
+ * receive `memory_jobs` writes — doing so silently drops the jobs into a table
473
+ * that doesn't exist there.
472
474
  */
473
- export function enqueueEmbeds(slugs: string[], database: DrizzleDb): number {
475
+ export function enqueueEmbeds(slugs: string[]): number {
474
476
  for (const slug of slugs) {
475
- enqueueMemoryJob(
476
- "embed_concept_page",
477
- { slug },
478
- undefined,
479
- database as never,
480
- );
477
+ enqueueMemoryJob("embed_concept_page", { slug });
481
478
  }
482
479
  return slugs.length;
483
480
  }
@@ -621,10 +618,7 @@ export async function runMemoryV2Migration(
621
618
  }
622
619
  await appendPromotions(workspaceDir, promotions);
623
620
 
624
- const embedsEnqueued = enqueueEmbeds(
625
- finalizedPages.map((p) => p.slug),
626
- database,
627
- );
621
+ const embedsEnqueued = enqueueEmbeds(finalizedPages.map((p) => p.slug));
628
622
 
629
623
  await writeSentinel(workspaceDir);
630
624
 
@@ -75,13 +75,23 @@ export type HookFunction<TCtx = unknown> = (
75
75
  * Context passed to `Plugin.init()` during bootstrap. Carries the resolved
76
76
  * config, a pino-compatible logger scoped to the plugin, a per-plugin
77
77
  * writable data directory, and the assistant's version metadata.
78
+ *
79
+ * For user-installed plugins, config is read from `<pluginDir>/config.json`
80
+ * and `pluginStorageDir` points at `<pluginDir>/data/`. For first-party
81
+ * default plugins and standalone workspace hooks, config comes from the
82
+ * global `config.plugins.<name>` block and `pluginStorageDir` points at
83
+ * `<workspaceDir>/plugins-data/<name>/`.
78
84
  */
79
85
  export interface InitContext {
80
86
  /** Parsed config for this plugin (may be `unknown` until the manifest validates). */
81
87
  config: unknown;
82
88
  /** Pino-compatible child logger bound to `{ plugin: <name> }`. */
83
89
  logger: PluginLogger;
84
- /** Absolute path to `<workspaceDir>/plugins-data/<plugin>/` (created by bootstrap). */
90
+ /**
91
+ * Absolute path to the per-plugin writable data directory. For user plugins
92
+ * this is `<pluginDir>/data/`; for defaults and workspace hooks it falls back
93
+ * to `<workspaceDir>/plugins-data/<plugin>/`. Created by bootstrap.
94
+ */
85
95
  pluginStorageDir: string;
86
96
  /**
87
97
  * Assistant semver. Plugins can compare against this for defensive
@@ -485,7 +485,7 @@ async function activatePlugin(
485
485
  }
486
486
 
487
487
  // Run the `init` hook if present.
488
- await runInitHook(pluginName);
488
+ await runInitHook(pluginName, pluginDir);
489
489
 
490
490
  activatedPlugins.push({ name: pluginName });
491
491
  }