@vellumai/assistant 0.8.9 → 0.8.10-dev.202606092238.d04fd59

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 (147) hide show
  1. package/AGENTS.md +1 -1
  2. package/examples/plugins/echo/README.md +3 -3
  3. package/node_modules/@vellumai/skill-host-contracts/src/tool-types.ts +2 -0
  4. package/openapi.yaml +38 -12
  5. package/package.json +1 -1
  6. package/scripts/sync-llm-catalog.ts +2 -0
  7. package/src/__tests__/agent-loop-exit-reason.test.ts +19 -14
  8. package/src/__tests__/build-persisted-content.test.ts +75 -1
  9. package/src/__tests__/config-managed-gemini-defaults.test.ts +2 -46
  10. package/src/__tests__/context-overflow-reducer.test.ts +264 -124
  11. package/src/__tests__/context-window-manager-overflow-rung.test.ts +289 -0
  12. package/src/__tests__/conversation-agent-loop-overflow.test.ts +22 -22
  13. package/src/__tests__/conversation-agent-loop.test.ts +45 -37
  14. package/src/__tests__/conversation-fork-crud.test.ts +110 -0
  15. package/src/__tests__/conversation-provider-retry-repair.test.ts +16 -20
  16. package/src/__tests__/conversation-runtime-assembly.test.ts +118 -5
  17. package/src/__tests__/conversation-surfaces-app-control.test.ts +4 -1
  18. package/src/__tests__/conversation-tool-setup-app-refresh.test.ts +91 -142
  19. package/src/__tests__/conversation-tool-setup-skill-attribution.test.ts +116 -0
  20. package/src/__tests__/conversation-tool-setup-test-helpers.ts +98 -0
  21. package/src/__tests__/corrected-target.test.ts +93 -0
  22. package/src/__tests__/credential-execution-feature-gates.test.ts +3 -5
  23. package/src/__tests__/credential-security-invariants.test.ts +1 -0
  24. package/src/__tests__/embedding-managed-proxy-selection.test.ts +6 -40
  25. package/src/__tests__/external-plugin-loader.test.ts +0 -1
  26. package/src/__tests__/guardian-routing-invariants.test.ts +91 -0
  27. package/src/__tests__/history-repair-hook.test.ts +2 -0
  28. package/src/__tests__/host-app-control-proxy.test.ts +45 -0
  29. package/src/__tests__/llm-catalog-parity.test.ts +4 -0
  30. package/src/__tests__/memory-retrieval-hook.test.ts +29 -15
  31. package/src/__tests__/notification-decision-strategy.test.ts +3 -3
  32. package/src/__tests__/persistence-secret-redaction.test.ts +78 -0
  33. package/src/__tests__/plugin-bootstrap.test.ts +82 -73
  34. package/src/__tests__/plugin-tool-contribution.test.ts +7 -4
  35. package/src/__tests__/plugin-types.test.ts +0 -8
  36. package/src/__tests__/provider-catalog-visibility.test.ts +1 -9
  37. package/src/__tests__/retry-thinking-adaptive-only.test.ts +245 -0
  38. package/src/__tests__/server-history-render.test.ts +39 -0
  39. package/src/__tests__/skills.test.ts +123 -0
  40. package/src/__tests__/title-generate-hook.test.ts +2 -0
  41. package/src/__tests__/tool-audit-listener.test.ts +51 -0
  42. package/src/__tests__/tool-executor-lifecycle-events.test.ts +32 -0
  43. package/src/__tests__/tool-start-timestamp.test.ts +218 -0
  44. package/src/agent/loop.ts +26 -23
  45. package/src/api/events/tool-result.ts +9 -0
  46. package/src/api/events/tool-use-start.ts +7 -0
  47. package/src/api/responses/conversation-message.ts +91 -14
  48. package/src/approvals/guardian-request-resolvers.ts +26 -0
  49. package/src/cli/commands/channel-verification-sessions.ts +6 -6
  50. package/src/cli/commands/inference-providers.ts +0 -8
  51. package/src/cli/commands/plugins.ts +2 -2
  52. package/src/cli/lib/__tests__/install-from-github.test.ts +174 -18
  53. package/src/cli/lib/__tests__/plugin-catalog-cache.test.ts +1 -1
  54. package/src/cli/lib/__tests__/plugin-details.test.ts +1 -1
  55. package/src/cli/lib/__tests__/plugin-marketplace.test.ts +1 -1
  56. package/src/cli/lib/__tests__/search-plugins.test.ts +11 -11
  57. package/src/cli/lib/install-from-github.ts +130 -19
  58. package/src/cli/lib/plugin-catalog-cache.ts +1 -1
  59. package/src/cli/lib/plugin-details.ts +4 -4
  60. package/src/cli/lib/plugin-marketplace.ts +2 -2
  61. package/src/cli/lib/search-plugins.ts +6 -6
  62. package/src/config/bundled-skills/skill-management/SKILL.md +89 -1
  63. package/src/config/env-registry.ts +12 -0
  64. package/src/config/feature-flag-registry.json +0 -80
  65. package/src/config/loader.ts +5 -22
  66. package/src/config/seed-inference-profiles.ts +1 -1
  67. package/src/config/skills.ts +101 -47
  68. package/src/context/strip-injections.ts +7 -4
  69. package/src/daemon/conversation-agent-loop-handlers.ts +102 -6
  70. package/src/daemon/conversation-agent-loop.ts +134 -232
  71. package/src/daemon/conversation-runtime-assembly.ts +44 -8
  72. package/src/daemon/conversation-tool-setup.ts +9 -1
  73. package/src/daemon/external-plugins-bootstrap.ts +33 -87
  74. package/src/daemon/handlers/config-channels.ts +11 -2
  75. package/src/daemon/handlers/shared.ts +9 -1
  76. package/src/daemon/handlers/skills.ts +6 -2
  77. package/src/daemon/host-app-control-proxy.ts +72 -57
  78. package/src/daemon/message-protocol.ts +0 -7
  79. package/src/daemon/message-types/skills.ts +4 -0
  80. package/src/events/tool-audit-listener.ts +7 -1
  81. package/src/memory/__tests__/tool-invocation-test-helpers.ts +69 -0
  82. package/src/memory/conversation-crud.ts +44 -1
  83. package/src/memory/db-init.ts +4 -0
  84. package/src/memory/embedding-backend.ts +5 -22
  85. package/src/memory/memory-retrospective-startup-cleanup.ts +1 -1
  86. package/src/memory/migrations/275-tool-invocations-add-skill-id.test.ts +81 -0
  87. package/src/memory/migrations/275-tool-invocations-add-skill-id.ts +20 -0
  88. package/src/memory/migrations/276-tool-invocations-created-at-id-index.test.ts +68 -0
  89. package/src/memory/migrations/276-tool-invocations-created-at-id-index.ts +20 -0
  90. package/src/memory/migrations/index.ts +2 -0
  91. package/src/memory/schema/conversations.ts +3 -0
  92. package/src/memory/tool-execution-events-store.test.ts +162 -0
  93. package/src/memory/tool-execution-events-store.ts +73 -0
  94. package/src/memory/tool-usage-store.ts +4 -3
  95. package/src/memory/v2/__tests__/injected-block-slugs.test.ts +51 -0
  96. package/src/memory/v2/activation-store.ts +50 -1
  97. package/src/memory/v2/injected-block-slugs.ts +30 -0
  98. package/src/notifications/__tests__/copy-composer.test.ts +244 -0
  99. package/src/notifications/access-request-copy.ts +298 -0
  100. package/src/notifications/adapters/slack.ts +3 -3
  101. package/src/notifications/adapters/telegram.ts +2 -1
  102. package/src/notifications/copy-composer.ts +49 -267
  103. package/src/notifications/decision-engine.ts +16 -35
  104. package/src/notifications/home-feed-side-effect.ts +1 -6
  105. package/src/platform/client.ts +1 -3
  106. package/src/platform/feature-gate.ts +3 -12
  107. package/src/plugin-api/constants.ts +2 -0
  108. package/src/plugin-api/index.ts +34 -6
  109. package/src/plugin-api/types.ts +19 -0
  110. package/src/plugins/defaults/compaction/compact.ts +39 -1
  111. package/src/plugins/defaults/compaction/context-overflow-reducer.ts +240 -32
  112. package/src/plugins/defaults/compaction/corrected-target.ts +53 -0
  113. package/src/plugins/defaults/compaction/window-manager.ts +136 -0
  114. package/src/plugins/defaults/index.ts +24 -0
  115. package/src/plugins/defaults/memory-retrieval/hooks/post-compact.ts +68 -43
  116. package/src/plugins/defaults/memory-retrieval/hooks/{user-prompt-submit-temp.ts → user-prompt-submit.ts} +36 -67
  117. package/src/plugins/defaults/memory-retrieval/package.json +14 -0
  118. package/src/plugins/external-api.ts +1 -1
  119. package/src/plugins/types.ts +5 -51
  120. package/src/providers/inference/__tests__/base-url-route-validation.test.ts +1 -2
  121. package/src/providers/model-catalog.ts +57 -1
  122. package/src/providers/registry.ts +0 -8
  123. package/src/providers/retry.ts +35 -7
  124. package/src/runtime/routes/__tests__/acp-routes.test.ts +151 -0
  125. package/src/runtime/routes/__tests__/inference-provider-connection-routes.test.ts +0 -62
  126. package/src/runtime/routes/__tests__/plugins-routes.test.ts +4 -4
  127. package/src/runtime/routes/acp-routes.test.ts +106 -0
  128. package/src/runtime/routes/acp-routes.ts +248 -2
  129. package/src/runtime/routes/browser-tabs-routes.ts +1 -1
  130. package/src/runtime/routes/channel-verification-routes.ts +14 -5
  131. package/src/runtime/routes/chatgpt-subscription-auth-routes.ts +0 -14
  132. package/src/runtime/routes/inbound-stages/acl-enforcement.ts +33 -34
  133. package/src/runtime/routes/inference-provider-connection-routes.ts +0 -45
  134. package/src/runtime/routes/plugins-routes.ts +3 -3
  135. package/src/runtime/verification-outbound-actions.ts +147 -2
  136. package/src/runtime/verification-templates.ts +29 -3
  137. package/src/telemetry/types.ts +25 -1
  138. package/src/telemetry/usage-telemetry-reporter.test.ts +141 -7
  139. package/src/telemetry/usage-telemetry-reporter.ts +63 -7
  140. package/src/tools/executor.ts +4 -1
  141. package/src/tools/skills/load.ts +11 -6
  142. package/src/tools/terminal/safe-env.ts +1 -0
  143. package/src/tools/types.ts +10 -0
  144. package/src/__tests__/plugin-skill-contribution.test.ts +0 -355
  145. package/src/daemon/message-types/browser.ts +0 -10
  146. package/src/notifications/__tests__/emit-signal-home-feed.test.ts +0 -187
  147. package/src/plugins/plugin-skill-contributions.ts +0 -292
