agentic-diff 0.1.1 → 0.1.3

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
 
@@ -4382,8 +4382,8 @@ function suggestionBlocks(body) {
4382
4382
  continue;
4383
4383
  }
4384
4384
  const indent = open3[1].length;
4385
- const fence = open3[2];
4386
- const close = new RegExp(`^ {0,3}${fence[0] === "`" ? "`" : "~"}{${fence.length},}\\s*$`);
4385
+ const fence2 = open3[2];
4386
+ const close = new RegExp(`^ {0,3}${fence2[0] === "`" ? "`" : "~"}{${fence2.length},}\\s*$`);
4387
4387
  const unindent = new RegExp(`^ {0,${indent}}`);
4388
4388
  const content = [];
4389
4389
  let j = i + 1;
@@ -6058,6 +6058,28 @@ var ThreadStore = class {
6058
6058
  createdAt: row.created_at
6059
6059
  }));
6060
6060
  }
6061
+ /**
6062
+ * The name a conversation, a comment or a chat message has in review files: the one it arrived under, or its
6063
+ * own id when it was written here. It stays the same however often the file travels back and forth.
6064
+ */
6065
+ refOf(table, id) {
6066
+ const row = this.db.prepare(`SELECT import_ref FROM ${table} WHERE id = ?`).get(id);
6067
+ return row?.import_ref ?? id;
6068
+ }
6069
+ setRef(table, id, ref) {
6070
+ this.db.prepare(`UPDATE ${table} SET import_ref = ? WHERE id = ?`).run(ref, id);
6071
+ }
6072
+ /** The conversation of a scope that a review file calls `ref`. */
6073
+ threadByRef(scope, ref) {
6074
+ const row = this.db.prepare("SELECT id FROM threads WHERE scope = ? AND (import_ref = ? OR id = ?)").get(scope, ref, ref);
6075
+ return row ? this.get(row.id) : void 0;
6076
+ }
6077
+ hasComment(threadId, ref) {
6078
+ return this.db.prepare("SELECT 1 FROM comments WHERE thread_id = ? AND (import_ref = ? OR id = ?)").get(threadId, ref, ref) !== void 0;
6079
+ }
6080
+ hasChatMessage(scope, ref) {
6081
+ return this.db.prepare("SELECT 1 FROM chat_messages WHERE scope = ? AND (import_ref = ? OR id = ?)").get(scope, ref, ref) !== void 0;
6082
+ }
6061
6083
  clearChat(scope) {
6062
6084
  this.db.prepare("DELETE FROM chat_messages WHERE scope = ?").run(scope);
6063
6085
  }
@@ -6715,12 +6737,12 @@ function quoteOf(thread, intro) {
6715
6737
  const text = thread.anchorText?.join("\n") ?? "";
6716
6738
  if (text === "") return intro;
6717
6739
  const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map((run) => run[0].length));
6718
- const fence = "`".repeat(longest + 1);
6740
+ const fence2 = "`".repeat(longest + 1);
6719
6741
  return `${intro}
6720
6742
 
6721
- ${fence}
6743
+ ${fence2}
6722
6744
  ${text}
6723
- ${fence}`;
6745
+ ${fence2}`;
6724
6746
  }
6725
6747
  async function placeOnGitHub(context, files, from, to, thread) {
6726
6748
  const file = thread.detached ? void 0 : findFile(files, thread);
@@ -7035,7 +7057,10 @@ var AGENT_PRESETS = {
7035
7057
  claude: { id: "claude", name: "Claude Code", command: "npx", args: ["-y", "@agentclientprotocol/claude-agent-acp"] },
7036
7058
  codex: { id: "codex", name: "Codex", command: "npx", args: ["-y", "@agentclientprotocol/codex-acp"] },
7037
7059
  gemini: { id: "gemini", name: "Gemini CLI", command: "gemini", args: ["--acp"] },
7038
- opencode: { id: "opencode", name: "OpenCode", command: "opencode", args: ["acp"] }
7060
+ opencode: { id: "opencode", name: "OpenCode", command: "opencode", args: ["acp"] },
7061
+ cursor: { id: "cursor", name: "Cursor", command: "agent", args: ["acp"] },
7062
+ antigravity: { id: "antigravity", name: "Antigravity", command: "agy", args: ["acp"] },
7063
+ copilot: { id: "copilot", name: "GitHub Copilot", command: "copilot", args: ["--acp"] }
7039
7064
  };
7040
7065
  var BUILT_IN_AGENTS = {
7041
7066
  defaultAgent: "claude",
@@ -7352,14 +7377,14 @@ function fenceFor(lines2) {
7352
7377
  return "`".repeat(longest + 1);
7353
7378
  }
7354
7379
  function suggestionComment(rationale, replacement) {
7355
- const fence = fenceFor(replacement);
7380
+ const fence2 = fenceFor(replacement);
7356
7381
  const intro = rationale.trim();
7357
7382
  const content = replacement.length > 0 ? `${replacement.join("\n")}
7358
7383
  ` : "";
7359
7384
  return `${intro ? `${intro}
7360
7385
 
7361
- ` : ""}${fence}suggestion
7362
- ${content}${fence}`;
7386
+ ` : ""}${fence2}suggestion
7387
+ ${content}${fence2}`;
7363
7388
  }
