agentic-diff 0.1.2 → 0.1.4

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.
package/README.md CHANGED
@@ -46,7 +46,7 @@ One background server per user serves every repository you open. It stops with `
46
46
  Any command-line agent that speaks the [Agent Client Protocol](https://github.com/agentclientprotocol/typescript-sdk) can be asked about a comparison, from a comment (`@agent`) or from the side chat. Without configuration, Claude Code is used through `npx -y @agentclientprotocol/claude-agent-acp`. Others are named in `~/.agentic-diff/config.json`:
47
47
 
48
48
  ```json
49
- { "agents": ["claude", "gemini", "codex", "opencode"] }
49
+ { "agents": ["claude", "codex", "gemini", "opencode", "cursor", "antigravity", "copilot"] }
50
50
  ```
51
51
 
52
52
  The agent itself has to be installed and signed in; agentic-diff only starts it.
package/dist/cli.js CHANGED
@@ -3770,7 +3770,7 @@ var require_websocket_server = __commonJS({
3770
3770
 
3771
3771
  // packages/cli/src/cli.ts
3772
3772
  import { spawn as spawn4 } from "node:child_process";
3773
- import { statSync as statSync4 } from "node:fs";
3773
+ import { readFileSync as readFileSync6, statSync as statSync4 } from "node:fs";
3774
3774
  import { resolve as resolve2 } from "node:path";
3775
3775
  import { parseArgs } from "node:util";
3776
3776
 
@@ -4020,6 +4020,7 @@ function reduceRun(run, event) {
4020
4020
  }
4021
4021
 
4022
4022
  // packages/core/src/shared/calls.ts
4023
+ var USUAL_EFFORTS = /* @__PURE__ */ new Set(["minimal", "low", "medium", "high", "xhigh", "max"]);
4023
4024
  var normalize = (text) => text.toLowerCase().replace(/[^a-z0-9]/g, "");
4024
4025
  function modelOption(agent) {
4025
4026
  return agent?.options?.find((option) => option.category === "model") ?? agent?.options?.find((option) => option.kind === "select" && /model/i.test(option.id));
@@ -4059,11 +4060,16 @@ function parseCall(body, agents, defaultAgentId) {
4059
4060
  const option = modelOption(target);
4060
4061
  const value = findValue(option, model);
4061
4062
  if (option && value) call.options[option.id] = value.id;
4062
- else call.problems.push(option ? `${target?.name ?? "The agent"} does not offer a model called "${model}"; its own choice was used.` : `The models of ${target?.name ?? "this agent"} are not known yet (it tells them on its first run), so "${model}" was not set.`);
4063
+ else if (option) call.problems.push(`${target?.name ?? "The agent"} does not offer a model called "${model}"; its own choice was used.`);
4064
+ else call.pending = { ...call.pending, model };
4063
4065
  }
4064
4066
  const effort = effortOption(target);
4065
4067
  message = message.replace(EFFORT_WORD, (whole, before, word) => {
4066
4068
  const value = findValue(effort, word);
4069
+ if (!target?.options?.length && USUAL_EFFORTS.has(word.toLowerCase())) {
4070
+ call.pending = { ...call.pending, effort: word };
4071
+ return before;
4072
+ }
4067
4073
  if (!effort || !value) return whole;
4068
4074
  call.options[effort.id] = value.id;
4069
4075
  return before;
@@ -4075,6 +4081,21 @@ function parseCall(body, agents, defaultAgentId) {
4075
4081
  call.message = message.replace(/[ \t]{2,}/g, " ").replace(/[ \t]+$/gm, "").trim();
4076
4082
  return call;
4077
4083
  }
4084
+ function settlePending(pending, options, agentName) {
4085
+ const chosen = {};
4086
+ const problems = [];
4087
+ const agent = { options: [...options] };
4088
+ for (const [word, option, what] of [
4089
+ [pending?.model, modelOption(agent), "a model"],
4090
+ [pending?.effort, effortOption(agent), "an effort level"]
4091
+ ]) {
4092
+ if (word === void 0) continue;
4093
+ const value = findValue(option, word);
4094
+ if (option && value) chosen[option.id] = value.id;
4095
+ else problems.push(`${agentName} does not offer ${what} called "${word}"; its own choice was used.`);
4096
+ }
4097
+ return { chosen, problems };
4098
+ }
4078
4099
 
4079
4100
  // node_modules/.pnpm/diff@9.0.0/node_modules/diff/libesm/diff/base.js
4080
4101
  var Diff = class {
@@ -4382,8 +4403,8 @@ function suggestionBlocks(body) {
4382
4403
  continue;
4383
4404
  }
4384
4405
  const indent = open3[1].length;
4385
- const fence = open3[2];
4386
- const close = new RegExp(`^ {0,3}${fence[0] === "`" ? "`" : "~"}{${fence.length},}\\s*$`);
4406
+ const fence2 = open3[2];
4407
+ const close = new RegExp(`^ {0,3}${fence2[0] === "`" ? "`" : "~"}{${fence2.length},}\\s*$`);
4387
4408
  const unindent = new RegExp(`^ {0,${indent}}`);
4388
4409
  const content = [];
4389
4410
  let j = i + 1;
@@ -6058,6 +6079,28 @@ var ThreadStore = class {
6058
6079
  createdAt: row.created_at
6059
6080
  }));
6060
6081
  }
6082
+ /**
6083
+ * The name a conversation, a comment or a chat message has in review files: the one it arrived under, or its
6084
+ * own id when it was written here. It stays the same however often the file travels back and forth.
6085
+ */
6086
+ refOf(table, id) {
6087
+ const row = this.db.prepare(`SELECT import_ref FROM ${table} WHERE id = ?`).get(id);
6088
+ return row?.import_ref ?? id;
6089
+ }
6090
+ setRef(table, id, ref) {
6091
+ this.db.prepare(`UPDATE ${table} SET import_ref = ? WHERE id = ?`).run(ref, id);
6092
+ }
6093
+ /** The conversation of a scope that a review file calls `ref`. */
6094
+ threadByRef(scope, ref) {
6095
+ const row = this.db.prepare("SELECT id FROM threads WHERE scope = ? AND (import_ref = ? OR id = ?)").get(scope, ref, ref);
6096
+ return row ? this.get(row.id) : void 0;
6097
+ }
6098
+ hasComment(threadId, ref) {
6099
+ return this.db.prepare("SELECT 1 FROM comments WHERE thread_id = ? AND (import_ref = ? OR id = ?)").get(threadId, ref, ref) !== void 0;
6100
+ }
6101
+ hasChatMessage(scope, ref) {
6102
+ return this.db.prepare("SELECT 1 FROM chat_messages WHERE scope = ? AND (import_ref = ? OR id = ?)").get(scope, ref, ref) !== void 0;
6103
+ }
6061
6104
  clearChat(scope) {
6062
6105
  this.db.prepare("DELETE FROM chat_messages WHERE scope = ?").run(scope);
6063
6106
  }
@@ -6715,12 +6758,12 @@ function quoteOf(thread, intro) {
6715
6758
  const text = thread.anchorText?.join("\n") ?? "";
6716
6759
  if (text === "") return intro;
6717
6760
  const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map((run) => run[0].length));
6718
- const fence = "`".repeat(longest + 1);
6761
+ const fence2 = "`".repeat(longest + 1);
6719
6762
  return `${intro}
6720
6763
 
6721
- ${fence}
6764
+ ${fence2}
6722
6765
  ${text}
6723
- ${fence}`;
6766
+ ${fence2}`;
6724
6767
  }
6725
6768
  async function placeOnGitHub(context, files, from, to, thread) {
6726
6769
  const file = thread.detached ? void 0 : findFile(files, thread);
@@ -7035,7 +7078,10 @@ var AGENT_PRESETS = {
7035
7078
  claude: { id: "claude", name: "Claude Code", command: "npx", args: ["-y", "@agentclientprotocol/claude-agent-acp"] },
7036
7079
  codex: { id: "codex", name: "Codex", command: "npx", args: ["-y", "@agentclientprotocol/codex-acp"] },
7037
7080
  gemini: { id: "gemini", name: "Gemini CLI", command: "gemini", args: ["--acp"] },
7038
- opencode: { id: "opencode", name: "OpenCode", command: "opencode", args: ["acp"] }
7081
+ opencode: { id: "opencode", name: "OpenCode", command: "opencode", args: ["acp"] },
7082
+ cursor: { id: "cursor", name: "Cursor", command: "agent", args: ["acp"] },
7083
+ antigravity: { id: "antigravity", name: "Antigravity", command: "agy", args: ["acp"] },
7084
+ copilot: { id: "copilot", name: "GitHub Copilot", command: "copilot", args: ["--acp"] }
7039
7085
  };
7040
7086
  var BUILT_IN_AGENTS = {
7041
7087
  defaultAgent: "claude",
@@ -7352,14 +7398,14 @@ function fenceFor(lines2) {
7352
7398
  return "`".repeat(longest + 1);
