@vellumai/assistant 0.8.11-dev.202606120012.5656fc7 → 0.8.11-dev.202606120321.552e02e

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 (27) hide show
  1. package/package.json +1 -1
  2. package/src/__tests__/conversation-history-web-search.test.ts +1 -0
  3. package/src/__tests__/tool-result-spool.test.ts +337 -0
  4. package/src/agent/loop.ts +59 -2
  5. package/src/cli/commands/plugins.ts +90 -0
  6. package/src/cli/lib/__tests__/upgrade-plugin.test.ts +300 -0
  7. package/src/cli/lib/upgrade-plugin.ts +219 -0
  8. package/src/config/schemas/__tests__/memory-v3.test.ts +10 -0
  9. package/src/config/schemas/memory-v3.ts +92 -0
  10. package/src/context/post-turn-tool-result-truncation.ts +32 -18
  11. package/src/context/tool-result-spool.ts +104 -0
  12. package/src/daemon/conversation.ts +9 -0
  13. package/src/plugins/defaults/memory-v3-shadow/__tests__/carry-integration.test.ts +1 -0
  14. package/src/plugins/defaults/memory-v3-shadow/__tests__/fresh-set.test.ts +52 -0
  15. package/src/plugins/defaults/memory-v3-shadow/__tests__/injection.test.ts +1 -0
  16. package/src/plugins/defaults/memory-v3-shadow/__tests__/live-integration.test.ts +1 -0
  17. package/src/plugins/defaults/memory-v3-shadow/__tests__/orchestrate.test.ts +132 -1
  18. package/src/plugins/defaults/memory-v3-shadow/__tests__/selection-log-store.test.ts +6 -0
  19. package/src/plugins/defaults/memory-v3-shadow/__tests__/shadow-integration.test.ts +4 -0
  20. package/src/plugins/defaults/memory-v3-shadow/__tests__/shadow-plugin.test.ts +68 -4
  21. package/src/plugins/defaults/memory-v3-shadow/fresh-set.ts +59 -0
  22. package/src/plugins/defaults/memory-v3-shadow/injector.ts +4 -2
  23. package/src/plugins/defaults/memory-v3-shadow/learned-edges.test.ts +169 -0
  24. package/src/plugins/defaults/memory-v3-shadow/learned-edges.ts +178 -0
  25. package/src/plugins/defaults/memory-v3-shadow/orchestrate.ts +114 -26
  26. package/src/plugins/defaults/memory-v3-shadow/shadow-plugin.ts +104 -16
  27. package/src/plugins/defaults/memory-v3-shadow/types.ts +24 -6
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.8.11-dev.202606120012.5656fc7",
3
+ "version": "0.8.11-dev.202606120321.552e02e",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -755,6 +755,7 @@ describe("web_search_tool_result structural guard", () => {
755
755
  // (array of web_search_result objects) and is not truncated this way.
756
756
  "context/tool-result-truncation.ts",
757
757
  "context/post-turn-tool-result-truncation.ts",
758
+ "context/tool-result-spool.ts",
758
759
 
759
760
  // Anthropic provider type guards define API-specific discriminants.
760
761
  // It has a separate isWebSearchToolResultBlock for the other type.
@@ -0,0 +1,337 @@
1
+ import {
2
+ existsSync,
3
+ mkdtempSync,
4
+ readFileSync,
5
+ rmSync,
6
+ writeFileSync,
7
+ } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
11
+
12
+ import type { AgentEvent } from "../agent/loop.js";
13
+ import { AgentLoop } from "../agent/loop.js";
14
+ import {
15
+ getToolResultFilePath,
16
+ postTurnTruncateToolResults,
17
+ THRESHOLD_CHARS,
18
+ TOOL_RESULT_DIR,
19
+ TRUNCATION_MARKER,
20
+ } from "../context/post-turn-tool-result-truncation.js";
21
+ import { spoolAndStubOversizedToolResults } from "../context/tool-result-spool.js";
22
+ import { resetPluginRegistryAndRegisterDefaults } from "../plugins/defaults/index.js";
23
+ import type {
24
+ ContentBlock,
25
+ Message,
26
+ ToolDefinition,
27
+ } from "../providers/types.js";
28
+ import {
29
+ createMockProvider,
30
+ textResponse,
31
+ toolUseResponse,
32
+ } from "./helpers/mock-provider.js";
33
+
34
+ function makeToolResult(
35
+ content: string,
36
+ toolUseId = "tool_use_1",
37
+ is_error = false,
38
+ ): ContentBlock {
39
+ return {
40
+ type: "tool_result" as const,
41
+ tool_use_id: toolUseId,
42
+ content,
43
+ ...(is_error ? { is_error: true } : {}),
44
+ };
45
+ }
46
+
47
+ const LONG = "x".repeat(THRESHOLD_CHARS + 100);
48
+ const SHORT = "y".repeat(100);
49
+
50
+ describe("spoolAndStubOversizedToolResults", () => {
51
+ let convDir: string;
52
+ const noName = () => undefined;
53
+
54
+ beforeEach(() => {
55
+ convDir = mkdtempSync(join(tmpdir(), "tool-result-spool-"));
56
+ });
57
+
58
+ afterEach(() => {
59
+ rmSync(convDir, { recursive: true, force: true });
60
+ });
61
+
62
+ test("spools an oversized result and swaps in the stub", () => {
63
+ const blocks = [makeToolResult(LONG, "tu_big")];
64
+
65
+ const count = spoolAndStubOversizedToolResults(blocks, {
66
+ conversationDir: convDir,
67
+ toolNameById: noName,
68
+ });
69
+
70
+ expect(count).toBe(1);
71
+ const filePath = getToolResultFilePath(convDir, "tu_big");
72
+ expect(existsSync(filePath)).toBe(true);
73
+ expect(readFileSync(filePath, "utf-8")).toBe(LONG);
74
+ const stubbed = blocks[0] as { content: string };
75
+ expect(stubbed.content).toContain(TRUNCATION_MARKER);
76
+ expect(stubbed.content).toContain(filePath);
77
+ expect(stubbed.content.length).toBeLessThan(LONG.length);
78
+ });
79
+
80
+ test("stub is byte-identical to the post-turn truncation stub", () => {
81
+ const blocks = [makeToolResult(LONG, "tu_big")];
82
+ spoolAndStubOversizedToolResults(blocks, {
83
+ conversationDir: convDir,
84
+ toolNameById: noName,
85
+ });
86
+
87
+ const { messages: postTurn } = postTurnTruncateToolResults(
88
+ [{ role: "user", content: [makeToolResult(LONG, "tu_big")] }],
89
+ { conversationDir: convDir },
90
+ );
91
+
92
+ expect((blocks[0] as { content: string }).content).toBe(
93
+ (postTurn[0].content[0] as { content: string }).content,
94
+ );
95
+ });
96
+
97
+ test("post-turn pass is a no-op on result-time stubs", () => {
98
+ const blocks = [makeToolResult(LONG, "tu_big")];
99
+ spoolAndStubOversizedToolResults(blocks, {
100
+ conversationDir: convDir,
101
+ toolNameById: noName,
102
+ });
103
+
104
+ const history: Message[] = [{ role: "user", content: [...blocks] }];
105
+ const { messages, truncatedCount } = postTurnTruncateToolResults(history, {
106
+ conversationDir: convDir,
107
+ });
108
+
109
+ expect(truncatedCount).toBe(0);
110
+ expect(messages).toBe(history);
111
+ });
112
+
113
+ test("skips below-threshold, error, exempt, file_read, marked, and ax-tree results", () => {
114
+ const blocks = [
115
+ makeToolResult(SHORT, "tu_short"),
116
+ makeToolResult(LONG, "tu_err", true),
117
+ makeToolResult(LONG, "tu_skill"),
118
+ makeToolResult(LONG, "tu_read"),
119
+ makeToolResult(`${LONG}${TRUNCATION_MARKER}`, "tu_marked"),
120
+ makeToolResult(`<ax-tree>${LONG}</ax-tree>`, "tu_ax"),
121
+ { type: "text" as const, text: LONG },
122
+ ];
123
+ const originals = blocks.map((b) => b);
124
+
125
+ const count = spoolAndStubOversizedToolResults(blocks, {
126
+ conversationDir: convDir,
127
+ toolNameById: (id) => {
128
+ if (id === "tu_skill") return "skill_load";
129
+ if (id === "tu_read") return "file_read";
130
+ return undefined;
131
+ },
132
+ });
133
+
134
+ expect(count).toBe(0);
135
+ expect(blocks).toEqual(originals);
136
+ expect(existsSync(join(convDir, TOOL_RESULT_DIR))).toBe(false);
137
+ });
138
+
139
+ test("spools each eligible block in a mixed batch", () => {
140
+ const blocks = [
141
+ makeToolResult(LONG, "tu_a"),
142
+ makeToolResult(SHORT, "tu_b"),
143
+ makeToolResult(LONG, "tu_c"),
144
+ ];
145
+
146
+ const count = spoolAndStubOversizedToolResults(blocks, {
147
+ conversationDir: convDir,
148
+ toolNameById: noName,
149
+ });
150
+
151
+ expect(count).toBe(2);
152
+ expect(existsSync(getToolResultFilePath(convDir, "tu_a"))).toBe(true);
153
+ expect(existsSync(getToolResultFilePath(convDir, "tu_b"))).toBe(false);
154
+ expect(existsSync(getToolResultFilePath(convDir, "tu_c"))).toBe(true);
155
+ expect((blocks[0] as { content: string }).content).toContain(
156
+ TRUNCATION_MARKER,
157
+ );
158
+ expect((blocks[1] as { content: string }).content).toBe(SHORT);
159
+ expect((blocks[2] as { content: string }).content).toContain(
160
+ TRUNCATION_MARKER,
161
+ );
162
+ });
163
+
164
+ test("keeps full content when the spool directory cannot be created", () => {
165
+ // A regular file at the conversation-dir path makes mkdir throw, so no
166
+ // stub can be written; the block must keep its full content (a stub must
167
+ // never exist without its file on disk).
168
+ const fileAsDir = join(convDir, "not-a-dir");
169
+ writeFileSync(fileAsDir, "occupied", "utf-8");
170
+ const blocks = [makeToolResult(LONG, "tu_big")];
171
+
172
+ expect(() =>
173
+ spoolAndStubOversizedToolResults(blocks, {
174
+ conversationDir: fileAsDir,
175
+ toolNameById: noName,
176
+ }),
177
+ ).toThrow();
178
+ expect((blocks[0] as { content: string }).content).toBe(LONG);
179
+ });
180
+ });
181
+
182
+ describe("AgentLoop result-time spooling", () => {
183
+ let convDir: string;
184
+
185
+ const dummyTools: ToolDefinition[] = [
186
+ {
187
+ name: "fetch_transcript",
188
+ description: "Fetch a transcript",
189
+ input_schema: { type: "object", properties: {} },
190
+ },
191
+ ];
192
+
193
+ const userMessage: Message = {
194
+ role: "user",
195
+ content: [{ type: "text", text: "Import the transcripts" }],
196
+ };
197
+
198
+ beforeEach(() => {
199
+ resetPluginRegistryAndRegisterDefaults();
200
+ convDir = mkdtempSync(join(tmpdir(), "tool-result-spool-loop-"));
201
+ });
202
+
203
+ afterEach(() => {
204
+ rmSync(convDir, { recursive: true, force: true });
205
+ });
206
+
207
+ test("oversized result enters history as the stub; full content is never sent to the provider", async () => {
208
+ const { provider, calls } = createMockProvider([
209
+ toolUseResponse("tu_1", "fetch_transcript", {}),
210
+ textResponse("Done."),
211
+ ]);
212
+ const loop = new AgentLoop({
213
+ provider,
214
+ systemPrompt: "system",
215
+ conversationId: "test-conversation",
216
+ tools: dummyTools,
217
+ toolExecutor: async () => ({ content: LONG, isError: false }),
218
+ resolveConversationDir: () => convDir,
219
+ });
220
+
221
+ const events: AgentEvent[] = [];
222
+ const { history } = await loop.run({
223
+ requestId: "test-request",
224
+ messages: [userMessage],
225
+ onEvent: (e) => {
226
+ events.push(e);
227
+ },
228
+ trust: { sourceChannel: "vellum", trustClass: "unknown" },
229
+ });
230
+
231
+ const filePath = getToolResultFilePath(convDir, "tu_1");
232
+ expect(readFileSync(filePath, "utf-8")).toBe(LONG);
233
+
234
+ // The second provider call carries the stub, not the full content.
235
+ const sentResult = calls[1].messages[2].content[0] as { content: string };
236
+ expect(sentResult.content).toContain(TRUNCATION_MARKER);
237
+ expect(sentResult.content).toContain(filePath);
238
+ expect(JSON.stringify(calls.map((c) => c.messages))).not.toContain(LONG);
239
+
240
+ // Durable history and the emitted tool_result event match what was sent.
241
+ const historyResult = history[2].content[0] as { content: string };
242
+ expect(historyResult.content).toBe(sentResult.content);
243
+ const resultEvent = events.find((e) => e.type === "tool_result") as {
244
+ content: string;
245
+ };
246
+ expect(resultEvent.content).toBe(sentResult.content);
247
+ });
248
+
249
+ test("outbound payloads stay append-only across calls (prompt-cache prefix invariant)", async () => {
250
+ const { provider, calls } = createMockProvider([
251
+ toolUseResponse("tu_1", "fetch_transcript", {}),
252
+ toolUseResponse("tu_2", "fetch_transcript", {}),
253
+ textResponse("Done."),
254
+ ]);
255
+ const loop = new AgentLoop({
256
+ provider,
257
+ systemPrompt: "system",
258
+ conversationId: "test-conversation",
259
+ tools: dummyTools,
260
+ toolExecutor: async () => ({ content: LONG, isError: false }),
261
+ resolveConversationDir: () => convDir,
262
+ });
263
+
264
+ await loop.run({
265
+ requestId: "test-request",
266
+ messages: [userMessage],
267
+ onEvent: () => {},
268
+ trust: { sourceChannel: "vellum", trustClass: "unknown" },
269
+ });
270
+
271
+ expect(calls).toHaveLength(3);
272
+ // Each call's payload extends the previous call's payload without
273
+ // rewriting it — the property that keeps the provider's prompt-cache
274
+ // prefix valid across the turn's iterations.
275
+ for (let i = 1; i < calls.length; i++) {
276
+ expect(calls[i].messages.slice(0, calls[i - 1].messages.length)).toEqual(
277
+ calls[i - 1].messages,
278
+ );
279
+ }
280
+ });
281
+
282
+ test("spools the raw output even when it exceeds the post-tool-use truncation budget", async () => {
283
+ // maxInputTokens of 10k gives the default truncate plugin a 12k-char
284
+ // budget (0.3 share × 4 chars/token). The spool must run before that
285
+ // hook, so the file holds all 20k chars of raw output rather than the
286
+ // hook's tail-dropped copy — otherwise the omitted tail is unrecoverable.
287
+ const HUGE = "z".repeat(20_000);
288
+ const { provider } = createMockProvider([
289
+ toolUseResponse("tu_1", "fetch_transcript", {}),
290
+ textResponse("Done."),
291
+ ]);
292
+ const loop = new AgentLoop({
293
+ provider,
294
+ systemPrompt: "system",
295
+ conversationId: "test-conversation",
296
+ config: { maxInputTokens: 10_000 },
297
+ tools: dummyTools,
298
+ toolExecutor: async () => ({ content: HUGE, isError: false }),
299
+ resolveConversationDir: () => convDir,
300
+ });
301
+
302
+ await loop.run({
303
+ requestId: "test-request",
304
+ messages: [userMessage],
305
+ onEvent: () => {},
306
+ trust: { sourceChannel: "vellum", trustClass: "unknown" },
307
+ });
308
+
309
+ const filePath = getToolResultFilePath(convDir, "tu_1");
310
+ expect(readFileSync(filePath, "utf-8")).toBe(HUGE);
311
+ });
312
+
313
+ test("without resolveConversationDir the full content is sent and post-turn handles it", async () => {
314
+ const { provider, calls } = createMockProvider([
315
+ toolUseResponse("tu_1", "fetch_transcript", {}),
316
+ textResponse("Done."),
317
+ ]);
318
+ const loop = new AgentLoop({
319
+ provider,
320
+ systemPrompt: "system",
321
+ conversationId: "test-conversation",
322
+ tools: dummyTools,
323
+ toolExecutor: async () => ({ content: LONG, isError: false }),
324
+ });
325
+
326
+ await loop.run({
327
+ requestId: "test-request",
328
+ messages: [userMessage],
329
+ onEvent: () => {},
330
+ trust: { sourceChannel: "vellum", trustClass: "unknown" },
331
+ });
332
+
333
+ const sentResult = calls[1].messages[2].content[0] as { content: string };
334
+ expect(sentResult.content).toBe(LONG);
335
+ expect(existsSync(join(convDir, TOOL_RESULT_DIR))).toBe(false);
336
+ });
337
+ });
package/src/agent/loop.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  estimateToolsTokens,
12
12
  getCalibrationProviderKey,
13
13
  } from "../context/token-estimator.js";
14
+ import { spoolAndStubOversizedToolResults } from "../context/tool-result-spool.js";
14
15
  import type { ToolActivityMetadata } from "../daemon/message-types/web-activity.js";
15
16
  import { parseActualTokensFromError } from "../daemon/parse-actual-tokens-from-error.js";
16
17
  import type { TrustContext } from "../daemon/trust-context.js";
@@ -595,6 +596,16 @@ export interface AgentLoopConstructorOptions {
595
596
  * post-compaction re-injection resolve the live conversation through.
596
597
  */
597
598
  conversationId: string;
599
+ /**
600
+ * Resolve the conversation's on-disk directory, used to spool oversized
601
+ * tool results to `.tool-results/` and swap the inline copy for the
602
+ * post-turn pass's stub at result time — before the result joins history,
603
+ * so the provider-bound prefix stays append-only for prompt caching.
604
+ * Returns `null` while the directory cannot be resolved (e.g. the
605
+ * conversation row is not yet persisted); the loop then skips the
606
+ * result-time pass and the post-turn truncation covers the turn instead.
607
+ */
608
+ resolveConversationDir?: () => string | null;
598
609
  }
599
610
 
600
611
  export class AgentLoop {
@@ -616,6 +627,9 @@ export class AgentLoop {
616
627
  */
617
628
  private readonly conversationId: string;
618
629
 
630
+ /** See {@link AgentLoopConstructorOptions.resolveConversationDir}. */
631
+ private readonly resolveConversationDir: (() => string | null) | null;
632
+
619
633
  /**
620
634
  * Loop-held compaction circuit breaker. The loop has a 1:1 lifetime with its
621
635
  * conversation, so it is the source of truth for the cross-turn failure
@@ -635,6 +649,7 @@ export class AgentLoop {
635
649
  resolveTools,
636
650
  resolveSystemPrompt,
637
651
  conversationId,
652
+ resolveConversationDir,
638
653
  } = options;
639
654
  this.provider = provider;
640
655
  this.systemPrompt = systemPrompt;
@@ -644,6 +659,7 @@ export class AgentLoop {
644
659
  this.resolveSystemPrompt = resolveSystemPrompt ?? null;
645
660
  this.toolExecutor = toolExecutor ?? null;
646
661
  this.conversationId = conversationId;
662
+ this.resolveConversationDir = resolveConversationDir ?? null;
647
663
  this.compactionCircuit = new CompactionCircuit(this.conversationId);
648
664
  }
649
665
 
@@ -885,6 +901,19 @@ export class AgentLoop {
885
901
  let overflowAutoCompressApplied = false;
886
902
  const rlog = log.child({ requestId });
887
903
 
904
+ // Conversation directory for the result-time tool-result spool/stub pass.
905
+ // Resolved once per run; `null` disables the pass for this run and the
906
+ // post-turn truncation covers the turn instead.
907
+ let conversationDir: string | null = null;
908
+ try {
909
+ conversationDir = this.resolveConversationDir?.() ?? null;
910
+ } catch (err) {
911
+ rlog.warn(
912
+ { err },
913
+ "Resolving conversation dir for tool-result spooling failed (non-fatal)",
914
+ );
915
+ }
916
+
888
917
  // Resolve the inference-profile override that applies right now. The
889
918
  // optional resolver lets a turn observe a confirmed mid-turn profile switch
890
919
  // before the next model call; absent a resolver the turn-start value holds.
@@ -1723,11 +1752,39 @@ export class AgentLoop {
1723
1752
  }),
1724
1753
  );
1725
1754
 
1755
+ // Spool oversized results to `.tool-results/` and swap the inline
1756
+ // copy for the post-turn pass's stub now — on the raw blocks, before
1757
+ // the post-tool-use hooks, event emission, and history append. Running
1758
+ // ahead of the hooks means the spooled file holds the tool's full
1759
+ // output rather than the truncate plugin's tail-dropped copy, and the
1760
+ // hooks then see the stub. Stubbing before the first send keeps the
1761
+ // provider-bound history strictly append-only (rewriting an earlier
1762
+ // message between calls would invalidate the prompt-cache prefix on
1763
+ // every iteration).
1764
+ if (conversationDir) {
1765
+ const toolNameByUseId = new Map(
1766
+ toolUseBlocks.map((tu) => [tu.id, tu.name]),
1767
+ );
1768
+ try {
1769
+ spoolAndStubOversizedToolResults(rawResultBlocks, {
1770
+ conversationDir,
1771
+ toolNameById: (id) => toolNameByUseId.get(id),
1772
+ });
1773
+ } catch (err) {
1774
+ rlog.warn(
1775
+ { err, turn: toolUseTurns },
1776
+ "Spooling oversized tool results to disk failed (non-fatal)",
1777
+ );
1778
+ }
1779
+ }
1780
+
1726
1781
  // Run the `post-tool-use` hook once per tool result, after the tool
1727
1782
  // returns and before the result joins the provider-bound history.
1728
1783
  // The default tool-result-truncate plugin tail-drops oversized output
1729
- // to fit the context window; user hooks can swap in a smarter strategy
1730
- // (e.g. a summariser) or observe results for side effects.
1784
+ // to fit the context window (spool-stubbed results are already tiny;
1785
+ // spool-exempt ones still rely on it); user hooks can swap in a
1786
+ // smarter strategy (e.g. a summariser) or observe results for side
1787
+ // effects.
1731
1788
  const contextWindowTokens =
1732
1789
  resolveContextWindow?.().maxInputTokens ??
1733
1790
  this.config.maxInputTokens ??
@@ -32,6 +32,11 @@ import {
32
32
  PluginNotInstalledError,
33
33
  uninstallPlugin,
34
34
  } from "../lib/uninstall-plugin.js";
35
+ import {
36
+ PluginNotUpgradableError,
37
+ type PluginUpgradeResult,
38
+ upgradePlugin,
39
+ } from "../lib/upgrade-plugin.js";
35
40
  import { getCliLogger } from "../logger.js";
36
41
 
37
42
  const log = getCliLogger("plugins");
@@ -53,6 +58,8 @@ Examples:
53
58
  $ assistant plugins list --json
54
59
  $ assistant plugins inspect example
55
60
  $ assistant plugins inspect example --json
61
+ $ assistant plugins upgrade example
62
+ $ assistant plugins upgrade example --dry-run
56
63
  $ assistant plugins search example
57
64
  $ assistant plugins search "^example"
58
65
  $ assistant plugins search example --json
@@ -308,6 +315,61 @@ Examples:
308
315
  process.exitCode = 1;
309
316
  }
310
317
  });
318
+
319
+ plugins
320
+ .command("upgrade <name>")
321
+ .description(
322
+ "Upgrade an installed plugin to the marketplace's current pin",
323
+ )
324
+ .option(
325
+ "--dry-run",
326
+ "Show what would change without modifying the install",
327
+ )
328
+ .option("--json", "Emit machine-readable JSON instead of a summary")
329
+ .action(
330
+ async (name: string, opts: { dryRun?: boolean; json?: boolean }) => {
331
+ try {
332
+ const result = await upgradePlugin(
333
+ { name, dryRun: opts.dryRun },
334
+ { fetch: globalThis.fetch.bind(globalThis) },
335
+ );
336
+
337
+ if (opts.json) {
338
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
339
+ return;
340
+ }
341
+
342
+ // Logged after the JSON early-return: the CLI logger writes
343
+ // info to stdout, which would otherwise corrupt --json output.
344
+ log.info(
345
+ {
346
+ name: result.name,
347
+ outcome: result.outcome,
348
+ from: result.fromCommit,
349
+ to: result.toCommit,
350
+ },
351
+ "plugin upgrade",
352
+ );
353
+
354
+ for (const line of formatUpgrade(result)) {
355
+ console.log(line);
356
+ }
357
+ } catch (err) {
358
+ if (
359
+ err instanceof PluginNotInstalledError ||
360
+ err instanceof PluginNotUpgradableError ||
361
+ err instanceof InvalidPluginNameError
362
+ ) {
363
+ console.error(err.message);
364
+ process.exitCode = 1;
365
+ return;
366
+ }
367
+ const message = err instanceof Error ? err.message : String(err);
368
+ console.error(`Plugin upgrade failed: ${message}`);
369
+ process.exitCode = 1;
370
+ }
371
+ },
372
+ );
311
373
  },
312
374
  });
313
375
  }
@@ -380,3 +442,31 @@ function formatInspection(inspection: PluginInspection): string[] {
380
442
 
381
443
  return lines;
382
444
  }
445
+
446
+ /** Render an upgrade result as human-readable summary lines. */
447
+ function formatUpgrade(result: PluginUpgradeResult): string[] {
448
+ const { name, fromCommit, toCommit } = result;
449
+ const move = `${shortSha(fromCommit)} → ${shortSha(toCommit)}`;
450
+ const provenanceNote = result.provenanceWasUnknown
451
+ ? " (previous install had no recorded provenance)"
452
+ : "";
453
+
454
+ switch (result.outcome) {
455
+ case "already-up-to-date":
456
+ return [`"${name}" is already up to date (${shortSha(toCommit)}).`];
457
+ case "would-upgrade":
458
+ return [
459
+ `"${name}" would upgrade ${move}${provenanceNote} (dry run; no changes made).`,
460
+ ];
461
+ case "upgraded": {
462
+ const count =
463
+ result.fileCount === null
464
+ ? ""
465
+ : ` (${result.fileCount} file${result.fileCount === 1 ? "" : "s"})`;
466
+ return [
467
+ `Upgraded "${name}" ${move}${count}${provenanceNote} → ${result.target}`,
468
+ "Restart the assistant to pick up the upgrade.",
469
+ ];
470
+ }
471
+ }
472
+ }