@vellumai/assistant 0.10.11-dev.202607221636.b1b80c3 → 0.10.11-dev.202607221815.530ef8d

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 (30) hide show
  1. package/package.json +1 -1
  2. package/scripts/voice-ttft-spike.ts +241 -0
  3. package/src/__tests__/config-watcher-skill-reseed.test.ts +170 -176
  4. package/src/__tests__/llm-usage-store.test.ts +47 -0
  5. package/src/calls/__tests__/voice-control-protocol.test.ts +20 -19
  6. package/src/calls/__tests__/voice-session-bridge.test.ts +287 -6
  7. package/src/calls/__tests__/voice-triage-escalate.test.ts +223 -39
  8. package/src/calls/voice-control-protocol.ts +17 -9
  9. package/src/calls/voice-session-bridge.ts +300 -11
  10. package/src/calls/voice-triage-escalate.ts +222 -63
  11. package/src/config/call-site-defaults.ts +13 -0
  12. package/src/config/feature-flag-registry.json +1 -1
  13. package/src/config/schemas/call-site-catalog.ts +7 -0
  14. package/src/config/schemas/llm.ts +1 -0
  15. package/src/daemon/config-watcher.ts +73 -79
  16. package/src/daemon/conversation-agent-loop-handlers.ts +37 -0
  17. package/src/daemon/conversation-agent-loop.ts +8 -2
  18. package/src/live-voice/__tests__/live-voice-events.test.ts +7 -2
  19. package/src/live-voice/__tests__/live-voice-metrics.test.ts +3 -0
  20. package/src/live-voice/__tests__/live-voice-progress.test.ts +35 -0
  21. package/src/live-voice/__tests__/live-voice-triage-escalate.test.ts +67 -24
  22. package/src/live-voice/__tests__/live-voice-tts-session.test.ts +6 -3
  23. package/src/live-voice/__tests__/live-voice-vad.test.ts +358 -2
  24. package/src/live-voice/live-voice-metrics.ts +37 -0
  25. package/src/live-voice/live-voice-session.ts +589 -72
  26. package/src/persistence/llm-usage-store.ts +39 -16
  27. package/src/telemetry/__tests__/telemetry-event-fixtures.ts +4 -0
  28. package/src/telemetry/telemetry-event-sources.ts +2 -0
  29. package/src/telemetry/types.ts +16 -0
  30. package/src/telemetry/usage-telemetry-reporter.test.ts +16 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.11-dev.202607221636.b1b80c3",
