@vellumai/assistant 0.10.3-dev.202606301343.ebf8f0b → 0.10.3-dev.202606301500.9739193

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.202606301343.ebf8f0b",
3
+ "version": "0.10.3-dev.202606301500.9739193",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -186,6 +186,7 @@ mock.module("../persistence/jobs-store.js", () => ({
186
186
  enqueuePruneOldConversationsJob: mock(() => "job-prune-conv"),
187
187
  enqueuePruneOldLlmRequestLogsJob: mock(() => "job-prune-llm"),
188
188
  enqueuePruneOldTraceEventsJob: mock(() => "job-prune-trace"),
189
+ enqueuePruneOldToolInvocationsJob: mock(() => "job-prune-tool"),
189
190
  failMemoryJob: mock(() => {}),
190
191
  failStalledJobs: mockFailStalledJobs,
191
192
  getMemoryJobCounts: mock(() => ({})),
@@ -53,6 +53,7 @@ const NON_PLUGIN_JOB_TYPES = [
53
53
  "prune_old_conversations",
54
54
  "prune_old_llm_request_logs",
55
55
  "prune_old_trace_events",
56
+ "prune_old_tool_invocations",
56
57
  "build_conversation_summary",
57
58
  "media_processing",
58
59
  "conversation_analyze",
@@ -629,6 +629,25 @@ describe("plugin runtime activation", () => {
629
629
  expect(existsSync(shutdownMarker)).toBe(true);
630
630
  });
631
631
 
632
+ test("a user plugin's shutdown hook is surfaced through the unified hook lookup", async () => {
633
+ // Plugin `shutdown` hooks fire at daemon shutdown through the same
634
+ // getHooksFor/runHook pipeline as every other lifecycle hook. Prove the
635
+ // user-land side is discoverable that way: the plugin's shutdown hook is
636
+ // returned by the unified per-name lookup and runs when invoked.
637
+ const dir = freshPluginDir("shutdown-hook-plugin");
638
+ writePackageJson(dir, { ...SIMPLE_PKG, name: "shutdown-hook-plugin" });
639
+ const shutdownMarker = join(ROOT, "user-shutdown.log");
640
+ writeMarkerHook(dir, "shutdown", shutdownMarker, "bye");
641
+
642
+ await populateCacheAtBoot();
643
+
644
+ const shutdownHooks = await getUserHooksFor("shutdown");
645
+ expect(shutdownHooks).toHaveLength(1);
646
+
647
+ await shutdownHooks[0]!({ assistantVersion: "test", reason: "shutdown" });
648
+ expect(existsSync(shutdownMarker)).toBe(true);
649
+ });
650
+
632
651
  test("disabling a plugin at runtime tears down its tools", async () => {
633
652
  const dir = freshPluginDir("disable-plugin");
634
653
  writePackageJson(dir, { ...SIMPLE_PKG, name: "disable-plugin" });
@@ -7,7 +7,8 @@
7
7
  * - Version-mismatch registration fails with an error that names the plugin
8
8
  * (the registry enforces this at `registerPlugin` time, so bootstrap never
9
9
  * sees the malformed plugin).
10
- * - Shutdown hook walks plugins in reverse registration order.
10
+ * - Plugins' `shutdown` hooks fire through the unified `runHook(HOOKS.SHUTDOWN)`
11
+ * pipeline; flag-gated and `.disabled` plugins are excluded from that dispatch.
11
12
  *
12
13
  * `resetPluginRegistryForTests()` isolates registry state between cases.
13
14
  */
@@ -20,9 +21,10 @@ import { beforeEach, describe, expect, test } from "bun:test";
20
21
 
21
22
  import { clearFeatureFlagOverridesCache } from "../config/assistant-feature-flags.js";
22
23
  import { bootstrapPlugins } from "../daemon/external-plugins-bootstrap.js";
23
- import { runShutdownHooks } from "../daemon/shutdown-registry.js";
24
24
  import { RiskLevel } from "../permissions/types.js";
25
+ import { HOOKS } from "../plugin-api/constants.js";
25
26
  import { registerDefaultPlugins } from "../plugins/defaults/index.js";
27
+ import { runHook } from "../plugins/pipeline.js";
26
28
  import {
27
29
  closeRegistration,
28
30
  getRegisteredPlugins,
@@ -233,7 +235,7 @@ describe("plugin bootstrap", () => {
233
235
  expect(names).toContain("default-title-generate");
234
236
  });
235
237
 
236
- test("shutdown order: onShutdown fires in reverse registration order", async () => {
238
+ test("shutdown: onShutdown fires through the runHook pipeline in registration order", async () => {
237
239
  const callOrder: string[] = [];
238
240
  registerPlugin(
239
241
  buildPlugin("first-registered", {
@@ -251,12 +253,15 @@ describe("plugin bootstrap", () => {
251
253
  );
252
254
 
253
255
  await bootstrapPlugins();
254
- await runShutdownHooks("test-shutdown");
256
+ // The plugins' `shutdown` hooks fire through the unified pipeline — the same
257
+ // dispatch path (and registration order) as every other lifecycle hook, so
258
+ // the first plugin to register runs first.
259
+ await runHook(HOOKS.SHUTDOWN, {
260
+ assistantVersion: APP_VERSION,
261
+ reason: "shutdown",
262
+ });
255
263
 
256
- // The last plugin to register must shut down first; the first to register
257
- // shuts down last. Symmetric tear-down around registration order is the
258
- // whole point of the reverse walk.
259
- expect(callOrder).toEqual(["second-registered", "first-registered"]);
264
+ expect(callOrder).toEqual(["first-registered", "second-registered"]);
260
265
  });
261
266
 
262
267
  test("empty registry: bootstrap seeds the first-party defaults without throwing", async () => {
@@ -463,11 +468,14 @@ describe("plugin bootstrap", () => {
463
468
  registerPlugin(plugin);
464
469
 
465
470
  await bootstrapPlugins();
466
- await runShutdownHooks("test-shutdown");
471
+ await runHook(HOOKS.SHUTDOWN, {
472
+ assistantVersion: APP_VERSION,
473
+ reason: "shutdown",
474
+ });
467
475
 
468
- // The shutdown hook is a single registered callback that walks a
469
- // snapshot taken at bootstrap. A skipped plugin should never appear in
470
- // that snapshot, so its `onShutdown` must never fire.
476
+ // A flag-gated plugin is dropped from the registry at bootstrap
477
+ // (`unregisterPlugin`), so it never appears in the `getHooksFor("shutdown")`
478
+ // the pipeline dispatches — its `onShutdown` must never fire.
471
479
  expect(shutdownFired).toBe(false);
472
480
  });
473
481
 
@@ -549,8 +557,14 @@ describe("plugin bootstrap", () => {
549
557
  await writeFile(join(sentinelDir, ".disabled"), "");
550
558
 
551
559
  await bootstrapPlugins();
552
- await runShutdownHooks("test-shutdown");
560
+ await runHook(HOOKS.SHUTDOWN, {
561
+ assistantVersion: APP_VERSION,
562
+ reason: "shutdown",
563
+ });
553
564
 
565
+ // A `.disabled` plugin keeps its hooks registered but they are filtered out
566
+ // at read time by `isPluginDisabled` inside `getHooksFor`, so the pipeline
567
+ // dispatch skips its `onShutdown` too.
554
568
  expect(shutdownFired).toBe(false);
555
569
 
556
570
  await rm(sentinelDir, { recursive: true, force: true });
@@ -4,7 +4,8 @@
4
4
  * A plugin may declare an `injectors` array on its {@link Plugin} shape; after
5
5
  * its model-visible surface is wired and before `init()` succeeds, bootstrap
6
6
  * registers each entry into the global injector registry via
7
- * {@link registerPluginInjectors}, and on shutdown calls
7
+ * {@link registerPluginInjectors}. A plugin rolled back after a failed bring-up
8
+ * (or uninstalled/disabled at runtime) is unregistered via
8
9
  * {@link unregisterPluginInjectors}. This mirrors the tools/routes contribution
9
10
  * path (see `plugin-route-contribution.test.ts`).
10
11
  *
@@ -12,8 +13,7 @@
12
13
  *
13
14
  * 1. Bootstrap → the contributed injector appears in
14
15
  * {@link getRegisteredInjectors}, and `init()` ran.
15
- * 2. Shutdown → the contributed injector is unregistered.
16
- * 3. A plugin without `injectors` bootstraps and shuts down cleanly.
16
+ * 2. A plugin without `injectors` bootstraps cleanly.
17
17
  *
18
18
  * `getRegisteredInjectors()` after `bootstrapPlugins()` also contains the
19
19
  * first-party defaults (bootstrap registers `default-memory`'s injectors), so
@@ -26,7 +26,6 @@ import { join } from "node:path";
26
26
  import { beforeEach, describe, expect, test } from "bun:test";
27
27
 
28
28
  import { bootstrapPlugins } from "../daemon/external-plugins-bootstrap.js";
29
- import { runShutdownHooks } from "../daemon/shutdown-registry.js";
30
29
  import {
31
30
  clearInjectorRegistry,
32
31
  getRegisteredInjectors,
@@ -122,27 +121,12 @@ describe("plugin injector contributions", () => {
122
121
  expect(isTestInjectorRegistered()).toBe(true);
123
122
  });
124
123
 
125
- test("shutdown unregisters the plugin's injectors", async () => {
126
- registerPlugin(
127
- buildPlugin("injector-plugin", { injectors: [makeTestInjector()] }),
128
- );
129
-
130
- await bootstrapPlugins();
131
- expect(isTestInjectorRegistered()).toBe(true);
132
-
133
- // Shutdown runs the reverse-order teardown hook registered by bootstrap.
134
- await runShutdownHooks("test-shutdown");
135
-
136
- expect(isTestInjectorRegistered()).toBe(false);
137
- });
138
-
139
- test("plugin with no injectors bootstraps and shuts down cleanly", async () => {
124
+ test("plugin with no injectors bootstraps cleanly", async () => {
140
125
  // Declaring no `injectors` field is the common case; bootstrap must skip
141
126
  // injector handling entirely (the guard is `if plugin.injectors && length`).
142
127
  registerPlugin(buildPlugin("no-injectors-plugin", { async init() {} }));
143
128
 
144
129
  await bootstrapPlugins();
145
- await runShutdownHooks("test-shutdown");
146
130
 
147
131
  expect(isTestInjectorRegistered()).toBe(false);
148
132
  });
@@ -3,24 +3,24 @@
3
3
  *
4
4
  * A plugin may declare a `routes` array on its {@link Plugin} shape; after
5
5
  * `init()` succeeds, bootstrap wires each entry into the skill-route registry
6
- * via {@link registerSkillRoute}, retains the opaque {@link SkillRouteHandle}
7
- * it receives back, and on shutdown calls {@link unregisterSkillRoute} with
8
- * that exact handle. Handle-keyed unregistration ensures that two
9
- * owners (e.g. a plugin and a skill) that legitimately register the same
10
- * regex cannot have one owner's teardown silently evict another owner's
11
- * route, preserving the "no traffic hits a plugin handler during
12
- * onShutdown" invariant.
6
+ * via {@link registerSkillRoute} and retains the opaque {@link SkillRouteHandle}
7
+ * it receives back. A plugin rolled back after a failed bring-up (or a user
8
+ * plugin uninstalled/disabled at runtime) is unregistered with that exact handle
9
+ * via {@link unregisterSkillRoute}. Handle-keyed unregistration ensures that two
10
+ * owners (e.g. a plugin and a skill) that legitimately register the same regex
11
+ * cannot have one owner's teardown silently evict another owner's route. At
12
+ * daemon shutdown the plugins' `shutdown` hooks fire through the unified
13
+ * `runHook(HOOKS.SHUTDOWN, …)` pipeline (surfaces are not unregistered — the
14
+ * process is exiting).
13
15
  *
14
16
  * The registry doesn't own HTTP itself — the tests here exercise:
15
17
  *
16
18
  * 1. Bootstrap → `registerSkillRoute` → `matchSkillRoute` returns the plugin's
17
19
  * handler, and the handler responds as expected.
18
- * 2. Shutdown → `unregisterSkillRoute` drops the entry, and subsequent
19
- * `matchSkillRoute` lookups return `null`.
20
- * 3. Plugins without `routes` (or with an empty array) bootstrap cleanly.
21
- * 4. When two plugins register regex patterns with identical `source+flags`,
22
- * each plugin's shutdown only removes its own route — the other plugin's
23
- * route stays live until its own teardown runs.
20
+ * 2. Plugins without `routes` (or with an empty array) bootstrap cleanly.
21
+ * 3. Handle-keyed unregistration: unregistering one route's handle leaves a
22
+ * sibling's identical-pattern route live until its own handle is dropped.
23
+ * 4. Every contributing plugin's `shutdown` hook fires via `runHook`.
24
24
  *
25
25
  * `resetPluginRegistryForTests()` isolates plugin-registry state and
26
26
  * `resetSkillRoutesForTests()` isolates skill-route-registry state between
@@ -33,7 +33,8 @@ import { join } from "node:path";
33
33
  import { beforeEach, describe, expect, test } from "bun:test";
34
34
 
35
35
  import { bootstrapPlugins } from "../daemon/external-plugins-bootstrap.js";
36
- import { runShutdownHooks } from "../daemon/shutdown-registry.js";
36
+ import { HOOKS } from "../plugin-api/constants.js";
37
+ import { runHook } from "../plugins/pipeline.js";
37
38
  import {
38
39
  registerPlugin,
39
40
  resetPluginRegistryForTests,
@@ -41,9 +42,10 @@ import {
41
42
  import type { InitContext, Plugin } from "../plugins/types.js";
42
43
  import {
43
44
  matchSkillRoute,
45
+ registerSkillRoute,
44
46
  resetSkillRoutesForTests,
45
47
  type SkillRoute,
46
- type SkillRouteMatch,
48
+ unregisterSkillRoute,
47
49
  } from "../runtime/skill-route-registry.js";
48
50
 
49
51
  // Redirect plugin storage creation into a per-process temp tree so the test
@@ -147,96 +149,59 @@ describe("plugin route contributions", () => {
147
149
  expect(await res.text()).toBe("echo");
148
150
  });
149
151
 
150
- test("shutdown unregisters the plugin's routes", async () => {
151
- const route: SkillRoute = {
152
- pattern: echoPattern,
153
- methods: ["GET"],
154
- handler: async () => new Response("echo", { status: 200 }),
155
- };
156
-
157
- registerPlugin(buildPlugin("echo-plugin", { routes: [route] }));
158
-
159
- await bootstrapPlugins();
160
-
161
- // Sanity: route is live after bootstrap.
162
- expect(matchSkillRoute("/_plugin/echo", "GET")).not.toBeNull();
163
-
164
- // Shutdown runs the reverse-order teardown hook registered by bootstrap.
165
- await runShutdownHooks("test-shutdown");
166
-
167
- // Route is gone — matchSkillRoute returns null because no pattern
168
- // matches the path at all anymore.
169
- expect(matchSkillRoute("/_plugin/echo", "GET")).toBeNull();
170
- });
171
-
172
- test("plugin with no routes bootstraps and shuts down cleanly", async () => {
152
+ test("plugin with no routes bootstraps and tears down cleanly", async () => {
173
153
  // Declaring no `routes` field is the common case; bootstrap must skip
174
154
  // route handling entirely (the guard is `if plugin.routes && length > 0`).
175
155
  registerPlugin(buildPlugin("no-routes-plugin", { async init() {} }));
176
156
 
177
157
  await bootstrapPlugins();
178
- await runShutdownHooks("test-shutdown");
158
+ await runHook(HOOKS.SHUTDOWN, {
159
+ assistantVersion: "test",
160
+ reason: "shutdown",
161
+ });
179
162
 
180
163
  // Nothing to verify beyond "neither throws" — an empty `routes` must not
181
164
  // regress existing no-op bootstrap semantics.
182
165
  expect(true).toBe(true);
183
166
  });
184
167
 
185
- test("shutdown tolerates a route whose registry entry was wiped externally", async () => {
186
- // Guard against the case where a stale handle no longer points at a live
187
- // registry entry (e.g. the registry was cleared externally). The shutdown
188
- // hook must not crash — unregisterSkillRoute returns false, and
189
- // bootstrap's try/catch around the call swallows the signal. This
190
- // exercises the defensive path so a partial-crash recovery still runs
191
- // every plugin's onShutdown in reverse order.
192
- let shutdownFired = false;
193
- registerPlugin(
194
- buildPlugin("echo-plugin", {
195
- routes: [
196
- {
197
- pattern: echoPattern,
198
- methods: ["GET"],
199
- handler: async () => new Response("echo", { status: 200 }),
200
- },
201
- ],
202
- async onShutdown() {
203
- shutdownFired = true;
204
- },
205
- }),
206
- );
207
-
208
- await bootstrapPlugins();
168
+ test("unregistering one route handle leaves a sibling's identical-pattern route live", async () => {
169
+ // Regression for the reviewer-flagged invariant: keying unregistration on
170
+ // `pattern.source + flags` would let one owner's teardown drop another
171
+ // owner's route when both declared regex with identical text. The plugin
172
+ // surface teardown unregisters routes by the opaque handle retained at
173
+ // registration time (`unregisterSkillRoute(handle)`), so that is the
174
+ // mechanism keeping sibling routes intact. Exercise it directly: two routes
175
+ // with byte-identical patterns, drop one handle, and the other must still
176
+ // match until its own handle is dropped too.
177
+ const handleA = registerSkillRoute({
178
+ pattern: /^\/_plugin\/echo$/,
179
+ methods: ["GET"],
180
+ handler: async () => new Response("a", { status: 200 }),
181
+ });
182
+ const handleB = registerSkillRoute({
183
+ pattern: /^\/_plugin\/echo$/,
184
+ methods: ["GET"],
185
+ handler: async () => new Response("b", { status: 200 }),
186
+ });
209
187
 
210
- // Simulate an external wipe before the shutdown hook runs — e.g. a
211
- // different subsystem calling `resetSkillRoutesForTests` or a hot-reload
212
- // flow clearing the registry. The plugin's retained handle is now stale.
213
- resetSkillRoutesForTests();
188
+ expect(matchSkillRoute("/_plugin/echo", "GET")).not.toBeNull();
214
189
 
215
- await runShutdownHooks("test-shutdown");
190
+ // Drop B (reverse-order teardown drops the last-registered owner first).
191
+ expect(unregisterSkillRoute(handleB)).toBe(true);
192
+ // A's identical-pattern route must still be live.
193
+ expect(matchSkillRoute("/_plugin/echo", "GET")).not.toBeNull();
216
194
 
217
- // onShutdown still ran despite the stale handle — proving the
218
- // route-unregister step does not short-circuit plugin teardown.
219
- expect(shutdownFired).toBe(true);
195
+ // Only once A's own handle is dropped does the route disappear.
196
+ expect(unregisterSkillRoute(handleA)).toBe(true);
197
+ expect(matchSkillRoute("/_plugin/echo", "GET")).toBeNull();
220
198
  });
221
199
 
222
- test("shutdown of one plugin does not evict a sibling's same-pattern route", async () => {
223
- // Regression for the reviewer-flagged invariant: keying unregistration on
224
- // `pattern.source + flags` would let plugin-A's teardown drop plugin-B's
225
- // route when both declared regex with identical text. With handle-keyed
226
- // identity, each plugin's teardown removes only its own registrations.
227
- //
228
- // We simulate this by wiring two plugins that both contribute a route
229
- // matching `/^\/_plugin\/echo$/`. Teardown runs in reverse registration
230
- // order, so plugin-B is torn down first; plugin-A's route must still
231
- // match afterwards, and only disappear once plugin-A's own teardown
232
- // runs.
233
- let pluginAShutdown = false;
234
- let pluginBShutdown = false;
235
- // Capture the match result from inside plugin-B's onShutdown so assertions
236
- // run after runShutdownHooks returns. teardownPlugin wraps onShutdown in a
237
- // try/catch that swallows thrown assertion errors, so asserting inline
238
- // would let a failing match silently pass the test.
239
- let pluginBOnShutdownMatch: SkillRouteMatch | null = null;
200
+ test("every contributing plugin's shutdown hook fires through the runHook pipeline", async () => {
201
+ // At daemon shutdown the plugins' `shutdown` hooks fire through the unified
202
+ // `runHook` pipeline — the same dispatch path every other lifecycle hook
203
+ // uses. Two plugins prove each one's hook fires exactly once.
204
+ const pluginsThatShutDown: string[] = [];
240
205
 
241
206
  registerPlugin(
242
207
  buildPlugin("plugin-a", {
@@ -248,16 +213,10 @@ describe("plugin route contributions", () => {
248
213
  },
249
214
  ],
250
215
  async onShutdown() {
251
- // When plugin-A's teardown runs, plugin-B has already been torn
252
- // down — but plugin-A's route must still be live because
253
- // `onShutdown` fires *after* the route-unregister step for this
254
- // plugin but *before* it leaves teardownPlugin. We check liveness
255
- // from plugin-B's teardown instead (see below).
256
- pluginAShutdown = true;
216
+ pluginsThatShutDown.push("plugin-a");
257
217
  },
258
218
  }),
259
219
  );
260
-
261
220
  registerPlugin(
262
221
  buildPlugin("plugin-b", {
263
222
  routes: [
@@ -268,31 +227,19 @@ describe("plugin route contributions", () => {
268
227
  },
269
228
  ],
270
229
  async onShutdown() {
271
- // Plugin-B's routes have already been unregistered by the time
272
- // this fires, but plugin-A's route is still live — it only gets
273
- // torn down after this hook returns and the loop moves on to
274
- // plugin-A. Confirm the registry still has a matching route.
275
- pluginBShutdown = true;
276
- pluginBOnShutdownMatch = matchSkillRoute("/_plugin/echo", "GET");
230
+ pluginsThatShutDown.push("plugin-b");
277
231
  },
278
232
  }),
279
233
  );
280
234
 
281
235
  await bootstrapPlugins();
282
236
 
283
- // Both plugins' routes landed in the registry; matching returns one of
284
- // them (order defined by registration, but we only care that *some*
285
- // route matches before shutdown starts).
286
- expect(matchSkillRoute("/_plugin/echo", "GET")).not.toBeNull();
287
-
288
- await runShutdownHooks("test-shutdown");
237
+ await runHook(HOOKS.SHUTDOWN, {
238
+ assistantVersion: "test",
239
+ reason: "shutdown",
240
+ });
289
241
 
290
- expect(pluginBShutdown).toBe(true);
291
- expect(pluginAShutdown).toBe(true);
292
- expect(pluginBOnShutdownMatch).not.toBeNull();
293
- expect(pluginBOnShutdownMatch!.kind).toBe("match");
294
-
295
- // After both plugins shut down, no routes remain.
296
- expect(matchSkillRoute("/_plugin/echo", "GET")).toBeNull();
242
+ // Both plugins' hooks fired exactly once.
243
+ expect(pluginsThatShutDown.sort()).toEqual(["plugin-a", "plugin-b"]);
297
244
  });
298
245
  });
@@ -27,7 +27,6 @@ import { join } from "node:path";
27
27
  import { beforeEach, describe, expect, mock, test } from "bun:test";
28
28
 
29
29
  import { bootstrapPlugins } from "../daemon/external-plugins-bootstrap.js";
30
- import { runShutdownHooks } from "../daemon/shutdown-registry.js";
31
30
  import { RiskLevel } from "../permissions/types.js";
32
31
  import {
33
32
  registerPlugin,
@@ -154,22 +153,6 @@ describe("plugin tool contributions", () => {
154
153
  expect(names).toContain("plugin-contrib-tool");
155
154
  });
156
155
 
157
- test("plugin tools are unregistered when shutdown hooks run", async () => {
158
- const plugin = buildPlugin("bravo-contributor", {
159
- async init() {},
160
- tools: [makeFakeTool("bravo-tool")],
161
- });
162
- registerPlugin(plugin);
163
-
164
- await bootstrapPlugins();
165
- expect(getTool("bravo-tool")).toBeDefined();
166
-
167
- await runShutdownHooks("test-shutdown");
168
-
169
- expect(getTool("bravo-tool")).toBeUndefined();
170
- expect(getPluginRefCount("bravo-contributor")).toBe(0);
171
- });
172
-
173
156
  test("bootstrap is a no-op for plugins that declare no tools", async () => {
174
157
  const plugin = buildPlugin("no-tools", { async init() {} });
175
158
  registerPlugin(plugin);
@@ -180,11 +163,6 @@ describe("plugin tool contributions", () => {
180
163
  // empty. What matters here is that the no-tools plugin contributed nothing
181
164
  // of its own — its tool refcount stays at zero.
182
165
  expect(getPluginRefCount("no-tools")).toBe(0);
183
-
184
- // Shutdown must also be safe — `unregisterPluginTools` is idempotent for
185
- // plugins that never contributed any tools.
186
- await runShutdownHooks("test-shutdown");
187
- expect(getPluginRefCount("no-tools")).toBe(0);
188
166
  });
189
167
 
190
168
  test("tools declared before init() runs are only visible after bootstrap", async () => {
@@ -0,0 +1,97 @@
1
+ import { beforeEach, describe, expect, mock, test } from "bun:test";
2
+
3
+ // Silence the logger.
4
+ mock.module("../util/logger.js", () => ({
5
+ getLogger: () =>
6
+ new Proxy({} as Record<string, unknown>, {
7
+ get: () => () => {},
8
+ }),
9
+ }));
10
+
11
+ import type { AssistantConfig } from "../config/schema.js";
12
+ import { getDb } from "../persistence/db-connection.js";
13
+ import { initializeDb } from "../persistence/db-init.js";
14
+ import { pruneOldToolInvocationsJob } from "../persistence/job-handlers/cleanup.js";
15
+ import type { MemoryJob } from "../persistence/jobs-store.js";
16
+ import { conversations, toolInvocations } from "../persistence/schema/index.js";
17
+
18
+ await initializeDb();
19
+
20
+ const DAY_MS = 86_400_000;
21
+
22
+ function seedInvocation(id: string, createdAt: number): void {
23
+ getDb()
24
+ .insert(toolInvocations)
25
+ .values({
26
+ id,
27
+ conversationId: "conv-1",
28
+ toolName: "bash",
29
+ input: "{}",
30
+ result: "{}",
31
+ decision: "allow",
32
+ riskLevel: "low",
33
+ durationMs: 5,
34
+ createdAt,
35
+ })
36
+ .run();
37
+ }
38
+
39
+ function remainingIds(): string[] {
40
+ return getDb()
41
+ .select()
42
+ .from(toolInvocations)
43
+ .all()
44
+ .map((r) => r.id)
45
+ .sort();
46
+ }
47
+
48
+ function job(payload: Record<string, unknown> = {}): MemoryJob {
49
+ return { payload } as unknown as MemoryJob;
50
+ }
51
+
52
+ function config(retentionDays: number): AssistantConfig {
53
+ return { auditLog: { retentionDays } } as unknown as AssistantConfig;
54
+ }
55
+
56
+ describe("pruneOldToolInvocationsJob", () => {
57
+ beforeEach(() => {
58
+ const db = getDb();
59
+ db.delete(toolInvocations).run();
60
+ db.delete(conversations).run();
61
+ // tool_invocations.conversation_id is an FK into conversations.
62
+ db.insert(conversations)
63
+ .values({
64
+ id: "conv-1",
65
+ title: "test",
66
+ createdAt: Date.now(),
67
+ updatedAt: Date.now(),
68
+ })
69
+ .run();
70
+ });
71
+
72
+ test("deletes audit rows older than auditLog.retentionDays, keeps recent ones", async () => {
73
+ seedInvocation("old", Date.now() - 60 * DAY_MS);
74
+ seedInvocation("fresh", Date.now());
75
+
76
+ await pruneOldToolInvocationsJob(job(), config(30));
77
+
78
+ expect(remainingIds()).toEqual(["fresh"]);
79
+ });
80
+
81
+ test("payload retentionDays overrides the config window", async () => {
82
+ seedInvocation("ten-days", Date.now() - 10 * DAY_MS);
83
+
84
+ // Config would keep it (30d), but the payload tightens to 7d.
85
+ await pruneOldToolInvocationsJob(job({ retentionDays: 7 }), config(30));
86
+
87
+ expect(remainingIds()).toEqual([]);
88
+ });
89
+
90
+ test("retentionDays of 0 is a no-op (keep forever)", async () => {
91
+ seedInvocation("ancient", Date.now() - 999 * DAY_MS);
92
+
93
+ await pruneOldToolInvocationsJob(job(), config(0));
94
+
95
+ expect(remainingIds()).toEqual(["ancient"]);
96
+ });
97
+ });
@@ -15,9 +15,9 @@
15
15
  * 3. For each plugin, consults `manifest.requiresFlag` against
16
16
  * {@link isAssistantFeatureFlagEnabled}. If any listed flag is disabled,
17
17
  * the plugin is skipped wholesale — no `init()`, no tool/route
18
- * contributions, no entry in the shutdown hook, and the plugin is also
19
- * dropped from the hook registry via {@link unregisterPlugin} so none of its
20
- * hooks participate in the turn lifecycle. This is the primary mechanism for
18
+ * contributions, and the plugin is also dropped from the hook registry via
19
+ * {@link unregisterPlugin} so none of its hooks (including `shutdown`)
20
+ * participate in the turn lifecycle. This is the primary mechanism for
21
21
  * shipping experimental plugins behind a feature flag.
22
22
  * 4. Validates the config block under `plugins.<name>` against
23
23
  * `manifest.config` if the manifest supplies a parser-like validator
@@ -43,15 +43,13 @@
43
43
  * history repair, title generation) — so the daemon comes up with the
44
44
  * failing plugin absent rather than blacking out the whole plugin layer.
45
45
  *
46
- * A single shutdown hook is registered via
47
- * {@link registerShutdownHook} that walks the plugin list in **reverse
48
- * registration order**. Only plugins that actually initialized (i.e. were
49
- * not skipped by the feature-flag gate) appear in that walk. For each such
50
- * plugin it first unregisters the contributed tools (so `onShutdown()`
51
- * observes a clean model-visible surface) and then awaits the optional
52
- * `onShutdown()`. Per-plugin shutdown failures are logged and swallowed —
53
- * the hook registry already swallows hook-level throws, but we log at the
54
- * plugin level so the plugin name is attributed.
46
+ * Plugin `shutdown` hooks fire through the unified `runHook(HOOKS.SHUTDOWN, …)`
47
+ * pipeline that the daemon shutdown handler runs — the same path every other
48
+ * lifecycle hook uses; this module does not register a shutdown hook of its own.
49
+ * Surfaces (tools/routes/injectors) are not unregistered at daemon shutdown:
50
+ * the process is exiting, so that in-memory registry state is discarded anyway.
51
+ * Surfaces are only torn down when a single plugin is rolled back after a failed
52
+ * bring-up, via {@link teardownPlugin}.
55
53
  */
56
54
 
57
55
  import { existsSync, mkdirSync } from "node:fs";
@@ -95,7 +93,6 @@ import {
95
93
  import { getLogger } from "../util/logger.js";
96
94
  import { getWorkspaceDir, getWorkspacePluginsDir } from "../util/platform.js";
97
95
  import { APP_VERSION } from "../version.js";
98
- import { registerShutdownHook } from "./shutdown-registry.js";
99
96
 
100
97
  const log = getLogger("plugins-bootstrap");
101
98
 
@@ -190,8 +187,8 @@ export async function initializePlugins(): Promise<void> {
190
187
  }
191
188
 
192
189
  /**
193
- * Run every registered plugin's `init()` hook sequentially and install a
194
- * reverse-order shutdown hook. See the module docstring for full semantics.
190
+ * Run every registered plugin's `init()` hook sequentially. See the module
191
+ * docstring for full lifecycle semantics (including how `shutdown` hooks fire).
195
192
  *
196
193
  * Returns once every plugin has been processed. A plugin whose `init()` throws
197
194
  * is rolled back, dropped from the registry, and logged; bootstrap continues
@@ -253,25 +250,6 @@ export async function bootstrapPlugins(): Promise<void> {
253
250
 
254
251
  const assistantConfig = getConfig();
255
252
 
256
- // Plugins that passed `requiresFlag` gating and therefore need the full
257
- // init → contribute → shutdown lifecycle. Plugins skipped by the flag gate
258
- // are omitted from this list so the shutdown hook below never tears down
259
- // capabilities that were never wired up in the first place. Each entry
260
- // carries the opaque route handles returned by `registerSkillRoute` so
261
- // teardown can key on identity rather than regex-pattern text — two plugins
262
- // registering the same pattern would otherwise step on each other's routes
263
- // during shutdown, violating the "no traffic hits a plugin handler during
264
- // onShutdown" invariant.
265
- const activePlugins: ActivePlugin[] = [];
266
-
267
- // Shutdown context is identical for every plugin in this boot — construct
268
- // once and reuse across the per-plugin teardown and the normal shutdown
269
- // hook below. Only `assistantVersion` is exposed today; future additions
270
- // live on {@link ShutdownContext}.
271
- const shutdownContext: ShutdownContext = {
272
- assistantVersion: APP_VERSION,
273
- };
274
-
275
253
  for (const plugin of plugins) {
276
254
  const name = plugin.manifest.name;
277
255
  const disabledFlag = getDisabledPluginFlag(plugin, assistantConfig);
@@ -314,7 +292,7 @@ export async function bootstrapPlugins(): Promise<void> {
314
292
  }
315
293
 
316
294
  try {
317
- activePlugins.push(await initializePlugin(plugin, assistantConfig));
295
+ await initializePlugin(plugin, assistantConfig);
318
296
  } catch (err) {
319
297
  // Contain the failure to this plugin. `initializePlugin` already rolled
320
298
  // back its own partial tool/route contributions, so we just drop
@@ -330,27 +308,6 @@ export async function bootstrapPlugins(): Promise<void> {
330
308
  );
331
309
  }
332
310
  }
333
-
334
- // Shutdown hook — walks plugins in REVERSE registration order. We snapshot
335
- // only the plugins that actually initialized so later registrations (if
336
- // any) don't end up being torn down by this hook, and plugins skipped by
337
- // `requiresFlag` gating do not appear in the tear-down list. Subsequent
338
- // bootstraps (hot-reload) would register their own hook.
339
- //
340
- // For each plugin we:
341
- // 1. Unregister contributed HTTP routes so incoming requests stop hitting
342
- // the plugin's handlers before its state is torn down.
343
- // 2. Unregister contributed tools so the model-visible tool surface is
344
- // cleared before `onShutdown()` runs.
345
- // 3. Call `onShutdown()` (if defined) so the plugin can release resources
346
- // (background tasks, timers, connections) with its tools and routes
347
- // already removed.
348
- const shutdownSnapshot: ActivePlugin[] = [...activePlugins];
349
- registerShutdownHook("plugins", async (reason) => {
350
- for (let i = shutdownSnapshot.length - 1; i >= 0; i--) {
351
- await teardownPlugin(shutdownSnapshot[i]!, reason, shutdownContext);
352
- }
353
- });
354
311
  }
355
312
 
356
313
  /**
@@ -449,9 +406,10 @@ async function initializePlugin(
449
406
  return { plugin, routeHandles };
450
407
  } catch (err) {
451
408
  if (initCompleted) {
452
- await teardownPlugin({ plugin, routeHandles }, "bootstrap-failed", {
453
- assistantVersion: APP_VERSION,
454
- });
409
+ await teardownPlugin(
410
+ { plugin, routeHandles },
411
+ { assistantVersion: APP_VERSION, reason: "disable" },
412
+ );
455
413
  } else {
456
414
  for (const handle of routeHandles) {
457
415
  unregisterSkillRoute(handle);
@@ -465,29 +423,34 @@ async function initializePlugin(
465
423
  }
466
424
 
467
425
  /**
468
- * Tear down a single fully-initialized plugin: unregister routes, unregister
469
- * tools, then invoke `onShutdown()` if present. Every step swallows errors and
470
- * logs with plugin attribution so one bad plugin can't block teardown of the
471
- * rest.
426
+ * Unregister every initialized plugin's contributed routes and tools in reverse
427
+ * registration order, clearing the model-visible surface before the shutdown
428
+ * handler dispatches `shutdown` hooks via `runHook(HOOKS.SHUTDOWN, …)`. Reads
429
+ * the snapshot captured by the most recent {@link bootstrapPlugins} run; a
430
+ * no-op when no plugins initialized. Called by the daemon shutdown handler.
431
+ */
432
+ /**
433
+ * Tear down a single fully-initialized plugin: unregister its model-visible
434
+ * surfaces (contributed HTTP routes — keyed by the opaque handles retained at
435
+ * registration time, since pattern text is not a stable key when two owners
436
+ * register the same regex — plus its tools and runtime injectors), then invoke
437
+ * its optional `shutdown` hook with the tools/routes already gone. Every step
438
+ * swallows errors and logs with plugin attribution so one bad plugin can't
439
+ * block teardown.
472
440
  *
473
- * Shared between the normal shutdown hook and the bootstrap error path; both
474
- * consume plugins that already cleared every contribution step.
441
+ * Used by the bootstrap-failure rollback path. The normal daemon shutdown path
442
+ * does not unregister surfaces (the process is exiting, so that in-memory state
443
+ * is discarded anyway); it only fires `shutdown` hooks through the unified
444
+ * `runHook(HOOKS.SHUTDOWN, …)` pipeline.
475
445
  */
476
446
  async function teardownPlugin(
477
447
  active: ActivePlugin,
478
- reason: string,
479
448
  shutdownContext: ShutdownContext,
480
449
  ): Promise<void> {
481
450
  const { plugin, routeHandles } = active;
482
451
  const name = plugin.manifest.name;
452
+ const { reason } = shutdownContext;
483
453
 
484
- // Unregister model-visible surfaces before invoking `onShutdown()` so the
485
- // plugin's onShutdown hook observes a registry state where its tools and
486
- // routes are already gone. `unregisterPluginTools` is a no-op when the
487
- // plugin never contributed tools, so we don't need to guard on
488
- // `plugin.tools` here. Route unregistration keys on the opaque handles
489
- // retained at registration time — pattern text is not a stable key because
490
- // two owners can legitimately register the same regex.
491
454
  for (const handle of routeHandles) {
492
455
  try {
493
456
  unregisterSkillRoute(handle);
@@ -515,10 +478,6 @@ async function teardownPlugin(
515
478
  try {
516
479
  await plugin.hooks[HOOKS.SHUTDOWN](shutdownContext);
517
480
  } catch (err) {
518
- // Swallow — we want every plugin's shutdown to get a chance to run
519
- // even when an earlier one throws. The outer runShutdownHooks already
520
- // logs at hook level, but the plugin-name attribution here is what
521
- // operators read first.
522
481
  log.warn(
523
482
  { err, plugin: name, reason },
524
483
  "plugin shutdown hook failed (continuing with remaining plugins)",
@@ -65,7 +65,6 @@ import { recoverInterruptedImport } from "../runtime/migrations/vbundle-streamin
65
65
  import { publishConfigChanged } from "../runtime/sync/resource-sync-events.js";
66
66
  import { recoverStaleSchedules } from "../schedule/schedule-recovery.js";
67
67
  import { startScheduler } from "../schedule/scheduler.js";
68
- import { rotateToolInvocations } from "../telemetry/tool-usage-store.js";
69
68
  import { startUsageTelemetryReporter } from "../telemetry/usage-telemetry-reporter.js";
70
69
  import { syncFlagGatedTools } from "../tools/registry.js";
71
70
  import { registerBuiltinTtsProviders } from "../tts/providers/register-builtins.js";
@@ -1091,12 +1090,6 @@ export async function runDaemon(): Promise<void> {
1091
1090
  }
1092
1091
  })();
1093
1092
 
1094
- if (config.auditLog.retentionDays > 0) {
1095
- void rotateToolInvocations(config.auditLog.retentionDays).catch((err) => {
1096
- log.warn({ err }, "Audit log rotation failed");
1097
- });
1098
- }
1099
-
1100
1093
  startWorkspaceHeartbeatService();
1101
1094
 
1102
1095
  startHeartbeatService();
@@ -10,6 +10,8 @@ import { getSqlite, resetDb } from "../persistence/db-connection.js";
10
10
  import { stopQdrantManager } from "../persistence/embeddings/qdrant-manager.js";
11
11
  import { stopMemoryJobsWorker } from "../persistence/jobs-worker.js";
12
12
  import { stopMemoryWorkerProcess } from "../persistence/worker-control.js";
13
+ import { HOOKS } from "../plugin-api/constants.js";
14
+ import { runHook } from "../plugins/pipeline.js";
13
15
  import { stopRuntimeHttpServer } from "../runtime/http-server.js";
14
16
  import { stopScheduler } from "../schedule/scheduler.js";
15
17
  import { getSubagentManager } from "../subagent/index.js";
@@ -17,6 +19,7 @@ import { stopUsageTelemetryReporter } from "../telemetry/usage-telemetry-reporte
17
19
  import { browserManager } from "../tools/browser/browser-manager.js";
18
20
  import { cleanupShellOutputTempFiles } from "../tools/shared/shell-output.js";
19
21
  import { getLogger } from "../util/logger.js";
22
+ import { APP_VERSION } from "../version.js";
20
23
  import { getEnrichmentService } from "../workspace/commit-message-enrichment-service.js";
21
24
  import {
22
25
  commitAllPendingWorkspaceChanges,
@@ -78,8 +81,8 @@ async function shutdown(): Promise<void> {
78
81
  await stopWorkspaceHeartbeatService();
79
82
  await stopHeartbeatService();
80
83
 
81
- // Run registered plugin/skill shutdown hooks (e.g. the memory plugin's
82
- // filing-service teardown, meet-join session teardown) before stopping the
84
+ // Run registered shutdown-registry hooks (skill teardown like meet-join, plus
85
+ // daemon singletons such as the consent-cache refresh) before stopping the
83
86
  // server so any HTTP round-trips and SSE emissions still have live transports.
84
87
  try {
85
88
  await runShutdownHooks("daemon-shutdown");
@@ -87,6 +90,20 @@ async function shutdown(): Promise<void> {
87
90
  log.warn({ err }, "Skill shutdown hooks failed (non-fatal)");
88
91
  }
89
92
 
93
+ // Fire plugin / user / workspace `shutdown` hooks through the unified hook
94
+ // pipeline — the same dispatch path every other lifecycle hook uses — before
95
+ // stopping the server so any teardown work still has live transports. We don't
96
+ // unregister tool/route surfaces here: the daemon is exiting, so that
97
+ // in-memory registry state is discarded with the process anyway.
98
+ try {
99
+ await runHook(HOOKS.SHUTDOWN, {
100
+ assistantVersion: APP_VERSION,
101
+ reason: "shutdown",
102
+ });
103
+ } catch (err) {
104
+ log.warn({ err }, "Plugin shutdown hooks failed (non-fatal)");
105
+ }
106
+
90
107
  // Commit any uncommitted workspace changes before stopping the server.
91
108
  // This ensures no workspace state is lost during graceful shutdown.
92
109
  try {
@@ -4,6 +4,7 @@ import { mediaProcessingJob } from "../media/job-handlers/media-processing.js";
4
4
  import {
5
5
  pruneOldConversationsJob,
6
6
  pruneOldLlmRequestLogsJob,
7
+ pruneOldToolInvocationsJob,
7
8
  pruneOldTraceEventsJob,
8
9
  } from "../persistence/job-handlers/cleanup.js";
9
10
  import { registerJobHandler } from "../persistence/jobs-worker.js";
@@ -56,6 +57,9 @@ export function registerMemoryJobHandlers(): void {
56
57
  registerJobHandler("prune_old_trace_events", (job, config) =>
57
58
  pruneOldTraceEventsJob(job, config),
58
59
  );
60
+ registerJobHandler("prune_old_tool_invocations", (job, config) =>
61
+ pruneOldToolInvocationsJob(job, config),
62
+ );
59
63
  registerJobHandler("build_conversation_summary", async (job, config) => {
60
64
  // Stale rows enqueued before v2 was enabled must not consume the
61
65
  // `conversationSummarization` LLM budget — v2 readers do not consume
@@ -1,4 +1,5 @@
1
1
  import type { AssistantConfig } from "../../config/types.js";
2
+ import { rotateToolInvocations } from "../../telemetry/tool-usage-store.js";
2
3
  import { getLogger } from "../../util/logger.js";
3
4
  import { getLogsDbPath } from "../../util/logs-db-path.js";
4
5
  import { runAsyncSqlite } from "../db-async-query.js";
@@ -139,6 +140,32 @@ SELECT changes();`,
139
140
  );
140
141
  }
141
142
 
143
+ /**
144
+ * Delete audit-log (`tool_invocations`) entries older than the configured
145
+ * retention window. Retention comes from `auditLog.retentionDays` (0 = keep
146
+ * forever). The DELETE itself lives in {@link rotateToolInvocations}; this
147
+ * handler just resolves the window and dispatches, mirroring the other
148
+ * scheduled cleanup jobs.
149
+ */
150
+ export async function pruneOldToolInvocationsJob(
151
+ job: MemoryJob,
152
+ config: AssistantConfig,
153
+ ): Promise<void> {
154
+ const rawRetention = job.payload.retentionDays;
155
+ const retentionDays =
156
+ typeof rawRetention === "number" &&
157
+ Number.isFinite(rawRetention) &&
158
+ rawRetention >= 0
159
+ ? rawRetention
160
+ : config.auditLog.retentionDays;
161
+
162
+ // 0 means disabled. rotateToolInvocations no-ops on this too, but
163
+ // short-circuit so we don't dispatch a pointless async query.
164
+ if (!retentionDays) return;
165
+
166
+ await rotateToolInvocations(retentionDays);
167
+ }
168
+
142
169
  /**
143
170
  * Parse the `SELECT changes()` result emitted by the sqlite3 CLI after
144
171
  * the prune DELETE. Returns 0 if stdout is missing or unparseable —
@@ -36,6 +36,7 @@ export type MemoryJobType =
36
36
  | "prune_old_conversations"
37
37
  | "prune_old_llm_request_logs"
38
38
  | "prune_old_trace_events"
39
+ | "prune_old_tool_invocations"
39
40
  | "build_conversation_summary"
40
41
  | "conversation_analyze"
41
42
  | "backfill"
@@ -501,6 +502,55 @@ export function enqueuePruneOldTraceEventsJob(retentionDays?: number): string {
501
502
  return enqueueMemoryJob("prune_old_trace_events", payload);
502
503
  }
503
504
 
505
+ export function enqueuePruneOldToolInvocationsJob(
506
+ retentionDays?: number,
507
+ ): string {
508
+ const db = memoryDb();
509
+ const existing = db
510
+ .select()
511
+ .from(memoryJobs)
512
+ .where(
513
+ and(
514
+ eq(memoryJobs.type, "prune_old_tool_invocations"),
515
+ inArray(memoryJobs.status, ["pending", "running"]),
516
+ ),
517
+ )
518
+ .orderBy(asc(memoryJobs.createdAt))
519
+ .get();
520
+ if (existing) {
521
+ if (
522
+ existing.status === "pending" &&
523
+ typeof retentionDays === "number" &&
524
+ Number.isFinite(retentionDays) &&
525
+ retentionDays >= 0
526
+ ) {
527
+ let payload: Record<string, unknown> = {};
528
+ try {
529
+ payload = JSON.parse(existing.payload) as Record<string, unknown>;
530
+ } catch {
531
+ payload = {};
532
+ }
533
+ if (payload.retentionDays !== retentionDays) {
534
+ db.update(memoryJobs)
535
+ .set({
536
+ payload: JSON.stringify({ ...payload, retentionDays }),
537
+ updatedAt: Date.now(),
538
+ })
539
+ .where(eq(memoryJobs.id, existing.id))
540
+ .run();
541
+ }
542
+ }
543
+ return existing.id;
544
+ }
545
+ const payload =
546
+ typeof retentionDays === "number" &&
547
+ Number.isFinite(retentionDays) &&
548
+ retentionDays >= 0
549
+ ? { retentionDays }
550
+ : {};
551
+ return enqueueMemoryJob("prune_old_tool_invocations", payload);
552
+ }
553
+
504
554
  export interface LaneBudgets {
505
555
  slowLlm: number;
506
556
  fast: number;
@@ -37,6 +37,7 @@ import {
37
37
  enqueueMemoryJob,
38
38
  enqueuePruneOldConversationsJob,
39
39
  enqueuePruneOldLlmRequestLogsJob,
40
+ enqueuePruneOldToolInvocationsJob,
40
41
  enqueuePruneOldTraceEventsJob,
41
42
  failMemoryJob,
42
43
  failStalledJobs,
@@ -650,16 +651,24 @@ function maybeEnqueueScheduledCleanupJobs(
650
651
  cleanup.traceEventRetentionDays > 0
651
652
  ? enqueuePruneOldTraceEventsJob(cleanup.traceEventRetentionDays)
652
653
  : null;
654
+ // Audit-log (tool_invocations) retention is configured separately under
655
+ // `auditLog.retentionDays`, but rides this same cleanup cadence for now.
656
+ const pruneToolInvocationsJobId =
657
+ config.auditLog.retentionDays > 0
658
+ ? enqueuePruneOldToolInvocationsJob(config.auditLog.retentionDays)
659
+ : null;
653
660
  markScheduledCleanupEnqueued(nowMs);
654
661
  log.debug(
655
662
  {
656
663
  pruneConversationsJobId,
657
664
  pruneLlmRequestLogsJobId,
658
665
  pruneTraceEventsJobId,
666
+ pruneToolInvocationsJobId,
659
667
  enqueueIntervalMs: cleanup.enqueueIntervalMs,
660
668
  conversationRetentionDays: cleanup.conversationRetentionDays,
661
669
  llmRequestLogRetentionMs: cleanup.llmRequestLogRetentionMs,
662
670
  traceEventRetentionDays: cleanup.traceEventRetentionDays,
671
+ auditLogRetentionDays: config.auditLog.retentionDays,
663
672
  },
664
673
  "Enqueued scheduled memory cleanup jobs",
665
674
  );
@@ -134,20 +134,32 @@ export interface ModelProfileInfo {
134
134
  // ─── Shutdown context ────────────────────────────────────────────────────────
135
135
 
136
136
  /**
137
- * Context passed to the `shutdown` hook during daemon teardown. Kept
138
- * intentionally narrower than {@link InitContext} — most teardown
139
- * paths only need to know which assistant version they're shutting
140
- * down against (e.g. for version-conditional cleanup of state files
141
- * written by a previous boot).
137
+ * Why a plugin's `shutdown` hook is firing.
142
138
  *
143
- * Additional fields may be added as concrete plugin needs surface; the
144
- * `assistantVersion` field mirrors the init context's so plugins that
145
- * stash a version stamp at init can compare against the same name on
146
- * tear-down without keeping their own copy.
139
+ * - `shutdown` — the daemon is tearing down (process exit).
140
+ * - `uninstall` — the plugin's directory was removed at runtime.
141
+ * - `disable` — the plugin was disabled at runtime (e.g. a `.disabled`
142
+ * sentinel was added, or a feature flag turned it off).
143
+ */
144
+ export type ShutdownReason = "shutdown" | "uninstall" | "disable";
145
+
146
+ /**
147
+ * Context passed to the `shutdown` hook. Kept intentionally narrower than
148
+ * {@link InitContext} — teardown paths only need to know which assistant
149
+ * version they're shutting down against (e.g. for version-conditional cleanup
150
+ * of state files written by a previous boot) and {@link ShutdownReason why}
151
+ * they're being torn down (so a plugin can, e.g., delete its state on
152
+ * `uninstall` but preserve it across a plain `shutdown`).
153
+ *
154
+ * The `assistantVersion` field mirrors the init context's so plugins that stash
155
+ * a version stamp at init can compare against the same name on tear-down
156
+ * without keeping their own copy.
147
157
  */
148
158
  export interface ShutdownContext {
149
159
  /** Assistant semver for compatibility checks inside the plugin. */
150
160
  assistantVersion: string;
161
+ /** Why the plugin is shutting down. */
162
+ reason: ShutdownReason;
151
163
  }
152
164
 
153
165
  // ─── User-prompt-submit hook context ─────────────────────────────────────────
@@ -22,7 +22,6 @@
22
22
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
23
23
  import { join } from "node:path";
24
24
 
25
- import { registerShutdownHook } from "../daemon/shutdown-registry.js";
26
25
  import {
27
26
  clearPluginHooks,
28
27
  collectUserHooks,
@@ -35,7 +34,7 @@ import {
35
34
  runShutdownHook,
36
35
  WORKSPACE_HOOKS_OWNER,
37
36
  } from "../hooks/hook-loader.js";
38
- import type { HookFunction, ShutdownContext } from "../plugin-api/types.js";
37
+ import type { HookFunction, ShutdownReason } from "../plugin-api/types.js";
39
38
  import {
40
39
  registerPluginTools,
41
40
  unregisterPluginTools,
@@ -320,7 +319,7 @@ async function scanPlugins(): Promise<void> {
320
319
  const manifest = await parsePluginManifest(pluginDir);
321
320
  const pluginName = manifest?.name ?? entry;
322
321
  if (discoveredPluginDirs.has(pluginDir)) {
323
- await deactivatePlugin(pluginName);
322
+ await deactivatePlugin(pluginName, "disable");
324
323
  await evictPlugin(pluginDir, pluginName);
325
324
  }
326
325
  if (!disabledPluginDirs.has(pluginDir)) {
@@ -351,7 +350,7 @@ async function scanPlugins(): Promise<void> {
351
350
  // Deactivate and evict cache entries for deleted plugins.
352
351
  for (const [pluginDir, pluginName] of discoveredPluginDirs) {
353
352
  if (!currentDirs.has(pluginDir)) {
354
- await deactivatePlugin(pluginName);
353
+ await deactivatePlugin(pluginName, "uninstall");
355
354
  await evictPlugin(pluginDir, pluginName);
356
355
  }
357
356
  }
@@ -422,8 +421,10 @@ async function evictAll(): Promise<void> {
422
421
 
423
422
  /**
424
423
  * Plugins (and the workspace-hooks pseudo-owner) fully activated (tools
425
- * registered + `init` hook run) within this process, in activation order. The
426
- * process shutdown hook walks this list in reverse to tear everything down.
424
+ * registered + `init` hook run) within this process, in activation order. A
425
+ * runtime uninstall/disable tears a single entry down via
426
+ * {@link deactivatePlugin}; at daemon shutdown the owners' `shutdown` hooks
427
+ * fire through the unified `runHook(HOOKS.SHUTDOWN)` pipeline.
427
428
  */
428
429
  const activatedPlugins: Array<{ name: string }> = [];
429
430
 
@@ -436,16 +437,12 @@ const activatedPlugins: Array<{ name: string }> = [];
436
437
  */
437
438
  const activatedNames = new Set<string>();
438
439
 
439
- const shutdownContext: ShutdownContext = {
440
- assistantVersion: APP_VERSION,
441
- };
442
-
443
440
  /**
444
441
  * Activate a single discovered plugin: pre-import its hooks, register its tools
445
442
  * into the global tool registry, and run its `init` hook. Idempotent — a plugin
446
443
  * already activated (or mid-activation) is skipped. Never throws; per-surface
447
444
  * failures are logged and the plugin still counts as activated so the shutdown
448
- * hook tears down whatever came up (mirrors boot semantics).
445
+ * teardown handles whatever came up (mirrors boot semantics).
449
446
  *
450
447
  * Called from `scanPlugins`, which runs both at boot and on every subsequent
451
448
  * scan — so a plugin whose files appear at runtime (installed via the CLI or
@@ -491,12 +488,16 @@ async function activatePlugin(
491
488
  }
492
489
 
493
490
  /**
494
- * Deactivate a plugin whose directory was removed or disabled at runtime:
495
- * unregister its tools and run its `shutdown` hook. Must run *before*
496
- * `evictPlugin` clears the hook cache, since the shutdown hook is read from it.
497
- * Idempotent — a plugin that was never activated is a no-op.
491
+ * Deactivate a plugin whose directory was removed (`uninstall`) or disabled
492
+ * (`disable`) at runtime: unregister its tools and run its `shutdown` hook with
493
+ * the matching {@link ShutdownReason}. Must run *before* `evictPlugin` clears
494
+ * the hook cache, since the shutdown hook is read from it. Idempotent — a plugin
495
+ * that was never activated is a no-op.
498
496
  */
499
- async function deactivatePlugin(pluginName: string): Promise<void> {
497
+ async function deactivatePlugin(
498
+ pluginName: string,
499
+ reason: ShutdownReason,
500
+ ): Promise<void> {
500
501
  if (!activatedNames.has(pluginName)) return;
501
502
  activatedNames.delete(pluginName);
502
503
  const idx = activatedPlugins.findIndex((p) => p.name === pluginName);
@@ -513,7 +514,11 @@ async function deactivatePlugin(pluginName: string): Promise<void> {
513
514
  );
514
515
  }
515
516
 
516
- await runShutdownHook(pluginName, shutdownContext, "plugin-removed");
517
+ await runShutdownHook(
518
+ pluginName,
519
+ { assistantVersion: APP_VERSION, reason },
520
+ reason,
521
+ );
517
522
  }
518
523
 
519
524
  // ─── Boot population ─────────────────────────────────────────────────────────
@@ -521,8 +526,10 @@ async function deactivatePlugin(pluginName: string): Promise<void> {
521
526
  /**
522
527
  * Populate the caches at boot by scanning the plugins directory once (which
523
528
  * imports surfaces, registers tools, and runs `init` hooks via `activatePlugin`
524
- * inside `scanPlugins`), activating standalone workspace hooks, and installing
525
- * the process shutdown hook.
529
+ * inside `scanPlugins`) and activating standalone workspace hooks. At daemon
530
+ * shutdown these owners' `shutdown` hooks fire through the unified
531
+ * `runHook(HOOKS.SHUTDOWN)` pipeline; a runtime uninstall/disable tears a single
532
+ * owner down via {@link deactivatePlugin}.
526
533
  *
527
534
  * This replaces the old `loadExternalPlugin` → `registerPlugin` →
528
535
  * `bootstrapPlugins` path for user plugins. Instead of registering whole
@@ -555,33 +562,6 @@ export async function populateCacheAtBoot(
555
562
  await runInitHook(WORKSPACE_HOOKS_OWNER);
556
563
  activatedPlugins.push({ name: WORKSPACE_HOOKS_OWNER });
557
564
  }
558
-
559
- // Register a single shutdown hook that walks all activated owners in reverse
560
- // order, unregistering tools and running shutdown hooks. It reads the live
561
- // `activatedPlugins` array at teardown time, so plugins activated after boot
562
- // (runtime installs) are torn down too.
563
- registerShutdownHook("user-plugins", async (reason) => {
564
- for (let i = activatedPlugins.length - 1; i >= 0; i--) {
565
- const entry = activatedPlugins[i];
566
- if (entry === undefined) continue;
567
- const { name } = entry;
568
-
569
- // Unregister tools before running shutdown so onShutdown sees a
570
- // clean model-visible surface. (No-op for the workspace-hooks owner,
571
- // which registers no tools.)
572
- try {
573
- unregisterPluginTools(name);
574
- } catch (err) {
575
- log.warn(
576
- { err, plugin: name, reason },
577
- "user plugin tool unregister failed (continuing)",
578
- );
579
- }
580
-
581
- // Run the `shutdown` hook if present.
582
- await runShutdownHook(name, shutdownContext, reason);
583
- }
584
- });
585
565
  }
586
566
 
587
567
  // ─── Test hooks ──────────────────────────────────────────────────────────────
@@ -71,6 +71,7 @@ export type {
71
71
  HookFunction,
72
72
  InitContext,
73
73
  ShutdownContext,
74
+ ShutdownReason,
74
75
  } from "../plugin-api/types.js";
75
76
 
76
77
  // ─── Memory-graph result ─────────────────────────────────────────────────────