From a1dbe2caca3dd62460e6646b5784a5d348afe3a7 Mon Sep 17 00:00:00 2001 From: Andy Moore Date: Thu, 19 Nov 2026 07:33:47 -0700 Subject: [PATCH] Add conversation continuity Save what each review applied to conversations/.json and replay those turns to Claude on the next run, so it remembers its earlier suggestions and can continue comment threads. Closes #3 --- .gitignore | 3 +++ README.md | 3 ++- src/claude/analyzer.ts | 4 +++- src/claude/conversation.ts | 24 +++++++++++++++++++++ src/claude/prompts.ts | 8 ++++++- src/cli.ts | 12 ++++++++++- tests/analyzer.test.ts | 25 ++++++++++++++++++++++ tests/conversation.test.ts | 43 ++++++++++++++++++++++++++++++++++++++ tests/prompts.test.ts | 6 ++++++ 9 files changed, 124 insertions(+), 4 deletions(-) create mode 100644 src/claude/conversation.ts create mode 100644 tests/conversation.test.ts diff --git a/.gitignore b/.gitignore index fb82981..9c3580e 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,9 @@ credentials.json agent-browser-data/ playwright/ +# Saved conversations +conversations/ + # Logs and screenshots *.log screenshots/ diff --git a/README.md b/README.md index b3be91c..b865bcd 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ When you run the CLI with a Google Doc URL: 3. **Analyzes** the document with Claude 4. **Makes** suggested edits as native Google Docs suggestions 5. **Replies** to comment threads with what it did +6. **Remembers** what it applied, so the next run on that document continues the conversation ## Development @@ -112,6 +113,7 @@ src/ │ └── types.ts ├── claude/ │ ├── analyzer.ts # Claude integration +│ ├── conversation.ts # Per-document conversation, replayed on the next run │ ├── prompts.ts # System/user prompts │ └── types.ts # ReviewResponse interface ├── browser/ @@ -135,7 +137,6 @@ See [GitHub Issues](https://github.com/gsiener/track-changes/issues) for planned Key upcoming features: - Web dashboard for easier collaboration - Real-time presence indicators -- Conversation continuity with Claude - Review history tracking ## License diff --git a/src/claude/analyzer.ts b/src/claude/analyzer.ts index 1e671c3..aab227f 100644 --- a/src/claude/analyzer.ts +++ b/src/claude/analyzer.ts @@ -41,7 +41,8 @@ export class DocumentAnalyzer { async analyze( document: DocumentContent, - focusPrompt?: string + focusPrompt?: string, + conversation: Anthropic.MessageParam[] = [] ): Promise { logger.trace("Sending document to Claude for analysis", { title: document.title, @@ -54,6 +55,7 @@ export class DocumentAnalyzer { max_tokens: 4096, system: buildSystemPrompt(), messages: [ + ...conversation, { role: "user", content: buildUserPrompt(document, focusPrompt), diff --git a/src/claude/conversation.ts b/src/claude/conversation.ts new file mode 100644 index 0000000..d8f911a --- /dev/null +++ b/src/claude/conversation.ts @@ -0,0 +1,24 @@ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; +import { dirname, join } from "path"; +import { fileURLToPath } from "url"; +import type Anthropic from "@anthropic-ai/sdk"; +import type { ReviewResponse } from "./types.js"; + +const CONVERSATIONS_DIR = join(dirname(fileURLToPath(import.meta.url)), "../../conversations"); + +/** Earlier turns of the conversation with Claude about a document. */ +export function loadConversation(docId: string, dir = CONVERSATIONS_DIR): Anthropic.MessageParam[] { + const file = join(dir, `${docId}.json`); + return existsSync(file) ? JSON.parse(readFileSync(file, "utf-8")) : []; +} + +/** Add a review, as applied, to the document's conversation. */ +export function saveReview(docId: string, applied: ReviewResponse, dir = CONVERSATIONS_DIR): void { + const conversation: Anthropic.MessageParam[] = [ + ...loadConversation(docId, dir), + { role: "user", content: "Please review this document. [Earlier version omitted]" }, + { role: "assistant", content: JSON.stringify(applied) }, + ]; + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, `${docId}.json`), JSON.stringify(conversation, null, 2)); +} diff --git a/src/claude/prompts.ts b/src/claude/prompts.ts index ead5d2d..b05ed38 100644 --- a/src/claude/prompts.ts +++ b/src/claude/prompts.ts @@ -15,6 +15,12 @@ Example: - Your action: Create a suggestion to shorten the text - Your reply: "Made this sentence more concise by removing redundant phrases." +## Earlier Reviews + +If this conversation has earlier turns, they are your previous reviews of this document, as applied. Pick up where you left off: +- Don't repeat suggestions or comments you already made. +- A thread you already replied to needs a new reply only if someone has responded since. This includes @mention tasks. + Your output must be valid JSON matching this schema: { "suggestions": [ @@ -27,7 +33,7 @@ Your output must be valid JSON matching this schema: ], "commentReplies": [ { - "commentQuote": "quote from the comment to identify it", + "commentQuote": "quote from the thread's first comment to identify it", "reply": "your response", "resolve": true/false } diff --git a/src/cli.ts b/src/cli.ts index 537d635..ca9d08c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -7,6 +7,7 @@ import { logger } from "./utils/logger.js"; import { extractDocId, buildDocsUrl } from "./utils/url.js"; import { DocsReader } from "./google/docs-reader.js"; import { DocumentAnalyzer } from "./claude/analyzer.js"; +import { loadConversation, saveReview } from "./claude/conversation.js"; import { BrowserSession } from "./browser/session.js"; import { DocsWriter } from "./browser/docs-writer.js"; import type { DocumentContent } from "./google/types.js"; @@ -100,7 +101,7 @@ program console.log("\n🤖 Analyzing with Claude..."); const analyzeStart = Date.now(); const analyzer = new DocumentAnalyzer(config); - const review = await analyzer.analyze(document); + const review = await analyzer.analyze(document, undefined, loadConversation(docId)); const analyzeDuration = Date.now() - analyzeStart; console.log(` ⏱️ Analyzed in ${formatDuration(analyzeDuration)}`); @@ -222,6 +223,15 @@ program const replyResults = results.filter((r) => r.type === "commentReply"); const commentResults = results.filter((r) => r.type === "newComment"); + // Remember what was applied (skipped suggestions come first in the results) + if (results.some((r) => r.success)) { + saveReview(docId, { + suggestions: suggestionsToApply.filter((_, i) => suggestionResults[skippedSuggestions + i].success), + commentReplies: review.commentReplies.filter((_, i) => replyResults[i].success), + newComments: review.newComments.filter((_, i) => commentResults[i].success), + }); + } + const suggestionSuccess = suggestionResults.filter((r) => r.success).length; const replySuccess = replyResults.filter((r) => r.success).length; const commentSuccess = commentResults.filter((r) => r.success).length; diff --git a/tests/analyzer.test.ts b/tests/analyzer.test.ts index 55cf944..492e248 100644 --- a/tests/analyzer.test.ts +++ b/tests/analyzer.test.ts @@ -350,6 +350,31 @@ describe("DocumentAnalyzer", () => { ); }); + it("should replay the earlier conversation before the new prompt", async () => { + mockCreate.mockResolvedValue({ + usage: { input_tokens: 100, output_tokens: 50 }, + content: [ + { + type: "text", + text: JSON.stringify({ suggestions: [], commentReplies: [], newComments: [] }), + }, + ], + }); + const conversation = [ + { role: "user" as const, content: "Please review this document. [Earlier version omitted]" }, + { role: "assistant" as const, content: '{"suggestions":[],"commentReplies":[],"newComments":[]}' }, + ]; + + const { DocumentAnalyzer } = await import("../src/claude/analyzer.js"); + const analyzer = new DocumentAnalyzer(mockConfig); + await analyzer.analyze(testDocument, undefined, conversation); + + expect(mockCreate.mock.calls[0][0].messages).toEqual([ + ...conversation, + { role: "user", content: expect.stringContaining("Test Document") }, + ]); + }); + it("should handle optional fields in suggestions", async () => { const mockResponse = { usage: { input_tokens: 100, output_tokens: 50 }, diff --git a/tests/conversation.test.ts b/tests/conversation.test.ts new file mode 100644 index 0000000..eb409e3 --- /dev/null +++ b/tests/conversation.test.ts @@ -0,0 +1,43 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkdtempSync, rmSync } from "fs"; +import { tmpdir } from "os"; +import { join } from "path"; +import { loadConversation, saveReview } from "../src/claude/conversation.js"; + +describe("conversation", () => { + const first = { + suggestions: [{ findText: "old", replaceWith: "new" }], + commentReplies: [], + newComments: [], + }; + const second = { + suggestions: [], + commentReplies: [{ commentQuote: "@claude tighten this", reply: "Tightened.", resolve: false }], + newComments: [], + }; + let tmp: string; + let dir: string; + + beforeEach(() => { + tmp = mkdtempSync(join(tmpdir(), "track-changes-")); + dir = join(tmp, "conversations"); + }); + + afterEach(() => rmSync(tmp, { recursive: true })); + + it("is empty for a document that has not been reviewed", () => { + expect(loadConversation("doc123", dir)).toEqual([]); + }); + + it("restores each document's reviews as alternating turns", () => { + saveReview("doc123", first, dir); + saveReview("doc123", second, dir); + saveReview("other", second, dir); + + const conversation = loadConversation("doc123", dir); + + expect(conversation.map((m) => m.role)).toEqual(["user", "assistant", "user", "assistant"]); + expect(JSON.parse(conversation[1].content as string)).toEqual(first); + expect(JSON.parse(conversation[3].content as string)).toEqual(second); + }); +}); diff --git a/tests/prompts.test.ts b/tests/prompts.test.ts index be8baf3..ee7d0f0 100644 --- a/tests/prompts.test.ts +++ b/tests/prompts.test.ts @@ -16,6 +16,12 @@ describe("buildSystemPrompt", () => { expect(prompt).toContain("resolve"); }); + it("should explain how to continue from earlier reviews", () => { + const prompt = buildSystemPrompt(); + expect(prompt).toContain("your previous reviews of this document"); + expect(prompt).toContain("only if someone has responded since"); + }); + it("should request JSON output", () => { const prompt = buildSystemPrompt(); expect(prompt).toContain("valid JSON");