7364
7389
  var sameText = (a, b) => a.replace(/\n$/, "") === b.replace(/\n$/, "");
7365
7390
  function editsFor(currentText, oldText, newText) {
@@ -11349,8 +11374,8 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
11349
11374
  });
11350
11375
  defineLazyInternal(inst, "pattern", (zod) => {
11351
11376
  if (zod.def.options.every((o) => o._zod.pattern)) {
11352
- const patterns2 = zod.def.options.map((o) => o._zod.pattern);
11353
- return new RegExp(`^(${patterns2.map((p) => cleanRegex(p.source)).join("|")})$`);
11377
+ const patterns = zod.def.options.map((o) => o._zod.pattern);
11378
+ return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
11354
11379
  }
11355
11380
  return void 0;
11356
11381
  });
@@ -13553,7 +13578,7 @@ var exactPattern = (p) => exactPatterns.get(p) ?? p;
13553
13578
  var stringProcessor = (schema, ctx, _json, _params) => {
13554
13579
  const json = _json;
13555
13580
  json.type = "string";
13556
- const { minimum, maximum, format, patterns: patterns2, contentEncoding, laxFormat } = aggregateChecks(schema);
13581
+ const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);
13557
13582
  if (typeof minimum === "number")
13558
13583
  json.minLength = minimum;
13559
13584
  if (typeof maximum === "number")
@@ -13568,8 +13593,8 @@ var stringProcessor = (schema, ctx, _json, _params) => {
13568
13593
  }
13569
13594
  if (contentEncoding)
13570
13595
  json.contentEncoding = contentEncoding;
