@vellumai/assistant 0.10.3-dev.202606300318.cf23f52 → 0.10.3-dev.202606300731.35e9ab8

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 (76) hide show
  1. package/docs/architecture/memory.md +26 -0
  2. package/openapi.yaml +39 -1
  3. package/package.json +1 -1
  4. package/scripts/generate-openapi.ts +80 -58
  5. package/src/__tests__/cli-memory-v2-reembed-skills.test.ts +1 -1
  6. package/src/__tests__/context-search-memory-v2-source.test.ts +1 -0
  7. package/src/__tests__/lifecycle-memory-v2-seed.test.ts +1 -0
  8. package/src/__tests__/mcp-config-secret-boundary.test.ts +1 -0
  9. package/src/__tests__/plugin-import-boundary-guard.test.ts +21 -0
  10. package/src/__tests__/qdrant-collection-migration.test.ts +4 -1
  11. package/src/__tests__/workspace-migration-117-normalize-stale-lean-memory-v3-defaults.test.ts +221 -0
  12. package/src/cli/commands/__tests__/conversations-wake.test.ts +147 -0
  13. package/src/cli/commands/conversations.ts +32 -2
  14. package/src/cli/commands/memory/memory-v2.ts +1 -1
  15. package/src/cli/commands/memory/memory-v3.ts +2 -2
  16. package/src/{__tests__/config-managed-gemini-defaults.test.ts → config/__tests__/deployment-context-defaults.test.ts} +64 -113
  17. package/src/config/loader.ts +38 -58
  18. package/src/config/schemas/__tests__/memory-v3.test.ts +12 -11
  19. package/src/config/schemas/memory-v3.ts +54 -10
  20. package/src/daemon/__tests__/embedding-reconcile.test.ts +456 -0
  21. package/src/daemon/__tests__/lifecycle-embedding-reconcile.test.ts +119 -0
  22. package/src/daemon/__tests__/memory-v2-startup.test.ts +86 -0
  23. package/src/daemon/embedding-reconcile.ts +340 -0
  24. package/src/daemon/lifecycle.ts +15 -0
  25. package/src/daemon/memory-v2-startup.ts +35 -1
  26. package/src/ipc/routes/__tests__/memory-v2-backfill.test.ts +1 -1
  27. package/src/memory/graph/__tests__/conversation-graph-memory-v2-routing.test.ts +1 -0
  28. package/src/memory/v2/__tests__/activation.test.ts +41 -0
  29. package/src/memory/v2/__tests__/backfill-jobs.test.ts +1 -0
  30. package/src/memory/v2/__tests__/injection.test.ts +1 -0
  31. package/src/memory/v2/__tests__/qdrant.test.ts +31 -7
  32. package/src/memory/v2/__tests__/sim.test.ts +29 -0
  33. package/src/memory/v2/activation.ts +22 -10
  34. package/src/memory/v2/qdrant.ts +48 -1
  35. package/src/memory/v2/sim.ts +24 -10
  36. package/src/persistence/embeddings/__tests__/embedding-identity.test.ts +156 -0
  37. package/src/persistence/embeddings/__tests__/reconcile-decision.test.ts +95 -0
  38. package/src/persistence/embeddings/embedding-backend.test.ts +151 -0
  39. package/src/persistence/embeddings/embedding-backend.ts +132 -26
  40. package/src/persistence/embeddings/embedding-identity.ts +88 -0
  41. package/src/persistence/embeddings/embedding-types.ts +7 -0
  42. package/src/persistence/embeddings/qdrant-client.ts +9 -1
  43. package/src/persistence/embeddings/reconcile-decision.ts +53 -0
  44. package/src/{runtime → plugins/defaults/memory}/routes/__tests__/memory-v2-routes.test.ts +3 -3
  45. package/src/{runtime → plugins/defaults/memory}/routes/__tests__/memory-v2-simulate-route.test.ts +11 -11
  46. package/src/{runtime → plugins/defaults/memory}/routes/memory-eval-routes.ts +12 -9
  47. package/src/{runtime → plugins/defaults/memory}/routes/memory-item-routes.test.ts +19 -12
  48. package/src/{runtime → plugins/defaults/memory}/routes/memory-item-routes.ts +17 -13
  49. package/src/{runtime → plugins/defaults/memory}/routes/memory-v2-routes.ts +23 -23
  50. package/src/{runtime → plugins/defaults/memory}/routes/memory-v3-routes.ts +10 -7
  51. package/src/plugins/defaults/memory/v3/__tests__/dense.test.ts +15 -0
  52. package/src/plugins/defaults/memory/v3/__tests__/maintain-job.test.ts +24 -0
  53. package/src/plugins/defaults/memory/v3/__tests__/orchestrate.test.ts +69 -1
  54. package/src/plugins/defaults/memory/v3/__tests__/section-dense-store.test.ts +52 -9
  55. package/src/plugins/defaults/memory/v3/__tests__/selection-log-store.test.ts +2 -0
  56. package/src/plugins/defaults/memory/v3/__tests__/shadow-integration.test.ts +1 -0
  57. package/src/plugins/defaults/memory/v3/__tests__/shadow-plugin.test.ts +44 -1
  58. package/src/plugins/defaults/memory/v3/__tests__/tuning-profile.test.ts +96 -0
  59. package/src/plugins/defaults/memory/v3/dense.ts +13 -2
  60. package/src/plugins/defaults/memory/v3/entity-lane.test.ts +124 -0
  61. package/src/plugins/defaults/memory/v3/entity-lane.ts +113 -0
  62. package/src/plugins/defaults/memory/v3/hot-set.test.ts +1 -1
  63. package/src/plugins/defaults/memory/v3/maintain-job.ts +17 -20
  64. package/src/plugins/defaults/memory/v3/orchestrate.ts +43 -0
  65. package/src/plugins/defaults/memory/v3/section-dense-store.ts +56 -7
  66. package/src/plugins/defaults/memory/v3/section-needle.ts +20 -5
  67. package/src/plugins/defaults/memory/v3/shadow-plugin.ts +55 -11
  68. package/src/plugins/defaults/memory/v3/tuning-profile.ts +91 -0
  69. package/src/plugins/defaults/memory/v3/types.ts +4 -1
  70. package/src/runtime/routes/__tests__/memory-worker-routes.test.ts +107 -1
  71. package/src/runtime/routes/__tests__/wake-conversation-routes.test.ts +36 -0
  72. package/src/runtime/routes/index.ts +4 -4
  73. package/src/runtime/routes/memory-worker-routes.ts +19 -2
  74. package/src/runtime/routes/wake-conversation-routes.ts +18 -2
  75. package/src/workspace/migrations/117-normalize-stale-lean-memory-v3-defaults.ts +116 -0
  76. package/src/workspace/migrations/registry.ts +2 -0