@@ -70,7 +70,11 @@ import {
70
70
  toolInvocations,
71
71
  } from "./schema.js";
72
72
  import { cancelPendingJobsForConversation } from "./task-memory-cleanup.js";
73
- import { forkActivationState } from "./v2/activation-store.js";
73
+ import {
74
+ forkActivationState,
75
+ seedForkActivationState,
76
+ } from "./v2/activation-store.js";
77
+ import { extractInjectedConceptSlugs } from "./v2/injected-block-slugs.js";
74
78
 
75
79
  const log = getLogger("conversation-store");
76
80
 
@@ -166,6 +170,25 @@ function cloneForkMessageMetadata(
166
170
  return JSON.stringify({ forkSourceMessageId: sourceMessageId });
167
171
  }
168
172
 
173
+ /**
174
+ * Read the persisted `memoryInjectedBlock` off a message's metadata JSON, or
175
+ * `null` when absent/malformed. The block is what the request builder
176
+ * re-attaches as the message's `<memory>` content each turn.
177
+ */
178
+ function readMemoryInjectedBlock(metadata: string | null): string | null {
179
+ if (!metadata) return null;
180
+ try {
181
+ const parsed: unknown = JSON.parse(metadata);
182
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
183
+ const block = (parsed as Record<string, unknown>).memoryInjectedBlock;
184
+ if (typeof block === "string") return block;
185
+ }
186
+ } catch {
187
+ // Malformed metadata — treat as no block.
188
+ }
189
+ return null;
190
+ }
191
+
169
192
  /**
170
193
  * Extract provenance metadata fields from a TrustContext.
171
194
  * When no guardian context is provided, defaults to 'unknown' because the
@@ -1034,6 +1057,26 @@ export function forkConversation(params: {
1034
1057
  if (isFullHistoryFork) {
1035
1058
  forkActivationState(db, sourceConversation.id, fc.id);
1036
1059
  forkGraphMemoryState(sourceConversation.id, fc.id);
1060
+ } else {
1061
+ // Truncated fork: the wholesale copy above would over-claim, but
1062
+ // seeding nothing makes the child re-select and re-attach every page
1063
+ // whose `<memory>` attachment it already inherited (observed in
1064
+ // production: 89 duplicate page injections on one fork). Derive
1065
+ // `everInjected` from the inherited attachments themselves — scoped to
1066
+ // the child's visible window, since attachments behind an inherited
1067
+ // compaction boundary are not rendered and must stay re-injectable.
1068
+ const visibleStartIndex = preserveSourceCompactionState
1069
+ ? visibleWindowStartIndex
1070
+ : 0;
1071
+ const inheritedSlugs = new Set<string>();
1072
+ for (const message of messagesToCopy.slice(visibleStartIndex)) {
1073
+ const block = readMemoryInjectedBlock(message.metadata);
1074
+ if (!block) continue;
1075
+ for (const slug of extractInjectedConceptSlugs(block)) {
1076
+ inheritedSlugs.add(slug);
1077
+ }
1078
+ }
1079
+ seedForkActivationState(db, fc.id, [...inheritedSlugs]);
1037
1080
  }
1038
1081
  forkRetrospectiveState({
1039
1082
  database: db,
@@ -201,7 +201,9 @@ import {
201
201
  migrateStripIntegrationPrefixFromProviderKeys,
202
202
  migrateStripPlaceholderSentinelsFromMessages,
203
203
  migrateStripThinkingFromConsolidated,
204
+ migrateToolInvocationsCreatedAtIdIndex,
204
205
  migrateToolInvocationsMatchedRuleId,
206
+ migrateToolInvocationsSkillId,
205
207
  migrateTraceEventsCreatedAtIndex,
206
208
  migrateUsageDashboardIndexes,
207
209
  migrateUsageLlmCallCount,
@@ -484,6 +486,8 @@ export function initializeDb(): void {
484
486
  migrateAcpSessionHistoryCwd,
485
487
  migrateOnboardingEventsFunnelColumns,
486
488
  createActivationSessionsTable,
489
+ migrateToolInvocationsSkillId,
490
+ migrateToolInvocationsCreatedAtIdIndex,
487
491
  ];
488
492
 
489
493
  // Run each migration step, catching and logging individual failures so one
@@ -1,6 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
2
 
3
- import { isAssistantFeatureFlagEnabled } from "../config/assistant-feature-flags.js";
4
3
  import { getOllamaBaseUrlEnv } from "../config/env.js";
5
4
  import { resolveCallSiteConfig } from "../config/llm-resolver.js";
6
5
  import type { AssistantConfig } from "../config/types.js";
@@ -302,13 +301,10 @@ export async function selectEmbeddingBackend(
302
301
  };
303
302
  }
304
303
 
305
- // When the managed-gemini-embeddings-enabled flag is on AND managed proxy
306
- // prerequisites are satisfied, insert managed-proxy Gemini at the front of
307
- // the auto chain so platform assistants use Vellum-managed Gemini embeddings.
308
- if (
309
- (requested === "auto" || requested === "gemini") &&
310
- isAssistantFeatureFlagEnabled("managed-gemini-embeddings-enabled", config)
311
- ) {
304
+ // When managed proxy prerequisites are satisfied, insert managed-proxy Gemini
305
+ // at the front of the auto chain so platform assistants use Vellum-managed
306
+ // Gemini embeddings.
307
+ if (requested === "auto" || requested === "gemini") {
312
308
  const proxyCtx = await resolveManagedProxyContext();
313
309
  if (proxyCtx.enabled) {
314
310
  const meta = PLATFORM_PROVIDER_META["gemini"];
@@ -677,12 +673,7 @@ async function selectFallbackBackends(
677
673
  geminiCacheExtras(config),
678
674
  ),
679
675
  );
680
- } else if (
681
- isAssistantFeatureFlagEnabled(
682
- "managed-gemini-embeddings-enabled",
683
- config,
684
- )
685
- ) {
676
+ } else {
686
677
  // Try managed proxy Gemini as fallback when no direct key exists.
687
678
  const proxyCtx = await resolveManagedProxyContext();
688
679
  const meta = PLATFORM_PROVIDER_META["gemini"];
@@ -724,14 +715,6 @@ async function selectFallbackBackends(
724
715
  );
725
716
  if (cached) backends.push(cached);
726
717
  }
727
- } else {
728
- // Preserve cached backend on transient credential-store failures.
729
- const cached = getCached(
730
- "gemini",
731
- config.memory.embeddings.geminiModel,
732
- geminiCacheExtras(config),
733
- );
734
- if (cached) backends.push(cached);
735
718
  }
736
719
  break;
737
720
  }
@@ -93,7 +93,7 @@ export function sweepOrphanMemoryRetrospectiveConversations(
93
93
  // Compute the most-recent retro per source so we can preserve it.
94
94
  // `findMostRecentRetrospectiveFor` (called by the next retrospective run)
95
95
  // pulls dedup context from this row; sweeping it would re-introduce the
96
- // unbounded-growth bug PR #30331 was created to fix.
96
+ // unbounded retrospective growth this cleanup exists to prevent.
97
97
  const allRetros = db
98
98
  .select({
99
99
  id: conversations.id,
@@ -0,0 +1,81 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { describe, expect, test } from "bun:test";
3
+
4
+ import { drizzle } from "drizzle-orm/bun-sqlite";
5
+
6
+ import * as schema from "../schema.js";
7
+ import { migrateToolInvocationsSkillId } from "./275-tool-invocations-add-skill-id.js";
8
+
9
+ function createTestDb() {
10
+ const sqlite = new Database(":memory:");
11
+ // Pre-275 shape: no skill_id column.
12
+ sqlite.exec(/*sql*/ `
13
+ CREATE TABLE tool_invocations (
14
+ id TEXT PRIMARY KEY,
15
+ conversation_id TEXT NOT NULL,
16
+ tool_name TEXT NOT NULL,
17
+ input TEXT NOT NULL,
18
+ result TEXT NOT NULL,
19
+ decision TEXT NOT NULL,
20
+ risk_level TEXT NOT NULL,
21
+ matched_trust_rule_id TEXT,
22
+ duration_ms INTEGER NOT NULL,
23
+ created_at INTEGER NOT NULL
24
+ )
25
+ `);
26
+ return { sqlite, db: drizzle(sqlite, { schema }) };
27
+ }
28
+
29
+ function columnNames(sqlite: Database): string[] {
30
+ return (
31
+ sqlite.query("PRAGMA table_info(tool_invocations)").all() as Array<{
32
+ name: string;
33
+ }>
34
+ ).map((c) => c.name);
35
+ }
36
+
37
+ describe("migration 275: tool_invocations skill_id", () => {
38
+ test("adds a nullable skill_id column", () => {
39
+ const { sqlite, db } = createTestDb();
40
+ expect(columnNames(sqlite)).not.toContain("skill_id");
41
+
42
+ migrateToolInvocationsSkillId(db);
43
+
44
+ const column = (
45
+ sqlite.query("PRAGMA table_info(tool_invocations)").all() as Array<{
46
+ name: string;
47
+ notnull: number;
48
+ }>
49
+ ).find((c) => c.name === "skill_id");
50
+ expect(column).toBeDefined();
51
+ expect(column?.notnull).toBe(0);
52
+ });
53
+
54
+ test("existing rows read back with skill_id null", () => {
55
+ const { sqlite, db } = createTestDb();
56
+ sqlite.exec(/*sql*/ `
57
+ INSERT INTO tool_invocations
58
+ (id, conversation_id, tool_name, input, result, decision, risk_level, duration_ms, created_at)
59
+ VALUES
60
+ ('ti-1', 'conv-1', 'bash', '{}', 'ok', 'allow', 'low', 5, 1000)
61
+ `);
62
+
63
+ migrateToolInvocationsSkillId(db);
64
+
65
+ const row = sqlite
66
+ .query("SELECT skill_id FROM tool_invocations WHERE id = 'ti-1'")
67
+ .get() as { skill_id: string | null };
68
+ expect(row.skill_id).toBeNull();
69
+ });
70
+
71
+ test("is idempotent — re-run is a no-op", () => {
72
+ const { sqlite, db } = createTestDb();
73
+
74
+ migrateToolInvocationsSkillId(db);
75
+ expect(() => migrateToolInvocationsSkillId(db)).not.toThrow();
76
+
77
+ expect(
78
+ columnNames(sqlite).filter((name) => name === "skill_id"),
79
+ ).toHaveLength(1);
80
+ });
81
+ });
@@ -0,0 +1,20 @@
1
+ import type { DrizzleDb } from "../db-connection.js";
2
+ import { tableHasColumn } from "./schema-introspection.js";
3
+
4
+ /**
5
+ * Add a nullable `skill_id` column to `tool_invocations`.
6
+ *
7
+ * Records which skill's `skill_execute` dispatch triggered the tool call so
8
+ * the `tool_execution` telemetry event can attribute skill-routed
9
+ * invocations. `NULL` for direct (non-skill) tool calls and for rows
10
+ * persisted before this migration ran.
11
+ *
12
+ * Idempotent — re-running is a no-op once the column exists. Pure DDL with a
13
+ * PRAGMA guard, no registry entry needed (matches the 273 pattern).
14
+ */
15
+ export function migrateToolInvocationsSkillId(database: DrizzleDb): void {
16
+ if (tableHasColumn(database, "tool_invocations", "skill_id")) {
17
+ return;
18
+ }
19
+ database.run(`ALTER TABLE tool_invocations ADD COLUMN skill_id TEXT`);
20
+ }
@@ -0,0 +1,68 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { describe, expect, test } from "bun:test";
3
+
4
+ import { drizzle } from "drizzle-orm/bun-sqlite";
5
+
6
+ import * as schema from "../schema.js";
7
+ import { migrateToolInvocationsCreatedAtIdIndex } from "./276-tool-invocations-created-at-id-index.js";
8
+
9
+ function createTestDb() {
10
+ const sqlite = new Database(":memory:");
11
+ // Pre-276 shape: no (created_at, id) index.
12
+ sqlite.exec(/*sql*/ `
13
+ CREATE TABLE tool_invocations (
14
+ id TEXT PRIMARY KEY,
15
+ conversation_id TEXT NOT NULL,
16
+ tool_name TEXT NOT NULL,
17
+ input TEXT NOT NULL,
18
+ result TEXT NOT NULL,
19
+ decision TEXT NOT NULL,
20
+ risk_level TEXT NOT NULL,
21
+ matched_trust_rule_id TEXT,
22
+ skill_id TEXT,
23
+ duration_ms INTEGER NOT NULL,
24
+ created_at INTEGER NOT NULL
25
+ )
26
+ `);
27
+ return { sqlite, db: drizzle(sqlite, { schema }) };
28
+ }
29
+
30
+ function indexNames(sqlite: Database): string[] {
31
+ return (
32
+ sqlite.query("PRAGMA index_list(tool_invocations)").all() as Array<{
33
+ name: string;
34
+ }>
35
+ ).map((i) => i.name);
36
+ }
37
+
38
+ describe("migration 276: tool_invocations (created_at, id) index", () => {
39
+ test("creates the index on (created_at, id)", () => {
40
+ const { sqlite, db } = createTestDb();
41
+ expect(indexNames(sqlite)).not.toContain(
42
+ "idx_tool_invocations_created_at_id",
43
+ );
44
+
45
+ migrateToolInvocationsCreatedAtIdIndex(db);
46
+
47
+ expect(indexNames(sqlite)).toContain("idx_tool_invocations_created_at_id");
48
+ const columns = (
49
+ sqlite
50
+ .query("PRAGMA index_info(idx_tool_invocations_created_at_id)")
51
+ .all() as Array<{ name: string }>
52
+ ).map((c) => c.name);
53
+ expect(columns).toEqual(["created_at", "id"]);
54
+ });
55
+
56
+ test("is idempotent — re-run is a no-op", () => {
57
+ const { sqlite, db } = createTestDb();
58
+
59
+ migrateToolInvocationsCreatedAtIdIndex(db);
60
+ expect(() => migrateToolInvocationsCreatedAtIdIndex(db)).not.toThrow();
61
+
62
+ expect(
63
+ indexNames(sqlite).filter(
64
+ (name) => name === "idx_tool_invocations_created_at_id",
65
+ ),
66
+ ).toHaveLength(1);
67
+ });
68
+ });
@@ -0,0 +1,20 @@
1
+ import type { DrizzleDb } from "../db-connection.js";
2
+
3
+ /**
4
+ * Indexes `tool_invocations(created_at, id)` so the tool_execution telemetry
5
+ * cursor can seek to the next unreported batch instead of scanning the table.
6
+ *
7
+ * `queryUnreportedToolExecutionEvents` filters and orders by `(created_at, id)`
8
+ * every telemetry flush (~5 min); without this index each flush scans and
9
+ * sorts the whole audit table, which grows unboundedly by default and carries
10
+ * large `input`/`result` text blobs.
11
+ *
12
+ * Idempotent — `CREATE INDEX IF NOT EXISTS` is a no-op once the index exists.
13
+ */
14
+ export function migrateToolInvocationsCreatedAtIdIndex(
15
+ database: DrizzleDb,
16
+ ): void {
17
+ database.run(
18
+ /*sql*/ `CREATE INDEX IF NOT EXISTS idx_tool_invocations_created_at_id ON tool_invocations (created_at, id)`,
19
+ );
20
+ }
@@ -262,6 +262,8 @@ export { createAuthFallbackEventsTable } from "./271-create-auth-fallback-events
262
262
  export { migrateAcpSessionHistoryCwd } from "./272-acp-session-history-cwd.js";
