@vellumai/assistant 0.10.6-dev.202607071257.f3dae96 → 0.10.6-dev.202607071505.bca897f

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 (74) hide show
  1. package/AGENTS.md +2 -0
  2. package/openapi.yaml +80 -1
  3. package/package.json +1 -1
  4. package/src/__tests__/config-loader-backfill.test.ts +15 -9
  5. package/src/__tests__/db-template-cache.ts +48 -0
  6. package/src/__tests__/db-template-helpers.ts +264 -0
  7. package/src/__tests__/events-tail-route.test.ts +179 -0
  8. package/src/__tests__/mtime-cache.test.ts +29 -1
  9. package/src/__tests__/plugin-effective-enabled-set.test.ts +16 -9
  10. package/src/__tests__/scheduler-recurrence.test.ts +19 -88
  11. package/src/__tests__/scheduler-reuse-conversation.test.ts +18 -77
  12. package/src/__tests__/scheduler-wake.test.ts +12 -52
  13. package/src/__tests__/test-preload.ts +8 -0
  14. package/src/__tests__/tools-get-route.test.ts +70 -0
  15. package/src/cli/commands/tools.ts +23 -7
  16. package/src/cli/lib/__tests__/diff-plugin.test.ts +2 -5
  17. package/src/cli/lib/__tests__/inspect-plugin.test.ts +1 -1
  18. package/src/cli/lib/__tests__/install-from-github.test.ts +1 -1
  19. package/src/cli/lib/__tests__/plugin-details.test.ts +1 -1
  20. package/src/cli/lib/__tests__/plugin-marketplace.test.ts +1 -1
  21. package/src/cli/lib/__tests__/plugin-pin-history.test.ts +1 -1
  22. package/src/cli/lib/__tests__/search-plugins.test.ts +1 -1
  23. package/src/cli/lib/__tests__/upgrade-plugin.test.ts +1 -1
  24. package/src/cli/lib/diff-plugin.ts +1 -1
  25. package/src/cli/lib/fetch-like.ts +11 -0
  26. package/src/cli/lib/inspect-plugin.ts +1 -1
  27. package/src/cli/lib/install-from-github.ts +1 -12
  28. package/src/cli/lib/plugin-details.ts +1 -1
  29. package/src/cli/lib/plugin-marketplace.ts +1 -4
  30. package/src/cli/lib/plugin-pin-history.ts +2 -1
  31. package/src/cli/lib/search-plugins.ts +1 -5
  32. package/src/cli/lib/upgrade-plugin.ts +1 -1
  33. package/src/config/__tests__/default-profile-catalog.test.ts +196 -0
  34. package/src/config/default-profile-catalog.ts +396 -0
  35. package/src/config/default-profile-names.ts +24 -0
  36. package/src/config/inference-profile-validation.ts +5 -4
  37. package/src/config/llm-resolver.ts +13 -8
  38. package/src/config/schemas/llm.ts +4 -0
  39. package/src/config/seed-inference-profiles.ts +13 -197
  40. package/src/config/sync-gated-profiles.ts +5 -3
  41. package/src/daemon/conversation-runtime-assembly.ts +2 -1
  42. package/src/daemon/conversation-slash.ts +2 -4
  43. package/src/daemon/conversation-tool-setup.ts +1 -1
  44. package/src/hooks/__tests__/hook-live-reload.test.ts +49 -29
  45. package/src/hooks/hook-loader.ts +187 -172
  46. package/src/monitoring/__tests__/resource-sampler.test.ts +2 -4
  47. package/src/monitoring/__tests__/stall-capture.test.ts +1 -1
  48. package/src/monitoring/resource-sample-types.ts +71 -0
  49. package/src/monitoring/resource-sampler.ts +7 -69
  50. package/src/monitoring/stall-capture.ts +1 -1
  51. package/src/persistence/db-init.ts +41 -152
  52. package/src/plugin-api/vision-support.ts +3 -2
  53. package/src/plugins/defaults/memory/v2/harness/harness-types.ts +12 -0
  54. package/src/plugins/defaults/memory/v2/harness/retriever.ts +1 -8
  55. package/src/plugins/defaults/memory/v2/harness/trace.ts +1 -1
  56. package/src/plugins/mtime-cache.ts +25 -22
  57. package/src/providers/inference/connections.ts +6 -10
  58. package/src/providers/vellum-model-routing.ts +11 -0
  59. package/src/runtime/http-router-types.ts +119 -0
  60. package/src/runtime/http-router.ts +2 -115
  61. package/src/runtime/routes/__tests__/monitoring-routes.test.ts +1 -1
  62. package/src/runtime/routes/conversation-query-routes.ts +5 -2
  63. package/src/runtime/routes/conversation-routes.ts +2 -1
  64. package/src/runtime/routes/events-routes.ts +144 -8
  65. package/src/runtime/routes/http-adapter.ts +1 -1
  66. package/src/runtime/routes/inference-profile-session-handler.ts +2 -1
  67. package/src/runtime/routes/inference-provider-connection-routes.ts +2 -1
  68. package/src/runtime/routes/inference-send-routes.ts +2 -1
  69. package/src/runtime/routes/llm-call-sites-routes.ts +2 -1
  70. package/src/runtime/routes/monitoring-routes.ts +1 -1
  71. package/src/runtime/routes/settings-routes.ts +153 -15
  72. package/src/tools/workflows/manage-workflows.ts +2 -1
  73. package/src/usage/attribution.ts +2 -1
  74. package/src/workflows/leaf-runner.ts +2 -1
