feat(walkthrough): plan-then-explain generation with selectable diff sources

This commit is contained in:
Chris Scott committed 2026-10-08 15:53:49 -04:00
1 parent aeea96b466
commit 88b3543dc1
35 files changed
+2583 -609

No files matched your search

+55 -15
View File
@@ -1,21 +1,21 @@
import { z } from "zod";
import { gitRefSchema } from './git'
export const WALKTHROUGH_DIFF_MAX_CHARS = 60000;
export const WALKTHROUGH_HUNK_MAX_CHARS = 8000;
export const MECHANICAL_TEXT_BUDGET = 20000;
export const WALKTHROUGH_MAX_STOPS = 20;
export const WALKTHROUGH_TEXT_MAX_CHARS = 2000;
export const WALKTHROUGH_OUTLINE_PREVIEW_LINES = 6;
export const WALKTHROUGH_OUTLINE_LINE_MAX_CHARS = 160;
export const GitRefSchema = z.string().trim().min(1).max(200).regex(/^[^-\s][^\s]*$/)
export const WalkthroughSourceSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('session') }),
z.object({ kind: z.literal('uncommitted') }),
z.object({ kind: z.literal('staged') }),
z.object({ kind: z.literal('unstaged') }),
z.object({ kind: z.literal('branch'), base: GitRefSchema.optional() }),
z.object({ kind: z.literal('pullRequest'), number: z.number().int().positive(), base: GitRefSchema.optional() }),
z.object({ kind: z.literal('branch'), base: gitRefSchema.optional() }),
z.object({ kind: z.literal('pullRequest'), number: z.number().int().positive(), base: gitRefSchema.optional() }),
])
export type WalkthroughSource = z.infer<typeof WalkthroughSourceSchema>
@@ -39,7 +39,7 @@ export function walkthroughSourceKey(source: WalkthroughSource): string {
export function describeWalkthroughSource(source: WalkthroughSource): string {
switch (source.kind) {
case 'session':
return 'session changes'
return 'the changes in this session'
case 'uncommitted':
return 'uncommitted changes'
case 'staged':
@@ -53,13 +53,35 @@ export function describeWalkthroughSource(source: WalkthroughSource): string {
}
}
export function toWalkthroughSource(candidate: {
kind: WalkthroughSource['kind']
base?: string
number?: number
}): WalkthroughSource | null {
const base = candidate.base?.trim()
switch (candidate.kind) {
case 'session':
case 'uncommitted':
case 'staged':
case 'unstaged':
return { kind: candidate.kind }
case 'branch':
return parseWalkthroughSourceCandidate(base ? { kind: 'branch', base } : { kind: 'branch' })
case 'pullRequest':
return parseWalkthroughSourceCandidate(
base
? { kind: 'pullRequest', number: candidate.number, base }
: { kind: 'pullRequest', number: candidate.number },
)
}
}
export function parseWalkthroughSourceKey(key: string): WalkthroughSource | null {
if (key === 'session' || key === 'uncommitted' || key === 'staged' || key === 'unstaged') {
return { kind: key }
}
if (key.startsWith('branch:')) {
const base = key.slice('branch:'.length)
return parseWalkthroughSourceCandidate(base ? { kind: 'branch', base } : { kind: 'branch' })
return toWalkthroughSource({ kind: 'branch', base: key.slice('branch:'.length) })
}
if (key.startsWith('pr:')) {
const rest = key.slice('pr:'.length)
@@ -67,11 +89,11 @@ export function parseWalkthroughSourceKey(key: string): WalkthroughSource | null
if (separator < 0) {
return null
}
const number = Number(rest.slice(0, separator))
const base = rest.slice(separator + 1)
return parseWalkthroughSourceCandidate(
base ? { kind: 'pullRequest', number, base } : { kind: 'pullRequest', number },
)
return toWalkthroughSource({
kind: 'pullRequest',
number: Number(rest.slice(0, separator)),
base: rest.slice(separator + 1),
})
}
return null
}
@@ -88,6 +110,8 @@ export const WalkthroughHunkSchema = z.object({
header: z.string(),
text: z.string(),
truncated: z.boolean(),
additions: z.number().int().nonnegative().optional(),
deletions: z.number().int().nonnegative().optional(),
});
export type WalkthroughHunk = z.infer<typeof WalkthroughHunkSchema>;
@@ -103,11 +127,9 @@ export const WalkthroughStopSchema = z.object({
export type WalkthroughStop = z.infer<typeof WalkthroughStopSchema>;
export type WalkthroughStopStatus = WalkthroughStop["status"];
export const WalkthroughOmittedFileSchema = z.object({
file: z.string(),
reason: z.enum(["binary", "budget"]),
reason: z.enum(["binary", "budget", "renamed", "modeChange"]),
});
export type WalkthroughOmittedFile = z.infer<typeof WalkthroughOmittedFileSchema>;
@@ -144,6 +166,24 @@ export const ChangeWalkthroughStateSchema = z.object({
export type ChangeWalkthroughState = z.infer<typeof ChangeWalkthroughStateSchema>;
export const ChangeWalkthroughWireSchema = ChangeWalkthroughSchema.extend({
hunks: z.array(WalkthroughHunkSchema).optional(),
});
export type ChangeWalkthroughWire = z.infer<typeof ChangeWalkthroughWireSchema>;
export const ChangeWalkthroughStateWireSchema = ChangeWalkthroughStateSchema.extend({
walkthrough: ChangeWalkthroughWireSchema.nullable(),
});
export type ChangeWalkthroughStateWire = z.infer<typeof ChangeWalkthroughStateWireSchema>;
export function walkthroughHunksIdentity(
walkthrough: Pick<ChangeWalkthrough, 'diffHash' | 'createdAt'>,
): string {
return `${walkthrough.diffHash}:${walkthrough.createdAt}`
}
export const GenerateChangeWalkthroughRequestSchema = z.object({
regenerate: z.boolean().optional(),
source: WalkthroughSourceSchema.optional(),
+12 -2
View File
@@ -1,12 +1,22 @@
import { z } from 'zod'
import { getBranchNameError } from '../utils/repo'
const branchNameSchema = z.string().trim().superRefine((value, ctx) => {
function addBranchNameIssue(value: string, ctx: z.RefinementCtx) {
const error = getBranchNameError(value)
if (error) {
ctx.addIssue({ code: 'custom', message: error })
}
})
}
const branchNameSchema = z.string().trim().superRefine(addBranchNameIssue)
export const gitRefSchema = z
.string()
.trim()
.min(1)
.max(200)
.regex(/^\S+$/)
.superRefine(addBranchNameIssue)
export const RenameBranchRequestSchema = z.object({
from: branchNameSchema,
+51 -33
View File
@@ -1,3 +1,5 @@
import type { FileDiffInfo } from '../opencode'
export interface DiffLine {
type: "add" | "remove" | "context" | "header" | "hunk";
content: string;
@@ -90,6 +92,19 @@ export function parseDiffLines(diff: string): DiffLine[] {
return result;
}
export function countDiffLineChanges(text: string): { added: number; removed: number } {
let added = 0;
let removed = 0;
for (const line of parseDiffLines(text)) {
if (line.type === "add") {
added += 1;
} else if (line.type === "remove") {
removed += 1;
}
}
return { added, removed };
}
export function splitDiffHunks(patch: string): DiffHunk[] {
const hunks: DiffHunk[] = [];
let current: string[] | null = null;
@@ -116,19 +131,11 @@ function toHunk(lines: string[]): DiffHunk {
return { header: lines[0]!, text: lines.join("\n") };
}
export interface UnifiedFileDiff {
file: string;
status: "added" | "deleted" | "modified";
patch: string;
additions: number;
deletions: number;
}
export function splitUnifiedDiffByFile(diff: string): UnifiedFileDiff[] {
export function splitUnifiedDiffByFile(diff: string): FileDiffInfo[] {
const blocks: string[][] = [];
for (const line of diff.split("\n")) {
if (line.startsWith("diff --git ")) {
if (line.startsWith("diff --git ") || line.startsWith("diff --cc ") || line.startsWith("diff --combined ")) {
blocks.push([line]);
} else if (blocks.length > 0) {
blocks[blocks.length - 1]!.push(line);
@@ -138,15 +145,13 @@ export function splitUnifiedDiffByFile(diff: string): UnifiedFileDiff[] {
return blocks.map((lines) => toUnifiedFileDiff(lines));
}
function toUnifiedFileDiff(lines: string[]): UnifiedFileDiff {
function toUnifiedFileDiff(lines: string[]): FileDiffInfo {
const header = lines[0]!;
const newPath = lines.find((line) => line.startsWith("+++ "));
const oldPath = lines.find((line) => line.startsWith("--- "));
const renameTo = lines.find((line) => line.startsWith("rename to "));
let file = "";
let status: UnifiedFileDiff["status"] = "modified";
let additions = 0;
let deletions = 0;
let status: FileDiffInfo["status"] = "modified";
if (newPath && newPath.slice(4) !== "/dev/null") {
file = parseDiffPathToken(newPath.slice(4), "b/");
@@ -164,19 +169,12 @@ function toUnifiedFileDiff(lines: string[]): UnifiedFileDiff {
} else if (line.startsWith("deleted file mode")) {
status = "deleted";
}
if (line.startsWith("+++") || line.startsWith("---")) {
continue;
}
if (line.startsWith("+")) {
additions++;
} else if (line.startsWith("-")) {
deletions++;
}
}
return { file, status, patch: lines.join("\n"), additions, deletions };
const patch = lines.join("\n");
const { added: additions, removed: deletions } = countDiffLineChanges(patch);
return { file, status, patch, additions, deletions };
}
function stripDiffPathPrefix(path: string, prefix: string): string {
@@ -234,30 +232,50 @@ function decodeGitQuotedPath(raw: string): string {
}
function newPathFromDiffHeader(header: string): string {
const rest = header.slice("diff --git ".length);
const match = /^diff --(?:git|cc|combined) (.*)$/.exec(header);
const rest = match ? match[1]! : "";
if (rest.startsWith('"')) {
const end = findClosingQuote(rest);
const end = findClosingQuoteFrom(rest, 0);
if (end >= 0) {
let index = end + 1;
while (rest[index] === " ") {
index += 1;
}
return parseDiffPathToken(rest.slice(index), "b/");
return stripKnownDiffPrefix(parseDiffPathToken(rest.slice(index), ""));
}
}
const quoted = rest.indexOf(' "');
if (quoted >= 0) {
return parseDiffPathToken(rest.slice(quoted + 1), "b/");
return stripKnownDiffPrefix(parseDiffPathToken(rest.slice(quoted + 1), ""));
}
const index = rest.lastIndexOf(" b/");
return index >= 0 ? parseDiffPathToken(rest.slice(index + 1), "b/") : "";
for (const prefix of GIT_DIFF_DEST_PREFIXES) {
const index = rest.lastIndexOf(prefix);
if (index >= 0) {
return parseDiffPathToken(rest.slice(index + 1), prefix.trim());
}
}
const lastSpace = rest.lastIndexOf(" ");
return lastSpace >= 0 ? rest.slice(lastSpace + 1) : rest;
}
function findClosingQuote(raw: string): number {
for (let index = 1; index < raw.length; index += 1) {
const GIT_DIFF_DEST_PREFIXES = [" b/", " w/", " 2/", " 3/", " i/", " c/", " o/", " 1/", " a/"];
const GIT_DIFF_PREFIXES = ["a/", "b/", "i/", "w/", "c/", "o/", "1/", "2/", "3/"];
function stripKnownDiffPrefix(path: string): string {
for (const prefix of GIT_DIFF_PREFIXES) {
if (path.startsWith(prefix)) {
return path.slice(prefix.length);
}
}
return path;
}
function findClosingQuoteFrom(raw: string, start: number): number {
for (let index = start + 1; index < raw.length; index += 1) {
if (raw[index] === "\\") {
index += 1;
continue;