263
263
  export { migrateOnboardingEventsFunnelColumns } from "./273-onboarding-events-funnel-columns.js";
264
264
  export { createActivationSessionsTable } from "./274-create-activation-sessions.js";
265
+ export { migrateToolInvocationsSkillId } from "./275-tool-invocations-add-skill-id.js";
266
+ export { migrateToolInvocationsCreatedAtIdIndex } from "./276-tool-invocations-created-at-id-index.js";
265
267
  export {
266
268
  MIGRATION_REGISTRY,
267
269
  type MigrationRegistryEntry,
@@ -91,11 +91,14 @@ export const toolInvocations = sqliteTable(
91
91
  decision: text("decision").notNull(),
92
92
  riskLevel: text("risk_level").notNull(),
93
93
  matchedTrustRuleId: text("matched_trust_rule_id"),
94
+ /** Id of the skill whose `skill_execute` dispatch triggered this tool call. Null for direct tool calls. */
95
+ skillId: text("skill_id"),
94
96
  durationMs: integer("duration_ms").notNull(),
95
97
  createdAt: integer("created_at").notNull(),
96
98
  },
97
99
  (table) => [
98
100
  index("idx_tool_invocations_conversation_id").on(table.conversationId),
101
+ index("idx_tool_invocations_created_at_id").on(table.createdAt, table.id),
99
102
  ],
100
103
  );