package/AGENTS.md CHANGED
@@ -12,6 +12,8 @@ When you introduce a new env var that the assistant process needs to read at run
12
12
 
13
13
  **Default to including it.** If the var doesn't contain secrets (e.g. a URL, a feature flag, a path, a mode string), add it. Only omit it if it carries credential material (tokens, passwords, private keys) — those must stay isolated to CES.
14
14
 
15
+ `CES_LOCAL_SOCKET` is intentionally included despite the socket exposing credential RPCs — assistant subprocesses are expected to reach CES. Credential protection is rules-based access control inside CES, not socket-path secrecy (see root `AGENTS.md`).
16
+
15
17
  ## Daemon startup philosophy
16
18
 
17
19
  The daemon must **never** block startup due to **subsystem** failures (DB, Qdrant, plugins, feature flags, etc.). If an individual subsystem fails, log the error and continue in degraded mode so the process remains reachable for health checks and diagnostics.
package/openapi.yaml CHANGED
@@ -11320,6 +11320,76 @@ paths:
11320
11320
  responses:
11321
11321
  "204":
11322
11322
  description: Successful response
11323
+ /v1/events/tail:
11324
+ get:
11325
+ operationId: events_tail_get
11326
+ summary: Fetch a conversation's buffered event tail
11327
+ description:
11328
+ Return the ring-buffered assistant events for one conversation with seq greater than fromSeq — the
11329
+ request/response twin of reconnecting the SSE stream with lastSeenSeq. A client recovering from a delivery gap
11330
+ fetches the /messages snapshot (anchored at its seq watermark) and then this tail from that anchor, folding the
11331
+ returned envelopes through the same apply path as live events; snapshot plus tail is deterministically complete.
11332
+ complete=false means the ring no longer reaches back to fromSeq and the snapshot alone must serve as the
11333
+ recovery.
11334
+ tags:
11335
+ - events
11336
+ parameters:
11337
+ - name: conversationId
11338
+ in: query
11339
+ required: false
11340
+ schema:
11341
+ type: string
11342
+ description: Assistant-minted internal conversation id whose events to return. Required.
11343
+ - name: fromSeq
11344
+ in: query
11345
+ required: false
11346
+ schema:
11347
+ type: string
11348
+ description:
11349
+ Return buffered events with seq strictly greater than this value — typically the seq watermark of a
11350
+ just-fetched /messages snapshot. Must be a non-negative integer.
11351
+ - name: toSeq
11352
+ in: query
11353
+ required: false
11354
+ schema:
11355
+ type: string
11356
+ description:
11357
+ Optional inclusive upper bound on returned seqs. A caller that already knows where its live delivery
11358
+ resumed (e.g. the first live event after a gap) can trim the response to exactly the hole. Purely a
11359
+ bandwidth trim — client folds are seq-idempotent, so overlap with live delivery is harmless without it. Must
11360
+ be an integer >= fromSeq.
11361
+ responses:
11362
+ "200":
11363
+ description: Successful response
11364
+ content:
11365
+ application/json:
11366
+ schema:
11367
+ type: object
11368
+ properties:
11369
+ events:
11370
+ type: array
11371
+ items: {}
11372
+ description:
11373
+ Buffered assistant event envelopes ({id, conversationId, emittedAt, seq, message}) with seq > fromSeq,
11374
+ ascending, filtered to the conversation and to the caller's delivery set (client identity
11375
+ headers). Same wire shape as the /events SSE data frames.
11376
+ complete:
11377
+ type: boolean
11378
+ description:
11379
+ True when the ring still covered fromSeq, so the returned events are the contiguous tail. False when
11380
+ eviction broke contiguity — events is empty and the caller must recover from the snapshot alone.
11381
+ frontier:
11382
+ anyOf:
11383
+ - type: number
11384
+ - type: "null"
11385
+ description:
11386
+ Seq of the last returned event (or fromSeq when the tail is empty but contiguous). Null when complete is
11387
+ false.
11388
+ required:
11389
+ - events
11390
+ - complete
11391
+ - frontier
11392
+ additionalProperties: false
11323
11393
  /v1/export:
11324
11394
  post:
11325
11395
  operationId: export_post
