Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ credentials.json
agent-browser-data/
playwright/

# Saved conversations
conversations/

# Logs and screenshots
*.log
screenshots/
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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/
Expand All @@ -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
Expand Down
4 changes: 3 additions & 1 deletion src/claude/analyzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ export class DocumentAnalyzer {

async analyze(
document: DocumentContent,
focusPrompt?: string
focusPrompt?: string,
conversation: Anthropic.MessageParam[] = []
): Promise<ReviewResponse> {
logger.trace("Sending document to Claude for analysis", {
title: document.title,
Expand All @@ -54,6 +55,7 @@ export class DocumentAnalyzer {
max_tokens: 4096,
system: buildSystemPrompt(),
messages: [
...conversation,
{
role: "user",
content: buildUserPrompt(document, focusPrompt),
Expand Down
24 changes: 24 additions & 0 deletions src/claude/conversation.ts
Original file line number Diff line number Diff line change
@@ -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));
}
8 changes: 7 additions & 1 deletion src/claude/prompts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand All @@ -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
}
Expand Down
12 changes: 11 additions & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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)}`);
Expand Down Expand Up @@ -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;
Expand Down
25 changes: 25 additions & 0 deletions tests/analyzer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down
43 changes: 43 additions & 0 deletions tests/conversation.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
6 changes: 6 additions & 0 deletions tests/prompts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down