@@ -405,6 +405,32 @@ When the embedding backend or Qdrant is unavailable:
405
405
  - If embeddings are optional (default), the pipeline returns empty results (no fallback search path exists without Qdrant).
406
406
  - Degradation status is reported to clients via `memory_status` events.
407
407
 
408
+ ### Embedding Dimension Reconciliation
409
+
410
+ The embedding dimension is a **committed property of the Qdrant collection**, derived from the dimension of whichever embedding backend built it. It is not a free-standing config value the user picks: `memory.qdrant.vectorSize` records the dimension the collections were created at, and reconciliation keeps that record consistent with the reachable backend.
411
+
412
+ `reconcileEmbeddingIdentity` (`assistant/src/daemon/embedding-reconcile.ts`) runs once at daemon startup. It reads the committed collection dimension and probes the configured backend in parallel, then routes both observations through the pure `decideEmbeddingReconcile` (`assistant/src/persistence/embeddings/reconcile-decision.ts`) and executes the resulting action. A transient backend outage **degrades** (recall returns empty results, surfaced via `memory_worker_status`'s `embedding.degraded` flag) — it never destroys the collection.
413
+
414
+ #### Decision table
415
+
416
+ | Probe | Committed dim | Provider | Action | Effect |
417
+ | --------------------------- | ------------- | ----------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
418
+ | down (no reachable backend) | — | — | `defer-degraded` | No write, no destructive call. Warn and leave the collection untouched. |
419
+ | up | none | — | `commit-fresh` | Adopt the probed dimension: commit it, ensure the collections exist at it (create-if-absent), enqueue a reembed. |
420
+ | up | matches probe | — | `noop` | No writes. |
421
+ | up | mismatch | explicit (`openai` / `gemini` / `ollama`) | `migrate` | Deliberate intent, confirmed by a successful probe: commit the new dim, destroy + recreate the collections, enqueue a reembed. The only destructive path. |
422
+ | up | mismatch | `auto` | `noop` | No thrash. Under `auto` the reachable backend can flip between a small local model (384) and a large managed model (3072) on transient availability, so a per-boot mismatch is not allowed to recreate the collection. |
423
+
424
+ Confirm-before-destroy: a destructive recreate runs only on a `migrate` action, and only after a non-null backend probe. This makes the dimension change depend on the backend being reachable rather than on a config flag written before the backend is known to answer.
425
+
426
+ #### Platform intent is a fill-only deployment default
427
+
428
+ Platform deployments express an embedding-provider preference through `getDeploymentContextDefaults` in `assistant/src/config/loader.ts`: when `IS_PLATFORM` is set, the loader **fills** `memory.embeddings.provider: "gemini"` as an in-memory default. This default is layered at config-load time and is **not persisted** to `config.json`, and it does **not** set `memory.qdrant.vectorSize` or `geminiModel`. The dimension stays derived from the live probe; the explicit provider only lifts a genuine upgrade from `noop` (auto) to `migrate` (explicit) in the decision table above. There is no config migration that writes a provider or dimension to disk.
429
+
430
+ #### Lazy ensure vs. startup reconcile
431
+
432
+ The lazy `ensureCollection` paths (`ensureConceptPageCollection` in `assistant/src/memory/v2/qdrant.ts`, `ensureSectionCollection` for v3) **create-if-absent only** for the committed dimension. They never perform a dimension migration — destructive dimension change is owned solely by the startup reconcile's `migrate` action. The lazy paths still recreate on **schema drift**: a collection missing a required named vector (e.g. an unnamed-vector layout, or one lacking `summary_dense` / `summary_sparse`) is rebuilt and signalled via `{ migrated: true }` so callers enqueue a backfill.
433
+
408
434
  ---
409
435
 
410
436
  ## Workspace Context Injection — Directory Awareness
package/openapi.yaml CHANGED
@@ -9140,6 +9140,10 @@ paths:
9140
9140
  cronRunId:
9141
9141
  type: string
9142
9142
  minLength: 1
9143
+ persist:
9144
+ type: boolean
9145
+ externalContent:
9146
+ type: string
9143
9147
  required:
9144
9148
  - conversationId
9145
9149
  - hint
@@ -16649,7 +16653,9 @@ paths:
16649
16653
  get:
16650
16654
  operationId: memory_worker_status_get
16651
16655
  summary: Memory worker status
16652
- description: Reports the memory worker process state, memory.worker.enabled, and the synchronous in-process runner.
16656
+ description:
16657
+ Reports the memory worker process state, memory.worker.enabled, the synchronous in-process runner, and the
16658
+ embedding-backend status (including a degraded flag and reason when no backend resolves).
16653
16659
  tags:
16654
16660
  - system
16655
16661
  responses:
@@ -16682,10 +16688,42 @@ paths:
16682
16688
  required:
16683
16689
  - status
16684
16690
  additionalProperties: false
16691
+ embedding:
16692
+ type: object
16693
+ properties:
16694
+ enabled:
16695
+ type: boolean
16696
+ degraded:
16697
+ type: boolean
16698
+ provider:
16699
+ anyOf:
16700
+ - type: string
16701
+ enum:
16702
+ - local
16703
+ - openai
16704
+ - gemini
16705
+ - ollama
16706
+ - type: "null"
16707
+ model:
16708
+ anyOf:
16709
+ - type: string
16710
+ - type: "null"
16711
+ reason:
16712
+ anyOf:
16713
+ - type: string
16714
+ - type: "null"
16715
+ required:
16716
+ - enabled
16717
+ - degraded
16718
+ - provider
16719
+ - model
16720
+ - reason
16721
+ additionalProperties: false
16685
16722
  required:
16686
16723
  - status
16687
16724
  - workerEnabled
16688
16725
  - syncRunner
16726
+ - embedding
16689
16727
  additionalProperties: false
16690
16728
  /v1/memory/worker/stop:
16691
16729
  post:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.3-dev.202606300318.cf23f52",
3
+ "version": "0.10.3-dev.202606300731.35e9ab8",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -16,7 +16,7 @@
16
16
  * cd assistant && bun run generate:openapi -- --check # CI: fail if stale
17
17
  */
18
18
 
19
- import { readFileSync } from "node:fs";
19
+ import { existsSync, readFileSync } from "node:fs";
20
20
  import { readdir, readFile, writeFile } from "node:fs/promises";
21
21
  import { join, resolve } from "node:path";
22
22
 
@@ -32,6 +32,7 @@ import { createDocument } from "zod-openapi";
32
32
 
33
33
  const ROOT = resolve(import.meta.dir, "..");
34
34
  const ROUTES_DIR = join(ROOT, "src/runtime/routes");
35
+ const PLUGIN_DEFAULTS_DIR = join(ROOT, "src/plugins/defaults");
35
36
  const OUTPUT_PATH = join(ROOT, "openapi.yaml");
36
37
  const PKG_PATH = join(ROOT, "package.json");
37
38
 
@@ -147,68 +148,89 @@ function resolveSchemaForDocument(schemaSource: unknown): ContentSchema {
147
148
  // ---------------------------------------------------------------------------
148
149
 
149
150
  /**
150
- * Dynamically import every route module under `src/runtime/routes/`
151
- * and collect all exported `ROUTES` arrays.
152
- *
153
- * Each route module is expected to export a `ROUTES: RouteDefinition[]`
154
- * constant. The function automatically picks up new route modules
155
- * without manual updates.
151
+ * Directories holding `RouteDefinition` modules: the host `runtime/routes`
152
+ * tree plus every default plugin's `routes/` subdirectory. A default plugin
153
+ * that owns model-facing HTTP/IPC routes defines them under
154
+ * `plugins/defaults/<plugin>/routes/` and the host route aggregator registers
155
+ * them at runtime; the generator scans those dirs too so the spec stays
156
+ * complete no matter which package a route lives in. Sorted for reproducible
157
+ * output (see {@link collectRoutesFromModules}).
158
+ */
159
+ async function routeModuleDirs(): Promise<string[]> {
160
+ const dirs = [ROUTES_DIR];
161
+ for (const entry of await readdir(PLUGIN_DEFAULTS_DIR, {
162
+ withFileTypes: true,
163
+ })) {
164
+ if (!entry.isDirectory()) continue;
165
+ const routesDir = join(PLUGIN_DEFAULTS_DIR, entry.name, "routes");
166
+ if (existsSync(routesDir)) dirs.push(routesDir);
167
+ }
168
+ return dirs.sort();
169
+ }
170
+
171
+ /**
172
+ * Dynamically import every route module under each {@link routeModuleDirs}
173
+ * entry and collect all exported `ROUTES` / `*_ROUTES` arrays. Each route
174
+ * module exports a `RouteDefinition[]`; new modules are picked up without
175
+ * manual updates.
156
176
  */
157
177
  async function collectRoutesFromModules(): Promise<RouteEntry[]> {
158
178
  const routes: RouteEntry[] = [];
159
179
 
160
- // Skip the `index.ts` barrel: it re-exports every other route module's
161
- // ROUTES into a single combined array, so importing it would double-count
162
- // every entry. The duplicate `method:endpoint` keys are deduped later by
163
- // first-seen, but the surviving entry's `sourceModule` (used to derive
164
- // OpenAPI `tags`) depends on `readdir` order — which is filesystem
165
- // dependent and diverges between local sandbox and the CI runner, making
166
- // the generator non-reproducible. Sort the file list as well so directory
167
- // entry order can never affect the output.
168
- const files = (await readdir(ROUTES_DIR, { recursive: true }))
169
- .filter(
170
- (f) =>
171
- typeof f === "string" &&
172
- f.endsWith(".ts") &&
173
- !f.endsWith(".test.ts") &&
174
- !f.endsWith(".benchmark.test.ts") &&
175
- !f.includes("node_modules") &&
176
- f !== "index.ts" &&
177
- !f.endsWith("/index.ts"),
178
- )
179
- .sort();
180
-
181
- for (const file of files) {
182
- const filePath = join(ROUTES_DIR, file);
183
- let mod: Record<string, unknown>;
184
- try {
185
- mod = (await import(filePath)) as Record<string, unknown>;
186
- } catch (err) {
187
- console.warn(
188
- `Warning: could not import ${file}: ${err instanceof Error ? err.message : err}`,
189
- );
190
- continue;
191
- }
192
-
193
- // Collect every export whose name is `ROUTES` or ends in `_ROUTES`.
194
- // A handful of route files (e.g. `channel-route-definitions.ts`,
195
- // `contact-prompt-routes.ts`) export under domain-prefixed names like
196
- // `CHANNEL_ROUTES` and `CONTACT_PROMPT_ROUTES` rather than the
197
- // canonical `ROUTES`. Without this fan-out the only way those routes
198
- // reached the spec was via the `index.ts` barrel — which is excluded
199
- // above for reproducibility.
200
- const exportNames = Object.keys(mod)
201
- .filter((k) => k === "ROUTES" || k.endsWith("_ROUTES"))
180
+ for (const dir of await routeModuleDirs()) {
181
+ // Skip the `index.ts` barrel: it re-exports every other route module's
182
+ // ROUTES into a single combined array, so importing it would double-count
183
+ // every entry. The duplicate `method:endpoint` keys are deduped later by
184
+ // first-seen, but the surviving entry's `sourceModule` (used to derive
185
+ // OpenAPI `tags`) depends on `readdir` order — which is filesystem
186
+ // dependent and diverges between local sandbox and the CI runner, making
187
+ // the generator non-reproducible. Sort the file list as well so directory
188
+ // entry order can never affect the output.
189
+ const files = (await readdir(dir, { recursive: true }))
190
+ .filter(
191
+ (f) =>
192
+ typeof f === "string" &&
193
+ f.endsWith(".ts") &&
194
+ !f.endsWith(".test.ts") &&
195
+ !f.endsWith(".benchmark.test.ts") &&
196
+ !f.includes("node_modules") &&
197
+ f !== "index.ts" &&
198
+ !f.endsWith("/index.ts"),
199
+ )
202
200
  .sort();
203
- for (const name of exportNames) {
204
- const arr = mod[name];
205
- if (!Array.isArray(arr)) continue;
206
- for (const raw of arr) {
207
- const result = RouteEntrySchema.safeParse({
208
- ...(typeof raw === "object" && raw !== null ? raw : {}),
209
- sourceModule: file,
210
- });
211
- if (result.success) routes.push(result.data);
201
+
202
+ for (const file of files) {
203
+ const filePath = join(dir, file);
204
+ let mod: Record<string, unknown>;
205
+ try {
206
+ mod = (await import(filePath)) as Record<string, unknown>;
207
+ } catch (err) {
208
+ console.warn(
209
+ `Warning: could not import ${file}: ${err instanceof Error ? err.message : err}`,
210
+ );
211
+ continue;
212
+ }
213
+
214
+ // Collect every export whose name is `ROUTES` or ends in `_ROUTES`.
215
+ // A handful of route files (e.g. `channel-route-definitions.ts`,
216
+ // `contact-prompt-routes.ts`) export under domain-prefixed names like
217
+ // `CHANNEL_ROUTES` and `CONTACT_PROMPT_ROUTES` rather than the
218
+ // canonical `ROUTES`. Without this fan-out the only way those routes
219
+ // reached the spec was via the `index.ts` barrel — which is excluded
220
+ // above for reproducibility.
221
+ const exportNames = Object.keys(mod)
222
+ .filter((k) => k === "ROUTES" || k.endsWith("_ROUTES"))
223
+ .sort();
224
+ for (const name of exportNames) {
225
+ const arr = mod[name];
226
+ if (!Array.isArray(arr)) continue;
227
+ for (const raw of arr) {
228
+ const result = RouteEntrySchema.safeParse({
229
+ ...(typeof raw === "object" && raw !== null ? raw : {}),
230
+ sourceModule: file,
231
+ });
232
+ if (result.success) routes.push(result.data);
233
+ }
212
234
  }
213
235
  }
214
236
  }
@@ -54,7 +54,7 @@ mock.module("../memory/v2/skill-store.js", () => ({
54
54
  const { registerMemoryV2Command } =
55
55
  await import("../cli/commands/memory/memory-v2.js");
56
56
  const { ROUTES: memoryV2Routes, MEMORY_V2_DISABLED_CODE } =
57
- await import("../runtime/routes/memory-v2-routes.js");
57
+ await import("../plugins/defaults/memory/routes/memory-v2-routes.js");
58
58
  const { RouteError } = await import("../runtime/routes/errors.js");
59
59
 
60
60
  // ---------------------------------------------------------------------------
@@ -36,6 +36,7 @@ mock.module("../util/logger.js", () => ({
36
36
 
37
37
  let denseEmbedReturn: number[] = [0.1, 0.2, 0.3];
38
38
  mock.module("../persistence/embeddings/embedding-backend.js", () => ({
39
+ isEmbeddingDimensionAvailable: async () => true,
39
40
  embedWithBackend: async () => ({
40
41
  provider: "test",
41
42
  model: "test-model",
@@ -113,6 +113,7 @@ mock.module("../persistence/jobs-store.js", () => ({
113
113
  state.enqueueCalls.push({ type, payload });
114
114
  return "test-job-id";
115
115
  },
116
+ hasActiveJobOfType: (): boolean => false,
116
117
  }));
117
118
 
118
119
  mock.module("../util/platform.js", () => ({
@@ -115,6 +115,7 @@ mock.module("../providers/registry.js", () => ({
115
115
  }));
116
116
 
117
117
  mock.module("../persistence/embeddings/embedding-backend.js", () => ({
118
+ isEmbeddingDimensionAvailable: async () => true,
118
119
  EmbeddingBackendUnavailableError: class EmbeddingBackendUnavailableError extends Error {},
119
120
  SPARSE_EMBEDDING_VERSION: 4,
120
121
  clearEmbeddingBackendCache: () => {},
@@ -91,15 +91,29 @@ const BASELINE: Record<string, readonly string[]> = {
91
91
  "../../../../daemon/message-types/memory.js",
92
92
  "../../../../daemon/trust-context.js",
93
93
  "../../../../memory/graph/conversation-graph-memory.js",
94
+ "../../../../memory/graph/store.js",
95
+ "../../../../memory/graph/types.js",
94
96
  "../../../../memory/memory-marker.js",
95
97
  "../../../../memory/memory-recall-log-store.js",
98
+ "../../../../memory/memory-v2-concept-frequency.js",
96
99
  "../../../../memory/prompt-override.js",
97
100
  "../../../../memory/v2/cli-command-store.js",
101
+ "../../../../memory/v2/edge-index.js",
102
+ "../../../../memory/v2/harness/compare.js",
103
+ "../../../../memory/v2/harness/retriever.js",
104
+ "../../../../memory/v2/harness/router-retriever.js",
105
+ "../../../../memory/v2/harness/runner.js",
98
106
  "../../../../memory/v2/injected-block-slugs.js",
107
+ "../../../../memory/v2/injection-events.js",
108
+ "../../../../memory/v2/now-text.js",
99
109
  "../../../../memory/v2/page-index.js",
100
110
  "../../../../memory/v2/page-store.js",
111
+ "../../../../memory/v2/prompts/router.js",
112
+ "../../../../memory/v2/router.js",
101
113
  "../../../../memory/v2/sim.js",
102
114
  "../../../../memory/v2/skill-store.js",
115
+ "../../../../memory/v3-eval/eval-packets.js",
116
+ "../../../../memory/v3-eval/eval-tally.js",
103
117
  "../../../../persistence/checkpoints.js",
104
118
  "../../../../persistence/conversation-crud.js",
105
119
  "../../../../persistence/db-connection.js",
@@ -108,13 +122,18 @@ const BASELINE: Record<string, readonly string[]> = {
108
122
  "../../../../persistence/embeddings/embedding-billing-breaker.js",
109
123
  "../../../../persistence/embeddings/embedding-cache.js",
110
124
  "../../../../persistence/embeddings/embedding-types.js",
125
+ "../../../../persistence/embeddings/qdrant-circuit-breaker.js",
111
126
  "../../../../persistence/embeddings/qdrant-client.js",
112
127
  "../../../../persistence/jobs-store.js",
113
128
  "../../../../persistence/message-content.js",
129
+ "../../../../persistence/schema/index.js",
114
130
  "../../../../providers/cache-control.js",
115
131
  "../../../../providers/provider-send-message.js",
116
132
  "../../../../providers/types.js",
117
133
  "../../../../runtime/assistant-event-hub.js",
134
+ "../../../../runtime/auth/route-policy.js",
135
+ "../../../../runtime/routes/errors.js",
136
+ "../../../../runtime/routes/types.js",
118
137
  "../../../../skills/frontmatter.js",
119
138
  "../../../../skills/install-meta.js",
120
139
  "../../../../tools/skills/delete-managed.js",
@@ -167,8 +186,10 @@ const BASELINE: Record<string, readonly string[]> = {
167
186
  "../injection-presence.js",
168
187
  "../injector-order.js",
169
188
  "@qdrant/js-client-rest",
189
+ "drizzle-orm",
170
190
  "node:crypto",
171
191
  "node:fs",
192
+ "node:fs/promises",
172
193
  "node:path",
173
194
  "uuid",
174
195
  "zod",
@@ -104,7 +104,7 @@ beforeEach(() => {
104
104
  });
105
105
 
106
106
  describe("Qdrant collection migration", () => {
107
- test("deletes and recreates collection on dimension mismatch", async () => {
107
+ test("deletes and recreates collection on pure dimension mismatch", async () => {
108
108
  mockCollectionExists = true;
109
109
  mockUseNamedVectors = true;
110
110
  mockCollectionSize = 384; // Current collection has 384-dim vectors
@@ -120,6 +120,9 @@ describe("Qdrant collection migration", () => {
120
120
 
121
121
  const result = await client.ensureCollection();
122
122
 
123
+ // The v1 collection is not managed by the startup embedding reconcile, so
124
+ // dimension drift is repaired here: delete + recreate, then rebuild_index
125
+ // re-embeds from the SQLite cache via the lifecycle hook.
123
126
  expect(callLog.deleteCollection).toBe(1);
124
127
  expect(callLog.createCollection).toBe(1);
125
128
  expect(result.migrated).toBe(true);
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Tests for workspace migration `117-normalize-stale-lean-memory-v3-defaults`.
3
+ *
4
+ * The first-launch seed persists the fully-defaulted config.json, so assistants
5
+ * created during the lean-default window stored the lean v3 tuning values as if
6
+ * explicit. The migration strips persisted v3 tuning leaves that equal the
7
+ * retired lean defaults so the restored full schema defaults re-apply, while
8
+ * preserving deliberate (non-lean) values, pre-lean full values, and untouched
9
+ * sibling fields. It never creates config.json and is idempotent.
10
+ */
11
+
12
+ import {
13
+ existsSync,
14
+ mkdtempSync,
15
+ readFileSync,
16
+ rmSync,
17
+ writeFileSync,
18
+ } from "node:fs";
19
+ import { tmpdir } from "node:os";
20
+ import { join } from "node:path";
21
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
22
+
23
+ import { MemoryV3ConfigSchema } from "../config/schemas/memory-v3.js";
24
+ import { normalizeStaleLeanMemoryV3DefaultsMigration } from "../workspace/migrations/117-normalize-stale-lean-memory-v3-defaults.js";
25
+
26
+ let workspaceDir: string;
27
+ let configPath: string;
28
+
29
+ beforeEach(() => {
30
+ workspaceDir = mkdtempSync(join(tmpdir(), "vellum-migration-117-test-"));
31
+ configPath = join(workspaceDir, "config.json");
32
+ });
33
+
34
+ afterEach(() => {
35
+ if (existsSync(workspaceDir)) {
36
+ rmSync(workspaceDir, { recursive: true, force: true });
37
+ }
38
+ });
39
+
40
+ function readConfig(): Record<string, unknown> {
41
+ return JSON.parse(readFileSync(configPath, "utf-8"));
42
+ }
43
+
44
+ /** A config.json as the first-launch seed would persist it on the lean build:
45
+ * the full v3 block with every tuning value at its lean default. */
46
+ function leanSeedConfig(): Record<string, unknown> {
47
+ return {
48
+ memory: {
49
+ v3: {
50
+ live: true,
51
+ prune: { maxResidentBytes: 393216, targetResidentBytes: 262144 },
52
+ hotSet: { k: 8, halfLifeDays: 14 },
53
+ freshSet: { k: 8 },
54
+ learnedEdges: {
55
+ halfLifeDays: 30,
56
+ minCount: 3,
57
+ npmiFloor: 0.2,
58
+ maxPerPage: 6,
59
+ perSeed: 3,
60
+ cap: 0,
61
+ },
62
+ spotlight: { n: 6, windowTurns: 2 },
63
+ needleK: 12,
64
+ denseK: 0,
65
+ replyQueryK: 0,
66
+ selectorEnabled: false,
67
+ selectorPromptPath: null,
68
+ edge: { hubDegree: 30, seedCount: 6, perSeed: 1, cap: 6 },
69
+ },
70
+ },
71
+ };
72
+ }
73
+
74
+ describe("117-normalize-stale-lean-memory-v3-defaults migration", () => {
75
+ test("has correct id and description", () => {
76
+ expect(normalizeStaleLeanMemoryV3DefaultsMigration.id).toBe(
77
+ "117-normalize-stale-lean-memory-v3-defaults",
78
+ );
79
+ expect(normalizeStaleLeanMemoryV3DefaultsMigration.description).toContain(
80
+ "memory.v3",
81
+ );
82
+ });
83
+
84
+ test("strips lean tuning leaves so the full schema defaults re-apply", () => {
85
+ writeFileSync(configPath, JSON.stringify(leanSeedConfig()), "utf-8");
86
+
87
+ normalizeStaleLeanMemoryV3DefaultsMigration.run(workspaceDir);
88
+
89
+ const v3 = (readConfig().memory as Record<string, unknown>).v3 as Record<
90
+ string,
91
+ unknown
92
+ >;
93
+ // The switched leaves are gone…
94
+ expect("needleK" in v3).toBe(false);
95
+ expect("denseK" in v3).toBe(false);
96
+ expect("replyQueryK" in v3).toBe(false);
97
+ expect("selectorEnabled" in v3).toBe(false);
98
+ expect("k" in (v3.hotSet as Record<string, unknown>)).toBe(false);
99
+ expect("k" in (v3.freshSet as Record<string, unknown>)).toBe(false);
100
+ expect("cap" in (v3.learnedEdges as Record<string, unknown>)).toBe(false);
101
+ const edge = v3.edge as Record<string, unknown>;
102
+ expect("seedCount" in edge).toBe(false);
103
+ expect("perSeed" in edge).toBe(false);
104
+ expect("cap" in edge).toBe(false);
105
+
106
+ // …untouched siblings survive…
107
+ expect(v3.live).toBe(true);
108
+ expect((v3.hotSet as Record<string, unknown>).halfLifeDays).toBe(14);
109
+ expect(edge.hubDegree).toBe(30);
110
+ expect((v3.learnedEdges as Record<string, unknown>).perSeed).toBe(3);
111
+
112
+ // …and re-parsing yields the restored full profile.
113
+ const parsed = MemoryV3ConfigSchema.parse(v3);
114
+ expect(parsed.needleK).toBe(100);
115
+ expect(parsed.denseK).toBe(100);
116
+ expect(parsed.replyQueryK).toBe(12);
117
+ expect(parsed.selectorEnabled).toBe(true);
118
+ expect(parsed.hotSet.k).toBe(40);
119
+ expect(parsed.freshSet.k).toBe(100);
120
+ expect(parsed.learnedEdges.cap).toBe(20);
121
+ expect(parsed.edge).toEqual({
122
+ hubDegree: 30,
123
+ seedCount: 18,
124
+ perSeed: 6,
125
+ cap: 45,
126
+ });
127
+ });
128
+
129
+ test("leaves a config with any non-lean tuning untouched (not the lean-seed signature)", () => {
130
+ // A lean-seed config the user later edited one field of no longer matches
131
+ // the all-lean signature, so the migration leaves it alone rather than
132
+ // partially rewriting an explicit config.
133
+ const config = leanSeedConfig();
134
+ (
135
+ (config.memory as Record<string, unknown>).v3 as Record<string, unknown>
136
+ ).needleK = 50;
137
+ const original = JSON.stringify(config);
138
+ writeFileSync(configPath, original, "utf-8");
139
+
140
+ normalizeStaleLeanMemoryV3DefaultsMigration.run(workspaceDir);
141
+
142
+ expect(readFileSync(configPath, "utf-8")).toBe(original);
143
+ });
144
+
145
+ test("preserves a deliberate lean-valued override (partial config, not a full seed)", () => {
146
+ // An established assistant that deliberately disables dense retrieval must
147
+ // keep that choice — a lone lean-valued leaf is not the seed signature.
148
+ const original = JSON.stringify({ memory: { v3: { denseK: 0 } } });
149
+ writeFileSync(configPath, original, "utf-8");
150
+
151
+ normalizeStaleLeanMemoryV3DefaultsMigration.run(workspaceDir);
152
+
153
+ expect(readFileSync(configPath, "utf-8")).toBe(original);
154
+ });
155
+
156
+ test("leaves a pre-lean full config untouched (no write)", () => {
157
+ const fullConfig = {
158
+ memory: {
159
+ v3: {
160
+ needleK: 100,
161
+ denseK: 100,
162
+ replyQueryK: 12,
163
+ selectorEnabled: true,
164
+ hotSet: { k: 40, halfLifeDays: 14 },
165
+ freshSet: { k: 100 },
166
+ learnedEdges: { cap: 20, maxPerPage: 6 },
167
+ edge: { hubDegree: 30, seedCount: 18, perSeed: 6, cap: 45 },
168
+ },
169
+ },
170
+ };
171
+ const original = JSON.stringify(fullConfig);
172
+ writeFileSync(configPath, original, "utf-8");
173
+
174
+ normalizeStaleLeanMemoryV3DefaultsMigration.run(workspaceDir);
175
+
176
+ expect(readFileSync(configPath, "utf-8")).toBe(original);
177
+ });
178
+
179
+ test("no-op when config.json is absent (never creates it)", () => {
180
+ normalizeStaleLeanMemoryV3DefaultsMigration.run(workspaceDir);
181
+ expect(existsSync(configPath)).toBe(false);
182
+ });
183
+
184
+ test("no-op when there is no memory.v3 block", () => {
185
+ const original = JSON.stringify({ memory: { enabled: true } });
186
+ writeFileSync(configPath, original, "utf-8");
187
+
188
+ normalizeStaleLeanMemoryV3DefaultsMigration.run(workspaceDir);
189
+
190
+ expect(readFileSync(configPath, "utf-8")).toBe(original);
191
+ });
192
+
193
+ test("leaves malformed config.json untouched", () => {
194
+ writeFileSync(configPath, "{ not json", "utf-8");
195
+
196
+ normalizeStaleLeanMemoryV3DefaultsMigration.run(workspaceDir);
197
+
198
+ expect(readFileSync(configPath, "utf-8")).toBe("{ not json");
199
+ });
200
+
201
+ test("is idempotent", () => {
202
+ writeFileSync(configPath, JSON.stringify(leanSeedConfig()), "utf-8");
203
+
204
+ normalizeStaleLeanMemoryV3DefaultsMigration.run(workspaceDir);
205
+ const afterFirst = readFileSync(configPath, "utf-8");
206
+
207
+ normalizeStaleLeanMemoryV3DefaultsMigration.run(workspaceDir);
208
+
209
+ expect(readFileSync(configPath, "utf-8")).toBe(afterFirst);
210
+ });
211
+
212
+ test("down is a no-op", () => {
213
+ writeFileSync(configPath, JSON.stringify(leanSeedConfig()), "utf-8");
214
+ normalizeStaleLeanMemoryV3DefaultsMigration.run(workspaceDir);
215
+ const before = readFileSync(configPath, "utf-8");
216
+
217
+ normalizeStaleLeanMemoryV3DefaultsMigration.down(workspaceDir);
218
+
219
+ expect(readFileSync(configPath, "utf-8")).toBe(before);
220
+ });
221
+ });