@@ -28597,7 +28667,8 @@ paths:
28597
28667
  skill, plugin, or MCP server) and `names`/`schemas` additionally cover skill tools whose manifests are present
28598
28668
  but not yet loaded, for the permission-simulator catalog. With `conversationId`, scopes the result to the tools
28599
28669
  available to that conversation as of its most recent turn (including skill/MCP tools registered over its
28600
- lifecycle); 404 if no such conversation is active."
28670
+ lifecycle); 404 if no such conversation is active. With `agent`, simulates the subagent tool projection for a
28671
+ given role or resolves a live subagent's conversation."
28601
28672
  tags:
28602
28673
  - tools
28603
28674
  parameters:
@@ -28607,6 +28678,14 @@ paths:
28607
28678
  schema:
28608
28679
  type: string
28609
28680
  description: When set, scope the tool inventory to this conversation's most recent turn instead of the global registry.
28681
+ - name: agent
28682
+ in: query
28683
+ required: false
28684
+ schema:
28685
+ type: string
28686
+ description:
28687
+ A subagent role name or a live subagent id. Simulates the subagent tool projection for that role or
28688
+ resolves the live subagent's conversation.
28610
28689
  responses:
28611
28690
  "200":
28612
28691
  description: Successful response
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.6-dev.202607071257.f3dae96",
3
+ "version": "0.10.6-dev.202607071505.bca897f",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -67,6 +67,11 @@ afterAll(() => {
67
67
  mock.restore();
68
68
  });
69
69
 
70
+ import {
71
+ MANAGED_PROFILE_NAMES,
72
+ materializeProfile,
73
+ OS_BETA_PROFILE_TEMPLATE,
74
+ } from "../config/default-profile-catalog.js";
70
75
  import { resolveCallSiteConfig } from "../config/llm-resolver.js";