7353
7399
  }
7354
7400
  function suggestionComment(rationale, replacement) {
7355
- const fence = fenceFor(replacement);
7401
+ const fence2 = fenceFor(replacement);
7356
7402
  const intro = rationale.trim();
7357
7403
  const content = replacement.length > 0 ? `${replacement.join("\n")}
7358
7404
  ` : "";
7359
7405
  return `${intro ? `${intro}
7360
7406
 
7361
- ` : ""}${fence}suggestion
7362
- ${content}${fence}`;
7407
+ ` : ""}${fence2}suggestion
7408
+ ${content}${fence2}`;
7363
7409
  }
7364
7410
  var sameText = (a, b) => a.replace(/\n$/, "") === b.replace(/\n$/, "");
7365
7411
  function editsFor(currentText, oldText, newText) {
@@ -17622,8 +17668,11 @@ async function runPrompt(options) {
17622
17668
  if (signal.aborted) return { stopReason: "cancelled", text };
17623
17669
  const offered = describeSessionOptions(session);
17624
17670
  options.onSessionOptions?.(offered);
17671
+ const settled = settlePending(options.pending, offered, options.agent.name);
17672
+ for (const problem of settled.problems) options.onOptionProblem?.(problem);
17673
+ const chosen = { ...options.chosen, ...settled.chosen };
17625
17674
  for (const option of offered) {
17626
- const wanted = options.chosen?.[option.id];
17675
+ const wanted = chosen[option.id];
17627
17676
  if (wanted === void 0 || wanted === option.current || !option.values.some((value) => value.id === wanted)) continue;
17628
17677
  const request = option.kind === "mode" ? connection.agent.request(methods.agent.session.setMode, { sessionId: session.sessionId, modeId: wanted }) : connection.agent.request(
17629
17678
  methods.agent.session.setConfigOption,
@@ -17816,6 +17865,30 @@ import { join as join10 } from "node:path";
17816
17865
  var OWN_TOOL_NAMES = AGENT_TOOLS.map((tool) => tool.name);
17817
17866
  var MAX_LISTED_FILES = 200;
17818
17867
  var sideName = (endpoint) => endpoint.kind === "rev" ? `${endpoint.label} (${endpoint.oid.slice(0, 12)})` : endpoint.kind === "index" ? "the staged changes" : "the working tree";
17868
+ var MAX_REVIEW_FINDINGS = 20;
17869
+ var REVIEW_REQUEST = [
17870
+ "Review all the changes of this comparison, file by file. Read each changed file with `get_diff`, and read the code around a change when you need it to judge the change.",
17871
+ "",
17872
+ "Report only real problems: bugs, broken edge cases, security issues, data loss, races, behaviour that contradicts what the change says it does, names or comments that mislead, risky code without a test. Do not comment on formatting or taste, and do not praise.",
17873
+ "",
17874
+ "- For each finding call `add_comment` on the lines it is about, in the new version of the file. Start the comment with its severity in bold (**High**, **Medium** or **Low**), then say what is wrong, why it matters, and what to do.",
17875
+ "- When the fix is short and you are sure of it, call `propose_change` for those lines instead, with the severity and the reason in `rationale`.",
17876
+ `- At most ${MAX_REVIEW_FINDINGS} findings, the most serious first. One finding per problem: do not repeat it for every place it occurs, name the other places in the comment.`,
17877
+ "- Do not repeat what an existing conversation already says.",
17878
+ "",
17879
+ "Your final message is the summary of the review: one line with your overall judgement, then the findings by severity as `path:line` with a few words each, then what you did not look at or could not judge. If you found nothing worth reporting, say so plainly."
17880
+ ];
17881
+ var MAX_NEIGHBOURS = 12;
17882
+ function otherConversations(threads, title) {
17883
+ if (threads.length === 0) return [];
17884
+ const listed = threads.slice(0, MAX_NEIGHBOURS).map((other) => {
17885
+ const where = other.side === "file" ? other.path : `${other.path}:${other.startLine ?? "?"}${other.endLine !== void 0 && other.endLine !== other.startLine ? `-${other.endLine}` : ""}`;
17886
+ const opening = (other.comments[0]?.body ?? "").replace(/\s+/g, " ").trim();
17887
+ return `- ${where} (${other.comments.length} comment${other.comments.length === 1 ? "" : "s"}): ${opening.length > 160 ? `${opening.slice(0, 160)}\u2026` : opening}`;
17888
+ });
17889
+ if (threads.length > MAX_NEIGHBOURS) listed.push(`- \u2026 and ${threads.length - MAX_NEIGHBOURS} more`);
17890
+ return ["", `## ${title}`, "They are context, so that your answer does not contradict or repeat them. Call `list_threads` to read one in full.", ...listed];
17891
+ }
17819
17892
  async function buildPrompt(repo, input, thread, cwdKind) {
17820
17893
  const { comparison } = input;
17821
17894
  const { files, totals } = await listChangedFiles(repo, { from: comparison.diffFrom, to: comparison.diffTo });
@@ -17844,10 +17917,17 @@ async function buildPrompt(repo, input, thread, cwdKind) {
17844
17917
  if (thread.anchorText?.length) parts.push("Commented code:", "```", ...thread.anchorText, "```");
17845
17918
  parts.push("Comments so far:", ...thread.comments.map((comment) => `[${comment.authorKind === "agent" ? "agent" : comment.authorName}]: ${comment.body}`));
17846
17919
  parts.push("", "Your final message is posted as a reply in this conversation.");
17920
+ parts.push(...otherConversations(input.neighbours ?? [], `Other open conversations on ${thread.path}`));
17847
17921
  } else if (input.transcript?.length) {
17848
17922
  parts.push("", "## Earlier in this chat", ...input.transcript.map((message) => `[${message.role === "agent" ? "you" : "developer"}]: ${message.body}`));
17849
17923
  }
17850
- parts.push("", "## Request", input.message);
17924
+ if (!thread) parts.push(...otherConversations(input.neighbours ?? [], "Open review conversations on this comparison"));
17925
+ if (input.review) {
17926
+ parts.push("", "## Request", ...REVIEW_REQUEST);
17927
+ if (input.message.trim() !== "") parts.push("", "What the developer asked you to pay attention to:", input.message);
17928
+ } else {
17929
+ parts.push("", "## Request", input.message);
17930
+ }
17851
17931
  return parts.join("\n");
17852
17932
  }
17853
17933
  var RunFailure = class extends Error {
@@ -17864,15 +17944,15 @@ var RunFailure = class extends Error {
17864
17944
  var MAX_NOTE_LINES = 60;
17865
17945
  function shown(lines2) {
17866
17946
  const part = lines2.slice(0, MAX_NOTE_LINES);
17867
- const fence = fenceFor(part);
17947
+ const fence2 = fenceFor(part);
17868
17948
  const rest = lines2.length > part.length ? `
17869
17949
 
17870
17950
  \u2026 and ${lines2.length - part.length} more lines.` : "";
17871
17951
  return `
17872
17952
 
17873
- ${fence}
17953
+ ${fence2}
17874
17954
  ${part.join("\n")}
17875
- ${fence}${rest}`;
17955
+ ${fence2}${rest}`;
17876
17956
  }
17877
17957
  var asQuote = (note) => note.split("\n").map((line) => line === "" ? ">" : `> ${line}`).join("\n");
17878
17958
  async function executeRun(env, input, signal) {
@@ -17938,6 +18018,7 @@ async function executeRun(env, input, signal) {
17938
18018
  signal,
17939
18019
  startTimeoutMs: env.startTimeoutMs,
17940
18020
  chosen: input.chosen,
18021
+ pending: input.pending,
17941
18022
  onSessionOptions: env.onSessionOptions,
17942
18023
  onCommands: env.onCommands,
17943
18024
  onOptionProblem: (message) => notes.push(message)
@@ -18174,6 +18255,137 @@ async function readFileAt(repo, reader, rev, path) {
18174
18255
  return readBlobText(reader, oid);
18175
18256
  }
18176
18257
 
18258
+ // packages/core/src/reviewFile.ts
18259
+ var MAX_THREADS = 2e3;
18260
+ var MAX_COMMENTS = 200;
18261
+ var MAX_CHAT = 2e3;
18262
+ var MAX_BODY_CHARS = 65536;
18263
+ var sideLabel = (endpoint) => endpoint.kind === "rev" ? endpoint.label : endpoint.kind === "index" ? "staged changes" : "working tree";
18264
+ var sideOid = (endpoint) => endpoint.kind === "rev" ? endpoint.oid : void 0;
18265
+ function exportReview(store, comparison, scope, spec, now = /* @__PURE__ */ new Date()) {
18266
+ const threads = store.list(scope).filter((thread) => !thread.github).map((thread) => ({
18267
+ ref: store.refOf("threads", thread.id),
18268
+ path: thread.path,
18269
+ side: thread.side,
18270
+ startLine: thread.startLine,
18271
+ endLine: thread.endLine,
18272
+ state: thread.state,
18273
+ anchorText: thread.anchorText,
18274
+ createdAt: thread.createdAt,
18275
+ comments: thread.comments.map((comment) => ({
18276
+ ref: store.refOf("comments", comment.id),
18277
+ authorKind: comment.authorKind === "agent" ? "agent" : "user",
18278
+ authorName: comment.authorName,
18279
+ body: comment.body,
18280
+ createdAt: comment.createdAt
18281
+ }))
18282
+ }));
18283
+ return {
18284
+ format: "agentic-diff-review",
18285
+ version: 1,
18286
+ exportedAt: now.toISOString(),
18287
+ comparison: { spec, base: sideLabel(comparison.base), head: sideLabel(comparison.head), baseOid: sideOid(comparison.base), headOid: sideOid(comparison.head) },
18288
+ threads,
18289
+ chat: store.chatMessages(scope).map((message) => ({ ref: store.refOf("chat_messages", message.id), role: message.role, body: message.body, createdAt: message.createdAt }))
18290
+ };
18291
+ }
18292
+ var isText = (value, max = MAX_BODY_CHARS) => typeof value === "string" && value.length <= max;
18293
+ var isRef2 = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value);
18294
+ var isLine = (value) => value === void 0 || Number.isInteger(value) && value > 0;
18295
+ var dateOf = (value) => {
18296
+ const date2 = new Date(typeof value === "string" ? value : NaN);
18297
+ return Number.isNaN(date2.getTime()) ? /* @__PURE__ */ new Date() : date2;
18298
+ };
18299
+ function parseReviewFile(value) {
18300
+ const bad = (what) => {
18301
+ throw new AppError("invalid_review_file", `This is not a review file that agentic-diff can read: ${what}.`);
18302
+ };
18303
+ const file = value;
18304
+ if (typeof file !== "object" || file === null || file.format !== "agentic-diff-review") return bad("it does not say it is one");
18305
+ if (file.version !== 1) return bad(`it is of version ${String(file.version)}, and this agentic-diff knows version 1; update agentic-diff`);
18306
+ if (typeof file.comparison !== "object" || file.comparison === null || !isText(file.comparison.spec, 1e3)) return bad("it does not name a comparison");
18307
+ if (!Array.isArray(file.threads) || file.threads.length > MAX_THREADS) return bad("its list of conversations is missing or too long");
18308
+ if (!Array.isArray(file.chat) || file.chat.length > MAX_CHAT) return bad("its chat is missing or too long");
18309
+ for (const thread of file.threads) {
18310
+ const comments = thread.comments;
18311
+ const ok = isRef2(thread.ref) && isText(thread.path, 4096) && (thread.side === "L" || thread.side === "R" || thread.side === "file") && isLine(thread.startLine) && isLine(thread.endLine) && (thread.state === "open" || thread.state === "resolved") && (thread.anchorText === void 0 || Array.isArray(thread.anchorText) && thread.anchorText.length <= 5e3 && thread.anchorText.every((line) => isText(line, 2e4))) && Array.isArray(comments) && comments.length > 0 && comments.length <= MAX_COMMENTS && comments.every(
18312
+ (comment) => isRef2(comment.ref) && (comment.authorKind === "user" || comment.authorKind === "agent") && isText(comment.authorName, 200) && isText(comment.body)
18313
+ );
18314
+ if (!ok) return bad("one of its conversations is not in the expected form");
18315
+ }
18316
+ for (const message of file.chat) {
18317
+ if (!isRef2(message.ref) || message.role !== "user" && message.role !== "agent" || !isText(message.body)) return bad("one of its chat messages is not in the expected form");
18318
+ }
18319
+ return file;
18320
+ }
18321
+ function locate(lines2, wanted, hint) {
18322
+ if (wanted.length === 0) return void 0;
18323
+ const at = (start2) => wanted.every((line, index) => lines2[start2 - 1 + index] === line);
18324
+ if (hint !== void 0 && at(hint)) return hint;
18325
+ const found = [];
18326
+ for (let start2 = 1; start2 + wanted.length - 1 <= lines2.length && found.length < 2; start2 += 1) if (at(start2)) found.push(start2);
18327
+ return found.length === 1 ? found[0] : void 0;
18328
+ }
18329
+ var fence = (lines2) => "`".repeat(Math.max(3, ...lines2.map((line) => (/`+/.exec(line)?.[0].length ?? 0) + 1)));
18330
+ async function importReview(repo, store, reader, target, file) {
18331
+ const result = { threadsAdded: 0, commentsAdded: 0, chatAdded: 0, movedToFile: 0, skipped: [] };
18332
+ const { files } = await listChangedFiles(repo, { from: target.from, to: target.to });
18333
+ for (const thread of file.threads) {
18334
+ let existing = store.threadByRef(target.scope, thread.ref);
18335
+ const [first, ...rest] = thread.comments;
18336
+ let pending = thread.comments;
18337
+ if (!existing) {
18338
+ const changed = findFile(files, thread);
18339
+ if (!changed) {
18340
+ result.skipped.push({ path: thread.path, reason: "the file is not part of this comparison here" });
18341
+ continue;
18342
+ }
18343
+ const startedAt = dateOf(thread.createdAt);
18344
+ const author = { authorKind: first.authorKind, authorName: first.authorName };
18345
+ const content = thread.side === "file" ? void 0 : await sideContent(repo, reader, changed, thread.side, target.to);
18346
+ const start2 = content && thread.anchorText ? locate(content.lines, thread.anchorText, thread.startLine) : void 0;
18347
+ if (thread.side !== "file" && content && start2 !== void 0 && thread.anchorText) {
18348
+ const anchor2 = snapshotAnchor(content.lines, start2, start2 + thread.anchorText.length - 1);
18349
+ await keepVersion(repo, content);
18350
+ existing = store.createThread({ scope: target.scope, path: pathOn(changed, thread.side), side: thread.side, anchorOid: content.oid, anchor: anchor2 }, { ...author, body: first.body }, startedAt);
18351
+ } else {
18352
+ const quoted = thread.side !== "file" && thread.anchorText?.length ? `> Written on lines ${thread.startLine ?? "?"}\u2013${thread.endLine ?? "?"} of another version of this file:
18353
+
18354
+ ${fence(thread.anchorText)}
18355
+ ${thread.anchorText.join("\n")}
18356
+ ${fence(thread.anchorText)}
18357
+
18358
+ ` : "";
18359
+ existing = store.createThread({ scope: target.scope, path: changed.path, side: "file" }, { ...author, body: `${quoted}${first.body}` }, startedAt);
18360
+ if (thread.side !== "file") result.movedToFile += 1;
18361
+ }
18362
+ store.setRef("threads", existing.id, thread.ref);
18363
+ store.setRef("comments", existing.comments[0].id, first.ref);
18364
+ result.threadsAdded += 1;
18365
+ result.commentsAdded += 1;
18366
+ pending = rest;
18367
+ }
18368
+ for (const comment of pending) {
18369
+ if (store.hasComment(existing.id, comment.ref)) continue;
18370
+ const updated = store.addComment(existing.id, { authorKind: comment.authorKind, authorName: comment.authorName, body: comment.body }, dateOf(comment.createdAt));
18371
+ store.setRef("comments", updated.comments.at(-1).id, comment.ref);
18372
+ result.commentsAdded += 1;
18373
+ }
18374
+ const inFile = new Set(thread.comments.map((comment) => comment.ref));
18375
+ const current = store.get(existing.id);
18376
+ if (thread.state === "resolved" && current.state !== "resolved" && current.comments.every((comment) => inFile.has(store.refOf("comments", comment.id)))) {
18377
+ store.setState(existing.id, "resolved");
18378
+ }
18379
+ }
18380
+ for (const message of file.chat) {
18381
+ if (store.hasChatMessage(target.scope, message.ref)) continue;
18382
+ const added = store.addChatMessage(target.scope, message.role, message.body, dateOf(message.createdAt));
18383
+ store.setRef("chat_messages", added.id, message.ref);
18384
+ result.chatAdded += 1;
18385
+ }
18386
+ return result;
18387
+ }
18388
+
18177
18389
  // packages/core/src/home/auth.ts
18178
18390
  import { createHmac, randomBytes as randomBytes4, timingSafeEqual } from "node:crypto";
18179
18391
  var LOGIN_TTL_MS = 6e4;
@@ -18385,6 +18597,15 @@ var MIGRATIONS = [
18385
18597
  ALTER TABLE threads ADD COLUMN base_start INTEGER;
18386
18598
  ALTER TABLE threads ADD COLUMN base_end INTEGER;
18387
18599
  `
18600
+ },
18601
+ {
18602
+ version: 6,
18603
+ name: "review files: what a conversation, a comment or a chat message is called in the file it came from",
18604
+ sql: `
18605
+ ALTER TABLE threads ADD COLUMN import_ref TEXT;
18606
+ ALTER TABLE comments ADD COLUMN import_ref TEXT;
18607
+ ALTER TABLE chat_messages ADD COLUMN import_ref TEXT;
18608
+ `
18388
18609
  }
18389
18610
  ];
18390
18611
 
@@ -18504,7 +18725,10 @@ var AgentRuns = class {
18504
18725
  }
18505
18726
  async start(repo, request) {
18506
18727
  const { home } = this.options;
18507
- if (typeof request.message !== "string" || request.message.trim() === "") throw new AppError("invalid_request", "A message for the agent is required");
18728
+ const review = request.review === true;
18729
+ if (review && request.message === void 0) request.message = "";
18730
+ if (typeof request.message !== "string" || !review && request.message.trim() === "") throw new AppError("invalid_request", "A message for the agent is required");
18731
+ if (review && typeof request.threadId === "string") throw new AppError("invalid_request", "A review of the whole comparison is not started from a conversation");
18508
18732
  if (request.message.length > MAX_MESSAGE_CHARS) throw new AppError("invalid_request", "This message is too long", 413);
18509
18733
  if (findRegisteredRepo(home, repo.id)?.untrusted) {
18510
18734
  throw new AppError("untrusted_repo", "This repository was cloned from a link. Confirm that you trust it before an agent runs in it.", 409);
@@ -18541,7 +18765,11 @@ var AgentRuns = class {
18541
18765
  const { store } = await this.options.store(repo);
18542
18766
  if (threadId) store.get(threadId);
18543
18767
  const transcript = threadId ? void 0 : store.chatMessages(scope);
18544
- if (!threadId) store.addChatMessage(scope, "user", request.message);
18768
+ const asked = threadId ? store.get(threadId) : void 0;
18769
+ const neighbours = store.list(scope).filter((other) => other.state === "open" && other.id !== threadId && (!asked || other.path === asked.path)).map(publicThread);
18770
+ if (!threadId) store.addChatMessage(scope, "user", review ? `Review all changes${request.message.trim() === "" ? "" : `
18771
+
18772
+ ${request.message}`}` : request.message);
18545
18773
  const run = {
18546
18774
  repo,
18547
18775
  token: randomBytes5(24).toString("hex"),
@@ -18563,7 +18791,7 @@ var AgentRuns = class {
18563
18791
  };
18564
18792
  this.runs.set(run.info.id, run);
18565
18793
  this.forget();
18566
- const message = call.message || "Please look at this conversation and the code it is about, and give your view.";
18794
+ const message = review ? call.message : call.message || "Please look at this conversation and the code it is about, and give your view.";
18567
18795
  run.finished = (async () => {
18568
18796
  try {
18569
18797
  const result = await executeRun(
@@ -18591,7 +18819,7 @@ var AgentRuns = class {
18591
18819
  onCommands: (commands) => rememberAgentCommands(home, agent.id, commands),
18592
18820
  startTimeoutMs: this.options.startTimeoutMs
18593
18821
  },
18594
- { runId: run.info.id, agent, comparison, scope, message, threadId, transcript, isolated, chosen: { ...chosenOptions(home, agent.id), ...call.options }, allowWeb: call.web, notes: call.problems },
18822
+ { runId: run.info.id, agent, comparison, scope, message, threadId, transcript, isolated, chosen: { ...chosenOptions(home, agent.id), ...call.options }, allowWeb: call.web, notes: call.problems, neighbours, review, pending: call.pending },
18595
18823
  run.controller.signal
18596
18824
  );
18597
18825
  run.snapshot = result.snapshot;
@@ -18961,6 +19189,23 @@ async function handleThreads(req, res, url2, context, repo, rest) {
18961
19189
  }
18962
19190
  return false;
18963
19191
  }
19192
+ if (rest === "/review") {
19193
+ const spec = method === "GET" ? stringParam(url2.searchParams.get("spec"), "spec") : void 0;
19194
+ if (method === "GET" && spec !== void 0) {
19195
+ const comparison = await resolveComparison(repo, parseSpec(spec));
19196
+ sendJson(res, 200, exportReview(store, comparison, threadScope(comparison), spec));
19197
+ return true;
19198
+ }
19199
+ if (method === "POST") {
19200
+ const body = await readJsonBody(req);
19201
+ const comparison = await resolveComparison(repo, parseSpec(stringParam(body.spec, "spec")));
19202
+ const imported = await importReview(repo, store, blobReader(context, repo), { scope: threadScope(comparison), from: comparison.diffFrom, to: comparison.diffTo }, parseReviewFile(body.review));
19203
+ announce(context, repo, "threads");
19204
+ sendJson(res, 200, imported);
19205
+ return true;
19206
+ }
19207
+ return false;
19208
+ }
18964
19209
  if (method === "POST" && rest === "/threads/sync") {
18965
19210
  const body = await readJsonBody(req);
18966
19211
  const threads = await syncThreads(repo, store, blobReader(context, repo), scopeIn(repo, body.scope), stringParam(body.from, "from"), stringParam(body.to, "to"));
@@ -19251,6 +19496,20 @@ async function handleApi(req, res, url2, context) {
19251
19496
  sendJson(res, 200, { repoId: repo.id, path: comparePath(repo.id, formatSpec(parsed)) });
19252
19497
  return;
19253
19498
  }
19499
+ if (method === "POST" && path === "/api/control/import-review") {
19500
+ requireControl(req, context);
19501
+ const body = await readJsonBody(req);
19502
+ const review = parseReviewFile(body.review);
19503
+ const repo = rememberRepo(context, await openRepo(stringParam(body.cwd, "cwd")));
19504
+ registerRepo(context.options.home, repo, { remotes: await repoRemoteKeys(repo) });
19505
+ const parsed = parseSpec(review.comparison.spec);
19506
+ const comparison = await resolveComparison(repo, parsed);
19507
+ const { store } = await threadStore(context, repo);
19508
+ const imported = await importReview(repo, store, blobReader(context, repo), { scope: threadScope(comparison), from: comparison.diffFrom, to: comparison.diffTo }, review);
19509
+ announce(context, repo, "threads");
19510
+ sendJson(res, 200, { repoId: repo.id, path: comparePath(repo.id, formatSpec(parsed)), imported });
19511
+ return;
19512
+ }
19254
19513
  if (method === "POST" && path === "/api/control/stop") {
19255
19514
  requireControl(req, context);
19256
19515
  sendJson(res, 200, { stopping: true });
@@ -19342,7 +19601,7 @@ async function handleApi(req, res, url2, context) {
19342
19601
  const repo = await repoById(context, repoMatch[1]);
19343
19602
  if (await handleViewed(req, res, url2, context, repo)) return;
19344
19603
  }
19345
- if (repoMatch && /^\/(?:threads|comments|drafts)(?:\/|$)/.test(repoMatch[2] ?? "")) {
19604
+ if (repoMatch && /^\/(?:threads|comments|drafts|review)(?:\/|$)/.test(repoMatch[2] ?? "")) {
19346
19605
  requireSession(req, context);
19347
19606
  const repo = await repoById(context, repoMatch[1]);
19348
19607
  if (await handleThreads(req, res, url2, context, repo, repoMatch[2])) return;
@@ -19593,7 +19852,7 @@ import { dirname as dirname7, join as join15 } from "node:path";
19593
19852
  import { fileURLToPath } from "node:url";
19594
19853
 
19595
19854
  // packages/cli/src/version.ts
19596
- var VERSION = true ? "0.1.2" : "0.0.0-dev";
19855
+ var VERSION = true ? "0.1.4" : "0.0.0-dev";
19597
19856
 
19598
19857
  // packages/cli/src/daemon.ts
19599
19858
  var CLI_FILE = fileURLToPath(import.meta.url);
@@ -19872,6 +20131,7 @@ var USAGE = `agentic-diff ${VERSION}
19872
20131
  Usage:
19873
20132
  agentic-diff [path] [comparison] open a comparison in the browser
19874
20133
  agentic-diff open <link> open a shared link or a GitHub compare / pull request URL
20134
+ agentic-diff open <review.json> add an exported review to the same comparison of this repository
19875
20135
  agentic-diff stop stop the background server
19876
20136
  agentic-diff doctor [--agents] check the environment; with --agents also start each configured agent
19877
20137
 
@@ -19897,6 +20157,13 @@ function isDirectory(path) {
19897
20157
  return false;
19898
20158
  }
19899
20159
  }
20160
+ function isFile2(path) {
20161
+ try {
20162
+ return statSync4(path).isFile();
20163
+ } catch {
20164
+ return false;
20165
+ }
20166
+ }
19900
20167
  function openInBrowser(url2) {
19901
20168
  const [command, args] = process.platform === "darwin" ? ["open", [url2]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url2]] : ["xdg-open", [url2]];
19902
20169
  const child = spawn4(command, args, { detached: true, stdio: "ignore" });
@@ -19934,8 +20201,25 @@ function show(home, url2, open3) {
19934
20201
  console.log("The sign-in part of this link works once and expires in a minute.");
19935
20202
  }
19936
20203
  }
20204
+ async function commandOpenReview(home, file, options) {
20205
+ let review;
20206
+ try {
20207
+ review = JSON.parse(readFileSync6(file, "utf8"));
20208
+ } catch (error2) {
20209
+ throw new Error(`Cannot read ${file} as a review file: ${error2 instanceof Error ? error2.message : "it is not JSON"}`);
20210
+ }
20211
+ await requireGit();
20212
+ const port = await ensureDaemon(home, options.port);
20213
+ const opened = await controlCall(home, port, "/api/control/import-review", { cwd: resolve2(options.repo ?? process.cwd()), review });
20214
+ const { imported } = opened;
20215
+ console.log(`Added ${imported.threadsAdded} conversation(s), ${imported.commentsAdded} comment(s) and ${imported.chatAdded} chat message(s).`);
20216
+ if (imported.movedToFile > 0) console.log(`${imported.movedToFile} conversation(s) could not be put on their lines (the code here differs) and are attached to their files.`);
20217
+ for (const skipped of imported.skipped) console.log(`Skipped a conversation on ${skipped.path}: ${skipped.reason}.`);
20218
+ show(home, `${baseUrl(port)}${opened.path}`, options.open);
20219
+ }
19937
20220
  async function commandOpenLink(home, input, options) {
19938
- if (!input) throw new Error("Usage: agentic-diff open <link>");
20221
+ if (!input) throw new Error("Usage: agentic-diff open <link or review file>");
20222
+ if (/\.json$/i.test(input) && isFile2(input)) return commandOpenReview(home, input, options);
19939
20223
  parseShareInput(input);
19940
20224
  await requireGit();
19941
20225
  const port = await ensureDaemon(home, options.port);
@@ -19984,7 +20268,7 @@ async function main() {
19984
20268
  case "doctor":
19985
20269
  return await runDoctor(home, { startAgents: values.agents }) ? 0 : 1;
19986
20270
  case "open":
19987
- await commandOpenLink(home, rest[0], { port, open: !values["no-open"] });
20271
+ await commandOpenLink(home, rest[0], { repo: values.repo, port, open: !values["no-open"] });
19988
20272
  return 0;
19989
20273
  case "mcp":
19990
20274
  await runMcpProxy(mcpOptionsFromEnv(process.env, VERSION));