From 9e94a3806c050aab24d35c6f80ebb130d8c9129d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 7 Aug 2025 15:40:14 -0700 Subject: [PATCH 01/29] feat: add utils for model-specific logic --- core/nextEdit/templating/model1.ts | 88 ++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 core/nextEdit/templating/model1.ts diff --git a/core/nextEdit/templating/model1.ts b/core/nextEdit/templating/model1.ts new file mode 100644 index 000000000..84a754efd --- /dev/null +++ b/core/nextEdit/templating/model1.ts @@ -0,0 +1,88 @@ +import { Position, Range } from "../.."; +import { + MODEL_1_CONTEXT_FILE_TOKEN, + MODEL_1_EDITABLE_REGION_END_TOKEN, + MODEL_1_EDITABLE_REGION_START_TOKEN, + MODEL_1_SNIPPET_TOKEN, + MODEL_1_USER_CURSOR_IS_HERE_TOKEN, +} from "../constants"; +import { extractMetadataFromUnifiedDiff } from "../context/diffFormatting"; +import { insertCursorToken } from "./utils"; + +export function recentlyViewedCodeSnippetsBlock( + recentlyViewedCodeSnippets: { filepath: string; content: string }[], +) { + return recentlyViewedCodeSnippets.reduce((acc, snippet, i) => { + const block = [ + `${MODEL_1_CONTEXT_FILE_TOKEN}: ${snippet.filepath}`, + `${MODEL_1_SNIPPET_TOKEN}\n${snippet.content}`, + ].join("\n"); + + return ( + acc + block + (i === recentlyViewedCodeSnippets.length - 1 ? "" : "\n") + ); + }, ""); +} + +export function currentFileContentBlock( + currentFileContent: string, + editableRegionStartLine: number, + editableRegionEndLine: number, + cursorPosition: Position, +) { + const currentFileContentLines = currentFileContent.split("\n"); + + const insertedCursorLines = insertCursorToken( + currentFileContentLines, + cursorPosition, + MODEL_1_USER_CURSOR_IS_HERE_TOKEN, + ); + + const instrumentedLines = [ + ...insertedCursorLines.slice(0, editableRegionStartLine), + MODEL_1_EDITABLE_REGION_START_TOKEN, + ...insertedCursorLines.slice( + editableRegionStartLine, + editableRegionEndLine + 1, + ), + MODEL_1_EDITABLE_REGION_END_TOKEN, + ...insertedCursorLines.slice(editableRegionEndLine + 1), + ]; + + return instrumentedLines.join("\n"); +} + +export function editHistoryBlock( + editDiffHistories: string[], // list of unified diffs +) { + // diffHistory is made from createDiff. + // This uses createPatch from npm diff library, which includes an index line and a separator. + // We get rid of these first two lines. + const block: string[] = []; + + editDiffHistories.forEach((diff) => { + const metadata = extractMetadataFromUnifiedDiff(diff); + block.push( + [ + `User edited file \"${metadata.oldFilename}\"`, + "", + "```diff", + `${diff.split("\n").slice(2).join("\n")}`, + "```", + ].join("\n"), + ); + }); + + return block.join("\n"); +} + +function mercuryNextEditTemplateBuilder( + recentlyViewedCodeSnippets: { filepath: string; code: string }[], + currentFileContent: string, + codeToEdit: string, + codeToEditRange: Range, + cursorPosition: Position, + editDiffHistory: string, // could be a singe large unified diff +): string { + return ""; +} From 326785f0226ff7fc338d9b2d98d957ac288052d5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 7 Aug 2025 15:40:24 -0700 Subject: [PATCH 02/29] feat: add tokens --- core/nextEdit/constants.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index 153563d11..1c94db662 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -6,6 +6,8 @@ export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5; export const MODEL_1_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>"; export const MODEL_1_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; export const MODEL_1_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; +export const MODEL_1_CONTEXT_FILE_TOKEN = "<|context_file|>"; +export const MODEL_1_SNIPPET_TOKEN = "<|snippet|>"; // Mercury Coder Next Edit-specific tokens. export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN = From eae28a87c1e8adc073eab88eb9b28d1d5fa167a2 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 7 Aug 2025 15:40:34 -0700 Subject: [PATCH 03/29] feat: add more to context --- core/nextEdit/NextEditProvider.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 0b97c4491..825515225 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -545,9 +545,17 @@ export class NextEditProvider { }; } else if (modelName.includes("model-1")) { ctx = { - userEdits: historyDiff ?? this.diffContext, + recentlyViewedCodeSnippets: + snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ + filepath: snip.filepath, + content: snip.content, + })) ?? [], + currentFileContent: helper.fileContents, + editableRegionStartLine, + editableRegionEndLine, + editDiffHistory: this.diffContext, + currentFilePath: helper.filepath, languageShorthand: helper.lang.name, - userExcerpts: helper.fileContents, }; } else { ctx = {}; From a736bcce0eabc5c2595dea1564260e2eb1805ec8 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 7 Aug 2025 15:40:48 -0700 Subject: [PATCH 04/29] feat: add more fields to template --- core/nextEdit/types.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 49a4c0862..2b9d3162c 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -91,9 +91,11 @@ export interface NextEditTemplate { export interface TemplateVars {} export interface Model1TemplateVars extends TemplateVars { - userEdits: string; + recentlyViewedCodeSnippets: string; + currentFileContent: string; + editDiffHistory: string; // could be a singe large unified diff + currentFilePath: string; languageShorthand: string; - userExcerpts: string; } export interface MercuryTemplateVars extends TemplateVars { From 55f081c2061f37122425a7e79abda53413adc377 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 7 Aug 2025 15:41:17 -0700 Subject: [PATCH 05/29] feat: edit template --- core/nextEdit/templating/NextEditPromptEngine.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 24f16e681..2c9235eb0 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -44,7 +44,7 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { }, "model-1": { template: - "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```", + "### User Edits:\n\n{{{editDiffHistory}}}\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{currentFileContent}}}```\n### Response:", }, "this field is not used": { template: "NEXT_EDIT", @@ -142,9 +142,18 @@ export async function renderPrompt( ); const model1Ctx: Model1TemplateVars = { - userEdits: ctx.userEdits, + recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( + ctx.recentlyViewedCodeSnippets, + ), + currentFileContent: currentFileContentBlock( + ctx.currentFileContent, + ctx.editableRegionStartLine, + ctx.editableRegionEndLine, + helper.pos, + ), + editDiffHistory: editHistoryBlock(ctx.editDiffHistory), + currentFilePath: ctx.currentFilePath, languageShorthand: ctx.languageShorthand, - userExcerpts: ctx.userExcerpts, }; tv = model1Ctx; From 1c41a7fd7027a42f4205aa974a0009928081513d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 10:28:18 -0700 Subject: [PATCH 06/29] feat: keep track of autocomplete context --- core/nextEdit/NextEditProvider.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 825515225..78690f200 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -59,6 +59,8 @@ import { PromptMetadata, RecentlyEditedRange, } from "./types.js"; +import { getAutocompleteContext } from "./context/autocompleteContextFetching.js"; +import { EditAggregator } from "./context/aggregateEdits.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -82,6 +84,7 @@ export class NextEditProvider { private contextRetrievalService: ContextRetrievalService; private endpointType: "default" | "fineTuned"; private diffContext: string = ""; + private autocompleteContext: string = ""; private promptMetadata: PromptMetadata | null = null; private currentEditChainId: string | null = null; private previousRequest: AutocompleteInput | null = null; @@ -136,6 +139,10 @@ export class NextEditProvider { this.diffContext = diff; } + public addAutocompleteContext(ctx: string): void { + this.autocompleteContext = ctx; + } + private async _prepareLlm(): Promise { const llm = await this._injectedGetLlm(); @@ -545,11 +552,7 @@ export class NextEditProvider { }; } else if (modelName.includes("model-1")) { ctx = { - recentlyViewedCodeSnippets: - snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ - filepath: snip.filepath, - content: snip.content, - })) ?? [], + contextSnippets: this.autocompleteContext, currentFileContent: helper.fileContents, editableRegionStartLine, editableRegionEndLine, From 92f60e2d15b7a0c5a1855a0d153db067f9ab7107 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 10:29:05 -0700 Subject: [PATCH 07/29] feat: add to autocomplete context on small edit --- core/nextEdit/context/processNextEditData.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/nextEdit/context/processNextEditData.ts b/core/nextEdit/context/processNextEditData.ts index aaa89d33a..0cecfe33e 100644 --- a/core/nextEdit/context/processNextEditData.ts +++ b/core/nextEdit/context/processNextEditData.ts @@ -3,6 +3,7 @@ import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types"; import { GetLspDefinitionsFunction } from "../../autocomplete/types"; import { ConfigHandler } from "../../config/ConfigHandler"; import { DataLogger } from "../../data/log"; +import { NextEditProvider } from "../NextEditProvider"; import { RecentlyEditedRange } from "../types"; import { getAutocompleteContext } from "./autocompleteContextFetching"; import { createDiff, DiffFormatType } from "./diffFormatting"; @@ -75,6 +76,8 @@ export const processNextEditData = async ({ modelName, ); + NextEditProvider.getInstance().addAutocompleteContext(autocompleteContext); + // console.log( // createDiff(beforeContent, afterContent, filePath, DiffFormatType.Unified), // ); From db87e89126882f7df5d60214b9ed01ad4d950655 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 10:30:01 -0700 Subject: [PATCH 08/29] feat: use contextSnippets instead of recentlyViewedCodeSnippets --- core/nextEdit/templating/NextEditPromptEngine.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 2c9235eb0..00e573646 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -30,6 +30,7 @@ import { insertCursorToken, insertEditableRegionTokensWithStaticRange, } from "./utils"; +import { contextSnippetsBlock } from "./model1"; type TemplateRenderer = (vars: TemplateVars) => string; @@ -142,9 +143,7 @@ export async function renderPrompt( ); const model1Ctx: Model1TemplateVars = { - recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( - ctx.recentlyViewedCodeSnippets, - ), + contextSnippets: contextSnippetsBlock(ctx.contextSnippets), currentFileContent: currentFileContentBlock( ctx.currentFileContent, ctx.editableRegionStartLine, From b4c7df46cdff342bda5dcfcb0b7f865fd0511ff9 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 10:30:30 -0700 Subject: [PATCH 09/29] feat: replace field --- core/nextEdit/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 2b9d3162c..4c50e0291 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -91,7 +91,7 @@ export interface NextEditTemplate { export interface TemplateVars {} export interface Model1TemplateVars extends TemplateVars { - recentlyViewedCodeSnippets: string; + contextSnippets: string; currentFileContent: string; editDiffHistory: string; // could be a singe large unified diff currentFilePath: string; From 534e4531848f94518bbe9b0ea8cff10de8bdb781 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 10:31:28 -0700 Subject: [PATCH 10/29] feat: add a helper function to parse contextSnippets --- core/nextEdit/templating/model1.ts | 49 ++++++++++++++++-------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/core/nextEdit/templating/model1.ts b/core/nextEdit/templating/model1.ts index 84a754efd..3248d6a05 100644 --- a/core/nextEdit/templating/model1.ts +++ b/core/nextEdit/templating/model1.ts @@ -9,19 +9,33 @@ import { import { extractMetadataFromUnifiedDiff } from "../context/diffFormatting"; import { insertCursorToken } from "./utils"; -export function recentlyViewedCodeSnippetsBlock( - recentlyViewedCodeSnippets: { filepath: string; content: string }[], -) { - return recentlyViewedCodeSnippets.reduce((acc, snippet, i) => { - const block = [ - `${MODEL_1_CONTEXT_FILE_TOKEN}: ${snippet.filepath}`, - `${MODEL_1_SNIPPET_TOKEN}\n${snippet.content}`, - ].join("\n"); +/** + * @param contextSnippets Codestral style snippet with +++++ filename\ncontent or an empty string. + */ +export function contextSnippetsBlock(contextSnippets: string) { + const headerRegex = /^(\+\+\+\+\+ )(.*)/g; + const lines = contextSnippets.split("\n"); - return ( - acc + block + (i === recentlyViewedCodeSnippets.length - 1 ? "" : "\n") - ); - }, ""); + return lines + .reduce((acc, line) => { + const matches = line.match(headerRegex); + if (matches) { + acc.push("\n"); + const filename = matches[2]; + acc.push(`${MODEL_1_CONTEXT_FILE_TOKEN}: ${filename}`); + } else { + if ( + acc.length > 0 && + acc[acc.length - 1].match(headerRegex) // if header was added just before + ) { + acc.push(`${MODEL_1_SNIPPET_TOKEN}`); + } + acc.push(line); + } + + return acc; + }, []) + .join("\n"); } export function currentFileContentBlock( @@ -75,14 +89,3 @@ export function editHistoryBlock( return block.join("\n"); } - -function mercuryNextEditTemplateBuilder( - recentlyViewedCodeSnippets: { filepath: string; code: string }[], - currentFileContent: string, - codeToEdit: string, - codeToEditRange: Range, - cursorPosition: Position, - editDiffHistory: string, // could be a singe large unified diff -): string { - return ""; -} From faa6c0f6c52f36f9fb4b99193d91a0c69d479bee Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:04:56 -0700 Subject: [PATCH 11/29] test: add vitest for helper functions --- core/nextEdit/templating/model1.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/core/nextEdit/templating/model1.ts b/core/nextEdit/templating/model1.ts index 3248d6a05..3a7a617c0 100644 --- a/core/nextEdit/templating/model1.ts +++ b/core/nextEdit/templating/model1.ts @@ -1,4 +1,4 @@ -import { Position, Range } from "../.."; +import { Position } from "../.."; import { MODEL_1_CONTEXT_FILE_TOKEN, MODEL_1_EDITABLE_REGION_END_TOKEN, @@ -13,20 +13,19 @@ import { insertCursorToken } from "./utils"; * @param contextSnippets Codestral style snippet with +++++ filename\ncontent or an empty string. */ export function contextSnippetsBlock(contextSnippets: string) { - const headerRegex = /^(\+\+\+\+\+ )(.*)/g; + const headerRegex = /^(\+\+\+\+\+ )(.*)/; const lines = contextSnippets.split("\n"); return lines .reduce((acc, line) => { const matches = line.match(headerRegex); if (matches) { - acc.push("\n"); const filename = matches[2]; acc.push(`${MODEL_1_CONTEXT_FILE_TOKEN}: ${filename}`); } else { if ( acc.length > 0 && - acc[acc.length - 1].match(headerRegex) // if header was added just before + acc[acc.length - 1].startsWith(MODEL_1_CONTEXT_FILE_TOKEN) // if header was added just before ) { acc.push(`${MODEL_1_SNIPPET_TOKEN}`); } @@ -75,13 +74,14 @@ export function editHistoryBlock( const block: string[] = []; editDiffHistories.forEach((diff) => { - const metadata = extractMetadataFromUnifiedDiff(diff); + const diffWithoutHeader = diff.split("\n").slice(2).join("\n"); + const metadata = extractMetadataFromUnifiedDiff(diffWithoutHeader); block.push( [ `User edited file \"${metadata.oldFilename}\"`, "", "```diff", - `${diff.split("\n").slice(2).join("\n")}`, + `${diffWithoutHeader}`, "```", ].join("\n"), ); From 9652276380fd79a2109c558c48ef4db8523e79f3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:05:13 -0700 Subject: [PATCH 12/29] feat: add helper for diffFormatting --- .continue/rules/comment-periods.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .continue/rules/comment-periods.md diff --git a/.continue/rules/comment-periods.md b/.continue/rules/comment-periods.md new file mode 100644 index 000000000..bfbcc0ae1 --- /dev/null +++ b/.continue/rules/comment-periods.md @@ -0,0 +1,5 @@ +--- +alwaysApply: true +--- + +End your comments with a period. From 5e38626a3419d4bcb38df5504f53a2558d0ba287 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:05:26 -0700 Subject: [PATCH 13/29] test: add vitest for templating --- core/nextEdit/templating/model1.vitest.ts | 402 ++++++++++++++++++++++ 1 file changed, 402 insertions(+) create mode 100644 core/nextEdit/templating/model1.vitest.ts diff --git a/core/nextEdit/templating/model1.vitest.ts b/core/nextEdit/templating/model1.vitest.ts new file mode 100644 index 000000000..3facc6f6d --- /dev/null +++ b/core/nextEdit/templating/model1.vitest.ts @@ -0,0 +1,402 @@ +import { describe, expect, test } from "vitest"; +import { Position } from "../.."; +import { + contextSnippetsBlock, + currentFileContentBlock, + editHistoryBlock, +} from "./model1"; + +describe("contextSnippetsBlock", () => { + test("should format empty context snippets", () => { + const result = contextSnippetsBlock(""); + expect(result).toBe(""); + }); + + test("should format single context snippet with codestral style header", () => { + const input = `+++++ src/utils.ts +function helper() { + return "test"; +}`; + + const expected = `<|context_file|>: src/utils.ts +<|snippet|> +function helper() { + return "test"; +}`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); + + test("should format multiple context snippets", () => { + const input = `+++++ src/file1.ts +const var1 = "value1"; + ++++++ src/file2.ts +const var2 = "value2"; +function test() {}`; + + const expected = `<|context_file|>: src/file1.ts +<|snippet|> +const var1 = "value1"; + +<|context_file|>: src/file2.ts +<|snippet|> +const var2 = "value2"; +function test() {}`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); + + test("should handle context snippet without content", () => { + const input = "+++++ src/empty.ts"; + + const expected = `<|context_file|>: src/empty.ts`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); + + test("should handle malformed headers gracefully", () => { + const input = `not a header ++++++ src/valid.ts +valid content`; + + const expected = `not a header +<|context_file|>: src/valid.ts +<|snippet|> +valid content`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); + + test("should handle multiple consecutive headers", () => { + const input = `+++++ src/file1.ts ++++++ src/file2.ts +content after headers`; + + const expected = `<|context_file|>: src/file1.ts +<|context_file|>: src/file2.ts +<|snippet|> +content after headers`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); +}); + +describe("currentFileContentBlock", () => { + test("should insert cursor and editable region tokens correctly", () => { + const content = `line 0 +line 1 +line 2 +line 3 +line 4`; + const cursorPosition: Position = { line: 2, character: 4 }; + const editableRegionStartLine = 1; + const editableRegionEndLine = 3; + + const result = currentFileContentBlock( + content, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `line 0 +<|editable_region_start|> +line 1 +line<|user_cursor_is_here|> 2 +line 3 +<|editable_region_end|> +line 4`; + + expect(result).toBe(expected); + }); + + test("should handle cursor at beginning of line", () => { + const content = `line 0 +line 1 +line 2`; + const cursorPosition: Position = { line: 1, character: 0 }; + const editableRegionStartLine = 0; + const editableRegionEndLine = 2; + + const result = currentFileContentBlock( + content, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `<|editable_region_start|> +line 0 +<|user_cursor_is_here|>line 1 +line 2 +<|editable_region_end|>`; + + expect(result).toBe(expected); + }); + + test("should handle cursor at end of line", () => { + const content = `line 0 +line 1 +line 2`; + const cursorPosition: Position = { line: 1, character: 6 }; // end of "line 1" + const editableRegionStartLine = 0; + const editableRegionEndLine = 2; + + const result = currentFileContentBlock( + content, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `<|editable_region_start|> +line 0 +line 1<|user_cursor_is_here|> +line 2 +<|editable_region_end|>`; + + expect(result).toBe(expected); + }); + + test("should handle single line editable region", () => { + const content = `line 0 +line 1 +line 2`; + const cursorPosition: Position = { line: 1, character: 2 }; + const editableRegionStartLine = 1; + const editableRegionEndLine = 1; + + const result = currentFileContentBlock( + content, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `line 0 +<|editable_region_start|> +li<|user_cursor_is_here|>ne 1 +<|editable_region_end|> +line 2`; + + expect(result).toBe(expected); + }); + + test("should handle cursor outside bounds gracefully", () => { + const content = `line 0 +line 1`; + const cursorPosition: Position = { line: 10, character: 0 }; // out of bounds + const editableRegionStartLine = 0; + const editableRegionEndLine = 1; + + const result = currentFileContentBlock( + content, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `<|editable_region_start|> +line 0 +line 1 +<|editable_region_end|>`; + + expect(result).toBe(expected); + }); + + test("should handle editable region covering entire file", () => { + const content = `line 0 +line 1 +line 2`; + const cursorPosition: Position = { line: 1, character: 0 }; + const editableRegionStartLine = 0; + const editableRegionEndLine = 2; + + const result = currentFileContentBlock( + content, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `<|editable_region_start|> +line 0 +<|user_cursor_is_here|>line 1 +line 2 +<|editable_region_end|>`; + + expect(result).toBe(expected); + }); +}); + +describe("editHistoryBlock", () => { + test("should format empty edit history", () => { + const result = editHistoryBlock([]); + expect(result).toBe(""); + }); + + test("should format single diff history entry", () => { + const diff = `Index: test.js +=================================================================== +--- a/test.js 2023-01-01 10:00:00.000000000 +0000 ++++ b/test.js 2023-01-01 10:01:00.000000000 +0000 +@@ -1,3 +1,3 @@ + function test() { +- console.log("old"); ++ console.log("new"); + }`; + + const result = editHistoryBlock([diff]); + const expected = `User edited file "test.js" + +\`\`\`diff +--- a/test.js 2023-01-01 10:00:00.000000000 +0000 ++++ b/test.js 2023-01-01 10:01:00.000000000 +0000 +@@ -1,3 +1,3 @@ + function test() { +- console.log("old"); ++ console.log("new"); + } +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should format multiple diff history entries", () => { + const diff1 = `Index: file1.js +=================================================================== +--- a/file1.js 2023-01-01 10:00:00.000000000 +0000 ++++ b/file1.js 2023-01-01 10:01:00.000000000 +0000 +@@ -1 +1 @@ +-const old = 1; ++const new = 1;`; + + const diff2 = `Index: file2.js +=================================================================== +--- a/file2.js 2023-01-01 10:02:00.000000000 +0000 ++++ b/file2.js 2023-01-01 10:03:00.000000000 +0000 +@@ -1 +1 @@ +-let x = "old"; ++let x = "new";`; + + const result = editHistoryBlock([diff1, diff2]); + const expected = `User edited file "file1.js" + +\`\`\`diff +--- a/file1.js 2023-01-01 10:00:00.000000000 +0000 ++++ b/file1.js 2023-01-01 10:01:00.000000000 +0000 +@@ -1 +1 @@ +-const old = 1; ++const new = 1; +\`\`\` +User edited file "file2.js" + +\`\`\`diff +--- a/file2.js 2023-01-01 10:02:00.000000000 +0000 ++++ b/file2.js 2023-01-01 10:03:00.000000000 +0000 +@@ -1 +1 @@ +-let x = "old"; ++let x = "new"; +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should handle diff with complex filename paths", () => { + const diff = `Index: src/components/Button/Button.tsx +=================================================================== +--- a/src/components/Button/Button.tsx 2023-01-01 10:00:00.000000000 +0000 ++++ b/src/components/Button/Button.tsx 2023-01-01 10:01:00.000000000 +0000 +@@ -1,2 +1,2 @@ +-export const Button = () => ; ++export const Button = () => ;`; + + const result = editHistoryBlock([diff]); + const expected = `User edited file "src/components/Button/Button.tsx" + +\`\`\`diff +--- a/src/components/Button/Button.tsx 2023-01-01 10:00:00.000000000 +0000 ++++ b/src/components/Button/Button.tsx 2023-01-01 10:01:00.000000000 +0000 +@@ -1,2 +1,2 @@ +-export const Button = () => ; ++export const Button = () => ; +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should handle diff with new file creation", () => { + const diff = `Index: newfile.js +=================================================================== +--- /dev/null 2023-01-01 10:00:00.000000000 +0000 ++++ b/newfile.js 2023-01-01 10:01:00.000000000 +0000 +@@ -0,0 +1,3 @@ ++function newFunction() { ++ return "hello world"; ++}`; + + const result = editHistoryBlock([diff]); + const expected = `User edited file "/dev/null" + +\`\`\`diff +--- /dev/null 2023-01-01 10:00:00.000000000 +0000 ++++ b/newfile.js 2023-01-01 10:01:00.000000000 +0000 +@@ -0,0 +1,3 @@ ++function newFunction() { ++ return "hello world"; ++} +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should handle diff with file deletion", () => { + const diff = `Index: deletedfile.js +=================================================================== +--- a/deletedfile.js 2023-01-01 10:00:00.000000000 +0000 ++++ /dev/null 2023-01-01 10:01:00.000000000 +0000 +@@ -1,3 +0,0 @@ +-function deletedFunction() { +- return "goodbye"; +-}`; + + const result = editHistoryBlock([diff]); + const expected = `User edited file "deletedfile.js" + +\`\`\`diff +--- a/deletedfile.js 2023-01-01 10:00:00.000000000 +0000 ++++ /dev/null 2023-01-01 10:01:00.000000000 +0000 +@@ -1,3 +0,0 @@ +-function deletedFunction() { +- return "goodbye"; +-} +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should handle minimal diff format", () => { + const diff = `Index: simple.txt +=================================================================== +@@ -1 +1 @@ +-old text ++new text`; + + const result = editHistoryBlock([diff]); + const expected = `User edited file "undefined" + +\`\`\`diff +@@ -1 +1 @@ +-old text ++new text +\`\`\``; + + expect(result).toBe(expected); + }); +}); From 109ef6e70d05ce117f48d5966b9d420417378fcf Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:05:44 -0700 Subject: [PATCH 14/29] feat: add helper to get metadata from unified diff --- core/nextEdit/context/diffFormatting.ts | 95 +++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/core/nextEdit/context/diffFormatting.ts b/core/nextEdit/context/diffFormatting.ts index 465a7106f..7103db88c 100644 --- a/core/nextEdit/context/diffFormatting.ts +++ b/core/nextEdit/context/diffFormatting.ts @@ -95,3 +95,98 @@ const createTokenLineDiff = ( // TODO: Implement token line diff return ""; }; + +export interface DiffMetadata { + oldFilename?: string; // Filename in the original version + newFilename?: string; // Filename in the modified version + oldTimestamp?: string; // Timestamp of the original file + newTimestamp?: string; // Timestamp of the modified file + hunks?: Array<{ + // Information about each change hunk + oldStart: number; // Starting line in original file + oldCount: number; // Number of lines in original file + newStart: number; // Starting line in modified file + newCount: number; // Number of lines in modified file + header?: string; // Optional section header + }>; + isBinary?: boolean; // Whether this is a binary file diff + isNew?: boolean; // Whether this is a new file + isDeleted?: boolean; // Whether this file was deleted + isRename?: boolean; // Whether this file was renamed +} + +export function extractMetadataFromUnifiedDiff( + unifiedDiff: string, +): DiffMetadata { + const metadata: DiffMetadata = {}; + const lines = unifiedDiff.split("\n"); + + // Parse the header lines (first two lines) + if (lines.length >= 2) { + // Parse original file info (--- line) + const oldFileMatch = lines[0].match( + /^--- (a\/)?([^\t\s]+)(?:[\t\s]+(.+))?$/, + ); + if (oldFileMatch) { + metadata.oldFilename = oldFileMatch[2]; + metadata.oldTimestamp = oldFileMatch[3]; + + // Check if this is a new file + if (metadata.oldFilename === "/dev/null") { + metadata.isNew = true; + } + } + + // Parse modified file info (+++ line) + const newFileMatch = lines[1].match( + /^\+\+\+ (b\/)?([^\t\s]+)(?:[\t\s]+(.+))?$/, + ); + if (newFileMatch) { + metadata.newFilename = newFileMatch[2]; + metadata.newTimestamp = newFileMatch[3]; + + // Check if this file was deleted + if (metadata.newFilename === "/dev/null") { + metadata.isDeleted = true; + } + } + + // Check if this is a rename (different old and new names) + if ( + metadata.oldFilename && + metadata.newFilename && + metadata.oldFilename !== "/dev/null" && + metadata.newFilename !== "/dev/null" && + metadata.oldFilename !== metadata.newFilename + ) { + metadata.isRename = true; + } + } + + // Parse hunk headers + metadata.hunks = []; + const hunkHeaderRegex = + /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s(.*))?$/; + + for (let i = 2; i < lines.length; i++) { + const line = lines[i]; + const hunkMatch = line.match(hunkHeaderRegex); + + if (hunkMatch) { + metadata.hunks.push({ + oldStart: parseInt(hunkMatch[1], 10), + oldCount: hunkMatch[2] ? parseInt(hunkMatch[2], 10) : 1, + newStart: parseInt(hunkMatch[3], 10), + newCount: hunkMatch[4] ? parseInt(hunkMatch[4], 10) : 1, + header: hunkMatch[5], + }); + } + + // Check for binary file marker + if (line.includes("Binary files") || line.includes("GIT binary patch")) { + metadata.isBinary = true; + } + } + + return metadata; +} From 5918041cc086d38743efc1f24e7e674c97541430 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:10:22 -0700 Subject: [PATCH 15/29] test: add vitest for diffFormatting --- .../nextEdit/context/diffFormatting.vitest.ts | 397 ++++++++++++++++++ 1 file changed, 397 insertions(+) create mode 100644 core/nextEdit/context/diffFormatting.vitest.ts diff --git a/core/nextEdit/context/diffFormatting.vitest.ts b/core/nextEdit/context/diffFormatting.vitest.ts new file mode 100644 index 000000000..05561d52b --- /dev/null +++ b/core/nextEdit/context/diffFormatting.vitest.ts @@ -0,0 +1,397 @@ +import { describe, expect, it } from "vitest"; +import { + BeforeAfterDiff, + createBeforeAfterDiff, + createDiff, + CreateDiffArgs, + DiffFormatType, + DiffMetadata, + extractMetadataFromUnifiedDiff, +} from "./diffFormatting"; + +describe("diffFormatting", () => { + const sampleFilePath = "test/sample.js"; + const beforeContent = "const a = 1;\nconst b = 2;"; + const afterContent = "const a = 1;\nconst b = 3;\nconst c = 4;"; + + describe("createDiff", () => { + it("should create unified diff when specified", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain("---"); + expect(result).toContain("+++"); + expect(result).toContain("@@"); + expect(result).toContain("-const b = 2;"); + expect(result).toContain("+const b = 3;"); + expect(result).toContain("+const c = 4;"); + }); + + it("should create token line diff when specified", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: sampleFilePath, + diffType: DiffFormatType.TokenLineDiff, + contextLines: 3, + }; + + const result = createDiff(args); + + // Currently returns empty string as TODO + expect(result).toBe(""); + }); + + it("should return empty string for unsupported diff types", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: sampleFilePath, + diffType: DiffFormatType.RawBeforeAfter, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toBe(""); + }); + + it("should handle empty content", () => { + const args: CreateDiffArgs = { + beforeContent: "", + afterContent: "new content", + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain("+++"); + expect(result).toContain("+new content"); + }); + + it("should handle deletion", () => { + const args: CreateDiffArgs = { + beforeContent: "old content", + afterContent: "", + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain("---"); + expect(result).toContain("-old content"); + }); + + it("should handle content without newlines", () => { + const args: CreateDiffArgs = { + beforeContent: "line1", + afterContent: "line2", + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain("-line1"); + expect(result).toContain("+line2"); + }); + + it("should respect contextLines parameter", () => { + const multiLineContent = Array(10) + .fill("line") + .map((l, i) => `${l}${i}`) + .join("\n"); + const modifiedContent = multiLineContent.replace("line5", "modified5"); + + const args: CreateDiffArgs = { + beforeContent: multiLineContent, + afterContent: modifiedContent, + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 2, + }; + + const result = createDiff(args); + + expect(result).toContain("@@ -4,5 +4,5 @@"); + }); + }); + + describe("createBeforeAfterDiff", () => { + it("should return BeforeAfterDiff with normalized content", () => { + const result: BeforeAfterDiff = createBeforeAfterDiff( + beforeContent, + afterContent, + sampleFilePath, + ); + + expect(result).toEqual({ + filePath: sampleFilePath, + beforeContent: beforeContent + "\n", + afterContent: afterContent + "\n", + }); + }); + + it("should not add extra newline if content already ends with one", () => { + const contentWithNewline = "const a = 1;\n"; + const result: BeforeAfterDiff = createBeforeAfterDiff( + contentWithNewline, + contentWithNewline, + sampleFilePath, + ); + + expect(result.beforeContent).toBe(contentWithNewline); + expect(result.afterContent).toBe(contentWithNewline); + }); + + it("should handle empty content", () => { + const result: BeforeAfterDiff = createBeforeAfterDiff( + "", + "", + sampleFilePath, + ); + + expect(result).toEqual({ + filePath: sampleFilePath, + beforeContent: "\n", + afterContent: "\n", + }); + }); + + it("should handle mixed newline scenarios", () => { + const beforeWithNewline = "line1\n"; + const afterWithoutNewline = "line2"; + const result: BeforeAfterDiff = createBeforeAfterDiff( + beforeWithNewline, + afterWithoutNewline, + sampleFilePath, + ); + + expect(result.beforeContent).toBe("line1\n"); + expect(result.afterContent).toBe("line2\n"); + }); + }); + + describe("extractMetadataFromUnifiedDiff", () => { + it("should extract basic file information", () => { + const unifiedDiff = `--- a/old.js\ttimestamp1 ++++ b/new.js\ttimestamp2 +@@ -1,3 +1,3 @@ + line1 +-line2 ++modified2 + line3`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("old.js"); + expect(metadata.newFilename).toBe("new.js"); + expect(metadata.oldTimestamp).toBe("timestamp1"); + expect(metadata.newTimestamp).toBe("timestamp2"); + expect(metadata.isNew).toBeFalsy(); + expect(metadata.isDeleted).toBeFalsy(); + expect(metadata.isRename).toBeTruthy(); + }); + + it("should detect new files", () => { + const unifiedDiff = `--- /dev/null ++++ b/new.js +@@ -0,0 +1,2 @@ ++line1 ++line2`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("/dev/null"); + expect(metadata.newFilename).toBe("new.js"); + expect(metadata.isNew).toBeTruthy(); + expect(metadata.isDeleted).toBeFalsy(); + expect(metadata.isRename).toBeFalsy(); + }); + + it("should detect deleted files", () => { + const unifiedDiff = `--- a/old.js ++++ /dev/null +@@ -1,2 +0,0 @@ +-line1 +-line2`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("old.js"); + expect(metadata.newFilename).toBe("/dev/null"); + expect(metadata.isNew).toBeFalsy(); + expect(metadata.isDeleted).toBeTruthy(); + expect(metadata.isRename).toBeFalsy(); + }); + + it("should parse hunk information", () => { + const unifiedDiff = `--- a/file.js ++++ b/file.js +@@ -1,5 +1,6 @@ function header + line1 +-line2 ++modified2 ++newline + line3 +@@ -10,3 +11,3 @@ + line10 +-line11 ++modified11 + line12`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.hunks).toHaveLength(2); + expect(metadata.hunks![0]).toEqual({ + oldStart: 1, + oldCount: 5, + newStart: 1, + newCount: 6, + header: "function header", + }); + expect(metadata.hunks![1]).toEqual({ + oldStart: 10, + oldCount: 3, + newStart: 11, + newCount: 3, + header: undefined, + }); + }); + + it("should handle single line hunks", () => { + const unifiedDiff = `--- a/file.js ++++ b/file.js +@@ -1 +1 @@ +-old ++new`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.hunks).toHaveLength(1); + expect(metadata.hunks![0]).toEqual({ + oldStart: 1, + oldCount: 1, + newStart: 1, + newCount: 1, + header: undefined, + }); + }); + + it("should detect binary files", () => { + const unifiedDiff = `--- a/image.png ++++ b/image.png +Binary files a/image.png and b/image.png differ`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.isBinary).toBeTruthy(); + }); + + it("should detect git binary patches", () => { + const unifiedDiff = `--- a/file.bin ++++ b/file.bin +GIT binary patch +delta 123 +...`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.isBinary).toBeTruthy(); + }); + + it("should handle files without a/ b/ prefixes", () => { + const unifiedDiff = `--- old.js ++++ new.js +@@ -1,2 +1,2 @@ +-line1 ++modified1 + line2`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("old.js"); + expect(metadata.newFilename).toBe("new.js"); + }); + + it("should handle empty diff", () => { + const metadata: DiffMetadata = extractMetadataFromUnifiedDiff(""); + + expect(metadata.oldFilename).toBeUndefined(); + expect(metadata.newFilename).toBeUndefined(); + expect(metadata.hunks).toEqual([]); + expect(metadata.isBinary).toBeFalsy(); + }); + + it("should handle malformed diff gracefully", () => { + const malformedDiff = `not a diff +random text`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(malformedDiff); + + expect(metadata.oldFilename).toBeUndefined(); + expect(metadata.newFilename).toBeUndefined(); + expect(metadata.hunks).toEqual([]); + }); + + it("should not consider same filenames as rename", () => { + const unifiedDiff = `--- a/file.js ++++ b/file.js +@@ -1,2 +1,2 @@ +-line1 ++modified1 + line2`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.isRename).toBeFalsy(); + }); + + it("should handle files with spaces in names", () => { + const unifiedDiff = `--- a/my file.js\t2023-01-01 00:00:00 ++++ b/my new file.js\t2023-01-01 00:01:00 +@@ -1,1 +1,1 @@ +-content ++new content`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("my file.js"); + expect(metadata.newFilename).toBe("my new file.js"); + expect(metadata.oldTimestamp).toBe("2023-01-01 00:00:00"); + expect(metadata.newTimestamp).toBe("2023-01-01 00:01:00"); + expect(metadata.isRename).toBeTruthy(); + }); + }); + + describe("DiffFormatType enum", () => { + it("should have correct enum values", () => { + expect(DiffFormatType.Unified).toBe("unified"); + expect(DiffFormatType.RawBeforeAfter).toBe("beforeAfter"); + expect(DiffFormatType.TokenLineDiff).toBe("linediff"); + }); + }); +}); From 59a37c95404dc86c9c01853a9d41e8f96cb6e173 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:10:39 -0700 Subject: [PATCH 16/29] fix: handle cases where filename includes spaces --- core/nextEdit/context/diffFormatting.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/core/nextEdit/context/diffFormatting.ts b/core/nextEdit/context/diffFormatting.ts index 7103db88c..c9c0ffa41 100644 --- a/core/nextEdit/context/diffFormatting.ts +++ b/core/nextEdit/context/diffFormatting.ts @@ -124,9 +124,7 @@ export function extractMetadataFromUnifiedDiff( // Parse the header lines (first two lines) if (lines.length >= 2) { // Parse original file info (--- line) - const oldFileMatch = lines[0].match( - /^--- (a\/)?([^\t\s]+)(?:[\t\s]+(.+))?$/, - ); + const oldFileMatch = lines[0].match(/^--- (a\/)?(.+?)(?:\t(.+))?$/); if (oldFileMatch) { metadata.oldFilename = oldFileMatch[2]; metadata.oldTimestamp = oldFileMatch[3]; @@ -138,9 +136,7 @@ export function extractMetadataFromUnifiedDiff( } // Parse modified file info (+++ line) - const newFileMatch = lines[1].match( - /^\+\+\+ (b\/)?([^\t\s]+)(?:[\t\s]+(.+))?$/, - ); + const newFileMatch = lines[1].match(/^\+\+\+ (b\/)?(.+?)(?:\t(.+))?$/); if (newFileMatch) { metadata.newFilename = newFileMatch[2]; metadata.newTimestamp = newFileMatch[3]; From 65cd7d47aa92ff7e40cf5d5fa0559a6f97ad5c1e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:17:05 -0700 Subject: [PATCH 17/29] fix: recover from bad merge --- core/nextEdit/templating/NextEditPromptEngine.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 94f80775c..6bd9c21d8 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -41,7 +41,7 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { }, "model-1": { template: - "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```", + "### User Edits:\n\n{{{editDiffHistory}}}\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{currentFileContent}}}```\n### Response:", }, }; From 4a6fe51fe21e346668629ca5ab58a99203611f9a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 12:10:44 -0700 Subject: [PATCH 18/29] feat: enrich model request with system and user prompt prefix --- core/nextEdit/NextEditProvider.ts | 7 +++--- core/nextEdit/constants.ts | 25 +++++++++++++++++++ .../templating/NextEditPromptEngine.ts | 4 +-- 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index ca5c23eaa..8f9f55527 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -37,6 +37,7 @@ import { replaceEscapedCharacters } from "../util/text.js"; import { MERCURY_CODE_TO_EDIT_OPEN, MERCURY_SYSTEM_PROMPT, + MODEL_1_SYSTEM_PROMPT, NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "./constants.js"; @@ -60,8 +61,6 @@ import { PromptMetadata, RecentlyEditedRange, } from "./types.js"; -import { getAutocompleteContext } from "./context/autocompleteContextFetching.js"; -import { EditAggregator } from "./context/aggregateEdits.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -578,7 +577,9 @@ export class NextEditProvider { const systemPrompt: Prompt = { role: "system", - content: MERCURY_SYSTEM_PROMPT, + content: modelName.includes("mercury-coder-nextedit") + ? MERCURY_SYSTEM_PROMPT + : MODEL_1_SYSTEM_PROMPT, }; return [systemPrompt, promptMetadata.prompt]; diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index 1c94db662..21e249b96 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -8,6 +8,31 @@ export const MODEL_1_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; export const MODEL_1_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; export const MODEL_1_CONTEXT_FILE_TOKEN = "<|context_file|>"; export const MODEL_1_SNIPPET_TOKEN = "<|snippet|>"; +export const MODEL_1_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags. + +You have access to the following information to help you make informed suggestions: + +- Context: In the section marked "### Context", there are context items from potentially relevant files in the developer's codebase. Each context item consists of a <|context_file|> marker, the filepath, a <|snippet|> marker, and then some content from that file, in that order. Keep in mind that not all of the context information may be relevant to the task, so use your judgement to determine which parts to consider. +- User Edits: In the section marked "### User Edits:", there is a record of the most recent changes made to the code, helping you understand the evolution of the code and the developer's intentions. These changes are listed from most recent to least recent. It's possible that some of the edit diff history is entirely irrelevant to the developer's change. The changes are provided in a unified line-diff format, i.e. with pluses and minuses for additions and deletions to the code. +- User Excerpt: In the section marked "### User Excerpt:", there is a filepath to the developer's current file, and then an excerpt from that file. The <|editable_region_start|> and <|editable_region_end|> markers are within this excerpt. Your job is to rewrite only this editable region, not the whole excerpt. The excerpt provides additional context on the surroundings of the developer's edit. +- Cursor Position: Within the user excerpt's editable region, the <|user_cursor_is_here|> flag indicates where the developer's cursor is currently located, which can be crucial for understanding what part of the code they are focusing on. Do not produce this marker in your output; simply take it into account. + +Your task is to predict and complete the changes the developer would have made next in the editable region. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they're following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn't get distracted by ensuring your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes. + +# Steps + +1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location. +2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements. +3. **Suggest Edits**: If changes are required, ensure they align with the developer's patterns and improve code quality. +4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style. + +# Output Format + +- Provide only the revised code within the tags. Do not include the tags in your output. +- Ensure that you do not output duplicate code that exists outside of these tags. +- Avoid undoing or reverting the developer's last change unless there are obvious typos or errors.`; +export const MODEL_1_USER_PROMPT_PREFIX = + "Reference the user excerpt, user edits, and the snippets to understand the developer's intent. Update the editable region of the user excerpt by predicting and completing the changes they would have made next. This may be a deletion, addition, or modification of code."; // Mercury Coder Next Edit-specific tokens. export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN = diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 6bd9c21d8..deb1b60c6 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -12,6 +12,7 @@ import { MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, MODEL_1_USER_CURSOR_IS_HERE_TOKEN, + MODEL_1_USER_PROMPT_PREFIX, } from "../constants"; import { MercuryTemplateVars, @@ -40,8 +41,7 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, }, "model-1": { - template: - "### User Edits:\n\n{{{editDiffHistory}}}\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{currentFileContent}}}```\n### Response:", + template: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`, }, }; From 345e90eb28fae30999647a5e6b2afc7cf7161796 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 12:15:45 -0700 Subject: [PATCH 19/29] fix: use proper import aliases --- core/nextEdit/templating/NextEditPromptEngine.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index deb1b60c6..7d4eb5b80 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -28,7 +28,11 @@ import { editHistoryBlock, recentlyViewedCodeSnippetsBlock, } from "./mercuryCoderNextEdit"; -import { contextSnippetsBlock } from "./model1"; +import { + contextSnippetsBlock, + currentFileContentBlock as model1CurrentFileContentBlock, + editHistoryBlock as model1EditHistoryBlock, +} from "./model1"; import { insertCursorToken, insertEditableRegionTokensWithStaticRange, @@ -41,7 +45,7 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, }, "model-1": { - template: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`, + template: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`, }, }; @@ -126,13 +130,13 @@ export async function renderPrompt( const model1Ctx: Model1TemplateVars = { contextSnippets: contextSnippetsBlock(ctx.contextSnippets), - currentFileContent: currentFileContentBlock( + currentFileContent: model1CurrentFileContentBlock( ctx.currentFileContent, ctx.editableRegionStartLine, ctx.editableRegionEndLine, helper.pos, ), - editDiffHistory: editHistoryBlock(ctx.editDiffHistory), + editDiffHistory: model1EditHistoryBlock(ctx.editDiffHistory), currentFilePath: ctx.currentFilePath, languageShorthand: ctx.languageShorthand, }; From 7106c9dd15f3c84452d7f1b63e0546aba1bd137f Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 12:15:59 -0700 Subject: [PATCH 20/29] feat: use 5 lines as context --- core/nextEdit/context/processSmallEdit.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/nextEdit/context/processSmallEdit.ts b/core/nextEdit/context/processSmallEdit.ts index 5824191b3..a98233cfe 100644 --- a/core/nextEdit/context/processSmallEdit.ts +++ b/core/nextEdit/context/processSmallEdit.ts @@ -20,7 +20,7 @@ export const processSmallEdit = async ( afterContent: beforeAfterdiff.afterContent, filePath: beforeAfterdiff.filePath, diffType: DiffFormatType.Unified, - contextLines: 3, // NOTE: This can change depending on experiments! + contextLines: 5, // NOTE: This can change depending on experiments! }), ); From fc08da2c29ed58dd683be6fbae572d8212eecd3e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 12:29:37 -0700 Subject: [PATCH 21/29] refactor: pass window range as well --- core/nextEdit/NextEditProvider.ts | 23 +++++++++++++++++-- .../templating/NextEditPromptEngine.ts | 2 ++ core/nextEdit/templating/model1.ts | 6 +++-- 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 8f9f55527..67f7d1cf0 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -559,11 +559,30 @@ export class NextEditProvider { currentFilePath: helper.filepath, }; } else if (modelName.includes("model-1")) { + // Calculate the window around the cursor position (25 lines above and below). + const windowStart = Math.max(0, helper.pos.line - 25); + const windowEnd = Math.min( + helper.fileLines.length - 1, + helper.pos.line + 25, + ); + + // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive). + const actualEditableStart = Math.max(0, helper.pos.line - 1); + const actualEditableEnd = Math.min( + helper.fileLines.length - 1, + helper.pos.line + 5, + ); + + // Ensure editable region boundaries are within the window. + const adjustedEditableStart = Math.max(windowStart, actualEditableStart); + const adjustedEditableEnd = Math.min(windowEnd, actualEditableEnd); ctx = { contextSnippets: this.autocompleteContext, currentFileContent: helper.fileContents, - editableRegionStartLine, - editableRegionEndLine, + windowStart, + windowEnd, + adjustedEditableStart, + adjustedEditableEnd, editDiffHistory: this.diffContext, currentFilePath: helper.filepath, languageShorthand: helper.lang.name, diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 7d4eb5b80..cf7748c17 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -132,6 +132,8 @@ export async function renderPrompt( contextSnippets: contextSnippetsBlock(ctx.contextSnippets), currentFileContent: model1CurrentFileContentBlock( ctx.currentFileContent, + ctx.windowStart, + ctx.windowEnd, ctx.editableRegionStartLine, ctx.editableRegionEndLine, helper.pos, diff --git a/core/nextEdit/templating/model1.ts b/core/nextEdit/templating/model1.ts index 3a7a617c0..ad547b549 100644 --- a/core/nextEdit/templating/model1.ts +++ b/core/nextEdit/templating/model1.ts @@ -39,6 +39,8 @@ export function contextSnippetsBlock(contextSnippets: string) { export function currentFileContentBlock( currentFileContent: string, + windowStart: number, + windowEnd: number, editableRegionStartLine: number, editableRegionEndLine: number, cursorPosition: Position, @@ -52,14 +54,14 @@ export function currentFileContentBlock( ); const instrumentedLines = [ - ...insertedCursorLines.slice(0, editableRegionStartLine), + ...insertedCursorLines.slice(windowStart, editableRegionStartLine), MODEL_1_EDITABLE_REGION_START_TOKEN, ...insertedCursorLines.slice( editableRegionStartLine, editableRegionEndLine + 1, ), MODEL_1_EDITABLE_REGION_END_TOKEN, - ...insertedCursorLines.slice(editableRegionEndLine + 1), + ...insertedCursorLines.slice(editableRegionEndLine + 1, windowEnd + 1), ]; return instrumentedLines.join("\n"); From 5314fcbe25ae55980a0a745caa2117300eab62d1 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 12:30:02 -0700 Subject: [PATCH 22/29] test: update test --- core/nextEdit/templating/model1.vitest.ts | 56 ++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/templating/model1.vitest.ts b/core/nextEdit/templating/model1.vitest.ts index 3facc6f6d..c2e603da0 100644 --- a/core/nextEdit/templating/model1.vitest.ts +++ b/core/nextEdit/templating/model1.vitest.ts @@ -94,12 +94,16 @@ line 1 line 2 line 3 line 4`; + const windowStart = 0; + const windowEnd = 4; const cursorPosition: Position = { line: 2, character: 4 }; const editableRegionStartLine = 1; const editableRegionEndLine = 3; const result = currentFileContentBlock( content, + windowStart, + windowEnd, editableRegionStartLine, editableRegionEndLine, cursorPosition, @@ -120,12 +124,16 @@ line 4`; const content = `line 0 line 1 line 2`; + const windowStart = 0; + const windowEnd = 2; const cursorPosition: Position = { line: 1, character: 0 }; const editableRegionStartLine = 0; const editableRegionEndLine = 2; const result = currentFileContentBlock( content, + windowStart, + windowEnd, editableRegionStartLine, editableRegionEndLine, cursorPosition, @@ -144,12 +152,16 @@ line 2 const content = `line 0 line 1 line 2`; + const windowStart = 0; + const windowEnd = 2; const cursorPosition: Position = { line: 1, character: 6 }; // end of "line 1" const editableRegionStartLine = 0; const editableRegionEndLine = 2; const result = currentFileContentBlock( content, + windowStart, + windowEnd, editableRegionStartLine, editableRegionEndLine, cursorPosition, @@ -168,12 +180,16 @@ line 2 const content = `line 0 line 1 line 2`; + const windowStart = 0; + const windowEnd = 2; const cursorPosition: Position = { line: 1, character: 2 }; const editableRegionStartLine = 1; const editableRegionEndLine = 1; const result = currentFileContentBlock( content, + windowStart, + windowEnd, editableRegionStartLine, editableRegionEndLine, cursorPosition, @@ -188,15 +204,19 @@ line 2`; expect(result).toBe(expected); }); - test("should handle cursor outside bounds gracefully", () => { + test("should handle cursor outside bounds gracefully (this shouldn't happen)", () => { const content = `line 0 line 1`; + const windowStart = 0; + const windowEnd = 1; const cursorPosition: Position = { line: 10, character: 0 }; // out of bounds const editableRegionStartLine = 0; const editableRegionEndLine = 1; const result = currentFileContentBlock( content, + windowStart, + windowEnd, editableRegionStartLine, editableRegionEndLine, cursorPosition, @@ -214,12 +234,16 @@ line 1 const content = `line 0 line 1 line 2`; + const windowStart = 0; + const windowEnd = 2; const cursorPosition: Position = { line: 1, character: 0 }; const editableRegionStartLine = 0; const editableRegionEndLine = 2; const result = currentFileContentBlock( content, + windowStart, + windowEnd, editableRegionStartLine, editableRegionEndLine, cursorPosition, @@ -233,6 +257,36 @@ line 2 expect(result).toBe(expected); }); + + test("should handle windowing - content outside window not included", () => { + const content = `line 0 +line 1 +line 2 +line 3 +line 4`; + const windowStart = 1; + const windowEnd = 3; + const cursorPosition: Position = { line: 2, character: 2 }; + const editableRegionStartLine = 2; + const editableRegionEndLine = 2; + + const result = currentFileContentBlock( + content, + windowStart, + windowEnd, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `line 1 +<|editable_region_start|> +li<|user_cursor_is_here|>ne 2 +<|editable_region_end|> +line 3`; + + expect(result).toBe(expected); + }); }); describe("editHistoryBlock", () => { From 9937209bb7bfa8037e5ea8a2a24c9d54e25393f5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 15:13:48 -0700 Subject: [PATCH 23/29] feat: add hunk details to metadata --- core/nextEdit/context/diffFormatting.ts | 61 +++++++++++++++++++++---- 1 file changed, 53 insertions(+), 8 deletions(-) diff --git a/core/nextEdit/context/diffFormatting.ts b/core/nextEdit/context/diffFormatting.ts index c9c0ffa41..38a76b051 100644 --- a/core/nextEdit/context/diffFormatting.ts +++ b/core/nextEdit/context/diffFormatting.ts @@ -108,6 +108,12 @@ export interface DiffMetadata { newStart: number; // Starting line in modified file newCount: number; // Number of lines in modified file header?: string; // Optional section header + lines: Array<{ + type: "context" | "addition" | "deletion"; + content: string; + oldLineNumber?: number; + newLineNumber?: number; + }>; }>; isBinary?: boolean; // Whether this is a binary file diff isNew?: boolean; // Whether this is a new file @@ -159,23 +165,62 @@ export function extractMetadataFromUnifiedDiff( } } - // Parse hunk headers + // Parse hunk headers and content metadata.hunks = []; const hunkHeaderRegex = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s(.*))?$/; + let currentHunk: NonNullable[0] | null = null; + let oldLineNumber = 0; + let newLineNumber = 0; + for (let i = 2; i < lines.length; i++) { const line = lines[i]; const hunkMatch = line.match(hunkHeaderRegex); if (hunkMatch) { - metadata.hunks.push({ - oldStart: parseInt(hunkMatch[1], 10), - oldCount: hunkMatch[2] ? parseInt(hunkMatch[2], 10) : 1, - newStart: parseInt(hunkMatch[3], 10), - newCount: hunkMatch[4] ? parseInt(hunkMatch[4], 10) : 1, - header: hunkMatch[5], - }); + currentHunk = { + oldStart: parseInt(hunkMatch[1], 10), // line number where changes start in original file + oldCount: hunkMatch[2] ? parseInt(hunkMatch[2], 10) : 1, // number of changed lines in original file, default to 1 if not specified + newStart: parseInt(hunkMatch[3], 10), // line number where changes start in modified file + newCount: hunkMatch[4] ? parseInt(hunkMatch[4], 10) : 1, // number of changed lines in modified file, default to 1 if not specified + header: hunkMatch[5], // the line starting with @@ + lines: [], // the actual line changes + }; + + oldLineNumber = currentHunk.oldStart; + newLineNumber = currentHunk.newStart; + + metadata.hunks.push(currentHunk); + } else if ( + currentHunk && + (line.startsWith(" ") || line.startsWith("+") || line.startsWith("-")) + ) { + // Process hunk content lines. + const lineType = line[0]; + const content = line.slice(1); + + if (lineType === " ") { + // Context line (unchanged). + currentHunk.lines.push({ + type: "context", + content, + oldLineNumber: oldLineNumber++, + newLineNumber: newLineNumber++, + }); + } else if (lineType === "+") { + currentHunk.lines.push({ + type: "addition", + content, + newLineNumber: newLineNumber++, + }); + } else if (lineType === "-") { + currentHunk.lines.push({ + type: "deletion", + content, + oldLineNumber: oldLineNumber++, + }); + } } // Check for binary file marker From 4cfe12f5e05cb5c4a2877f7da595882d98cf8a36 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 15:13:56 -0700 Subject: [PATCH 24/29] test: update test --- .../nextEdit/context/diffFormatting.vitest.ts | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/core/nextEdit/context/diffFormatting.vitest.ts b/core/nextEdit/context/diffFormatting.vitest.ts index 05561d52b..b010f7837 100644 --- a/core/nextEdit/context/diffFormatting.vitest.ts +++ b/core/nextEdit/context/diffFormatting.vitest.ts @@ -265,6 +265,35 @@ describe("diffFormatting", () => { newStart: 1, newCount: 6, header: "function header", + lines: [ + { + content: "line1", + newLineNumber: 1, + oldLineNumber: 1, + type: "context", + }, + { + content: "line2", + oldLineNumber: 2, + type: "deletion", + }, + { + content: "modified2", + newLineNumber: 2, + type: "addition", + }, + { + content: "newline", + newLineNumber: 3, + type: "addition", + }, + { + content: "line3", + newLineNumber: 4, + oldLineNumber: 3, + type: "context", + }, + ], }); expect(metadata.hunks![1]).toEqual({ oldStart: 10, @@ -272,6 +301,30 @@ describe("diffFormatting", () => { newStart: 11, newCount: 3, header: undefined, + lines: [ + { + content: "line10", + newLineNumber: 11, + oldLineNumber: 10, + type: "context", + }, + { + content: "line11", + oldLineNumber: 11, + type: "deletion", + }, + { + content: "modified11", + newLineNumber: 12, + type: "addition", + }, + { + content: "line12", + newLineNumber: 13, + oldLineNumber: 12, + type: "context", + }, + ], }); }); @@ -292,6 +345,18 @@ describe("diffFormatting", () => { newStart: 1, newCount: 1, header: undefined, + lines: [ + { + content: "old", + oldLineNumber: 1, + type: "deletion", + }, + { + content: "new", + newLineNumber: 1, + type: "addition", + }, + ], }); }); From 3c5d91aaaa6d18e8216476f28dd142394e718644 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 15:16:09 -0700 Subject: [PATCH 25/29] feat: add hunk to prompt --- core/nextEdit/templating/model1.ts | 68 +++++++++++++++++++++--------- 1 file changed, 49 insertions(+), 19 deletions(-) diff --git a/core/nextEdit/templating/model1.ts b/core/nextEdit/templating/model1.ts index ad547b549..821d46d3b 100644 --- a/core/nextEdit/templating/model1.ts +++ b/core/nextEdit/templating/model1.ts @@ -6,7 +6,6 @@ import { MODEL_1_SNIPPET_TOKEN, MODEL_1_USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; -import { extractMetadataFromUnifiedDiff } from "../context/diffFormatting"; import { insertCursorToken } from "./utils"; /** @@ -68,26 +67,57 @@ export function currentFileContentBlock( } export function editHistoryBlock( - editDiffHistories: string[], // list of unified diffs + editDiffHistories: string, // unified diffs with Index headers ) { - // diffHistory is made from createDiff. - // This uses createPatch from npm diff library, which includes an index line and a separator. - // We get rid of these first two lines. - const block: string[] = []; + if (!editDiffHistories.trim()) { + return ""; + } - editDiffHistories.forEach((diff) => { - const diffWithoutHeader = diff.split("\n").slice(2).join("\n"); - const metadata = extractMetadataFromUnifiedDiff(diffWithoutHeader); - block.push( - [ - `User edited file \"${metadata.oldFilename}\"`, - "", - "```diff", - `${diffWithoutHeader}`, - "```", - ].join("\n"), + const blocks: string[] = []; + + // Split on Index: lines to get the unified diff. + const diffSections = editDiffHistories + .split(/^Index: /m) + .filter((section) => section.trim()); + + for (const section of diffSections) { + const lines = section.split("\n"); + + // Extract filename from the first line (after "Index: " was split off). + const filename = lines[0]; + + // Find the start of the actual diff content (skip ---, +++, and === lines). + const diffLines = lines + .filter( + (line) => + !line.startsWith("---") && + !line.startsWith("+++") && + !line.startsWith("===") && + line.trim() !== "", // remove empty lines from header section + ) + .slice(1); // remove the filename line + + // Only include lines that are actual diff content (@@, +, -, or context lines). + const actualDiffContent = diffLines.filter( + (line) => + line.startsWith("@@") || + line.startsWith("+") || + line.startsWith("-") || + line.startsWith(" "), // context lines ); - }); - return block.join("\n"); + if (actualDiffContent.length === 0) continue; + + const diffBlock = [ + `User edited file "${filename}"`, + "", + "```diff", + actualDiffContent.join("\n"), + "```", + ].join("\n"); + + blocks.push(diffBlock); + } + + return blocks.join("\n"); } From 15a78628f094da80f1d5f2c7111d209cd17fb267 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 15:16:16 -0700 Subject: [PATCH 26/29] test: update test --- core/nextEdit/templating/model1.vitest.ts | 41 +++++++++-------------- 1 file changed, 15 insertions(+), 26 deletions(-) diff --git a/core/nextEdit/templating/model1.vitest.ts b/core/nextEdit/templating/model1.vitest.ts index c2e603da0..b1020f040 100644 --- a/core/nextEdit/templating/model1.vitest.ts +++ b/core/nextEdit/templating/model1.vitest.ts @@ -291,7 +291,7 @@ line 3`; describe("editHistoryBlock", () => { test("should format empty edit history", () => { - const result = editHistoryBlock([]); + const result = editHistoryBlock(""); expect(result).toBe(""); }); @@ -306,12 +306,10 @@ describe("editHistoryBlock", () => { + console.log("new"); }`; - const result = editHistoryBlock([diff]); + const result = editHistoryBlock(diff); const expected = `User edited file "test.js" \`\`\`diff ---- a/test.js 2023-01-01 10:00:00.000000000 +0000 -+++ b/test.js 2023-01-01 10:01:00.000000000 +0000 @@ -1,3 +1,3 @@ function test() { - console.log("old"); @@ -322,16 +320,16 @@ describe("editHistoryBlock", () => { expect(result).toBe(expected); }); - test("should format multiple diff history entries", () => { - const diff1 = `Index: file1.js + test("should format multiple diff history entries in unified format", () => { + // Multiple diffs should be concatenated into a single string + const unifiedDiff = `Index: file1.js =================================================================== --- a/file1.js 2023-01-01 10:00:00.000000000 +0000 +++ b/file1.js 2023-01-01 10:01:00.000000000 +0000 @@ -1 +1 @@ -const old = 1; -+const new = 1;`; - - const diff2 = `Index: file2.js ++const new = 1; +Index: file2.js =================================================================== --- a/file2.js 2023-01-01 10:02:00.000000000 +0000 +++ b/file2.js 2023-01-01 10:03:00.000000000 +0000 @@ -339,12 +337,10 @@ describe("editHistoryBlock", () => { -let x = "old"; +let x = "new";`; - const result = editHistoryBlock([diff1, diff2]); + const result = editHistoryBlock(unifiedDiff); const expected = `User edited file "file1.js" \`\`\`diff ---- a/file1.js 2023-01-01 10:00:00.000000000 +0000 -+++ b/file1.js 2023-01-01 10:01:00.000000000 +0000 @@ -1 +1 @@ -const old = 1; +const new = 1; @@ -352,8 +348,6 @@ describe("editHistoryBlock", () => { User edited file "file2.js" \`\`\`diff ---- a/file2.js 2023-01-01 10:02:00.000000000 +0000 -+++ b/file2.js 2023-01-01 10:03:00.000000000 +0000 @@ -1 +1 @@ -let x = "old"; +let x = "new"; @@ -362,6 +356,7 @@ User edited file "file2.js" expect(result).toBe(expected); }); + // Fix remaining tests to pass strings instead of arrays test("should handle diff with complex filename paths", () => { const diff = `Index: src/components/Button/Button.tsx =================================================================== @@ -371,12 +366,10 @@ User edited file "file2.js" -export const Button = () => ; +export const Button = () => ;`; - const result = editHistoryBlock([diff]); + const result = editHistoryBlock(diff); const expected = `User edited file "src/components/Button/Button.tsx" \`\`\`diff ---- a/src/components/Button/Button.tsx 2023-01-01 10:00:00.000000000 +0000 -+++ b/src/components/Button/Button.tsx 2023-01-01 10:01:00.000000000 +0000 @@ -1,2 +1,2 @@ -export const Button = () => ; +export const Button = () => ; @@ -395,12 +388,10 @@ User edited file "file2.js" + return "hello world"; +}`; - const result = editHistoryBlock([diff]); - const expected = `User edited file "/dev/null" + const result = editHistoryBlock(diff); + const expected = `User edited file "newfile.js" \`\`\`diff ---- /dev/null 2023-01-01 10:00:00.000000000 +0000 -+++ b/newfile.js 2023-01-01 10:01:00.000000000 +0000 @@ -0,0 +1,3 @@ +function newFunction() { + return "hello world"; @@ -420,12 +411,10 @@ User edited file "file2.js" - return "goodbye"; -}`; - const result = editHistoryBlock([diff]); + const result = editHistoryBlock(diff); const expected = `User edited file "deletedfile.js" \`\`\`diff ---- a/deletedfile.js 2023-01-01 10:00:00.000000000 +0000 -+++ /dev/null 2023-01-01 10:01:00.000000000 +0000 @@ -1,3 +0,0 @@ -function deletedFunction() { - return "goodbye"; @@ -442,8 +431,8 @@ User edited file "file2.js" -old text +new text`; - const result = editHistoryBlock([diff]); - const expected = `User edited file "undefined" + const result = editHistoryBlock(diff); + const expected = `User edited file "simple.txt" \`\`\`diff @@ -1 +1 @@ From 43dd4f622e9147260eb27384db6ca9adb761a8cb Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 15:16:38 -0700 Subject: [PATCH 27/29] fix: prompt and userEdits --- core/nextEdit/templating/NextEditPromptEngine.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index cf7748c17..326ac4d84 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -45,7 +45,7 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, }, "model-1": { - template: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`, + template: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`, }, }; @@ -120,7 +120,7 @@ export async function renderPrompt( break; } case "model-1": { - userEdits = ctx.userEdits; + userEdits = ctx.editDiffHistory; editedCodeWithTokens = insertTokens( helper.fileContents.split("\n"), From ea02b4b4469b99741f66599811aae361bf02a1b5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 15:16:45 -0700 Subject: [PATCH 28/29] test: update test --- .../templating/NextEditPromptEngine.vitest.ts | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts index 785dd79cc..23ae1d7cb 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -3,6 +3,7 @@ import { Position } from "../.."; import { SnippetPayload } from "../../autocomplete/snippets"; import { AutocompleteSnippetType } from "../../autocomplete/snippets/types"; import { HelperVars } from "../../autocomplete/util/HelperVars"; +import { NEXT_EDIT_MODELS } from "../../llm/constants"; import { MERCURY_CURRENT_FILE_CONTENT_CLOSE, MERCURY_CURRENT_FILE_CONTENT_OPEN, @@ -12,13 +13,13 @@ import { MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, MODEL_1_USER_CURSOR_IS_HERE_TOKEN, + MODEL_1_USER_PROMPT_PREFIX, } from "../constants"; import { renderDefaultSystemPrompt, renderDefaultUserPrompt, renderPrompt, } from "./NextEditPromptEngine"; -import { NEXT_EDIT_MODELS } from "../../llm/constants"; describe("NextEditPromptEngine", () => { describe("renderPrompt", () => { @@ -81,15 +82,33 @@ describe("NextEditPromptEngine", () => { }); it("should render model-1 prompt correctly", async () => { - const result = await renderPrompt(model1Helper, ctx); + // Create proper model-1 context structure matching NextEditProvider.ts + const model1Ctx = { + contextSnippets: + "+++++ /path/to/context.ts\nconst contextVar = 'test';", + currentFileContent: model1Helper.fileContents, + windowStart: 0, // Math.max(0, helper.pos.line - 25) + windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25) + adjustedEditableStart: 0, // Math.max(0, helper.pos.line - 1) within window + adjustedEditableEnd: 2, // Math.min(helper.pos.line + 5) within window + editDiffHistory: + "diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }", // unified diff + currentFilePath: "/path/to/file.ts", + languageShorthand: "ts", + }; + + const result = await renderPrompt(model1Helper, model1Ctx); + console.log(result); expect(result).toHaveProperty("prompt"); expect(result.prompt.role).toBe("user"); + expect(result.prompt.content).toContain(MODEL_1_USER_PROMPT_PREFIX); + expect(result.prompt.content).toContain("### Context:"); expect(result.prompt.content).toContain("### User Edits:"); expect(result.prompt.content).toContain("### User Excerpts:"); expect(result.prompt.content).toContain("```ts"); - expect(result.userEdits).toBe(ctx.userEdits); + expect(result.userEdits).toBe(model1Ctx.editDiffHistory); expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN); }); From 85314e54130c9c0c9af4ee282d357b08d5362e3b Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 8 Aug 2025 15:55:16 -0700 Subject: [PATCH 29/29] Delete .continue/rules/comment-periods.md --- .continue/rules/comment-periods.md | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 .continue/rules/comment-periods.md diff --git a/.continue/rules/comment-periods.md b/.continue/rules/comment-periods.md deleted file mode 100644 index bfbcc0ae1..000000000 --- a/.continue/rules/comment-periods.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -alwaysApply: true ---- - -End your comments with a period.