3
+ "version": "0.10.11-dev.202607221815.530ef8d",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Voice front-door TTFT decomposition spike (JARVIS-1320).
3
+ *
4
+ * Measures time-to-first-token for the same chatty utterance across prompt
5
+ * sizes and profiles, to attribute where the live-voice front-door leg's
6
+ * multi-second first token goes (provider intrinsic vs prompt prefill vs
7
+ * agent-loop dispatch overhead — the last one is the gap between this
8
+ * script's `full` variants and the live session's `llmFirstDeltaMs`).
9
+ *
10
+ * Variants:
11
+ * slim-haiku voiceFrontDecision call site (Haiku pin), slim prompt
12
+ * slim-flash cost-optimized profile, same slim prompt
13
+ * full-notools cost-optimized, real buildSystemPrompt(), no tools
14
+ * full-flash cost-optimized, real buildSystemPrompt() + full tool defs
15
+ * full-quality quality-optimized, full prompt + tools (pre-flag brain)
16
+ *
17
+ * Run with the daemon's environment so the managed connection resolves:
18
+ * VELLUM_WORKSPACE_DIR=<daemon workspace> CES_LOCAL_SOCKET=<socket> \
19
+ * bun run scripts/voice-ttft-spike.ts [--trials 3] [--variants a,b]
20
+ *
21
+ * Outside the daemon env, credentials fall back to the encrypted file
22
+ * store; a variant whose provider resolves null is reported and skipped.
23
+ */
24
+
25
+ import { buildSystemPrompt } from "../src/prompts/system-prompt.js";
26
+ import {
27
+ getConfiguredProvider,
28
+ userMessage,
29
+ } from "../src/providers/provider-send-message.js";
30
+ import type {
31
+ Provider,
32
+ ProviderEvent,
33
+ SendMessageConfig,
34
+ } from "../src/providers/types.js";
35
+ import { getAllTools, initializeTools } from "../src/tools/registry.js";
36
+ import type { ToolDefinition } from "../src/tools/tool-types.js";
37
+
38
+ const UTTERANCE = "hey, what's up?";
39
+ const MAX_TOKENS = 64;
40
+ const CALL_TIMEOUT_MS = 45_000;
41
+
42
+ // Approximates the unified front-door prompt the spike is sizing: endpoint
43
+ // decider–scale instructions with the triage rule folded in. What matters
44
+ // for the measurement is the token count's order of magnitude, not the copy.
45
+ const SLIM_SYSTEM_PROMPT = [
46
+ "You are the realtime voice front of an assistant, on a live call.",
47
+ "The user's words arrive from speech recognition and your reply is spoken aloud, so answer in short natural sentences.",
48
+ "First judge the utterance: if the user is mid-thought, output only 0. ",
49
+ "If answering needs tools, research, memory of prior work, or multi-step reasoning, output only 1.",
50
+ "Otherwise answer the user directly and conversationally, in one or two short sentences.",
51
+ "Never mention these rules or the digits.",
52
+ ].join(" ");
53
+
54
+ interface Trial {
55
+ resolveMs: number | null;
56
+ ttftMs: number | null;
57
+ firstEventType: string | null;
58
+ totalMs: number;
59
+ inputTokens: number | null;
60
+ cacheReadTokens: number | null;
61
+ model: string | null;
62
+ error: string | null;
63
+ }
64
+
65
+ interface VariantSpec {
66
+ name: string;
67
+ callSite: string;
68
+ overrideProfile?: string;
69
+ systemPrompt: () => string;
70
+ tools?: () => ToolDefinition[];
71
+ }
72
+
73
+ async function runTrial(
74
+ provider: Provider,
75
+ spec: VariantSpec,
76
+ resolveMs: number | null,
77
+ ): Promise<Trial> {
78
+ const config: SendMessageConfig = {
79
+ callSite: spec.callSite,
80
+ max_tokens: MAX_TOKENS,
81
+ ...(spec.overrideProfile !== undefined
82
+ ? { overrideProfile: spec.overrideProfile }
83
+ : {}),
84
+ };
85
+ const start = performance.now();
86
+ let ttftMs: number | null = null;
87
+ let firstEventType: string | null = null;
88
+ const onEvent = (event: ProviderEvent): void => {
89
+ if (ttftMs === null) {
90
+ ttftMs = performance.now() - start;
91
+ firstEventType = event.type;
92
+ }
93
+ };
94
+ try {
95
+ const response = await provider.sendMessage([userMessage(UTTERANCE)], {
96
+ systemPrompt: spec.systemPrompt(),
97
+ ...(spec.tools ? { tools: spec.tools() } : {}),
98
+ config,
99
+ onEvent,
100
+ signal: AbortSignal.timeout(CALL_TIMEOUT_MS),
101
+ });
102
+ return {
103
+ resolveMs,
104
+ ttftMs,
105
+ firstEventType,
106
+ totalMs: performance.now() - start,
107
+ inputTokens: response.usage.inputTokens,
108
+ cacheReadTokens: response.usage.cacheReadInputTokens ?? null,
109
+ model: response.model,
110
+ error: null,
111
+ };
112
+ } catch (error) {
113
+ return {
114
+ resolveMs,
115
+ ttftMs,
116
+ firstEventType,
117
+ totalMs: performance.now() - start,
118
+ inputTokens: null,
119
+ cacheReadTokens: null,
120
+ model: null,
121
+ error: error instanceof Error ? error.message : String(error),
122
+ };
123
+ }
124
+ }
125
+
126
+ function fmt(value: number | null, suffix = ""): string {
127
+ return value === null ? "—" : `${Math.round(value)}${suffix}`;
128
+ }
129
+
130
+ async function main(): Promise<void> {
131
+ const args = process.argv.slice(2);
132
+ const trials = Number(args[args.indexOf("--trials") + 1] || 0) || 3;
133
+ const variantFilter =
134
+ args.indexOf("--variants") !== -1
135
+ ? new Set(args[args.indexOf("--variants") + 1]?.split(",") ?? [])
136
+ : null;
137
+
138
+ // Tool init can wander into MCP/plugin registration; a failure there
139
+ // still leaves the core registry populated, which is all the size
140
+ // stand-in needs.
141
+ let toolInitError: string | null = null;
142
+ try {
143
+ await initializeTools();
144
+ } catch (error) {
145
+ toolInitError =
146
+ error instanceof Error ? error.message : String(error);
147
+ }
148
+ // Registry entries are definition-shaped objects (see tool-manifest.ts);
149
+ // getDefinition exists only on some registrations. Either way this
150
+ // payload is a size stand-in, not an executable tool set.
151
+ const toolDefs: ToolDefinition[] = getAllTools()
152
+ .map((tool) => {
153
+ const t = tool as unknown as ToolDefinition & {
154
+ getDefinition?: () => ToolDefinition;
155
+ };
156
+ return typeof t.getDefinition === "function"
157
+ ? t.getDefinition()
158
+ : { name: t.name, description: t.description, input_schema: t.input_schema };
159
+ })
160
+ .filter((def) => Boolean(def.name && def.input_schema));
161
+ const fullPrompt = buildSystemPrompt();
162
+ console.log(
163
+ `system prompt: ${fullPrompt.length} chars (~${Math.round(fullPrompt.length / 4)} tokens); ` +
164
+ `tools: ${toolDefs.length} defs, ${JSON.stringify(toolDefs).length} chars` +
165
+ (toolInitError ? ` (tool init degraded: ${toolInitError})` : ""),
166
+ );
167
+
168
+ const variants: VariantSpec[] = [
169
+ {
170
+ name: "slim-haiku",
171
+ callSite: "voiceFrontDecision",
172
+ systemPrompt: () => SLIM_SYSTEM_PROMPT,
173
+ },
174
+ {
175
+ name: "slim-flash",
176
+ callSite: "inference",
177
+ overrideProfile: "cost-optimized",
178
+ systemPrompt: () => SLIM_SYSTEM_PROMPT,
179
+ },
180
+ {
181
+ name: "full-notools",
182
+ callSite: "inference",
183
+ overrideProfile: "cost-optimized",
184
+ systemPrompt: () => fullPrompt,
185
+ },
186
+ {
187
+ name: "full-flash",
188
+ callSite: "inference",
189
+ overrideProfile: "cost-optimized",
190
+ systemPrompt: () => fullPrompt,
191
+ tools: () => toolDefs,
192
+ },
193
+ {
194
+ name: "full-quality",
195
+ callSite: "inference",
196
+ overrideProfile: "quality-optimized",
197
+ systemPrompt: () => fullPrompt,
198
+ tools: () => toolDefs,
199
+ },
200
+ ];
201
+
202
+ const results: Array<{ variant: string; trial: number } & Trial> = [];
203
+ for (const spec of variants) {
204
+ if (variantFilter && !variantFilter.has(spec.name)) {
205
+ continue;
206
+ }
207
+ const resolveStart = performance.now();
208
+ const provider = await getConfiguredProvider(spec.callSite, {
209
+ ...(spec.overrideProfile !== undefined
210
+ ? { overrideProfile: spec.overrideProfile }
211
+ : {}),
212
+ });
213
+ const resolveMs = performance.now() - resolveStart;
214
+ if (!provider) {
215
+ console.error(
216
+ `${spec.name}: no provider resolved (managed credentials missing? ` +
217
+ `run with the daemon's VELLUM_WORKSPACE_DIR + CES_LOCAL_SOCKET)`,
218
+ );
219
+ continue;
220
+ }
221
+ for (let i = 0; i < trials; i++) {
222
+ const trial = await runTrial(provider, spec, i === 0 ? resolveMs : null);
223
+ results.push({ variant: spec.name, trial: i + 1, ...trial });
224
+ const line =
225
+ `${spec.name.padEnd(14)} #${i + 1} ` +
226
+ `ttft ${fmt(trial.ttftMs, "ms").padStart(8)} ` +
227
+ `total ${fmt(trial.totalMs, "ms").padStart(8)} ` +
228
+ `in ${fmt(trial.inputTokens, " tok").padStart(10)} ` +
229
+ `cacheRead ${fmt(trial.cacheReadTokens).padStart(6)} ` +
230
+ `${trial.model ?? ""}` +
231
+ (trial.error ? ` ERROR ${trial.error}` : "");
232
+ console.log(line);
233
+ }
234
+ }
235
+
236
+ console.log("\nJSON:");
237
+ console.log(JSON.stringify(results, null, 2));
238
+ }
239
+
240
+ await main();
241
+ process.exit(0);
@@ -162,204 +162,198 @@ describe("ConfigWatcher skills watcher reseeding", () => {
162
162
  rmSync(WORKSPACE_DIR, { recursive: true, force: true });
163
163
  });