13571
- if (patterns2 && patterns2.size > 0) {
13572
- const patternList = [...patterns2].map(exactPattern);
13596
+ if (patterns && patterns.size > 0) {
13597
+ const patternList = [...patterns].map(exactPattern);
13573
13598
  if (patternList.length === 1)
13574
13599
  json.pattern = patternList[0].source;
13575
13600
  else if (patternList.length > 1) {
@@ -13861,14 +13886,14 @@ var recordProcessor = (schema, ctx, _json, params) => {
13861
13886
  const def = schema._zod.def;
13862
13887
  json.type = "object";
13863
13888
  const keyType = def.keyType;
13864
- const patterns2 = aggregateChecks(keyType).patterns;
13865
- if (def.mode === "loose" && patterns2 && patterns2.size > 0) {
13889
+ const patterns = aggregateChecks(keyType).patterns;
13890
+ if (def.mode === "loose" && patterns && patterns.size > 0) {
13866
13891
  const valueSchema = processSchema(def.valueType, ctx, {
13867
13892
  ...params,
13868
13893
  path: [...params.path, "patternProperties", "*"]
13869
13894
  });
13870
13895
  json.patternProperties = {};
13871
- for (const pattern of patterns2) {
13896
+ for (const pattern of patterns) {
13872
13897
  assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);
13873
13898
  }
13874
13899
  } else {
@@ -17816,6 +17841,17 @@ import { join as join10 } from "node:path";
17816
17841
  var OWN_TOOL_NAMES = AGENT_TOOLS.map((tool) => tool.name);
17817
17842
  var MAX_LISTED_FILES = 200;
17818
17843
  var sideName = (endpoint) => endpoint.kind === "rev" ? `${endpoint.label} (${endpoint.oid.slice(0, 12)})` : endpoint.kind === "index" ? "the staged changes" : "the working tree";
17844
+ var MAX_NEIGHBOURS = 12;
17845
+ function otherConversations(threads, title) {
17846
+ if (threads.length === 0) return [];
17847
+ const listed = threads.slice(0, MAX_NEIGHBOURS).map((other) => {
17848
+ const where = other.side === "file" ? other.path : `${other.path}:${other.startLine ?? "?"}${other.endLine !== void 0 && other.endLine !== other.startLine ? `-${other.endLine}` : ""}`;
17849
+ const opening = (other.comments[0]?.body ?? "").replace(/\s+/g, " ").trim();
17850
+ return `- ${where} (${other.comments.length} comment${other.comments.length === 1 ? "" : "s"}): ${opening.length > 160 ? `${opening.slice(0, 160)}\u2026` : opening}`;
17851
+ });
17852
+ if (threads.length > MAX_NEIGHBOURS) listed.push(`- \u2026 and ${threads.length - MAX_NEIGHBOURS} more`);
17853
+ return ["", `## ${title}`, "They are context, so that your answer does not contradict or repeat them. Call `list_threads` to read one in full.", ...listed];
17854
+ }
17819
17855
  async function buildPrompt(repo, input, thread, cwdKind) {
17820
17856
  const { comparison } = input;
17821
17857
  const { files, totals } = await listChangedFiles(repo, { from: comparison.diffFrom, to: comparison.diffTo });
@@ -17844,9 +17880,11 @@ async function buildPrompt(repo, input, thread, cwdKind) {
17844
17880
  if (thread.anchorText?.length) parts.push("Commented code:", "```", ...thread.anchorText, "```");
17845
17881
  parts.push("Comments so far:", ...thread.comments.map((comment) => `[${comment.authorKind === "agent" ? "agent" : comment.authorName}]: ${comment.body}`));
17846
17882
  parts.push("", "Your final message is posted as a reply in this conversation.");
17883
+ parts.push(...otherConversations(input.neighbours ?? [], `Other open conversations on ${thread.path}`));
17847
17884
  } else if (input.transcript?.length) {
17848
17885
  parts.push("", "## Earlier in this chat", ...input.transcript.map((message) => `[${message.role === "agent" ? "you" : "developer"}]: ${message.body}`));
17849
17886
  }
17887
+ if (!thread) parts.push(...otherConversations(input.neighbours ?? [], "Open review conversations on this comparison"));
17850
17888
  parts.push("", "## Request", input.message);
17851
17889
  return parts.join("\n");
17852
17890
  }
@@ -17864,15 +17902,15 @@ var RunFailure = class extends Error {
17864
17902
  var MAX_NOTE_LINES = 60;
17865
17903
  function shown(lines2) {
17866
17904
  const part = lines2.slice(0, MAX_NOTE_LINES);
17867
- const fence = fenceFor(part);
17905
+ const fence2 = fenceFor(part);
17868
17906
  const rest = lines2.length > part.length ? `
17869
17907
 
17870
17908
  \u2026 and ${lines2.length - part.length} more lines.` : "";
17871
17909
  return `
17872
17910
 
17873
- ${fence}
17911
+ ${fence2}
17874
17912
  ${part.join("\n")}
17875
- ${fence}${rest}`;
17913
+ ${fence2}${rest}`;
17876
17914
  }
17877
17915
  var asQuote = (note) => note.split("\n").map((line) => line === "" ? ">" : `> ${line}`).join("\n");
17878
17916
  async function executeRun(env, input, signal) {
@@ -18108,35 +18146,31 @@ async function undoChange(repo, store, changeId) {
18108
18146
  }
18109
18147
 
18110
18148
  // packages/core/src/symbols.ts
18111
- var KEYWORDS = "function\\*?|def|class|interface|type|enum|struct|trait|fn|func|const|let|var|val|module|impl|record|object|namespace|defn?|sub|proc";
18149
+ var KEYWORDS = "function\\*?|def|class|interface|type|enum|struct|trait|fn|fun|func|const|let|var|val|module|impl|record|object|namespace|protocol|extension|defn?|sub|proc";
18112
18150
  var WORD = "A-Za-z0-9_$";
18151
+ var SOURCE_EXTENSIONS = "js jsx mjs cjs ts tsx mts cts vue svelte py pyi rb php go rs java kt kts scala groovy swift m mm c h cc cpp cxx hpp hh cs fs dart ex exs erl clj cljs lua pl pm r jl sh bash zsh ps1 sql ds isml".split(" ");
18152
+ var SOURCE_PATHS = [...SOURCE_EXTENSIONS.map((extension2) => `*.${extension2}`), ":(exclude)*.min.js", ":(exclude)*.d.ts", ":(exclude)**/node_modules/**", ":(exclude)**/vendor/**", ":(exclude)**/dist/**"];
18153
+ var SEARCH_TIMEOUT_MS = 3e4;
18113
18154
  var MAX_HITS = 200;
18114
18155
  var MAX_LINE_CHARS = 240;
18115
- var escapeEre = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
18116
- function patterns(name) {
18117
- return [
18118
- // "function name", "class Name", "def name", "const name" …
18119
- `(^|[^${WORD}])(${KEYWORDS})[[:space:]]+${name}([^${WORD}]|$)`,
18120
- // "name = function", "name: (a) =>", "name = async (" …
18121
- `(^|[^${WORD}.])${name}[[:space:]]*[:=][[:space:]]*(async[[:space:]]+)?(function|\\()`,
18122
- // Go methods: "func (r *T) name("
18123
- `func[[:space:]]+\\([^)]*\\)[[:space:]]+${name}[[:space:]]*\\(`,
18124
- // Methods in a class body: "name(args) {", "async name(", "public static name("
18125
- `^[[:space:]]+((public|private|protected|static|async|override|readonly|get|set)[[:space:]]+)*${name}[[:space:]]*\\([^;]*\\)[[:space:]]*(:[^;{]*)?\\{[[:space:]]*$`
18126
- ];
18127
- }
18128
18156
  var NAME_AFTER_KEYWORD = new RegExp(`(?:^|[^${WORD}])(${KEYWORDS})\\s+([A-Za-z_$][${WORD}]*)`);
18129
- var NAME_ASSIGNED = new RegExp(`([A-Za-z_$][${WORD}]*)\\s*[:=]\\s*(?:async\\s+)?(?:function|\\()`);
18157
+ var NAME_ASSIGNED = new RegExp(`(?:^|[^${WORD}.])([A-Za-z_$][${WORD}]*)\\s*=\\s*(?:async\\s+)?(?:function\\b|\\()`);
18158
+ var PROPERTY = new RegExp(`^\\s*([A-Za-z_$][${WORD}]*)\\s*:\\s*(?:async\\s+)?(?:function\\b|\\([^)]*\\)\\s*(?::[^=]*)?=>)`);
18130
18159
  var GO_METHOD = new RegExp(`func\\s+\\([^)]*\\)\\s+([A-Za-z_$][${WORD}]*)\\s*\\(`);
18131
- var METHOD = new RegExp(`^\\s+(?:(?:public|private|protected|static|async|override|readonly|get|set)\\s+)*([A-Za-z_$][${WORD}]*)\\s*\\(`);
18160
+ var METHOD = new RegExp(`^\\s+(?:(?:public|private|protected|static|async|override|readonly|get|set)\\s+)*([A-Za-z_$][${WORD}]*)\\s*\\([^;]*\\)\\s*(?::[^;{]*)?\\{\\s*$`);
18161
+ var TYPED = new RegExp(`^\\s*((?:[A-Za-z_][${WORD}<>,.:*&?\\s\\[\\]]*?))[\\s*&]+(?:[A-Za-z_][${WORD}]*::)?([A-Za-z_$][${WORD}]*)\\s*\\([^;]*$`);
18162
+ var NOT_TYPES = /(^|\s)(return|else|new|await|throw|case|typeof|delete|yield|in|of|if|while|for|switch|do|and|or|not|print|import|from|export\s+default|goto|using|echo)$/;
18132
18163
  var NOT_NAMES = /* @__PURE__ */ new Set(["if", "for", "while", "switch", "catch", "return", "function", "else", "do", "try", "with", "new", "await", "typeof"]);
18133
18164
  function describe3(text, wanted) {
18134
18165
  const candidates = [
18135
18166
  { name: GO_METHOD.exec(text)?.[1], kind: "method" },
18136
18167
  { name: NAME_AFTER_KEYWORD.exec(text)?.[2], kind: (NAME_AFTER_KEYWORD.exec(text)?.[1] ?? "").replace("*", "") },
18137
18168
  { name: NAME_ASSIGNED.exec(text)?.[1], kind: "function" },
18169
+ { name: PROPERTY.exec(text)?.[1], kind: "property" },
18138
18170
  { name: METHOD.exec(text)?.[1], kind: "method" }
18139
18171
  ];
18172
+ const typed = TYPED.exec(text);
18173
+ if (typed && typed[1] !== void 0 && !NOT_TYPES.test(typed[1].trim()) && !new RegExp(`^(${KEYWORDS})$`).test(typed[1].trim())) candidates.push({ name: typed[2], kind: "function" });
18140
18174
  const found = candidates.filter((candidate) => candidate.name !== void 0 && !NOT_NAMES.has(candidate.name));
18141
18175
  return found.find((candidate) => wanted(candidate.name));
18142
18176
  }
@@ -18145,13 +18179,9 @@ async function findSymbols(repo, { rev, query, exact = false }) {
18145
18179
  throw new AppError("invalid_request", exact ? "That is not a name" : "Type at least two letters of a name");
18146
18180
  }
18147
18181
  if (rev !== WORKTREE && rev !== STAGED && !/^[0-9a-f]{40,64}$/.test(rev)) throw new AppError("invalid_request", '"rev" must be a commit id, :worktree or :staged');
18148
- const name = exact ? escapeEre(query) : `[${WORD}]*${escapeEre(query)}[${WORD}]*`;
18149
- const args = ["grep", "-n", "-z", "-I", "-E", "--no-color", "--full-name", ...exact ? [] : ["-i"]];
18150
- for (const pattern of patterns(name)) args.push("-e", pattern);
18151
- if (rev === STAGED) args.push("--cached");
18152
- else if (rev !== WORKTREE) args.push(rev);
18153
- args.push("--");
18154
- const { stdout } = await runGit(args, { cwd: repo.root, allowExitCodes: [1], timeoutMs: 15e3 });
18182
+ const where = rev === STAGED ? ["--cached"] : rev === WORKTREE ? [] : [rev];
18183
+ const options = { cwd: repo.root, allowExitCodes: [1], timeoutMs: SEARCH_TIMEOUT_MS };
18184
+ const { stdout } = await runGit(["grep", "-n", "-z", "-I", "-F", "--no-color", "--full-name", ...exact ? ["-w"] : ["-i"], "-e", query, ...where, "--", ...SOURCE_PATHS], options);
18155
18185
  const lower = query.toLowerCase();
18156
18186
  const wanted = (candidate) => exact ? candidate === query : candidate.toLowerCase().includes(lower);
18157
18187
  const hits = [];
@@ -18159,12 +18189,16 @@ async function findSymbols(repo, { rev, query, exact = false }) {
18159
18189
  const [file, lineText, ...rest] = record2.split("\0");
18160
18190
  if (file === void 0 || lineText === void 0 || rest.length === 0) continue;
18161
18191
  const text = rest.join("\0");
18192
+ if (/^\s*(\/\/|\/\*|\*|#|--|<!--)/.test(text)) continue;
18162
18193
  const found = describe3(text, wanted);
18163
18194
  if (!found) continue;
18195
+ const local = /^(const|let|var|val)$/.test(found.kind) && /^\s/.test(text) && !/[:=]\s*(async\s+)?(function\b|\([^)]*\)\s*(:[^=]*)?=>|[A-Za-z_$][\w$]*\s*=>)/.test(text);
18196
+ if (local && !exact) continue;
18164
18197
  const path = rev !== WORKTREE && rev !== STAGED && file.startsWith(`${rev}:`) ? file.slice(rev.length + 1) : file;
18165
18198
  hits.push({ path, line: Number(lineText), text: text.trim().slice(0, MAX_LINE_CHARS), ...found });
18166
18199
  }
18167
- const rank = (hit) => (hit.name.toLowerCase() === lower ? 0 : hit.name.toLowerCase().startsWith(lower) ? 1 : 2) + (/(^|\/)(tests?|e2e|__tests__|fixtures?)\//.test(hit.path) || /\.(test|spec)\./.test(hit.path) ? 0.5 : 0);
18200
+ const rank = (hit) => (hit.name.toLowerCase() === lower ? 0 : hit.name.toLowerCase().startsWith(lower) ? 1 : 2) + // A property that holds a function is a definition of sorts, but rarely the one that was meant.
18201
+ (hit.kind === "property" ? 3 : 0) + (/(^|\/)(tests?|e2e|__tests__|fixtures?)\//.test(hit.path) || /\.(test|spec)\./.test(hit.path) ? 0.5 : 0);
18168
18202
  hits.sort((a, b) => rank(a) - rank(b) || a.path.localeCompare(b.path) || a.line - b.line);
18169
18203
  return { hits: hits.slice(0, MAX_HITS), truncated: hits.length > MAX_HITS };
18170
18204
  }
@@ -18178,6 +18212,137 @@ async function readFileAt(repo, reader, rev, path) {
18178
18212
  return readBlobText(reader, oid);
18179
18213
  }
18180
18214
 
18215
+ // packages/core/src/reviewFile.ts
18216
+ var MAX_THREADS = 2e3;
18217
+ var MAX_COMMENTS = 200;
18218
+ var MAX_CHAT = 2e3;
18219
+ var MAX_BODY_CHARS = 65536;
18220
+ var sideLabel = (endpoint) => endpoint.kind === "rev" ? endpoint.label : endpoint.kind === "index" ? "staged changes" : "working tree";
18221
+ var sideOid = (endpoint) => endpoint.kind === "rev" ? endpoint.oid : void 0;
18222
+ function exportReview(store, comparison, scope, spec, now = /* @__PURE__ */ new Date()) {
18223
+ const threads = store.list(scope).filter((thread) => !thread.github).map((thread) => ({
18224
+ ref: store.refOf("threads", thread.id),
18225
+ path: thread.path,
18226
+ side: thread.side,
18227
+ startLine: thread.startLine,
18228
+ endLine: thread.endLine,
18229
+ state: thread.state,
18230
+ anchorText: thread.anchorText,
18231
+ createdAt: thread.createdAt,
18232
+ comments: thread.comments.map((comment) => ({
18233
+ ref: store.refOf("comments", comment.id),
18234
+ authorKind: comment.authorKind === "agent" ? "agent" : "user",
18235
+ authorName: comment.authorName,
18236
+ body: comment.body,
18237
+ createdAt: comment.createdAt
18238
+ }))
18239
+ }));
18240
+ return {
18241
+ format: "agentic-diff-review",
18242
+ version: 1,
18243
+ exportedAt: now.toISOString(),
18244
+ comparison: { spec, base: sideLabel(comparison.base), head: sideLabel(comparison.head), baseOid: sideOid(comparison.base), headOid: sideOid(comparison.head) },
18245
+ threads,
18246
+ chat: store.chatMessages(scope).map((message) => ({ ref: store.refOf("chat_messages", message.id), role: message.role, body: message.body, createdAt: message.createdAt }))
18247
+ };
18248
+ }
18249
+ var isText = (value, max = MAX_BODY_CHARS) => typeof value === "string" && value.length <= max;
18250
+ var isRef2 = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value);
18251
+ var isLine = (value) => value === void 0 || Number.isInteger(value) && value > 0;
18252
+ var dateOf = (value) => {
18253
+ const date2 = new Date(typeof value === "string" ? value : NaN);
18254
+ return Number.isNaN(date2.getTime()) ? /* @__PURE__ */ new Date() : date2;
18255
+ };
18256
+ function parseReviewFile(value) {
18257
+ const bad = (what) => {
18258
+ throw new AppError("invalid_review_file", `This is not a review file that agentic-diff can read: ${what}.`);
18259
+ };
18260
+ const file = value;
18261
+ if (typeof file !== "object" || file === null || file.format !== "agentic-diff-review") return bad("it does not say it is one");
18262
+ if (file.version !== 1) return bad(`it is of version ${String(file.version)}, and this agentic-diff knows version 1; update agentic-diff`);
18263
+ if (typeof file.comparison !== "object" || file.comparison === null || !isText(file.comparison.spec, 1e3)) return bad("it does not name a comparison");
18264
+ if (!Array.isArray(file.threads) || file.threads.length > MAX_THREADS) return bad("its list of conversations is missing or too long");
18265
+ if (!Array.isArray(file.chat) || file.chat.length > MAX_CHAT) return bad("its chat is missing or too long");
18266
+ for (const thread of file.threads) {
18267
+ const comments = thread.comments;
18268
+ 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(
18269
+ (comment) => isRef2(comment.ref) && (comment.authorKind === "user" || comment.authorKind === "agent") && isText(comment.authorName, 200) && isText(comment.body)
18270
+ );
18271
+ if (!ok) return bad("one of its conversations is not in the expected form");
18272
+ }
18273
+ for (const message of file.chat) {
18274
+ 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");
18275
+ }
18276
+ return file;
18277
+ }
18278
+ function locate(lines2, wanted, hint) {
18279
+ if (wanted.length === 0) return void 0;
18280
+ const at = (start2) => wanted.every((line, index) => lines2[start2 - 1 + index] === line);
18281
+ if (hint !== void 0 && at(hint)) return hint;
18282
+ const found = [];
18283
+ for (let start2 = 1; start2 + wanted.length - 1 <= lines2.length && found.length < 2; start2 += 1) if (at(start2)) found.push(start2);
18284
+ return found.length === 1 ? found[0] : void 0;
18285
+ }
18286
+ var fence = (lines2) => "`".repeat(Math.max(3, ...lines2.map((line) => (/`+/.exec(line)?.[0].length ?? 0) + 1)));
18287
+ async function importReview(repo, store, reader, target, file) {
18288
+ const result = { threadsAdded: 0, commentsAdded: 0, chatAdded: 0, movedToFile: 0, skipped: [] };
18289
+ const { files } = await listChangedFiles(repo, { from: target.from, to: target.to });
18290
+ for (const thread of file.threads) {
18291
+ let existing = store.threadByRef(target.scope, thread.ref);
18292
+ const [first, ...rest] = thread.comments;
18293
+ let pending = thread.comments;
18294
+ if (!existing) {
18295
+ const changed = findFile(files, thread);
18296
+ if (!changed) {
18297
+ result.skipped.push({ path: thread.path, reason: "the file is not part of this comparison here" });
18298
+ continue;
18299
+ }
18300
+ const startedAt = dateOf(thread.createdAt);
18301
+ const author = { authorKind: first.authorKind, authorName: first.authorName };
18302
+ const content = thread.side === "file" ? void 0 : await sideContent(repo, reader, changed, thread.side, target.to);
18303
+ const start2 = content && thread.anchorText ? locate(content.lines, thread.anchorText, thread.startLine) : void 0;
18304
+ if (thread.side !== "file" && content && start2 !== void 0 && thread.anchorText) {
18305
+ const anchor2 = snapshotAnchor(content.lines, start2, start2 + thread.anchorText.length - 1);
18306
+ await keepVersion(repo, content);
18307
+ existing = store.createThread({ scope: target.scope, path: pathOn(changed, thread.side), side: thread.side, anchorOid: content.oid, anchor: anchor2 }, { ...author, body: first.body }, startedAt);
18308
+ } else {
18309
+ const quoted = thread.side !== "file" && thread.anchorText?.length ? `> Written on lines ${thread.startLine ?? "?"}\u2013${thread.endLine ?? "?"} of another version of this file:
18310
+
18311
+ ${fence(thread.anchorText)}
18312
+ ${thread.anchorText.join("\n")}
18313
+ ${fence(thread.anchorText)}
18314
+
18315
+ ` : "";
18316
+ existing = store.createThread({ scope: target.scope, path: changed.path, side: "file" }, { ...author, body: `${quoted}${first.body}` }, startedAt);
18317
+ if (thread.side !== "file") result.movedToFile += 1;
18318
+ }
18319
+ store.setRef("threads", existing.id, thread.ref);
18320
+ store.setRef("comments", existing.comments[0].id, first.ref);
18321
+ result.threadsAdded += 1;
18322
+ result.commentsAdded += 1;
18323
+ pending = rest;
18324
+ }
18325
+ for (const comment of pending) {
18326
+ if (store.hasComment(existing.id, comment.ref)) continue;
18327
+ const updated = store.addComment(existing.id, { authorKind: comment.authorKind, authorName: comment.authorName, body: comment.body }, dateOf(comment.createdAt));
18328
+ store.setRef("comments", updated.comments.at(-1).id, comment.ref);
18329
+ result.commentsAdded += 1;
18330
+ }
18331
+ const inFile = new Set(thread.comments.map((comment) => comment.ref));
18332
+ const current = store.get(existing.id);
18333
+ if (thread.state === "resolved" && current.state !== "resolved" && current.comments.every((comment) => inFile.has(store.refOf("comments", comment.id)))) {
18334
+ store.setState(existing.id, "resolved");
18335
+ }
18336
+ }
18337
+ for (const message of file.chat) {
18338
+ if (store.hasChatMessage(target.scope, message.ref)) continue;
18339
+ const added = store.addChatMessage(target.scope, message.role, message.body, dateOf(message.createdAt));
18340
+ store.setRef("chat_messages", added.id, message.ref);
18341
+ result.chatAdded += 1;
18342
+ }
18343
+ return result;
18344
+ }
18345
+
18181
18346
  // packages/core/src/home/auth.ts
18182
18347
  import { createHmac, randomBytes as randomBytes4, timingSafeEqual } from "node:crypto";
18183
18348
  var LOGIN_TTL_MS = 6e4;
@@ -18389,6 +18554,15 @@ var MIGRATIONS = [
18389
18554
  ALTER TABLE threads ADD COLUMN base_start INTEGER;
18390
18555
  ALTER TABLE threads ADD COLUMN base_end INTEGER;
18391
18556
  `
18557
+ },
18558
+ {
18559
+ version: 6,
18560
+ name: "review files: what a conversation, a comment or a chat message is called in the file it came from",
18561
+ sql: `
18562
+ ALTER TABLE threads ADD COLUMN import_ref TEXT;
18563
+ ALTER TABLE comments ADD COLUMN import_ref TEXT;
18564
+ ALTER TABLE chat_messages ADD COLUMN import_ref TEXT;
18565
+ `
18392
18566
  }
18393
18567
  ];
18394
18568
 
@@ -18545,6 +18719,8 @@ var AgentRuns = class {
18545
18719
  const { store } = await this.options.store(repo);
18546
18720
  if (threadId) store.get(threadId);
18547
18721
  const transcript = threadId ? void 0 : store.chatMessages(scope);
18722
+ const asked = threadId ? store.get(threadId) : void 0;
18723
+ const neighbours = store.list(scope).filter((other) => other.state === "open" && other.id !== threadId && (!asked || other.path === asked.path)).map(publicThread);
18548
18724
  if (!threadId) store.addChatMessage(scope, "user", request.message);
18549
18725
  const run = {
18550
18726
  repo,
@@ -18595,7 +18771,7 @@ var AgentRuns = class {
18595
18771
  onCommands: (commands) => rememberAgentCommands(home, agent.id, commands),
18596
18772
  startTimeoutMs: this.options.startTimeoutMs
18597
18773
  },
18598
- { runId: run.info.id, agent, comparison, scope, message, threadId, transcript, isolated, chosen: { ...chosenOptions(home, agent.id), ...call.options }, allowWeb: call.web, notes: call.problems },
18774
+ { 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 },
18599
18775
  run.controller.signal
18600
18776
  );
18601
18777
  run.snapshot = result.snapshot;
@@ -18965,6 +19141,23 @@ async function handleThreads(req, res, url2, context, repo, rest) {
18965
19141
  }
18966
19142
  return false;
18967
19143
  }
19144
+ if (rest === "/review") {
19145
+ const spec = method === "GET" ? stringParam(url2.searchParams.get("spec"), "spec") : void 0;
19146
+ if (method === "GET" && spec !== void 0) {
19147
+ const comparison = await resolveComparison(repo, parseSpec(spec));
19148
+ sendJson(res, 200, exportReview(store, comparison, threadScope(comparison), spec));
19149
+ return true;
19150
+ }
19151
+ if (method === "POST") {
19152
+ const body = await readJsonBody(req);
19153
+ const comparison = await resolveComparison(repo, parseSpec(stringParam(body.spec, "spec")));
19154
+ const imported = await importReview(repo, store, blobReader(context, repo), { scope: threadScope(comparison), from: comparison.diffFrom, to: comparison.diffTo }, parseReviewFile(body.review));
19155
+ announce(context, repo, "threads");
19156
+ sendJson(res, 200, imported);
19157
+ return true;
19158
+ }
19159
+ return false;
19160
+ }
18968
19161
  if (method === "POST" && rest === "/threads/sync") {
18969
19162
  const body = await readJsonBody(req);
18970
19163
  const threads = await syncThreads(repo, store, blobReader(context, repo), scopeIn(repo, body.scope), stringParam(body.from, "from"), stringParam(body.to, "to"));
@@ -19255,6 +19448,20 @@ async function handleApi(req, res, url2, context) {
19255
19448
  sendJson(res, 200, { repoId: repo.id, path: comparePath(repo.id, formatSpec(parsed)) });
19256
19449
  return;
19257
19450
  }
19451
+ if (method === "POST" && path === "/api/control/import-review") {
19452
+ requireControl(req, context);
19453
+ const body = await readJsonBody(req);
19454
+ const review = parseReviewFile(body.review);
19455
+ const repo = rememberRepo(context, await openRepo(stringParam(body.cwd, "cwd")));
19456
+ registerRepo(context.options.home, repo, { remotes: await repoRemoteKeys(repo) });
19457
+ const parsed = parseSpec(review.comparison.spec);
19458
+ const comparison = await resolveComparison(repo, parsed);
19459
+ const { store } = await threadStore(context, repo);
19460
+ const imported = await importReview(repo, store, blobReader(context, repo), { scope: threadScope(comparison), from: comparison.diffFrom, to: comparison.diffTo }, review);
19461
+ announce(context, repo, "threads");
19462
+ sendJson(res, 200, { repoId: repo.id, path: comparePath(repo.id, formatSpec(parsed)), imported });
19463
+ return;
19464
+ }
19258
19465
  if (method === "POST" && path === "/api/control/stop") {
19259
19466
  requireControl(req, context);
19260
19467
  sendJson(res, 200, { stopping: true });
@@ -19346,7 +19553,7 @@ async function handleApi(req, res, url2, context) {
19346
19553
  const repo = await repoById(context, repoMatch[1]);
19347
19554
  if (await handleViewed(req, res, url2, context, repo)) return;
19348
19555
  }
19349
- if (repoMatch && /^\/(?:threads|comments|drafts)(?:\/|$)/.test(repoMatch[2] ?? "")) {
19556
+ if (repoMatch && /^\/(?:threads|comments|drafts|review)(?:\/|$)/.test(repoMatch[2] ?? "")) {
19350
19557
  requireSession(req, context);
19351
19558
  const repo = await repoById(context, repoMatch[1]);
19352
19559
  if (await handleThreads(req, res, url2, context, repo, repoMatch[2])) return;
@@ -19597,7 +19804,7 @@ import { dirname as dirname7, join as join15 } from "node:path";
19597
19804
  import { fileURLToPath } from "node:url";
19598
19805
 
19599
19806
  // packages/cli/src/version.ts
19600
- var VERSION = true ? "0.1.1" : "0.0.0-dev";
19807
+ var VERSION = true ? "0.1.3" : "0.0.0-dev";
19601
19808
 
19602
19809
  // packages/cli/src/daemon.ts
19603
19810
  var CLI_FILE = fileURLToPath(import.meta.url);
@@ -19876,6 +20083,7 @@ var USAGE = `agentic-diff ${VERSION}
19876
20083
  Usage:
19877
20084
  agentic-diff [path] [comparison] open a comparison in the browser
19878
20085
  agentic-diff open <link> open a shared link or a GitHub compare / pull request URL
20086
+ agentic-diff open <review.json> add an exported review to the same comparison of this repository
19879
20087
  agentic-diff stop stop the background server
19880
20088
  agentic-diff doctor [--agents] check the environment; with --agents also start each configured agent
19881
20089
 
@@ -19901,6 +20109,13 @@ function isDirectory(path) {
19901
20109
  return false;
19902
20110
  }
19903
20111
  }
20112
+ function isFile2(path) {
20113
+ try {
20114
+ return statSync4(path).isFile();
20115
+ } catch {
20116
+ return false;
20117
+ }
20118
+ }
19904
20119
  function openInBrowser(url2) {
19905
20120
  const [command, args] = process.platform === "darwin" ? ["open", [url2]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url2]] : ["xdg-open", [url2]];
19906
20121
  const child = spawn4(command, args, { detached: true, stdio: "ignore" });
@@ -19938,8 +20153,25 @@ function show(home, url2, open3) {
19938
20153
  console.log("The sign-in part of this link works once and expires in a minute.");
19939
20154
  }
19940
20155
  }
20156
+ async function commandOpenReview(home, file, options) {
20157
+ let review;
20158
+ try {
20159
+ review = JSON.parse(readFileSync6(file, "utf8"));
20160
+ } catch (error2) {
20161
+ throw new Error(`Cannot read ${file} as a review file: ${error2 instanceof Error ? error2.message : "it is not JSON"}`);
20162
+ }
20163
+ await requireGit();
20164
+ const port = await ensureDaemon(home, options.port);
20165
+ const opened = await controlCall(home, port, "/api/control/import-review", { cwd: resolve2(options.repo ?? process.cwd()), review });
20166
+ const { imported } = opened;
20167
+ console.log(`Added ${imported.threadsAdded} conversation(s), ${imported.commentsAdded} comment(s) and ${imported.chatAdded} chat message(s).`);
20168
+ 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.`);
20169
+ for (const skipped of imported.skipped) console.log(`Skipped a conversation on ${skipped.path}: ${skipped.reason}.`);
20170
+ show(home, `${baseUrl(port)}${opened.path}`, options.open);
20171
+ }
19941
20172
  async function commandOpenLink(home, input, options) {
19942
- if (!input) throw new Error("Usage: agentic-diff open <link>");
20173
+ if (!input) throw new Error("Usage: agentic-diff open <link or review file>");
20174
+ if (/\.json$/i.test(input) && isFile2(input)) return commandOpenReview(home, input, options);
19943
20175
  parseShareInput(input);
19944
20176
  await requireGit();
19945
20177
  const port = await ensureDaemon(home, options.port);
@@ -19988,7 +20220,7 @@ async function main() {
19988
20220
  case "doctor":
19989
20221
  return await runDoctor(home, { startAgents: values.agents }) ? 0 : 1;
19990
20222
  case "open":
19991
- await commandOpenLink(home, rest[0], { port, open: !values["no-open"] });
20223
+ await commandOpenLink(home, rest[0], { repo: values.repo, port, open: !values["no-open"] });
19992
20224
  return 0;
19993
20225
  case "mcp":
19994
20226
  await runMcpProxy(mcpOptionsFromEnv(process.env, VERSION));