Skip to content

Commit 4bfd185

Browse files
amixclaude
andauthored
feat(comments): delete .dunk/comments.json when the review is empty (#12)
Resolving the last comment left an empty `{ "schema": 1, "comments": [] }` file that an agent or human reviewer still had to reason about. Reads already treat a missing file as "no comments", so `writeCommentsFile` now deletes the file on an empty review and round-trips cleanly. Because deletion is now part of the normal write path and the TUI and agent CLI ping-pong on the same review, a concurrent deletion could land between an `existsSync` check and the read. The read/fingerprint helpers now do a single ENOENT-safe read instead, and the comments-file path has one source of truth via `commentsFilePath`. Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 0f2cc2e commit 4bfd185

4 files changed

Lines changed: 152 additions & 15 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
88

99
## [Unreleased]
1010

11+
### Changed
12+
13+
- `.dunk/comments.json` is now deleted when the last comment is resolved instead of leaving an empty `{ "comments": [] }` file. Reads already treat a missing file as "no comments", so an empty review leaves no artifact for a coding agent or human reviewer to reason about.
14+
1115
## [0.15.0] - 2026-05-19
1216

1317
### Changed

‎src/core/cliComments.test.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { afterEach, describe, expect, test } from "bun:test";
2-
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2+
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
33
import { tmpdir } from "node:os";
44
import { join } from "node:path";
55
import { computeAnchor, readCommentsFile, splitLines, writeCommentsFile } from "./comments";
@@ -329,6 +329,24 @@ describe("dunk comments CLI", () => {
329329
expect(remaining.comments.map((c) => c.id)).toEqual([2]);
330330
});
331331

332+
test("resolving the last comment deletes the comments file", () => {
333+
const repoRoot = createTempRepo();
334+
writeCommentsFile(repoRoot, {
335+
schema: 1,
336+
comments: [
337+
{ id: 1, file: "a.ts", line: 1, range: [1, 1], anchor: "aaaaaaaaaaaaaaaa", body: "only" },
338+
],
339+
});
340+
341+
const output = runCommentsResolve([1], { cwd: repoRoot });
342+
expect(output).toBe("Resolved 1 comment: #1.\n");
343+
344+
// CLI-visible: the review reports clean.
345+
expect(runCommentsList("text", { cwd: repoRoot })).toBe("No pending comments.\n");
346+
// And the literal contract of this change: no empty artifact left behind.
347+
expect(existsSync(join(repoRoot, ".dunk", "comments.json"))).toBe(false);
348+
});
349+
332350
test("resolve refuses partial success when one id is missing", () => {
333351
const repoRoot = createTempRepo();
334352
writeCommentsFile(repoRoot, {

‎src/core/comments.test.ts‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
44
import { join } from "node:path";
55
import {
66
computeAnchor,
7+
mutateCommentsFile,
78
nextCommentId,
89
readCommentsFile,
910
resolveComments,
@@ -68,6 +69,84 @@ describe("dunk comments", () => {
6869
});
6970
});
7071

72+
test("writeCommentsFile deletes the file when the review has no comments", () => {
73+
withTempRepo((repoRoot) => {
74+
const path = join(repoRoot, ".dunk", "comments.json");
75+
writeCommentsFile(repoRoot, {
76+
schema: 1,
77+
comments: [
78+
{ id: 1, file: "a.ts", line: 1, range: [1, 1], anchor: "aaaaaaaaaaaaaaaa", body: "x" },
79+
],
80+
});
81+
expect(existsSync(path)).toBe(true);
82+
83+
writeCommentsFile(repoRoot, { schema: 1, comments: [] });
84+
85+
// No empty `{ "comments": [] }` artifact is left behind, and reads still
86+
// round-trip to "no comments".
87+
expect(existsSync(path)).toBe(false);
88+
expect(readCommentsFile(repoRoot).comments).toEqual([]);
89+
});
90+
});
91+
92+
test("writeCommentsFile with no comments is a no-op when the file is absent", () => {
93+
withTempRepo((repoRoot) => {
94+
expect(() => writeCommentsFile(repoRoot, { schema: 1, comments: [] })).not.toThrow();
95+
expect(existsSync(join(repoRoot, ".dunk", "comments.json"))).toBe(false);
96+
});
97+
});
98+
99+
test("mutateCommentsFile deletes the file when the last comment is removed", () => {
100+
withTempRepo((repoRoot) => {
101+
const path = join(repoRoot, ".dunk", "comments.json");
102+
writeCommentsFile(repoRoot, {
103+
schema: 1,
104+
comments: [
105+
{ id: 7, file: "a.ts", line: 1, range: [1, 1], anchor: "aaaaaaaaaaaaaaaa", body: "x" },
106+
],
107+
});
108+
109+
const next = mutateCommentsFile(repoRoot, (current) => withRemovedComment(current, 7));
110+
111+
expect(next.comments).toEqual([]);
112+
expect(existsSync(path)).toBe(false);
113+
});
114+
});
115+
116+
test("a concurrent deletion mid-mutation is treated as an empty review, not an error", () => {
117+
withTempRepo((repoRoot) => {
118+
const path = join(repoRoot, ".dunk", "comments.json");
119+
writeCommentsFile(repoRoot, {
120+
schema: 1,
121+
comments: [
122+
{ id: 1, file: "a.ts", line: 1, range: [1, 1], anchor: "aaaaaaaaaaaaaaaa", body: "old" },
123+
],
124+
});
125+
126+
// The first attempt deletes the file after the read but before the
127+
// fingerprint re-check, so currentFingerprint hits ENOENT and the
128+
// optimistic loop retries against the now-absent (empty) file.
129+
let deletedOnce = false;
130+
const result = mutateCommentsFile(repoRoot, (current) => {
131+
if (!deletedOnce) {
132+
deletedOnce = true;
133+
rmSync(path, { force: true });
134+
}
135+
return withAddedComment(current, {
136+
file: "b.ts",
137+
line: 2,
138+
range: [2, 2],
139+
anchor: "bbbbbbbbbbbbbbbb",
140+
body: "fresh",
141+
}).file;
142+
});
143+
144+
expect(deletedOnce).toBe(true);
145+
expect(result.comments.map((c) => c.body)).toEqual(["fresh"]);
146+
expect(readCommentsFile(repoRoot).comments.map((c) => c.body)).toEqual(["fresh"]);
147+
});
148+
});
149+
71150
test("nextCommentId never reuses an id, even after deletions", () => {
72151
let file: import("./comments").CommentsFile = { schema: 1, comments: [] };
73152
file = withAddedComment(file, {

‎src/core/comments.ts‎

Lines changed: 50 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
/** `.dunk/comments.json` reader/writer and drift detection. */
22
import { createHash } from "node:crypto";
3-
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
3+
import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
44
import { isAbsolute, join, relative, resolve as resolvePath } from "node:path";
55
import { z } from "zod";
6-
import { DUNK_COMMENTS_FILENAME, DUNK_DIR } from "./dunkPaths";
6+
import { DUNK_COMMENTS_FILENAME, DUNK_COMMENTS_RELATIVE_PATH, DUNK_DIR } from "./dunkPaths";
77
import { DunkUserError } from "./errors";
88
import { hunkLineRange } from "./hunkRange";
99
import { LARGE_FILE_MAX_BYTES } from "./limits";
@@ -217,7 +217,7 @@ function parseCommentsFile(raw: string, path: string): CommentsFile {
217217
} catch (error) {
218218
const detail = error instanceof Error ? error.message : String(error);
219219
throw new DunkUserError(`Malformed JSON in ${path}: ${detail}`, [
220-
"Repair the file by hand, or delete it to start fresh — dunk recreates an empty one on the next write.",
220+
"Repair the file by hand, or delete it to start fresh — dunk treats a missing file as no comments and recreates it on the next comment.",
221221
]);
222222
}
223223

@@ -242,20 +242,55 @@ function parseCommentsFile(raw: string, path: string): CommentsFile {
242242
return result.data;
243243
}
244244

245+
/** The absolute path to `.dunk/comments.json` for one repo root. */
246+
function commentsFilePath(repoRoot: string): string {
247+
return join(repoRoot, DUNK_COMMENTS_RELATIVE_PATH);
248+
}
249+
250+
/**
251+
* Read the comments file's raw bytes, or `null` when it does not exist.
252+
*
253+
* Resolving the last comment now deletes the file, and the TUI and agent CLI
254+
* ping-pong on the same review, so a concurrent deletion can land between an
255+
* `existsSync` check and the read. Catching `ENOENT` from a single read closes
256+
* that race instead of throwing for what is just an empty review.
257+
*/
258+
function readCommentsRawOrNull(path: string): string | null {
259+
try {
260+
return readFileSync(path, "utf8");
261+
} catch (error) {
262+
if (error instanceof Error && (error as NodeJS.ErrnoException).code === "ENOENT") {
263+
return null;
264+
}
265+
throw error;
266+
}
267+
}
268+
245269
/** Read `.dunk/comments.json` from the repo root, returning [] if missing. */
246270
export function readCommentsFile(repoRoot: string): CommentsFile {
247-
const path = join(repoRoot, DUNK_DIR, DUNK_COMMENTS_FILENAME);
248-
if (!existsSync(path)) {
271+
const path = commentsFilePath(repoRoot);
272+
const raw = readCommentsRawOrNull(path);
273+
if (raw === null) {
249274
return { schema: SCHEMA_VERSION, comments: [] };
250275
}
251-
return parseCommentsFile(readFileSync(path, "utf8"), path);
276+
return parseCommentsFile(raw, path);
252277
}
253278

254279
/** Atomically write the comments file using a unique temp + rename. */
255280
export function writeCommentsFile(repoRoot: string, file: CommentsFile): void {
256281
const dir = join(repoRoot, DUNK_DIR);
257-
mkdirSync(dir, { recursive: true });
258282
const finalPath = join(dir, DUNK_COMMENTS_FILENAME);
283+
284+
// An empty review has no file. A `{ "schema": 1, "comments": [] }` artifact
285+
// is just noise an agent or human reviewer would have to reason about, and
286+
// reads already treat a missing file as "no comments", so deleting on empty
287+
// round-trips cleanly. `force` makes this a no-op when the file is absent.
288+
if (file.comments.length === 0) {
289+
rmSync(finalPath, { force: true });
290+
return;
291+
}
292+
293+
mkdirSync(dir, { recursive: true });
259294
// Unique per-write temp filename so two writers (TUI + agent CLI) never
260295
// collide on the same `.tmp` and double-rename through it. Same-filesystem
261296
// rename remains atomic, so concurrent readers still see one whole file.
@@ -513,12 +548,12 @@ function readCommentsFileWithFingerprint(repoRoot: string): {
513548
file: CommentsFile;
514549
fingerprint: string | null;
515550
} {
516-
const path = join(repoRoot, DUNK_DIR, DUNK_COMMENTS_FILENAME);
517-
if (!existsSync(path)) {
551+
const path = commentsFilePath(repoRoot);
552+
const raw = readCommentsRawOrNull(path);
553+
if (raw === null) {
518554
return { file: { schema: SCHEMA_VERSION, comments: [] }, fingerprint: null };
519555
}
520556

521-
const raw = readFileSync(path, "utf8");
522557
return {
523558
file: parseCommentsFile(raw, path),
524559
fingerprint: createHash("sha256").update(raw).digest("hex"),
@@ -527,11 +562,12 @@ function readCommentsFileWithFingerprint(repoRoot: string): {
527562

528563
/** Compute the on-disk fingerprint for one comments file, or null if absent. */
529564
function currentFingerprint(repoRoot: string): string | null {
530-
const path = join(repoRoot, DUNK_DIR, DUNK_COMMENTS_FILENAME);
531-
if (!existsSync(path)) {
565+
const path = commentsFilePath(repoRoot);
566+
const raw = readCommentsRawOrNull(path);
567+
if (raw === null) {
532568
return null;
533569
}
534-
return createHash("sha256").update(readFileSync(path, "utf8")).digest("hex");
570+
return createHash("sha256").update(raw).digest("hex");
535571
}
536572

537573
/**
@@ -560,6 +596,6 @@ export function mutateCommentsFile(
560596
}
561597

562598
throw new Error(
563-
`dunk comments: gave up after ${MUTATE_MAX_ATTEMPTS} optimistic retries on ${join(repoRoot, DUNK_DIR, DUNK_COMMENTS_FILENAME)}.`,
599+
`dunk comments: gave up after ${MUTATE_MAX_ATTEMPTS} optimistic retries on ${commentsFilePath(repoRoot)}.`,
564600
);
565601
}

0 commit comments

Comments
 (0)