101
104
 
@@ -0,0 +1,162 @@
1
+ import { beforeEach, describe, expect, mock, test } from "bun:test";
2
+
3
+ mock.module("../util/logger.js", () => ({
4
+ getLogger: () =>
5
+ new Proxy({} as Record<string, unknown>, {
6
+ get: () => () => {},
7
+ }),
8
+ }));
9
+
10
+ import { createToolAuditListener } from "../events/tool-audit-listener.js";
11
+ import {
12
+ seedToolInvocation,
13
+ type SeedToolInvocationSpec,
14
+ TOOL_INVOCATION_PII_SENTINEL,
15
+ } from "./__tests__/tool-invocation-test-helpers.js";
16
+ import { getDb } from "./db-connection.js";
17
+ import { initializeDb } from "./db-init.js";
18
+ import { conversations, toolInvocations } from "./schema.js";
19
+ import { queryUnreportedToolExecutionEvents } from "./tool-execution-events-store.js";
20
+
21
+ initializeDb();
22
+
23
+ const CONVERSATION_ID = "conv-tool-exec-store-test";
24
+
25
+ function insertInvocation(
26
+ spec: Omit<SeedToolInvocationSpec, "conversationId">,
27
+ ): void {
28
+ seedToolInvocation(
29
+ { db: getDb(), conversations, toolInvocations },
30
+ { ...spec, conversationId: CONVERSATION_ID },
31
+ );
32
+ }
33
+
34
+ describe("tool-execution-events-store", () => {
35
+ beforeEach(() => {
36
+ getDb().delete(toolInvocations).run();
37
+ });
38
+
39
+ test("returns rows in (createdAt, id) order with projected fields", () => {
40
+ insertInvocation({
41
+ id: "ti-b",
42
+ createdAt: 2000,
43
+ toolName: "web_search",
44
+ skillId: "research-skill",
45
+ decision: "denied",
46
+ riskLevel: "high",
47
+ durationMs: 7,
48
+ });
49
+ insertInvocation({ id: "ti-a", createdAt: 1000 });
50
+
51
+ const rows = queryUnreportedToolExecutionEvents(0, undefined, 100);
52
+ expect(rows.map((r) => r.id)).toEqual(["ti-a", "ti-b"]);
53
+ expect(rows[0]).toEqual({
54
+ id: "ti-a",
55
+ toolName: "calendar_list_events",
56
+ skillId: null,
57
+ decision: "allow",
58
+ riskLevel: "low",
59
+ durationMs: 12,
60
+ conversationId: CONVERSATION_ID,
61
+ createdAt: 1000,
62
+ });
63
+ expect(rows[1]).toMatchObject({
64
+ toolName: "web_search",
65
+ skillId: "research-skill",
66
+ decision: "denied",
67
+ riskLevel: "high",
68
+ durationMs: 7,
69
+ });
70
+ // Raw tool args/outputs are potentially PII — the projection must
71
+ // never include them.
72
+ expect(JSON.stringify(rows)).not.toContain(TOOL_INVOCATION_PII_SENTINEL);
73
+ });
74
+
75
+ test("query advances past the compound (createdAt, id) cursor", () => {
76
+ // Two rows in the same millisecond: pagination must use the id
77
+ // tiebreaker to make forward progress, not loop.
78
+ insertInvocation({ id: "ti-1", createdAt: 5000 });
79
+ insertInvocation({ id: "ti-2", createdAt: 5000 });
80
+ insertInvocation({ id: "ti-3", createdAt: 6000 });
81
+
82
+ const first = queryUnreportedToolExecutionEvents(0, undefined, 1);
83
+ expect(first.map((r) => r.id)).toEqual(["ti-1"]);
84
+
85
+ const second = queryUnreportedToolExecutionEvents(
86
+ first[0].createdAt,
87
+ first[0].id,
88
+ 100,
89
+ );
90
+ expect(second.map((r) => r.id)).toEqual(["ti-2", "ti-3"]);
91
+
92
+ // Without an id cursor the timestamp-only branch is used.
93
+ expect(
94
+ queryUnreportedToolExecutionEvents(5000, undefined, 100).map((r) => r.id),
95
+ ).toEqual(["ti-3"]);
96
+
97
+ // Cursor past the last row returns nothing.
98
+ const last = second[second.length - 1];
99
+ expect(
100
+ queryUnreportedToolExecutionEvents(last.createdAt, last.id, 100).length,
101
+ ).toBe(0);
102
+ });
103
+
104
+ test("skill-routed lifecycle events persist skill_id end to end; direct calls stay null", () => {
105
+ // The audit listener writes through recordToolInvocation, which (unlike
106
+ // seedToolInvocation) does not seed the FK-required conversation row.
107
+ getDb()
108
+ .insert(conversations)
109
+ .values({
110
+ id: CONVERSATION_ID,
111
+ title: "test",
112
+ createdAt: 1000,
113
+ updatedAt: 1000,
114
+ })
115
+ .onConflictDoNothing()
116
+ .run();
117
+
118
+ // Default recorder = recordToolInvocation, so this exercises the full
119
+ // audit listener → tool_invocations → telemetry projection chain.
120
+ const listener = createToolAuditListener();
121
+
122
+ listener({
123
+ type: "executed",
124
+ toolName: "task_create",
125
+ input: { title: "t" },
126
+ workingDir: "/tmp",
127
+ conversationId: CONVERSATION_ID,
128
+ skillId: "tasks-skill",
129
+ riskLevel: "low",
130
+ decision: "allow",
131
+ durationMs: 4,
132
+ result: { content: "ok", isError: false },
133
+ });
134
+ listener({
135
+ type: "executed",
136
+ toolName: "bash",
137
+ input: { command: "ls" },
138
+ workingDir: "/tmp",
139
+ conversationId: CONVERSATION_ID,
140
+ riskLevel: "low",
141
+ decision: "allow",
142
+ durationMs: 2,
143
+ result: { content: "ok", isError: false },
144
+ });
145
+
146
+ const rows = queryUnreportedToolExecutionEvents(0, undefined, 100);
147
+ expect(rows).toHaveLength(2);
148
+ expect(rows.find((r) => r.toolName === "task_create")?.skillId).toBe(
149
+ "tasks-skill",
150
+ );
151
+ expect(rows.find((r) => r.toolName === "bash")?.skillId).toBeNull();
152
+ });
153
+
154
+ test("honors the limit", () => {
155
+ insertInvocation({ id: "ti-l1", createdAt: 1000 });
156
+ insertInvocation({ id: "ti-l2", createdAt: 2000 });
157
+ insertInvocation({ id: "ti-l3", createdAt: 3000 });
158
+
159
+ const rows = queryUnreportedToolExecutionEvents(0, undefined, 2);
160
+ expect(rows.map((r) => r.id)).toEqual(["ti-l1", "ti-l2"]);
161
+ });
162
+ });
@@ -0,0 +1,73 @@
1
+ import { and, asc, eq, gt, or } from "drizzle-orm";
2
+
3
+ import { getDb } from "./db-connection.js";
4
+ import { toolInvocations } from "./schema.js";
5
+
6
+ /**
7
+ * A `tool_invocations` audit row projected for telemetry reporting.
8
+ *
9
+ * Deliberately excludes the `input` / `result` columns — raw tool
10
+ * args/outputs are potentially PII and must never leave the device.
11
+ */
12
+ export interface UnreportedToolExecutionEvent {
13
+ id: string;
14
+ toolName: string;
15
+ /**
16
+ * Id of the skill whose `skill_execute` dispatch triggered this tool
17
+ * call. Null for direct (non-skill) tool calls and for rows persisted
18
+ * before migration 275 added the column.
19
+ */
20
+ skillId: string | null;
21
+ decision: string;
22
+ riskLevel: string;
23
+ durationMs: number;
24
+ conversationId: string;
25
+ createdAt: number;
26
+ }
27
+
28
+ /**
29
+ * Query tool invocations that haven't been reported to telemetry yet.
30
+ * Uses a compound cursor (createdAt + id) for reliable watermarking.
31
+ *
32
+ * Rows are written by the tool audit listener
33
+ * (`events/tool-audit-listener.ts`) — there is no record function here.
34
+ *
35
+ * Reporting is best-effort: `rotateToolInvocations` purges rows by
36
+ * `created_at` alone, so rows older than the configured
37
+ * `auditLog.retentionDays` window may be rotated away before they are
38
+ * reported (e.g. if the daemon is offline or failing for longer than
39
+ * the retention window).
40
+ */
41
+ export function queryUnreportedToolExecutionEvents(
42
+ afterCreatedAt: number,
43
+ afterId: string | undefined,
44
+ limit: number,
45
+ ): UnreportedToolExecutionEvent[] {
46
+ const db = getDb();
47
+ return db
48
+ .select({
49
+ id: toolInvocations.id,
50
+ toolName: toolInvocations.toolName,
51
+ skillId: toolInvocations.skillId,
52
+ decision: toolInvocations.decision,
53
+ riskLevel: toolInvocations.riskLevel,
54
+ durationMs: toolInvocations.durationMs,
55
+ conversationId: toolInvocations.conversationId,
56
+ createdAt: toolInvocations.createdAt,
57
+ })
58
+ .from(toolInvocations)
59
+ .where(
60
+ afterId
61
+ ? or(
62
+ gt(toolInvocations.createdAt, afterCreatedAt),
63
+ and(
64
+ eq(toolInvocations.createdAt, afterCreatedAt),
65
+ gt(toolInvocations.id, afterId),
66
+ ),
67
+ )
68
+ : gt(toolInvocations.createdAt, afterCreatedAt),
69
+ )
70
+ .orderBy(asc(toolInvocations.createdAt), asc(toolInvocations.id))
71
+ .limit(limit)
72
+ .all();
73
+ }
@@ -14,6 +14,8 @@ export interface ToolInvocationRecord {
14
14
  decision: string;
15
15
  riskLevel: string;
16
16
  matchedTrustRuleId?: string;
17
+ /** Id of the skill whose `skill_execute` dispatch triggered this tool call. Absent for direct tool calls. */
18
+ skillId?: string;
17
19
  durationMs: number;
18
20
  }