71
76
  import {
72
77
  deepMergeOverwrite,
@@ -75,12 +80,7 @@ import {
75
80
  loadConfig,
76
81
  mergeDefaultWorkspaceConfig,
77
82
  } from "../config/loader.js";
78
- import {
79
- MANAGED_PROFILE_NAMES,
80
- materializeProfile,
81
- OS_BETA_PROFILE_TEMPLATE,
82
- seedInferenceProfiles,
83
- } from "../config/seed-inference-profiles.js";
83
+ import { seedInferenceProfiles } from "../config/seed-inference-profiles.js";
84
84
  import type { DrizzleDb } from "../persistence/db-connection.js";
85
85
  import { migrateCreateProviderConnections } from "../persistence/migrations/243-provider-connections.js";
86
86
  import { migrateProviderConnectionStatusLabel } from "../persistence/migrations/244-provider-connection-status-label.js";
@@ -1191,7 +1191,8 @@ describe("loadConfig startup behavior", () => {
1191
1191
  const config = loadConfig();
1192
1192
  const mainAgentConfig = resolveCallSiteConfig("mainAgent", config.llm);
1193
1193
 
1194
- // Hatch boot: overlay fragment is preserved verbatim (preserveProfileNames).
1194
+ // Hatch boot: overlay fragment is preserved verbatim on disk
1195
+ // (preserveProfileNames).
1195
1196
  expect(config.llm.activeProfile).toBe("balanced");
1196
1197
  expect(config.llm.profiles.balanced).toEqual({
1197
1198
  source: "managed",
@@ -1199,8 +1200,13 @@ describe("loadConfig startup behavior", () => {
1199
1200
  model: "gpt-5.4",
1200
1201
  label: "Platform Balanced",
1201
1202
  });
1202
- expect(mainAgentConfig.provider).toBe("openai");
1203
- expect(mainAgentConfig.model).toBe("gpt-5.4");
1203
+ // Resolution serves default-profile CONTENT from the code catalog: a
1204
+ // managed-source workspace entry contributes only label/status/topP, so
1205
+ // the overlay's provider/model never reach the resolver — even on the
1206
+ // overlay boot. The overlay-set label is what survives into the
1207
+ // effective view.
1208
+ expect(mainAgentConfig.provider).toBe("fireworks");
1209
+ expect(mainAgentConfig.model).toBe("accounts/fireworks/models/glm-5p2");
1204
1210
 
1205
1211
  const raw = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
1206
1212
  expect(raw.llm.profiles.balanced).toEqual({
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Installs the test-only DB migration-template cache onto the shared
3
+ * `globalThis.vellumAssistant.dbTemplateCache` slot that
4
+ * `persistence/db-init.ts` reads. Called once from the test preload, alongside
5
+ * the other `install*()` mocks.
6
+ *
7
+ * Preload-safe by construction
8
+ * ----------------------------
9
+ * The test preload must not pull the heavy persistence graph (drizzle, schema)
10
+ * in at import time — that is the DB-ghost hazard the isolation rule guards
11
+ * against. So this module has ZERO static `src/` imports: the real
12
+ * implementation in `db-template-helpers.ts` (which does import `src/`) is
13
+ * loaded via a lazy `require()` on the FIRST `initializeDb()` call, i.e. at
14
+ * test-execution time after the workspace override is set.
15
+ *
16
+ * The slot shape is duplicated here on purpose (it also lives in
17
+ * `db-init.ts`) — matching the `dbSingletons` / `featureFlagCache` pattern, the
18
+ * production owner and the test installer reference the shared namespace
19
+ * independently and neither imports the other.
20
+ */
21
+
22
+ import { createRequire } from "node:module";
23
+
24
+ const require = createRequire(import.meta.url);
25
+
26
+ // Mirrors `DbTemplateCache` in `persistence/db-init.ts`. Duplicated by design —
27
+ // see the module comment above.
28
+ type DbTemplateCache = {
29
+ tryRestore(): boolean;
30
+ save(): void;
31
+ };
32
+
33
+ type VellumAssistantNamespace = {
34
+ dbTemplateCache?: DbTemplateCache | null;
35
+ };
36
+
37
+ export function installDbTemplateCache(): void {
38
+ const g = globalThis as { vellumAssistant?: VellumAssistantNamespace };
39
+ const ns = (g.vellumAssistant ??= {});
40
+ // Lazy require: defers loading the persistence graph until a test actually
41
+ // calls initializeDb(), keeping the preload's import chain free of `src/`.
42
+ const impl = () =>
43
+ require("./db-template-helpers.js") as typeof import("./db-template-helpers.js");
44
+ ns.dbTemplateCache = {
45
+ tryRestore: () => impl().tryRestoreTemplate(),
46
+ save: () => impl().saveTemplate(),
47
+ };
48
+ }
@@ -0,0 +1,264 @@
1
+ /**
2
+ * Test-only DB migration-template cache: run the migration chain once per
3
+ * process, then restore a pre-migrated template into every subsequent test file
4
+ * by file copy instead of re-running all ~260 steps.
5
+ *
6
+ * This is the implementation half of the seam declared in
7
+ * `persistence/db-init.ts`. `initializeDb()` reads a `tryRestore()`/`save()`
8
+ * hook off `globalThis.vellumAssistant.dbTemplateCache`; the test preload
9
+ * installs one (see `db-template-cache.ts`) whose bodies delegate here. Keeping
10
+ * the logic in a test file — not in `db-init.ts` — keeps this test-only
11
+ * machinery out of the production module.
12
+ *
13
+ * Why this file may import from `src/`
14
+ * ------------------------------------
15
+ * The test-machinery isolation rule (see `assistant/AGENTS.md`) forbids
16
+ * `src/`-reaching imports only for infrastructure that runs BEFORE the per-test
17
+ * workspace override is set — the preload, the verifier, and preload-imported
18
+ * helpers. This module is different: it is `require()`d lazily by
19
+ * `db-template-cache.ts` on the FIRST `initializeDb()` call, i.e. at
20
+ * test-execution time, after the workspace override is in place. It therefore
21
+ * imports production modules like any regular `*.test.ts` file. It must never be
22
+ * imported statically by the preload (that would pull the drizzle/schema graph
23
+ * in at preload time — the DB-ghost hazard the rule guards against).
24
+ */
25
+
26
+ import { createHash } from "node:crypto";
27
+ import {
28
+ copyFileSync,
29
+ existsSync,
30
+ readdirSync,
31
+ readFileSync,
32
+ renameSync,
33
+ rmSync,
34
+ } from "node:fs";
35
+ import { tmpdir } from "node:os";
36
+ import { dirname, join } from "node:path";
37
+ import type { Database } from "bun:sqlite";
38
+
39
+ import { _resetDisplayOrderMigrationForTests } from "../persistence/conversation-display-order-migration.js";
40
+ import { _resetGroupMigrationForTests } from "../persistence/conversation-group-migration.js";
41
+ import {
42
+ getDb,
43
+ getLogsDb,
44
+ getLogsSqlite,
45
+ getMemoryDb,
46
+ getMemorySqlite,
47
+ getSqlite,
48
+ getTelemetryDb,
49
+ getTelemetrySqlite,
50
+ } from "../persistence/db-connection.js";
51
+ import { getLogsDbPath } from "../util/logs-db-path.js";
52
+ import { getMemoryDbPath } from "../util/memory-db-path.js";
53
+ import { ensureDataDir, getDbPath } from "../util/platform.js";
54
+ import { getTelemetryDbPath } from "../util/telemetry-db-path.js";
55
+
56
+ function getTemplateDbPath(): string {
57
+ // Hash this file + all migration files + bootstrap migration + steps.ts so the
58
+ // template auto-invalidates when any migration (or the build logic here)
59
+ // changes. The migrations and steps array live in the `persistence/`
60
+ // directory; the bootstrap migration lives under the sibling `memory/`
61
+ // directory.
62
+ const thisFile = new URL(import.meta.url).pathname;
63
+ const persistenceDir = join(dirname(thisFile), "..", "persistence");
64
+ const memoryDir = join(persistenceDir, "..", "memory");
65
+ const hash = createHash("md5");
66
+ hash.update(readFileSync(thisFile, "utf-8"));
67
+ const migrationsDir = join(persistenceDir, "migrations");
68
+ for (const name of readdirSync(migrationsDir).sort()) {
69
+ if (name.endsWith(".ts")) {
70
+ hash.update(readFileSync(join(migrationsDir, name), "utf-8"));
71
+ }
72
+ }
73
+ // Include the bootstrap migration (migrateToolCreatedItems) which also runs
74
+ // during initializeDb but lives outside the migrations/ directory.
75
+ const bootstrapFile = join(memoryDir, "graph", "bootstrap.ts");
76
+ if (existsSync(bootstrapFile)) {
77
+ hash.update(readFileSync(bootstrapFile, "utf-8"));
78
+ }
79
+ // Include steps.ts which defines the migration step array so the template
80
+ // invalidates when steps change.
81
+ const stepsFile = join(persistenceDir, "steps.ts");
82
+ if (existsSync(stepsFile)) {
83
+ hash.update(readFileSync(stepsFile, "utf-8"));
84
+ }
85
+ return join(
86
+ tmpdir(),
87
+ `vellum-test-db-template-${hash.digest("hex").slice(0, 12)}.db`,
88
+ );
89
+ }
90
+
91
+ /**
92
+ * Template path for the dedicated `logs` database, kept alongside the main
93
+ * template. All three must be captured/restored together: the migrated state
94
+ * spans them (llm_request_logs and its indexes live in `logs`), so restoring
95
+ * only the main DB would leave a fresh, empty logs DB with no
96
+ * `llm_request_logs` table.
97
+ */
98
+ function getLogsTemplateDbPath(): string {
99
+ return `${getTemplateDbPath()}.logs`;
100
+ }
101
+
102
+ /**
103
+ * Template path for the dedicated `memory` database, kept alongside the main and
104
+ * logs templates. Captured/restored together with them so the restored test DB
105
+ * includes `memory_jobs` (created by migration 298).
106
+ */
107
+ function getMemoryTemplateDbPath(): string {
108
+ return `${getTemplateDbPath()}.memory`;
109
+ }
110
+
111
+ /**
112
+ * Template path for the dedicated `telemetry` database, kept alongside the other
113
+ * templates. Captured/restored together with them so the restored test DB
114
+ * includes `watchdog_events` (created by migration 301).
115
+ */
116
+ function getTelemetryTemplateDbPath(): string {
117
+ return `${getTemplateDbPath()}.telemetry`;
118
+ }
119
+
120
+ /**
121
+ * Replace `destPath` with a fresh copy of `templatePath`.
122
+ *
123
+ * Removes the destination `.db` AND its `-wal`/`-shm` sidecars before copying,
124
+ * for two reasons:
125
+ * - A test that re-restores mid-run (`resetDbForTesting()` + `initializeDb()`
126
+ * in a `beforeEach`) leaves `-wal`/`-shm` files behind: bun's
127
+ * `sqlite.close()` does not checkpoint, so committed frames sit in a stale
128
+ * `-wal`. Copying a fresh main `.db` over them leaves WAL frames that no
129
+ * longer match, so the next open reads back either stale rows or
130
+ * `SQLITE_CORRUPT` ("database disk image is malformed").
131
+ * - Deleting the main file (rather than overwriting it in place) hands SQLite
132
+ * a brand-new inode. Overwriting the existing inode while a just-closed
133
+ * connection's memory-map lingers can make the reopen fail with
134
+ * `SQLITE_BUSY` ("database is locked").
135
+ */
136
+ function restoreDbFile(templatePath: string, destPath: string): void {
137
+ rmSync(destPath, { force: true });
138
+ rmSync(`${destPath}-wal`, { force: true });
139
+ rmSync(`${destPath}-shm`, { force: true });
140
+ copyFileSync(templatePath, destPath);
141
+ }
142
+
143
+ /**
144
+ * Restore a pre-migrated template into the current workspace. Returns true on a
145
+ * cache hit (the DBs are ready and fully migrated), false on a miss (the caller
146
+ * must run the full migration chain, which then calls {@link saveTemplate}).
147
+ */
148
+ export function tryRestoreTemplate(): boolean {
149
+ const templatePath = getTemplateDbPath();
150
+ const logsTemplate = getLogsTemplateDbPath();
151
+ const memoryTemplate = getMemoryTemplateDbPath();
152
+ const telemetryTemplate = getTelemetryTemplateDbPath();
153
+ // Restore only when ALL FOUR templates are present. `saveTemplate()` renames
154
+ // them one at a time, so a parallel test worker can momentarily observe the
155
+ // main template without its logs/memory/telemetry siblings. Restoring then
156
+ // would copy the main DB, leave the dedicated DBs as fresh empty files, and
157
+ // skip migrations — so the next `watchdog_events`/`llm_request_logs`/
158
+ // `memory_jobs` access would fail with a missing-table error. Treating a
159
+ // partial set as "not ready" makes such a worker fall through to a full
160
+ // migrate, which creates every table.
161
+ if (
162
+ !existsSync(templatePath) ||
163
+ !existsSync(logsTemplate) ||
164
+ !existsSync(memoryTemplate) ||
165
+ !existsSync(telemetryTemplate)
166
+ ) {
167
+ return false;
168
+ }
169
+ // getDb() hasn't run yet, so the data directory may not exist.
170
+ ensureDataDir();
171
+ restoreDbFile(templatePath, getDbPath());
172
+ // Restore the dedicated logs/memory/telemetry DBs before their connections
173
+ // open, so the relocated tables are present.
174
+ restoreDbFile(logsTemplate, getLogsDbPath());
175
+ restoreDbFile(memoryTemplate, getMemoryDbPath());
176
+ restoreDbFile(telemetryTemplate, getTelemetryDbPath());
177
+ // Open the pre-migrated copies — the getters set PRAGMAs but skip DDL. Open
178
+ // ALL FOUR connections here, not just main. The full-migration path opens the
179
+ // dedicated logs/memory/telemetry connections as a side effect (migrations
180
+ // 297/298/301 touch them via getMemorySqlite() etc.), so those singletons end
181
+ // up cached against the current workspace. A test that pins the workspace in
182
+ // its top-level body, calls initializeDb(), then swaps VELLUM_WORKSPACE_DIR in
183
+ // a beforeAll hook relies on that caching: the swap is harmless only because
184
+ // the connection is already open. If restore left them unopened, the first
185
+ // post-swap getMemoryDb() would lazily open a fresh, empty DB in the new
186
+ // workspace — missing memory_jobs/llm_request_logs/watchdog_events. Opening
187
+ // them now keeps the restore path behaviourally identical to a full migrate.
188
+ getDb();
189
+ getLogsDb();
190
+ getMemoryDb();
191
+ getTelemetryDb();
192
+ // Reset the process-level guards for the lazy runtime migrations
193
+ // (conversations.group_id; display_order/is_pinned). These run on first
194
+ // conversation access — NOT as part of migrationSteps — so the template does
195
+ // not (and should not) contain their columns: the migrations' own tests need a
196
+ // pristine, pre-migration schema to exercise them. But the guards are
197
+ // module-level booleans that survive a DB swap. Without resetting them, a test
198
+ // that re-restores mid-run (resetDbForTesting() + initializeDb() in a
199
+ // beforeEach) gets a fresh template DB without those columns while the guard
200
+ // still reads "already migrated", so the next conversation query fails with
201
+ // "no such column". Resetting here makes each restored DB re-run the lazy
202
+ // migrations on first access, exactly as an un-cached full migrate would.
203
+ _resetGroupMigrationForTests();
204
+ _resetDisplayOrderMigrationForTests();
205
+ return true;
206
+ }
207
+
208
+ /**
209
+ * Snapshot a live connection to `destPath` via `VACUUM INTO`.
210
+ *
211
+ * We deliberately do NOT `copyFileSync` the live database file. These
212
+ * connections run in WAL mode; a raw file copy captures only the main file and
213
+ * not its `-wal`/`-shm` sidecars, so any page still living in the WAL — or a
214
+ * physical layout left behind by dropped virtual/FTS tables — produces a
215
+ * snapshot that opens but reads back as `SQLITE_CORRUPT` ("database disk image
216
+ * is malformed") on the wrong access pattern. `VACUUM INTO` asks SQLite itself
217
+ * to write a fresh, fully-checkpointed, defragmented database at `destPath`,
218
+ * which is guaranteed consistent regardless of WAL state or table history.
219
+ *
220
+ * `VACUUM INTO` requires the destination not to exist, so a stale temp file
221
+ * from a previously-crashed same-pid run is removed first.
222
+ */
223
+ function vacuumInto(sqlite: Database, destPath: string): void {
224
+ rmSync(destPath, { force: true });
225
+ // destPath is a machine-generated tmpdir path (no single quotes), so simple
226
+ // single-quote quoting is safe here.
227
+ sqlite.exec(`VACUUM INTO '${destPath}'`);
228
+ }
229
+
230
+ /**
231
+ * Capture the just-migrated main + dedicated DBs as the template for later
232
+ * restores. Best-effort: on any failure the next test file simply runs the full
233
+ * migration chain again.
234
+ */
235
+ export function saveTemplate(): void {
236
+ try {
237
+ const logsSqlite = getLogsSqlite();
238
+ const memorySqlite = getMemorySqlite();
239
+ const telemetrySqlite = getTelemetrySqlite();
240
+ // Every template must be captured or the set is unusable — tryRestoreTemplate
241
+ // treats a partial set as "not ready". If a dedicated connection failed to
242
+ // open, skip saving entirely so the next file falls through to a full migrate.
243
+ if (!logsSqlite || !memorySqlite || !telemetrySqlite) {
244
+ return;
245
+ }
246
+
247
+ const mainTmp = `${getTemplateDbPath()}.${process.pid}`;
248
+ vacuumInto(getSqlite(), mainTmp);
249
+ const logsTmp = `${getLogsTemplateDbPath()}.${process.pid}`;
250
+ vacuumInto(logsSqlite, logsTmp);
251
+ const memoryTmp = `${getMemoryTemplateDbPath()}.${process.pid}`;
252
+ vacuumInto(memorySqlite, memoryTmp);
253
+ const telemetryTmp = `${getTelemetryTemplateDbPath()}.${process.pid}`;
254
+ vacuumInto(telemetrySqlite, telemetryTmp);
255
+
256
+ // Atomic renames — safe even with parallel test workers.
257
+ renameSync(mainTmp, getTemplateDbPath());
258
+ renameSync(logsTmp, getLogsTemplateDbPath());
259
+ renameSync(memoryTmp, getMemoryTemplateDbPath());
260
+ renameSync(telemetryTmp, getTelemetryTemplateDbPath());
261
+ } catch {
262
+ // Best effort — next file will just run migrations normally.
263
+ }
264
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Tests for `GET /v1/events/tail` — the replay-by-request companion to the
3
+ * SSE `lastSeenSeq` resume.
4
+ *
5
+ * Pins:
6
+ * 1. The tail is the conversation-filtered ring window with
7
+ * `seq > fromSeq`, ascending, with `frontier` at the last returned seq.
8
+ * 2. `complete: false` when the ring no longer reaches back to `fromSeq`
9
+ * (eviction) — the caller must recover from the snapshot alone.
10
+ * 3. Targeting filters are re-applied from the caller's client identity
11
+ * headers, mirroring the SSE replay path.
12
+ * 4. Input validation rejects missing/invalid params.
13
+ */
14
+ import { beforeEach, describe, expect, mock, test } from "bun:test";
15
+
16
+ mock.module("../util/logger.js", () => ({
17
+ getLogger: () =>
18
+ new Proxy({} as Record<string, unknown>, {
19
+ get: () => () => {},
20
+ }),
21
+ }));
22
+
23
+ import type { AssistantEvent } from "../runtime/assistant-event.js";
24
+ import {
25
+ _resetStreamStateForTesting,
26
+ stampAndBuffer,
27
+ } from "../runtime/assistant-stream-state.js";
28
+ import { BadRequestError } from "../runtime/routes/errors.js";
29
+ import { ROUTES } from "../runtime/routes/events-routes.js";
30
+
31
+ const CONV = "conv-a";
32
+ const OTHER = "conv-b";
33
+
34
+ const tailRoute = ROUTES.find((r) => r.operationId === "events_tail_get");
35
+ if (!tailRoute) {
36
+ throw new Error("events_tail_get route not registered");
37
+ }
38
+
39
+ interface TailResponse {
40
+ events: AssistantEvent[];
41
+ complete: boolean;
42
+ frontier: number | null;
43
+ }
44
+
45
+ function callTail(
46
+ query: Record<string, string>,
47
+ headers?: Record<string, string>,
48
+ ): TailResponse {
49
+ return tailRoute!.handler({
50
+ queryParams: query,
51
+ headers,
52
+ }) as TailResponse;
53
+ }
54
+
55
+ function mkEvent(overrides: Partial<AssistantEvent> = {}): AssistantEvent {
56
+ const conversationId =
57
+ "conversationId" in overrides ? overrides.conversationId : CONV;
58
+ return {
59
+ id: `uuid-${Math.random().toString(36).slice(2, 10)}`,
60
+ conversationId,
61
+ emittedAt: new Date().toISOString(),
62
+ message: {
63
+ type: "assistant_text_delta",
64
+ conversationId,
65
+ text: "x",
66
+ },
67
+ ...overrides,
68
+ } as AssistantEvent;
69
+ }
70
+
71
+ describe("GET events/tail", () => {
72
+ beforeEach(() => {
73
+ _resetStreamStateForTesting();
74
+ });
75
+
76
+ test("returns the conversation's tail above fromSeq with the frontier", () => {
77
+ // GIVEN interleaved events across two conversations (seq 1..6)
78
+ for (let i = 0; i < 3; i++) {
79
+ stampAndBuffer(mkEvent()); // CONV: seq 1, 3, 5
80
+ stampAndBuffer(mkEvent({ conversationId: OTHER })); // OTHER: 2, 4, 6
81
+ }
82
+
83
+ // WHEN fetching CONV's tail above seq 1 (a snapshot anchored at 1)
84
+ const body = callTail({ conversationId: CONV, fromSeq: "1" });
85
+
86
+ // THEN only CONV's newer events come back, ascending, with the frontier
87
+ expect(body.complete).toBe(true);
88
+ expect(body.events.map((e) => e.seq)).toEqual([3, 5]);
89
+ expect(body.events.every((e) => e.conversationId === CONV)).toBe(true);
90
+ expect(body.frontier).toBe(5);
91
+ });
92
+
93
+ test("an up-to-date anchor yields an empty but complete tail", () => {
94
+ // GIVEN three buffered events (seq 1..3)
95
+ for (let i = 0; i < 3; i++) {
96
+ stampAndBuffer(mkEvent());
97
+ }
98
+
99
+ // WHEN fetching from the live frontier
100
+ const body = callTail({ conversationId: CONV, fromSeq: "3" });
101
+
102
+ // THEN nothing is missing and the frontier is the anchor itself
103
+ expect(body.complete).toBe(true);
104
+ expect(body.events).toEqual([]);
105
+ expect(body.frontier).toBe(3);
106
+ });
107
+
108
+ test("reports complete=false when the ring no longer covers fromSeq", () => {
109
+ // GIVEN a ring whose oldest retained entry is well past the anchor:
110
+ // overflow the 200-event count bound so seq 1 is evicted
111
+ for (let i = 0; i < 210; i++) {
112
+ stampAndBuffer(mkEvent());
113
+ }
114
+
115
+ // WHEN fetching from a pre-eviction anchor
116
+ const body = callTail({ conversationId: CONV, fromSeq: "1" });
117
+
118
+ // THEN no contiguous tail can be served
119
+ expect(body.complete).toBe(false);
120
+ expect(body.events).toEqual([]);
121
+ expect(body.frontier).toBeNull();
122
+ });
123
+
124
+ test("re-applies targeting filters from the caller's client identity", () => {
125
+ // GIVEN an event excluded from a specific client (self-echo suppression)
126
+ stampAndBuffer(mkEvent()); // seq 1 — untargeted
127
+ stampAndBuffer(mkEvent(), { targeting: { excludeClientId: "client-1" } }); // seq 2
128
+
129
+ // WHEN the excluded client fetches the tail
130
+ const excluded = callTail(
131
+ { conversationId: CONV, fromSeq: "0" },
132
+ { "x-vellum-client-id": "client-1", "x-vellum-interface-id": "web" },
133
+ );
134
+ // AND a different client fetches the same tail
135
+ const other = callTail(
136
+ { conversationId: CONV, fromSeq: "0" },
137
+ { "x-vellum-client-id": "client-2", "x-vellum-interface-id": "web" },
138
+ );
139
+
140
+ // THEN the targeted event is withheld only from its excluded client
141
+ expect(excluded.events.map((e) => e.seq)).toEqual([1]);
142
+ expect(other.events.map((e) => e.seq)).toEqual([1, 2]);
143
+ });
144
+
145
+ test("toSeq bounds the window inclusively and moves the frontier", () => {
146
+ // GIVEN five buffered events for the conversation (seq 1..5)
147
+ for (let i = 0; i < 5; i++) {
148
+ stampAndBuffer(mkEvent());
149
+ }
150
+
151
+ // WHEN fetching (1, 3] — the caller already has 4+ from live delivery
152
+ const body = callTail({ conversationId: CONV, fromSeq: "1", toSeq: "3" });
153
+
154
+ // THEN only the hole comes back, with the frontier at the bound
155
+ expect(body.complete).toBe(true);
156
+ expect(body.events.map((e) => e.seq)).toEqual([2, 3]);
157
+ expect(body.frontier).toBe(3);
158
+ });
159
+
160
+ test("rejects missing or invalid params", () => {
161
+ expect(() => callTail({ fromSeq: "1" })).toThrow(BadRequestError);
162
+ expect(() => callTail({ conversationId: CONV })).toThrow(BadRequestError);
163
+ expect(() =>
164
+ callTail({ conversationId: CONV, fromSeq: "not-a-number" }),
165
+ ).toThrow(BadRequestError);
166
+ expect(() => callTail({ conversationId: CONV, fromSeq: "-1" })).toThrow(
167
+ BadRequestError,
168
+ );
169
+ expect(() => callTail({ conversationId: CONV, fromSeq: "1.5" })).toThrow(
170
+ BadRequestError,
171
+ );
172
+ expect(() =>
173
+ callTail({ conversationId: CONV, fromSeq: "5", toSeq: "3" }),
174
+ ).toThrow(BadRequestError);
175
+ expect(() =>
176
+ callTail({ conversationId: CONV, fromSeq: "1", toSeq: "x" }),
177
+ ).toThrow(BadRequestError);
178
+ });
179
+ });