From a1f1d55de3caed50aa32154da4d83f81873ddda1 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 21 Nov 2025 16:19:21 -0800 Subject: [PATCH 1/2] Add agent session metadata tracking and reporting to control plane --- extensions/cli/src/commands/serve.ts | 49 +++- extensions/cli/src/util/exit.ts | 67 +++++ extensions/cli/src/util/metadata.test.ts | 337 +++++++++++++++++++++++ extensions/cli/src/util/metadata.ts | 167 +++++++++++ 4 files changed, 615 insertions(+), 5 deletions(-) create mode 100644 extensions/cli/src/util/metadata.test.ts create mode 100644 extensions/cli/src/util/metadata.ts diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index 2b3718462..e3e9c1108 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -27,7 +27,7 @@ import { messageQueue } from "../stream/messageQueue.js"; import { constructSystemMessage } from "../systemMessage.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { reportFailureTool } from "../tools/reportFailure.js"; -import { gracefulExit } from "../util/exit.js"; +import { gracefulExit, updateAgentMetadata } from "../util/exit.js"; import { formatError } from "../util/formatError.js"; import { getGitDiffSnapshot } from "../util/git.js"; import { logger } from "../util/logger.js"; @@ -351,9 +351,18 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { } // Give a moment for the response to be sent - const handleExitResponse = () => { - server.close(() => { + const handleExitResponse = async () => { + server.close(async () => { telemetryService.stopActiveTime(); + + // Update metadata one final time before exiting + try { + const history = services.chatHistory?.getHistory(); + await updateAgentMetadata(history); + } catch (err) { + logger.debug("Failed to update metadata (non-critical)", err as any); + } + gracefulExit(0).catch((err) => { logger.error(`Graceful exit failed: ${formatError(err)}`); process.exit(1); @@ -466,6 +475,18 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { // No direct persistence here; ChatHistoryService handles persistence when appropriate state.lastActivity = Date.now(); + + // Update metadata after successful agent turn + try { + const history = services.chatHistory?.getHistory(); + await updateAgentMetadata(history); + } catch (metadataErr) { + // Non-critical: log but don't fail the agent execution + logger.debug( + "Failed to update metadata after turn (non-critical)", + metadataErr as any, + ); + } } catch (e: any) { if (e.name === "AbortError") { logger.debug("Response interrupted"); @@ -522,8 +543,17 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { ); state.serverRunning = false; stopStorageSync(); - server.close(() => { + server.close(async () => { telemetryService.stopActiveTime(); + + // Update metadata one final time before exiting + try { + const history = services.chatHistory?.getHistory(); + await updateAgentMetadata(history); + } catch (err) { + logger.debug("Failed to update metadata (non-critical)", err as any); + } + gracefulExit(0).catch((err) => { logger.error(`Graceful exit failed: ${formatError(err)}`); process.exit(1); @@ -545,8 +575,17 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { clearInterval(inactivityChecker); inactivityChecker = null; } - server.close(() => { + server.close(async () => { telemetryService.stopActiveTime(); + + // Update metadata one final time before exiting + try { + const history = services.chatHistory?.getHistory(); + await updateAgentMetadata(history); + } catch (err) { + logger.debug("Failed to update metadata (non-critical)", err as any); + } + gracefulExit(0).catch((err) => { logger.error(`Graceful exit failed: ${formatError(err)}`); process.exit(1); diff --git a/extensions/cli/src/util/exit.ts b/extensions/cli/src/util/exit.ts index 31ec02652..ba27b9db2 100644 --- a/extensions/cli/src/util/exit.ts +++ b/extensions/cli/src/util/exit.ts @@ -1,7 +1,74 @@ +import type { ChatHistoryItem } from "core/index.js"; + import { sentryService } from "../sentry.js"; import { telemetryService } from "../telemetry/telemetryService.js"; +import { getGitDiffSnapshot } from "./git.js"; import { logger } from "./logger.js"; +import { + calculateDiffStats, + extractSummary, + getAgentIdFromArgs, + postAgentMetadata, +} from "./metadata.js"; + +/** + * Update agent session metadata in control plane + * Collects diff stats and conversation summary, posts to control plane + * This is called both during execution (after each turn) and before exit + * + * @param history - Chat history to extract summary from (optional, will fetch if not provided) + */ +export async function updateAgentMetadata( + history?: ChatHistoryItem[], +): Promise { + try { + const agentId = getAgentIdFromArgs(); + if (!agentId) { + logger.debug("No agent ID found, skipping metadata update"); + return; + } + + const metadata: Record = {}; + + // Calculate diff stats + try { + const { diff, repoFound } = await getGitDiffSnapshot(); + if (repoFound && diff) { + const { additions, deletions } = calculateDiffStats(diff); + if (additions > 0 || deletions > 0) { + metadata.additions = additions; + metadata.deletions = deletions; + } + } + } catch (err) { + logger.debug("Failed to calculate diff stats (non-critical)", err as any); + } + + // Extract summary from conversation + if (history && history.length > 0) { + try { + const summary = extractSummary(history); + if (summary) { + metadata.summary = summary; + } + } catch (err) { + logger.debug( + "Failed to extract conversation summary (non-critical)", + err as any, + ); + } + } + + // Post metadata if we have any + if (Object.keys(metadata).length > 0) { + await postAgentMetadata(agentId, metadata); + } + } catch (err) { + // Non-critical: log but don't fail the process + logger.debug("Error in updateAgentMetadata (ignored)", err as any); + } +} /** * Exit the process after flushing telemetry and error reporting. diff --git a/extensions/cli/src/util/metadata.test.ts b/extensions/cli/src/util/metadata.test.ts new file mode 100644 index 000000000..1b6fcc83f --- /dev/null +++ b/extensions/cli/src/util/metadata.test.ts @@ -0,0 +1,337 @@ +import type { ChatHistoryItem } from "core/index.js"; +import { describe, expect, it } from "vitest"; + +import { calculateDiffStats, extractSummary } from "./metadata.js"; + +// Helper to create a mock chat history item +function createMockChatHistoryItem( + content: string, + role: "user" | "assistant" | "system" = "assistant", +): ChatHistoryItem { + return { + message: { + role, + content, + }, + } as ChatHistoryItem; +} + +describe("metadata utilities", () => { + describe("calculateDiffStats", () => { + it("should count additions and deletions in a simple diff", () => { + const diff = `diff --git a/file.txt b/file.txt +index 123..456 789 +--- a/file.txt ++++ b/file.txt +@@ -1,3 +1,3 @@ + line 1 +-line 2 ++line 2 modified + line 3`; + + const stats = calculateDiffStats(diff); + + expect(stats.additions).toBe(1); + expect(stats.deletions).toBe(1); + }); + + it("should handle multiple hunks with multiple changes", () => { + const diff = `diff --git a/app.js b/app.js +--- a/app.js ++++ b/app.js +@@ -10,5 +10,7 @@ + const express = require('express'); +-const old = 'value'; ++const new = 'value'; ++const another = 'line'; + +@@ -50,3 +52,2 @@ +-function oldFunc() {} +-function anotherOld() {} ++function newFunc() {}`; + + const stats = calculateDiffStats(diff); + + expect(stats.additions).toBe(3); // +const new, +const another, +function newFunc + expect(stats.deletions).toBe(3); // -const old, -function oldFunc, -function anotherOld + }); + + it("should exclude diff metadata lines from counts", () => { + const diff = `diff --git a/file.txt b/file.txt +index abc123..def456 100644 +--- a/file.txt ++++ b/file.txt +@@ -1 +1 @@ +-old content ++new content`; + + const stats = calculateDiffStats(diff); + + // Should only count the actual changes, not the metadata lines + expect(stats.additions).toBe(1); + expect(stats.deletions).toBe(1); + }); + + it("should handle binary file changes", () => { + const diff = `diff --git a/image.png b/image.png +Binary files a/image.png and b/image.png differ`; + + const stats = calculateDiffStats(diff); + + // Binary files shouldn't be counted + expect(stats.additions).toBe(0); + expect(stats.deletions).toBe(0); + }); + + it("should return zeros for empty diff", () => { + const stats = calculateDiffStats(""); + + expect(stats.additions).toBe(0); + expect(stats.deletions).toBe(0); + }); + + it("should return zeros for whitespace-only diff", () => { + const stats = calculateDiffStats(" \n\n \t "); + + expect(stats.additions).toBe(0); + expect(stats.deletions).toBe(0); + }); + + it("should handle a diff with only additions", () => { + const diff = `diff --git a/new.txt b/new.txt +--- /dev/null ++++ b/new.txt +@@ -0,0 +1,3 @@ ++line 1 ++line 2 ++line 3`; + + const stats = calculateDiffStats(diff); + + expect(stats.additions).toBe(3); + expect(stats.deletions).toBe(0); + }); + + it("should handle a diff with only deletions", () => { + const diff = `diff --git a/old.txt b/old.txt +--- a/old.txt ++++ /dev/null +@@ -1,3 +0,0 @@ +-line 1 +-line 2 +-line 3`; + + const stats = calculateDiffStats(diff); + + expect(stats.additions).toBe(0); + expect(stats.deletions).toBe(3); + }); + + it("should handle real-world TypeScript diff", () => { + const diff = `diff --git a/src/util/metadata.ts b/src/util/metadata.ts +index abc123..def456 100644 +--- a/src/util/metadata.ts ++++ b/src/util/metadata.ts +@@ -1,10 +1,15 @@ + import type { ChatHistoryItem } from "core/index.js"; + +-export function oldFunction() { +- return "old"; ++export function newFunction() { ++ return "new"; ++} ++ ++export function anotherFunction() { ++ return "another"; + } + + // Comment line (unchanged) +-const OLD_CONSTANT = 42; ++const NEW_CONSTANT = 43;`; + + const stats = calculateDiffStats(diff); + + expect(stats.additions).toBe(7); + expect(stats.deletions).toBe(3); + }); + }); + + describe("extractSummary", () => { + it("should extract last assistant message", () => { + const history = [ + createMockChatHistoryItem("Hello", "user"), + createMockChatHistoryItem("Hi there, how can I help?", "assistant"), + createMockChatHistoryItem("Please fix the bug", "user"), + createMockChatHistoryItem( + "I've fixed the authentication bug in the login module.", + "assistant", + ), + ]; + + const summary = extractSummary(history); + + expect(summary).toBe( + "I've fixed the authentication bug in the login module.", + ); + }); + + it("should skip empty assistant messages", () => { + const history = [ + createMockChatHistoryItem("User message", "user"), + createMockChatHistoryItem("Valid assistant message", "assistant"), + createMockChatHistoryItem("", "assistant"), + createMockChatHistoryItem(" ", "assistant"), + ]; + + const summary = extractSummary(history); + + expect(summary).toBe("Valid assistant message"); + }); + + it("should truncate long messages to default 500 characters", () => { + const longMessage = "a".repeat(600); + const history = [createMockChatHistoryItem(longMessage, "assistant")]; + + const summary = extractSummary(history); + + expect(summary?.length).toBe(500); + expect(summary).toBe("a".repeat(497) + "..."); + }); + + it("should respect custom maxLength parameter", () => { + const longMessage = "b".repeat(200); + const history = [createMockChatHistoryItem(longMessage, "assistant")]; + + const summary = extractSummary(history, 100); + + expect(summary?.length).toBe(100); + expect(summary).toBe("b".repeat(97) + "..."); + }); + + it("should not truncate messages under the limit", () => { + const shortMessage = "This is a short message."; + const history = [createMockChatHistoryItem(shortMessage, "assistant")]; + + const summary = extractSummary(history, 500); + + expect(summary).toBe(shortMessage); + }); + + it("should return undefined for empty history", () => { + const summary = extractSummary([]); + + expect(summary).toBeUndefined(); + }); + + it("should return undefined when no assistant messages exist", () => { + const history = [ + createMockChatHistoryItem("User message 1", "user"), + createMockChatHistoryItem("User message 2", "user"), + createMockChatHistoryItem("System message", "system"), + ]; + + const summary = extractSummary(history); + + expect(summary).toBeUndefined(); + }); + + it("should handle message content as object (multimodal)", () => { + const history: ChatHistoryItem[] = [ + { + message: { + role: "assistant", + content: [ + { type: "text", text: "Here's the image analysis" }, + { type: "image_url", image_url: { url: "data:..." } }, + ], + }, + } as any, + ]; + + const summary = extractSummary(history); + + // Should stringify the object content + expect(summary).toBeDefined(); + expect(typeof summary).toBe("string"); + expect(summary).toContain("Here's the image analysis"); + }); + + it("should trim whitespace from content", () => { + const history = [ + createMockChatHistoryItem( + " \n Message with whitespace \n ", + "assistant", + ), + ]; + + const summary = extractSummary(history); + + expect(summary).toBe("Message with whitespace"); + }); + + it("should find last assistant message among mixed roles", () => { + const history = [ + createMockChatHistoryItem("First assistant message", "assistant"), + createMockChatHistoryItem("User response", "user"), + createMockChatHistoryItem("Second assistant message", "assistant"), + createMockChatHistoryItem("Another user message", "user"), + createMockChatHistoryItem("System notification", "system"), + ]; + + const summary = extractSummary(history); + + expect(summary).toBe("Second assistant message"); + }); + + it("should handle markdown formatting in messages", () => { + const history = [ + createMockChatHistoryItem( + "I've updated the code:\n\n```typescript\nfunction test() {}\n```\n\nThe changes are complete.", + "assistant", + ), + ]; + + const summary = extractSummary(history); + + // Should keep markdown formatting + expect(summary).toContain("```typescript"); + expect(summary).toContain("function test()"); + }); + + it("should handle special characters in messages", () => { + const history = [ + createMockChatHistoryItem( + 'Fixed the regex pattern: /[a-z]+/gi and added "quotes" & ', + "assistant", + ), + ]; + + const summary = extractSummary(history); + + expect(summary).toBe( + 'Fixed the regex pattern: /[a-z]+/gi and added "quotes" & ', + ); + }); + + it("should handle exactly 500 character message (no truncation)", () => { + const exactMessage = "x".repeat(500); + const history = [createMockChatHistoryItem(exactMessage, "assistant")]; + + const summary = extractSummary(history, 500); + + expect(summary).toBe(exactMessage); + expect(summary?.length).toBe(500); + expect(summary?.endsWith("...")).toBe(false); + }); + + it("should handle 501 character message (with truncation)", () => { + const longMessage = "y".repeat(501); + const history = [createMockChatHistoryItem(longMessage, "assistant")]; + + const summary = extractSummary(history, 500); + + expect(summary).toBe("y".repeat(497) + "..."); + expect(summary?.length).toBe(500); + }); + }); +}); diff --git a/extensions/cli/src/util/metadata.ts b/extensions/cli/src/util/metadata.ts new file mode 100644 index 000000000..f867218cf --- /dev/null +++ b/extensions/cli/src/util/metadata.ts @@ -0,0 +1,167 @@ +import type { ChatHistoryItem } from "core/index.js"; + +import { + post, + ApiRequestError, + AuthenticationRequiredError, +} from "./apiClient.js"; +import { logger } from "./logger.js"; + +/** + * Statistics about a git diff + */ +export interface DiffStats { + additions: number; + deletions: number; +} + +/** + * Calculate diff statistics from unified diff content + * Counts lines added (+) and deleted (-), excluding metadata lines + * + * @param diffContent - The unified diff content as a string + * @returns Object with additions and deletions counts + */ +export function calculateDiffStats(diffContent: string): DiffStats { + if (!diffContent || diffContent.trim() === "") { + return { additions: 0, deletions: 0 }; + } + + const lines = diffContent.split("\n"); + let additions = 0; + let deletions = 0; + + for (const line of lines) { + // Skip diff metadata lines (@@, +++, ---, diff, index, etc.) + if ( + line.startsWith("+++") || + line.startsWith("---") || + line.startsWith("@@") || + line.startsWith("diff ") || + line.startsWith("index ") || + line.startsWith("Binary files") + ) { + continue; + } + + // Count actual code changes + if (line.startsWith("+")) { + additions++; + } else if (line.startsWith("-")) { + deletions++; + } + } + + return { additions, deletions }; +} + +/** + * Extract the last assistant message from conversation history + * Truncates if too long + * + * @param history - Array of chat history items + * @param maxLength - Maximum length for the summary (default: 500) + * @returns The last assistant message content, or undefined if none found + */ +export function extractSummary( + history: ChatHistoryItem[], + maxLength: number = 500, +): string | undefined { + if (!history || history.length === 0) { + return undefined; + } + + // Find last assistant message (iterate backwards) + for (let i = history.length - 1; i >= 0; i--) { + const item = history[i]; + if (item.message.role === "assistant") { + const content = + typeof item.message.content === "string" + ? item.message.content + : JSON.stringify(item.message.content); + + if (!content || content.trim() === "") { + continue; + } + + const trimmedContent = content.trim(); + + // Truncate if too long + if (trimmedContent.length <= maxLength) { + return trimmedContent; + } + + return trimmedContent.substring(0, maxLength - 3) + "..."; + } + } + + return undefined; +} + +/** + * Extract the agent ID from the --id command line flag + * @returns The agent ID or undefined if not found + */ +export function getAgentIdFromArgs(): string | undefined { + const args = process.argv; + const idIndex = args.indexOf("--id"); + if (idIndex !== -1 && idIndex + 1 < args.length) { + return args[idIndex + 1]; + } + return undefined; +} + +/** + * POST metadata to the control plane for an agent session + * Non-blocking and error-tolerant - failures are logged but don't throw + * + * @param agentId - The agent session ID + * @param metadata - Arbitrary metadata object to post + */ +export async function postAgentMetadata( + agentId: string, + metadata: Record, +): Promise { + if (!agentId) { + logger.debug("No agent ID provided, skipping metadata update"); + return; + } + + if (!metadata || Object.keys(metadata).length === 0) { + logger.debug("Empty metadata object, skipping metadata update"); + return; + } + + try { + logger.debug("Posting metadata to control plane", { + agentId, + metadata, + }); + + const response = await post(`agents/${agentId}/metadata`, { metadata }); + + if (response.ok) { + logger.info("Successfully posted metadata to control plane"); + } else { + logger.warn( + `Unexpected response when posting metadata: ${response.status}`, + ); + } + } catch (error) { + // Non-critical: Log but don't fail the entire agent execution + if (error instanceof AuthenticationRequiredError) { + logger.debug( + "Authentication required for metadata update (skipping)", + error.message, + ); + } else if (error instanceof ApiRequestError) { + logger.warn( + `Failed to post metadata: ${error.status} ${error.response || error.statusText}`, + ); + } else { + const errorMessage = + error instanceof Error ? error.message : String(error); + logger.warn(`Error posting metadata: ${errorMessage}`); + } + } +} From 10ae310c7770b8b8c695c19ea724d3835f49ef10 Mon Sep 17 00:00:00 2001 From: "continue[bot]" Date: Mon, 1 Dec 2025 01:44:46 +0000 Subject: [PATCH 2/2] Fix calculateDiffStats to correctly handle code with ++ or -- operators The function was incorrectly treating lines like '+++counter;' or '---counter;' as diff file headers and skipping them. This happened when code containing ++ or -- operators at the start of a line was added or removed. Fixed by checking that file header lines (--- a/file, +++ b/file) contain a space after the --- or +++ prefix, distinguishing them from code changes. Added test cases to verify the fix handles these edge cases correctly. Co-authored-by: nate --- extensions/cli/src/util/metadata.test.ts | 44 ++++++++++++++++++++++++ extensions/cli/src/util/metadata.ts | 8 +++-- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/extensions/cli/src/util/metadata.test.ts b/extensions/cli/src/util/metadata.test.ts index 1b6fcc83f..668516d56 100644 --- a/extensions/cli/src/util/metadata.test.ts +++ b/extensions/cli/src/util/metadata.test.ts @@ -154,6 +154,50 @@ index abc123..def456 100644 expect(stats.additions).toBe(7); expect(stats.deletions).toBe(3); }); + + it("should correctly count code with ++ or -- operators", () => { + // This tests the edge case where code contains ++ or -- at the start + const diff = `diff --git a/counter.js b/counter.js +index abc123..def456 100644 +--- a/counter.js ++++ b/counter.js +@@ -1,5 +1,5 @@ + function increment(counter) { +- counter++; ++ ++counter; + } + + function decrement(counter) { +- counter--; ++ --counter; + }`; + + const stats = calculateDiffStats(diff); + + // Should count all 4 changes: 2 additions and 2 deletions + // Lines like "+++counter;" should be counted as additions, not skipped as file headers + expect(stats.additions).toBe(2); + expect(stats.deletions).toBe(2); + }); + + it("should handle code with multiple + or - at line start", () => { + const diff = `diff --git a/operators.c b/operators.c +--- a/operators.c ++++ b/operators.c +@@ -1,4 +1,4 @@ + int main() { +- x--; +- y++; ++ --x; ++ ++y; + return 0; + }`; + + const stats = calculateDiffStats(diff); + + expect(stats.additions).toBe(2); + expect(stats.deletions).toBe(2); + }); }); describe("extractSummary", () => { diff --git a/extensions/cli/src/util/metadata.ts b/extensions/cli/src/util/metadata.ts index f867218cf..a0759b5bb 100644 --- a/extensions/cli/src/util/metadata.ts +++ b/extensions/cli/src/util/metadata.ts @@ -32,10 +32,12 @@ export function calculateDiffStats(diffContent: string): DiffStats { let deletions = 0; for (const line of lines) { - // Skip diff metadata lines (@@, +++, ---, diff, index, etc.) + // Skip diff metadata lines + // File headers contain a space: "--- a/file" or "+++ b/file" + // But code changes with ++ or -- at start don't: "+++counter;" or "---counter;" if ( - line.startsWith("+++") || - line.startsWith("---") || + (line.startsWith("+++") && (line.length === 3 || line[3] === " ")) || + (line.startsWith("---") && (line.length === 3 || line[3] === " ")) || line.startsWith("@@") || line.startsWith("diff ") || line.startsWith("index ") ||