164
164
 
165
- test("watched skill file changes evict conversations and refresh skill memories", async () => {
166
- watcher.start();
165
+ describe("recursive watcher", () => {
166
+ beforeEach(() => {
167
+ recursiveWatchAvailable = true;
168
+ });
167
169
 
168
- const skillsWatcher = findWatcher(SKILLS_DIR);
169
- expect(skillsWatcher).toBeDefined();
170
- skillsWatcher!.callback("change", "example-skill/SKILL.md");
170
+ test("reloads on SKILL.md changes", async () => {
171
+ watcher.start();
171
172
 
172
- await new Promise((resolve) => setTimeout(resolve, 300));
173
+ const skillsWatcher = findWatcher(SKILLS_DIR);
174
+ expect(skillsWatcher).toBeDefined();
175
+ skillsWatcher!.callback("change", "example-skill/SKILL.md");
173
176
 
174
- expect(evictCalls).toBe(1);
175
- expect(skillsChangedCalls).toBe(1);
176
- });
177
-
178
- test("recursive watcher ignores skipped dependency and staging paths", async () => {
179
- recursiveWatchAvailable = true;
180
-
181
- watcher.start();
182
-
183
- const skillsWatcher = findWatcher(SKILLS_DIR);
184
- expect(skillsWatcher).toBeDefined();
185
- skillsWatcher!.callback(
186
- "change",
187
- "example-skill/node_modules/pkg/index.js",
188
- );
189
- skillsWatcher!.callback(
190
- "change",
191
- ".install-staging/example-skill/SKILL.md",
192
- );
193
-
194
- await new Promise((resolve) => setTimeout(resolve, 300));
195
-
196
- expect(evictCalls).toBe(0);
197
- expect(skillsChangedCalls).toBe(0);
198
-
199
- skillsWatcher!.callback("change", "example-skill/references/foo.md");
200
-
201
- await new Promise((resolve) => setTimeout(resolve, 300));
202
-
203
- expect(evictCalls).toBe(1);
204
- expect(skillsChangedCalls).toBe(1);
205
- });
177
+ await new Promise((resolve) => setTimeout(resolve, 300));
206
178
 
207
- test("recursive watcher reloads skill memories for build output changes", async () => {
208
- recursiveWatchAvailable = true;
179
+ expect(evictCalls).toBe(1);
180
+ expect(skillsChangedCalls).toBe(1);
181
+ });
209
182
 
210
- watcher.start();
183
+ test("reloads on TOOLS.json changes", async () => {
184
+ watcher.start();
211
185
 
212
- const skillsWatcher = findWatcher(SKILLS_DIR);
213
- expect(skillsWatcher).toBeDefined();
214
- skillsWatcher!.callback("change", "example-skill/dist/index.js");
186
+ const skillsWatcher = findWatcher(SKILLS_DIR);
187
+ skillsWatcher!.callback("change", "example-skill/TOOLS.json");
215
188
 
216
- await new Promise((resolve) => setTimeout(resolve, 300));
189
+ await new Promise((resolve) => setTimeout(resolve, 300));
217
190
 
218
- expect(evictCalls).toBe(1);
219
- expect(skillsChangedCalls).toBe(1);
220
- });
221
-
222
- test("coalesces multiple skill file changes into one catalog refresh", async () => {
223
- watcher.start();
224
-
225
- const skillsWatcher = findWatcher(SKILLS_DIR);
226
- expect(skillsWatcher).toBeDefined();
227
- skillsWatcher!.callback("change", "example-skill/SKILL.md");
228
- skillsWatcher!.callback("change", "example-skill/package.json");
229
- skillsWatcher!.callback("change", "other-skill/SKILL.md");
230
-
231
- await new Promise((resolve) => setTimeout(resolve, 300));
232
-
233
- expect(evictCalls).toBe(1);
234
- expect(skillsChangedCalls).toBe(1);
235
- });
236
-
237
- test("fallback watches existing nested skill directories", async () => {
238
- const referencesDir = join(SKILLS_DIR, "example-skill", "references");
239
- mkdirSync(referencesDir, { recursive: true });
240
-
241
- watcher.start();
191
+ expect(evictCalls).toBe(1);
192
+ expect(skillsChangedCalls).toBe(1);
193
+ });
242
194
 
243
- const referencesWatcher = findWatcher(referencesDir);
244
- expect(referencesWatcher).toBeDefined();
245
- referencesWatcher!.callback("change", "notes.md");
195
+ test("ignores non-catalog files (scripts, references, build output)", async () => {
196
+ watcher.start();
246
197
 
247
- await new Promise((resolve) => setTimeout(resolve, 300));
248
-
249
- expect(evictCalls).toBe(1);
250
- expect(skillsChangedCalls).toBe(1);
251
- });
198
+ const skillsWatcher = findWatcher(SKILLS_DIR);
199
+ skillsWatcher!.callback("change", "example-skill/references/foo.md");
200
+ skillsWatcher!.callback("change", "example-skill/dist/index.js");
201
+ skillsWatcher!.callback("change", "example-skill/package.json");
202
+ skillsWatcher!.callback("change", "example-skill/scripts/run.py");
252
203
 
253
- test("fallback skips dependency and staging directories", async () => {
254
- const skillDir = join(SKILLS_DIR, "example-skill");
255
- const nodeModulesDir = join(skillDir, "node_modules");
256
- const dependencyDir = join(nodeModulesDir, "pkg");
257
- const stagingDir = join(SKILLS_DIR, ".install-staging");
258
- const stagedSkillDir = join(stagingDir, "example-skill");
259
- const referencesDir = join(skillDir, "references");
260
- mkdirSync(dependencyDir, { recursive: true });
261
- mkdirSync(stagedSkillDir, { recursive: true });
262
- mkdirSync(referencesDir, { recursive: true });
204
+ await new Promise((resolve) => setTimeout(resolve, 300));
263
205
 
264
- watcher.start();
206
+ expect(evictCalls).toBe(0);
207
+ expect(skillsChangedCalls).toBe(0);
208
+ });
265
209
 
266
- expect(findWatcher(nodeModulesDir)).toBeUndefined();
267
- expect(findWatcher(dependencyDir)).toBeUndefined();
268
- expect(findWatcher(stagingDir)).toBeUndefined();
269
- expect(findWatcher(stagedSkillDir)).toBeUndefined();
210
+ test("ignores catalog files under skipped dependency and staging paths", async () => {
211
+ watcher.start();
270
212
 
271
- const skillsWatcher = findWatcher(SKILLS_DIR);
272
- const skillWatcher = findWatcher(skillDir);
273
- expect(skillsWatcher).toBeDefined();
274
- expect(skillWatcher).toBeDefined();
213
+ const skillsWatcher = findWatcher(SKILLS_DIR);
214
+ skillsWatcher!.callback(
215
+ "change",
216
+ "example-skill/node_modules/pkg/SKILL.md",
217
+ );
218
+ skillsWatcher!.callback(
219
+ "change",
220
+ ".install-staging/example-skill/SKILL.md",
221
+ );
275
222
 
276
- skillsWatcher!.callback("rename", ".install-staging");
277
- skillWatcher!.callback("rename", "node_modules");
278
- skillWatcher!.callback("change", "node_modules/pkg/index.js");
223
+ await new Promise((resolve) => setTimeout(resolve, 300));
279
224
 
280
- await new Promise((resolve) => setTimeout(resolve, 300));
225
+ expect(evictCalls).toBe(0);
226
+ expect(skillsChangedCalls).toBe(0);
227
+ });
281
228
 
282
- expect(evictCalls).toBe(0);
283
- expect(skillsChangedCalls).toBe(0);
229
+ test("coalesces multiple catalog changes into one reload", async () => {
230
+ watcher.start();
284
231
 
285
- const referencesWatcher = findWatcher(referencesDir);
286
- expect(referencesWatcher).toBeDefined();
287
- referencesWatcher!.callback("change", "foo.md");
232
+ const skillsWatcher = findWatcher(SKILLS_DIR);
233
+ skillsWatcher!.callback("change", "example-skill/SKILL.md");
234
+ skillsWatcher!.callback("change", "example-skill/package.json");
235
+ skillsWatcher!.callback("change", "example-skill/TOOLS.json");
236
+ skillsWatcher!.callback("change", "other-skill/SKILL.md");
288
237
 
289
- await new Promise((resolve) => setTimeout(resolve, 300));
238
+ await new Promise((resolve) => setTimeout(resolve, 300));
290
239
 
291
- expect(evictCalls).toBe(1);
292
- expect(skillsChangedCalls).toBe(1);
240
+ expect(evictCalls).toBe(1);
241
+ expect(skillsChangedCalls).toBe(1);
242
+ });
293
243
  });
294
244
 
295
- test("fallback watches skill build output directories", async () => {
296
- const distDir = join(SKILLS_DIR, "example-skill", "dist");
297
- const buildDir = join(SKILLS_DIR, "example-skill", "build");
298
- mkdirSync(distDir, { recursive: true });
299
- mkdirSync(buildDir, { recursive: true });
300
-
301
- watcher.start();
302
-
303
- const distWatcher = findWatcher(distDir);
304
- const buildWatcher = findWatcher(buildDir);
305
- expect(distWatcher).toBeDefined();
306
- expect(buildWatcher).toBeDefined();
307
-
308
- distWatcher!.callback("change", "index.js");
309
-
310
- await new Promise((resolve) => setTimeout(resolve, 300));
311
-
312
- expect(evictCalls).toBe(1);
313
- expect(skillsChangedCalls).toBe(1);
314
-
315
- buildWatcher!.callback("change", "tool.js");
316
-
317
- await new Promise((resolve) => setTimeout(resolve, 300));
318
-
319
- expect(evictCalls).toBe(2);
320
- expect(skillsChangedCalls).toBe(2);
321
- });
322
-
323
- test("fallback adds watchers for new nested skill directories without duplicates", () => {
324
- const skillDir = join(SKILLS_DIR, "example-skill");
325
- const toolsDir = join(skillDir, "tools");
326
- const generatedDir = join(toolsDir, "generated");
327
- mkdirSync(skillDir, { recursive: true });
328
-
329
- watcher.start();
330
-
331
- const skillWatcher = findWatcher(skillDir);
332
- expect(skillWatcher).toBeDefined();
333
-
334
- mkdirSync(generatedDir, { recursive: true });
335
- skillWatcher!.callback("rename", "tools");
336
- skillWatcher!.callback("rename", "tools");
337
-
338
- expect(findWatcher(toolsDir)).toBeDefined();
339
- expect(findWatcher(generatedDir)).toBeDefined();
340
- expect(capturedWatcherCount(toolsDir)).toBe(1);
341
- expect(capturedWatcherCount(generatedDir)).toBe(1);
342
- });
343
-
344
- test("fallback closes stale nested watchers when directories are removed", () => {
345
- const skillDir = join(SKILLS_DIR, "example-skill");
346
- const referencesDir = join(skillDir, "references");
347
- const deepDir = join(referencesDir, "deep");
348
- mkdirSync(deepDir, { recursive: true });
349
-
350
- watcher.start();
351
-
352
- expect(findWatcher(referencesDir)).toBeDefined();
353
- expect(findWatcher(deepDir)).toBeDefined();
354
-
355
- rmSync(referencesDir, { recursive: true, force: true });
356
- const skillWatcher = findWatcher(skillDir);
357
- expect(skillWatcher).toBeDefined();
358
- skillWatcher!.callback("rename", "references");
245
+ describe("per-skill-directory fallback", () => {
246
+ test("watches the root and each immediate skill directory, not nested subdirectories", () => {
247
+ const skillDir = join(SKILLS_DIR, "example-skill");
248
+ mkdirSync(join(skillDir, "references"), { recursive: true });
249
+ mkdirSync(join(skillDir, "dist"), { recursive: true });
359
250
 
360
- expect(findWatcher(referencesDir)).toBeUndefined();
361
- expect(findWatcher(deepDir)).toBeUndefined();
362
- expect(findCapturedWatcher(referencesDir)?.closed).toBe(true);
363
- expect(findCapturedWatcher(deepDir)?.closed).toBe(true);
251
+ watcher.start();
252
+
253
+ expect(findWatcher(SKILLS_DIR)).toBeDefined();
254
+ expect(findWatcher(skillDir)).toBeDefined();
255
+ expect(findWatcher(join(skillDir, "references"))).toBeUndefined();
256
+ expect(findWatcher(join(skillDir, "dist"))).toBeUndefined();
257
+ });
258
+
259
+ test("does not watch dependency or staging directories", () => {
260
+ const skillDir = join(SKILLS_DIR, "example-skill");
261
+ mkdirSync(join(skillDir, "node_modules", "pkg"), { recursive: true });
262
+ mkdirSync(join(SKILLS_DIR, ".install-staging", "staged"), {
263
+ recursive: true,
264
+ });
265
+
266
+ watcher.start();
267
+
268
+ expect(findWatcher(join(skillDir, "node_modules"))).toBeUndefined();
269
+ expect(findWatcher(join(SKILLS_DIR, ".install-staging"))).toBeUndefined();
270
+ expect(findWatcher(skillDir)).toBeDefined();
271
+ });
272
+
273
+ test("reloads on SKILL.md / TOOLS.json edits within a skill directory", async () => {
274
+ const skillDir = join(SKILLS_DIR, "example-skill");
275
+ mkdirSync(skillDir, { recursive: true });
276
+
277
+ watcher.start();
278
+ const skillWatcher = findWatcher(skillDir);
279
+ expect(skillWatcher).toBeDefined();
280
+
281
+ skillWatcher!.callback("change", "SKILL.md");
282
+ await new Promise((resolve) => setTimeout(resolve, 300));
283
+ expect(evictCalls).toBe(1);
284
+ expect(skillsChangedCalls).toBe(1);
285
+
286
+ skillWatcher!.callback("change", "TOOLS.json");
287
+ await new Promise((resolve) => setTimeout(resolve, 300));
288
+ expect(evictCalls).toBe(2);
289
+ expect(skillsChangedCalls).toBe(2);
290
+ });
291
+
292
+ test("ignores non-catalog file edits within a skill directory", async () => {
293
+ const skillDir = join(SKILLS_DIR, "example-skill");
294
+ mkdirSync(skillDir, { recursive: true });
295
+
296
+ watcher.start();
297
+ const skillWatcher = findWatcher(skillDir);
298
+
299
+ skillWatcher!.callback("change", "README.md");
300
+ skillWatcher!.callback("change", "package.json");
301
+ await new Promise((resolve) => setTimeout(resolve, 300));
302
+
303
+ expect(evictCalls).toBe(0);
304
+ expect(skillsChangedCalls).toBe(0);
305
+ });
306
+
307
+ test("watches and reloads when a skill is installed", async () => {
308
+ watcher.start();
309
+ const rootWatcher = findWatcher(SKILLS_DIR);
310
+ expect(rootWatcher).toBeDefined();
311
+
312
+ const newSkillDir = join(SKILLS_DIR, "new-skill");
313
+ mkdirSync(newSkillDir, { recursive: true });
314
+ rootWatcher!.callback("rename", "new-skill");
315
+
316
+ await new Promise((resolve) => setTimeout(resolve, 300));
317
+
318
+ expect(findWatcher(newSkillDir)).toBeDefined();
319
+ expect(evictCalls).toBe(1);
320
+ expect(skillsChangedCalls).toBe(1);
321
+ });
322
+
323
+ test("closes the watcher and reloads when a skill is removed", async () => {
324
+ const skillDir = join(SKILLS_DIR, "example-skill");
325
+ mkdirSync(skillDir, { recursive: true });
326
+
327
+ watcher.start();
328
+ expect(findWatcher(skillDir)).toBeDefined();
329
+
330
+ rmSync(skillDir, { recursive: true, force: true });
331
+ const rootWatcher = findWatcher(SKILLS_DIR);
332
+ rootWatcher!.callback("rename", "example-skill");
333
+
334
+ await new Promise((resolve) => setTimeout(resolve, 300));
335
+
336
+ expect(findWatcher(skillDir)).toBeUndefined();
337
+ expect(findCapturedWatcher(skillDir)?.closed).toBe(true);
338
+ expect(evictCalls).toBe(1);
339
+ expect(skillsChangedCalls).toBe(1);
340
+ });
341
+
342
+ test("does not duplicate a watcher or reload when the root changes but the skill set does not", async () => {
343
+ const skillDir = join(SKILLS_DIR, "example-skill");
344
+ mkdirSync(skillDir, { recursive: true });
345
+
346
+ watcher.start();
347
+ expect(capturedWatcherCount(skillDir)).toBe(1);
348
+
349
+ // A stray file event at the root: no skill directory added or removed.
350
+ const rootWatcher = findWatcher(SKILLS_DIR);
351
+ rootWatcher!.callback("change", "README.md");
352
+ await new Promise((resolve) => setTimeout(resolve, 300));
353
+
354
+ expect(capturedWatcherCount(skillDir)).toBe(1);
355
+ expect(evictCalls).toBe(0);
356
+ expect(skillsChangedCalls).toBe(0);
357
+ });
364
358
  });
365
359
  });
@@ -1897,6 +1897,53 @@ describe("queryUnreportedUsageEvents", () => {
1897
1897
  expect(events[0].parentTurnIndex).toBe(1);
1898
1898
  });
1899
1899
 
1900
+ test("fork parentTurnIndex anchors on the fork boundary message, not fork creation time", () => {
1901
+ const db = getDb();
1902
+ // Source conversation with turns at t=1000 and t=3000. The fork
1903
+ // branches from the FIRST turn (boundary message s1) but is created
1904
+ // at t=5000, after turn 2 exists — attribution must report turn 1.
1905
+ db.run(
1906
+ `INSERT INTO conversations (id, conversation_type, created_at, updated_at) VALUES ('source-2', 'standard', 500, 500)`,
1907
+ );
1908
+ db.run(
1909
+ `INSERT INTO messages (id, conversation_id, role, content, created_at) VALUES ('s2a', 'source-2', 'user', 'first', 1000)`,
1910
+ );
1911
+ db.run(
1912
+ `INSERT INTO messages (id, conversation_id, role, content, created_at) VALUES ('s2b', 'source-2', 'user', 'second', 3000)`,
1913
+ );
1914
+ db.run(
1915
+ `INSERT INTO conversations (id, conversation_type, created_at, updated_at, fork_parent_conversation_id, fork_parent_message_id) VALUES ('retro-2', 'background', 5000, 5000, 'source-2', 's2a')`,
1916
+ );
1917
+ insertEventAt(6000, { conversationId: "retro-2" });
1918
+
1919
+ const events = queryUnreportedUsageEvents(0, undefined, 100);
1920
+ expect(events).toHaveLength(1);
1921
+ expect(events[0].parentConversationId).toBe("source-2");
1922
+ expect(events[0].parentTurnIndex).toBe(1);
1923
+ });
1924
+
1925
+ test("user-initiated forks (standard type) do not inherit fork parent attribution", () => {
1926
+ const db = getDb();
1927
+ // A user forks a conversation: the fork stamps
1928
+ // fork_parent_conversation_id but is a first-class standard
1929
+ // conversation — its usage must not fold into the source turn.
1930
+ db.run(
1931
+ `INSERT INTO conversations (id, conversation_type, created_at, updated_at) VALUES ('source-3', 'standard', 500, 500)`,
1932
+ );
1933
+ db.run(
1934
+ `INSERT INTO messages (id, conversation_id, role, content, created_at) VALUES ('s3', 'source-3', 'user', 'hello', 1000)`,
1935
+ );
1936
+ db.run(
1937
+ `INSERT INTO conversations (id, conversation_type, created_at, updated_at, fork_parent_conversation_id, fork_parent_message_id) VALUES ('user-fork-1', 'standard', 2000, 2000, 'source-3', 's3')`,
1938
+ );
1939
+ insertEventAt(3000, { conversationId: "user-fork-1" });
1940
+
1941
+ const events = queryUnreportedUsageEvents(0, undefined, 100);
1942
+ expect(events).toHaveLength(1);
1943
+ expect(events[0].parentConversationId).toBeNull();
1944
+ expect(events[0].parentTurnIndex).toBeNull();
1945
+ });
1946
+
1900
1947
  test("parent fields are null for parentless conversations and no-conversation events", () => {
1901
1948
  const db = getDb();
1902
1949
  const now = Date.now();