19
21
 
@@ -29,6 +31,7 @@ export function recordToolInvocation(record: ToolInvocationRecord): void {
29
31
  decision: record.decision,
30
32
  riskLevel: record.riskLevel,
31
33
  matchedTrustRuleId: record.matchedTrustRuleId,
34
+ skillId: record.skillId,
32
35
  durationMs: record.durationMs,
33
36
  createdAt: Date.now(),
34
37
  })
@@ -65,9 +68,7 @@ export async function rotateToolInvocations(
65
68
 
66
69
  // Math.floor guarantees a plain integer literal in the inlined SQL
67
70
  // below; no decimal, no exponent, no surprise characters.
68
- const cutoffMs = Math.floor(
69
- Date.now() - retentionDays * 24 * 60 * 60 * 1000,
70
- );
71
+ const cutoffMs = Math.floor(Date.now() - retentionDays * 24 * 60 * 60 * 1000);
71
72
  const db = getDb();
72
73
 
73
74
  // Count before delete so we can return + log the affected row count
@@ -0,0 +1,51 @@
1
+ import { describe, expect, test } from "bun:test";
2
+
3
+ import { extractInjectedConceptSlugs } from "../injected-block-slugs.js";
4
+
5
+ describe("extractInjectedConceptSlugs", () => {
6
+ test("extracts nested concept slugs from page headers", () => {
7
+ const block = [
8
+ 'Use `file_read("memory/concepts/path/to/file.md")` to read the full pages for any of the injected memory summaries you want more information on.',
9
+ "",
10
+ "# memory/concepts/topics/page-a.md",
11
+ "Summary of page a.",
12
+ "",
13
+ "# memory/concepts/arcs/deep/nested/page-b.md",
14
+ "Summary of page b.",
15
+ ].join("\n");
16
+
17
+ expect(extractInjectedConceptSlugs(block)).toEqual([
18
+ "topics/page-a",
19
+ "arcs/deep/nested/page-b",
20
+ ]);
21
+ });
22
+
23
+ test("handles a <memory>-wrapped block the same as an unwrapped one", () => {
24
+ const wrapped =
25
+ "<memory>\n# memory/concepts/topics/page-a.md\nSummary.\n</memory>";
26
+ expect(extractInjectedConceptSlugs(wrapped)).toEqual(["topics/page-a"]);
27
+ });
28
+
29
+ test("ignores skill and CLI sections and non-header lines", () => {
30
+ const block = [
31
+ "# memory/concepts/topics/page-a.md",
32
+ "Summary mentioning memory/concepts/topics/page-x.md inline.",
33
+ "",
34
+ "### Skills You Can Use",
35
+ "- Meeting joiner skill → use skill_load to activate",
36
+ "",
37
+ "### CLI Commands You Can Use",
38
+ "Run `assistant <command> --help` for full usage.",
39
+ "- `assistant export`: export a conversation",
40
+ ].join("\n");
41
+
42
+ expect(extractInjectedConceptSlugs(block)).toEqual(["topics/page-a"]);
43
+ });
44
+
45
+ test("dedupes repeated headers and returns [] when none match", () => {
46
+ const block =
47
+ "# memory/concepts/topics/page-a.md\nA.\n\n# memory/concepts/topics/page-a.md\nA again.";
48
+ expect(extractInjectedConceptSlugs(block)).toEqual(["topics/page-a"]);
49
+ expect(extractInjectedConceptSlugs("no headers here")).toEqual([]);
50
+ });
51
+ });