feat(KB-617): add Changes tab to task detail modal with file diffs

- Add modifiedFiles and baseCommitSha fields to task schema for tracking changes
- Capture list of modified files during task execution in the executor
- Add GET /tasks/:id/diff API endpoint to retrieve file list and patches
- Create TaskChangesTab component with expandable file diffs
- Integrate Changes tab into TaskDetailModal for in-progress, in-review, and done tasks
- Add CSS styles for diff viewer with syntax highlighting
- Update API client with fetchTaskDiff function and Project Management types
This commit is contained in:
gsxdsm
2026-04-01 06:56:32 -07:00
parent 16c504228d
commit 08079da9ea
11 changed files with 561 additions and 55 deletions

View File

@@ -1416,7 +1416,7 @@ export async function runTaskPlan(initialPlanArg?: string, yesFlag = false): Pro
try { try {
showThinking(); showThinking();
result = await submitResponse(sessionId, response) as typeof result; result = await submitResponse(sessionId, response as Record<string, unknown>) as typeof result;
clearThinking(); clearThinking();
} catch (err) { } catch (err) {
clearThinking(); clearThinking();

View File

@@ -86,7 +86,7 @@ describe("Database", () => {
}); });
it("seeds schema version", () => { it("seeds schema version", () => {
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
}); });
it("seeds lastModified", () => { it("seeds lastModified", () => {
@@ -109,7 +109,7 @@ describe("Database", () => {
it("is idempotent - calling init() twice does not fail", () => { it("is idempotent - calling init() twice does not fail", () => {
expect(() => db.init()).not.toThrow(); expect(() => db.init()).not.toThrow();
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
}); });
it("does not overwrite existing config on re-init", () => { it("does not overwrite existing config on re-init", () => {
@@ -683,8 +683,8 @@ describe("schema migrations", () => {
// Now run init() which should trigger migration // Now run init() which should trigger migration
db.init(); db.init();
// Verify version bumped to 3 (includes both v1→v2 and v2→v3 migrations) // Verify version bumped to 4 (includes v1→v2, v2→v3, and v3→v4 migrations)
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
// Verify new columns exist and existing data is intact // Verify new columns exist and existing data is intact
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>; const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
@@ -709,11 +709,11 @@ describe("schema migrations", () => {
const db = new Database(kbDir); const db = new Database(kbDir);
db.init(); db.init();
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
// Re-init should not fail // Re-init should not fail
db.init(); db.init();
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
db.close(); db.close();
}); });
@@ -804,11 +804,11 @@ describe("schema migrations", () => {
// Insert a task on the v2 schema // Insert a task on the v2 schema
db.exec(`INSERT INTO tasks (id, description, "column", createdAt, updatedAt) VALUES ('KB-2', 'test v2', 'triage', '2025-01-01', '2025-01-01')`); db.exec(`INSERT INTO tasks (id, description, "column", createdAt, updatedAt) VALUES ('KB-2', 'test v2', 'triage', '2025-01-01', '2025-01-01')`);
// Now run init() which should trigger v2→v3 migration // Now run init() which should trigger migrations v2→v3→v4
db.init(); db.init();
// Verify version bumped to 3 // Verify version bumped to 4
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
// Verify new columns exist and existing data is intact // Verify new columns exist and existing data is intact
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>; const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
@@ -864,7 +864,7 @@ describe("createDatabase factory", () => {
const db = createDatabase(kbDir); const db = createDatabase(kbDir);
db.init(); db.init();
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
expect(db.getLastModified()).toBeGreaterThan(0); expect(db.getLastModified()).toBeGreaterThan(0);
db.close(); db.close();

View File

@@ -58,7 +58,7 @@ export function fromJson<T>(json: string | null | undefined): T | undefined {
// ── Schema Definition ──────────────────────────────────────────────── // ── Schema Definition ────────────────────────────────────────────────
const SCHEMA_VERSION = 3; const SCHEMA_VERSION = 4;
const SCHEMA_SQL = ` const SCHEMA_SQL = `
-- Tasks table with JSON columns for nested data -- Tasks table with JSON columns for nested data
@@ -75,6 +75,7 @@ CREATE TABLE IF NOT EXISTS tasks (
blockedBy TEXT, blockedBy TEXT,
paused INTEGER DEFAULT 0, paused INTEGER DEFAULT 0,
baseBranch TEXT, baseBranch TEXT,
baseCommitSha TEXT,
modelPresetId TEXT, modelPresetId TEXT,
modelProvider TEXT, modelProvider TEXT,
modelId TEXT, modelId TEXT,
@@ -99,7 +100,8 @@ CREATE TABLE IF NOT EXISTS tasks (
issueInfo TEXT, issueInfo TEXT,
mergeDetails TEXT, mergeDetails TEXT,
breakIntoSubtasks INTEGER DEFAULT 0, breakIntoSubtasks INTEGER DEFAULT 0,
enabledWorkflowSteps TEXT DEFAULT '[]' enabledWorkflowSteps TEXT DEFAULT '[]',
modifiedFiles TEXT DEFAULT '[]'
); );
-- Config table (single row with project settings) -- Config table (single row with project settings)
@@ -322,6 +324,15 @@ export class Database {
}); });
} }
if (version < 4) {
this.applyMigration(4, () => {
// Add modifiedFiles column to track files changed during agent execution
this.addColumnIfMissing("tasks", "modifiedFiles", "TEXT DEFAULT '[]'");
// Add baseCommitSha column to store the base commit for diff computation
this.addColumnIfMissing("tasks", "baseCommitSha", "TEXT");
});
}
// Future migrations go here: // Future migrations go here:
// if (version < 3) { this.applyMigration(3, () => { ... }); } // if (version < 3) { this.applyMigration(3, () => { ... }); }
} }

View File

@@ -133,6 +133,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
blockedBy: row.blockedBy || undefined, blockedBy: row.blockedBy || undefined,
paused: row.paused ? true : undefined, paused: row.paused ? true : undefined,
baseBranch: row.baseBranch || undefined, baseBranch: row.baseBranch || undefined,
baseCommitSha: row.baseCommitSha || undefined,
modelPresetId: row.modelPresetId || undefined, modelPresetId: row.modelPresetId || undefined,
modelProvider: row.modelProvider || undefined, modelProvider: row.modelProvider || undefined,
modelId: row.modelId || undefined, modelId: row.modelId || undefined,
@@ -157,6 +158,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
mergeDetails: fromJson<import("./types.js").MergeDetails>(row.mergeDetails), mergeDetails: fromJson<import("./types.js").MergeDetails>(row.mergeDetails),
breakIntoSubtasks: row.breakIntoSubtasks ? true : undefined, breakIntoSubtasks: row.breakIntoSubtasks ? true : undefined,
enabledWorkflowSteps: (() => { const e = fromJson<string[]>(row.enabledWorkflowSteps); return e && e.length > 0 ? e : undefined; })(), enabledWorkflowSteps: (() => { const e = fromJson<string[]>(row.enabledWorkflowSteps); return e && e.length > 0 ? e : undefined; })(),
modifiedFiles: (() => { const m = fromJson<string[]>(row.modifiedFiles); return m && m.length > 0 ? m : undefined; })(),
}; };
} }
@@ -167,15 +169,15 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
this.db.prepare(` this.db.prepare(`
INSERT OR REPLACE INTO tasks ( INSERT OR REPLACE INTO tasks (
id, title, description, "column", status, size, reviewLevel, currentStep, id, title, description, "column", status, size, reviewLevel, currentStep,
worktree, blockedBy, paused, baseBranch, modelPresetId, modelProvider, worktree, blockedBy, paused, baseBranch, baseCommitSha, modelPresetId, modelProvider,
modelId, validatorModelProvider, validatorModelId, mergeRetries, error, modelId, validatorModelProvider, validatorModelId, mergeRetries, error,
summary, thinkingLevel, createdAt, updatedAt, columnMovedAt, summary, thinkingLevel, createdAt, updatedAt, columnMovedAt,
dependencies, steps, log, attachments, steeringComments, dependencies, steps, log, attachments, steeringComments,
comments, workflowStepResults, prInfo, issueInfo, mergeDetails, comments, workflowStepResults, prInfo, issueInfo, mergeDetails,
breakIntoSubtasks, enabledWorkflowSteps breakIntoSubtasks, enabledWorkflowSteps, modifiedFiles
) VALUES ( ) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
) )
`).run( `).run(
task.id, task.id,
@@ -190,6 +192,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
task.blockedBy ?? null, task.blockedBy ?? null,
task.paused ? 1 : 0, task.paused ? 1 : 0,
task.baseBranch ?? null, task.baseBranch ?? null,
task.baseCommitSha ?? null,
task.modelPresetId ?? null, task.modelPresetId ?? null,
task.modelProvider ?? null, task.modelProvider ?? null,
task.modelId ?? null, task.modelId ?? null,
@@ -214,6 +217,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
toJsonNullable(task.mergeDetails), toJsonNullable(task.mergeDetails),
task.breakIntoSubtasks ? 1 : 0, task.breakIntoSubtasks ? 1 : 0,
toJson(task.enabledWorkflowSteps || []), toJson(task.enabledWorkflowSteps || []),
toJson(task.modifiedFiles || []),
); );
this.db.bumpLastModified(); this.db.bumpLastModified();
} }
@@ -875,7 +879,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
async updateTask( async updateTask(
id: string, id: string,
updates: { title?: string; description?: string; prompt?: string; worktree?: string; status?: string | null; dependencies?: string[]; blockedBy?: string | null; paused?: boolean; baseBranch?: string; size?: "S" | "M" | "L"; reviewLevel?: number; mergeRetries?: number; modelProvider?: string | null; modelId?: string | null; validatorModelProvider?: string | null; validatorModelId?: string | null; error?: string | null; summary?: string | null; workflowStepResults?: import("./types.js").WorkflowStepResult[] | null }, updates: { title?: string; description?: string; prompt?: string; worktree?: string; status?: string | null; dependencies?: string[]; blockedBy?: string | null; paused?: boolean; baseBranch?: string; baseCommitSha?: string; size?: "S" | "M" | "L"; reviewLevel?: number; mergeRetries?: number; modelProvider?: string | null; modelId?: string | null; validatorModelProvider?: string | null; validatorModelId?: string | null; error?: string | null; summary?: string | null; workflowStepResults?: import("./types.js").WorkflowStepResult[] | null; modifiedFiles?: string[] | null },
): Promise<Task> { ): Promise<Task> {
return this.withTaskLock(id, async () => { return this.withTaskLock(id, async () => {
// Validate that task doesn't depend on itself // Validate that task doesn't depend on itself
@@ -925,6 +929,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
} }
if (updates.paused !== undefined) task.paused = updates.paused || undefined; if (updates.paused !== undefined) task.paused = updates.paused || undefined;
if (updates.baseBranch !== undefined) task.baseBranch = updates.baseBranch; if (updates.baseBranch !== undefined) task.baseBranch = updates.baseBranch;
if (updates.baseCommitSha !== undefined) task.baseCommitSha = updates.baseCommitSha;
if (updates.size !== undefined) task.size = updates.size; if (updates.size !== undefined) task.size = updates.size;
if (updates.reviewLevel !== undefined) task.reviewLevel = updates.reviewLevel; if (updates.reviewLevel !== undefined) task.reviewLevel = updates.reviewLevel;
if (updates.mergeRetries !== undefined) task.mergeRetries = updates.mergeRetries; if (updates.mergeRetries !== undefined) task.mergeRetries = updates.mergeRetries;
@@ -963,6 +968,11 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
} else if (updates.workflowStepResults !== undefined) { } else if (updates.workflowStepResults !== undefined) {
task.workflowStepResults = updates.workflowStepResults; task.workflowStepResults = updates.workflowStepResults;
} }
if (updates.modifiedFiles === null) {
task.modifiedFiles = undefined;
} else if (updates.modifiedFiles !== undefined) {
task.modifiedFiles = updates.modifiedFiles;
}
task.updatedAt = new Date().toISOString(); task.updatedAt = new Date().toISOString();
await this.atomicWriteTaskJson(dir, task); await this.atomicWriteTaskJson(dir, task);
@@ -1465,8 +1475,10 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
breakIntoSubtasks: task.breakIntoSubtasks, breakIntoSubtasks: task.breakIntoSubtasks,
paused: task.paused, paused: task.paused,
baseBranch: task.baseBranch, baseBranch: task.baseBranch,
baseCommitSha: task.baseCommitSha,
mergeRetries: task.mergeRetries, mergeRetries: task.mergeRetries,
error: task.error, error: task.error,
modifiedFiles: task.modifiedFiles,
}; };
// Write to archivedTasks table in SQLite // Write to archivedTasks table in SQLite
@@ -2295,8 +2307,10 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
breakIntoSubtasks: task.breakIntoSubtasks, breakIntoSubtasks: task.breakIntoSubtasks,
paused: task.paused, paused: task.paused,
baseBranch: task.baseBranch, baseBranch: task.baseBranch,
baseCommitSha: task.baseCommitSha,
mergeRetries: task.mergeRetries, mergeRetries: task.mergeRetries,
error: task.error, error: task.error,
modifiedFiles: task.modifiedFiles,
}; };
// Write to archivedTasks table // Write to archivedTasks table
@@ -2359,7 +2373,8 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
validatorModelProvider: entry.validatorModelProvider, validatorModelProvider: entry.validatorModelProvider,
validatorModelId: entry.validatorModelId, validatorModelId: entry.validatorModelId,
breakIntoSubtasks: entry.breakIntoSubtasks, breakIntoSubtasks: entry.breakIntoSubtasks,
// Intentionally NOT restoring: worktree, status, blockedBy, paused, baseBranch, error, steeringComments modifiedFiles: entry.modifiedFiles,
// Intentionally NOT restoring: worktree, status, blockedBy, paused, baseBranch, baseCommitSha, error, steeringComments
}; };
// Write task.json // Write task.json

View File

@@ -387,6 +387,10 @@ export interface Task {
* unmerged branch. The executor reads this to branch from the * unmerged branch. The executor reads this to branch from the
* dependency's branch instead of HEAD. Cleared after worktree creation. */ * dependency's branch instead of HEAD. Cleared after worktree creation. */
baseBranch?: string; baseBranch?: string;
/** Commit SHA of the base branch at worktree creation time.
* Used for computing file diffs when reviewing task changes.
* Set by the executor when creating the worktree. */
baseCommitSha?: string;
attachments?: TaskAttachment[]; attachments?: TaskAttachment[];
steeringComments?: SteeringComment[]; steeringComments?: SteeringComment[];
comments?: TaskComment[]; comments?: TaskComment[];
@@ -428,6 +432,8 @@ export interface Task {
error?: string; error?: string;
/** Optional summary of what was changed/fixed when task is completed */ /** Optional summary of what was changed/fixed when task is completed */
summary?: string; summary?: string;
/** Files modified during agent execution, captured at task completion time */
modifiedFiles?: string[];
/** ISO-8601 timestamp of when the task last entered its current column. /** ISO-8601 timestamp of when the task last entered its current column.
* Used to sort cards within a column so that recently-moved cards appear at the top. */ * Used to sort cards within a column so that recently-moved cards appear at the top. */
columnMovedAt?: string; columnMovedAt?: string;
@@ -523,6 +529,9 @@ export interface GlobalSettings {
/** ntfy.sh topic name for push notifications. When set along with ntfyEnabled, /** ntfy.sh topic name for push notifications. When set along with ntfyEnabled,
* notifications are sent to https://ntfy.sh/{topic} when tasks complete or fail. */ * notifications are sent to https://ntfy.sh/{topic} when tasks complete or fail. */
ntfyTopic?: string; ntfyTopic?: string;
/** Default project ID for the current user. Used to automatically select
* the default project when opening the dashboard without a specific project. */
defaultProjectId?: string;
} }
/** /**
@@ -682,6 +691,7 @@ export const DEFAULT_GLOBAL_SETTINGS: Required<Pick<GlobalSettings, "themeMode"
defaultThinkingLevel: undefined, defaultThinkingLevel: undefined,
ntfyEnabled: false, ntfyEnabled: false,
ntfyTopic: undefined, ntfyTopic: undefined,
defaultProjectId: undefined,
}; };
/** Default values for project-level settings. */ /** Default values for project-level settings. */
@@ -740,6 +750,7 @@ export const GLOBAL_SETTINGS_KEYS: ReadonlyArray<keyof GlobalSettings> = [
"defaultThinkingLevel", "defaultThinkingLevel",
"ntfyEnabled", "ntfyEnabled",
"ntfyTopic", "ntfyTopic",
"defaultProjectId",
] as const; ] as const;
/** Keys that belong to the project settings scope. */ /** Keys that belong to the project settings scope. */
@@ -861,8 +872,11 @@ export interface ArchivedTaskEntry {
breakIntoSubtasks?: boolean; breakIntoSubtasks?: boolean;
paused?: boolean; paused?: boolean;
baseBranch?: string; baseBranch?: string;
baseCommitSha?: string;
mergeRetries?: number; mergeRetries?: number;
error?: string; error?: string;
/** Files modified during agent execution, captured at task completion time */
modifiedFiles?: string[];
} }
/** Type of planning question presented to the user */ /** Type of planning question presented to the user */

View File

@@ -1722,3 +1722,160 @@ export async function summarizeTitle(
return data.title; return data.title;
} }
// ── Project Management API (Multi-Project Support) ───────────────────────
/** Project information returned by project endpoints */
export interface ProjectInfo {
id: string;
name: string;
path: string;
status: "active" | "paused" | "errored" | "initializing";
isolationMode: "in-process" | "child-process";
createdAt: string;
updatedAt: string;
lastActivityAt?: string;
}
/** Project health metrics */
export interface ProjectHealth {
projectId: string;
status: "active" | "paused" | "errored" | "initializing";
activeTaskCount: number;
inFlightAgentCount: number;
lastActivityAt?: string;
lastErrorAt?: string;
lastErrorMessage?: string;
totalTasksCompleted: number;
totalTasksFailed: number;
averageTaskDurationMs?: number;
updatedAt: string;
}
/** Unified activity feed entry */
export interface ActivityFeedEntry {
id: string;
timestamp: string;
type: "task:created" | "task:moved" | "task:updated" | "task:deleted" | "task:merged" | "task:failed" | "settings:updated";
projectId: string;
projectName: string;
taskId?: string;
taskTitle?: string;
details: string;
metadata?: Record<string, unknown>;
}
/** Input for creating a new project */
export interface ProjectCreateInput {
name: string;
path: string;
isolationMode?: "in-process" | "child-process";
}
/** Options for fetching activity feed */
export interface FeedOptions {
limit?: number;
since?: string;
projectId?: string;
type?: ActivityFeedEntry["type"];
}
/** Global concurrency state across all projects */
export interface GlobalConcurrencyState {
globalMaxConcurrent: number;
currentlyActive: number;
queuedCount: number;
projectsActive: Record<string, number>;
}
/** First run status response */
export interface FirstRunStatus {
hasProjects: boolean;
singleProjectPath: string | null;
}
/** Fetch all registered projects */
export function fetchProjects(): Promise<ProjectInfo[]> {
return api<ProjectInfo[]>("/projects");
}
/** Register a new project */
export function registerProject(input: ProjectCreateInput): Promise<ProjectInfo> {
return api<ProjectInfo>("/projects", {
method: "POST",
body: JSON.stringify(input),
});
}
/** Unregister a project */
export function unregisterProject(id: string): Promise<void> {
return api<void>(`/projects/${encodeURIComponent(id)}`, {
method: "DELETE",
});
}
/** Fetch health metrics for a specific project */
export function fetchProjectHealth(id: string): Promise<ProjectHealth> {
return api<ProjectHealth>(`/projects/${encodeURIComponent(id)}/health`);
}
/** Fetch unified activity feed */
export function fetchActivityFeed(options?: FeedOptions): Promise<ActivityFeedEntry[]> {
const params = new URLSearchParams();
if (options?.limit !== undefined) params.set("limit", String(options.limit));
if (options?.since) params.set("since", options.since);
if (options?.projectId) params.set("projectId", options.projectId);
if (options?.type) params.set("type", options.type);
const query = params.size > 0 ? `?${params.toString()}` : "";
return api<ActivityFeedEntry[]>(`/activity-feed${query}`);
}
/** Pause a project */
export function pauseProject(id: string): Promise<ProjectInfo> {
return api<ProjectInfo>(`/projects/${encodeURIComponent(id)}/pause`, {
method: "POST",
});
}
/** Resume a paused project */
export function resumeProject(id: string): Promise<ProjectInfo> {
return api<ProjectInfo>(`/projects/${encodeURIComponent(id)}/resume`, {
method: "POST",
});
}
/** Fetch first run status to detect if user needs setup wizard */
export function fetchFirstRunStatus(): Promise<FirstRunStatus> {
return api<FirstRunStatus>("/first-run-status");
}
/** Fetch global concurrency state */
export function fetchGlobalConcurrency(): Promise<GlobalConcurrencyState> {
return api<GlobalConcurrencyState>("/global-concurrency");
}
/** Fetch tasks for a specific project */
export function fetchProjectTasks(projectId: string, limit?: number, offset?: number): Promise<Task[]> {
const params = new URLSearchParams();
params.set("projectId", projectId);
if (limit !== undefined) params.set("limit", String(limit));
if (offset !== undefined) params.set("offset", String(offset));
return api<Task[]>(`/tasks?${params.toString()}`);
}
/** Fetch project-specific config */
export function fetchProjectConfig(projectId: string): Promise<{ maxConcurrent: number; rootDir: string }> {
return api<{ maxConcurrent: number; rootDir: string }>(`/projects/${encodeURIComponent(projectId)}/config`);
}
/** Diff information for a task */
export interface TaskDiff {
files: string[];
diffs: Record<string, { stat: string; patch: string }>;
}
/** Fetch diff information for a task */
export function fetchTaskDiff(taskId: string): Promise<TaskDiff> {
return api<TaskDiff>(`/tasks/${encodeURIComponent(taskId)}/diff`);
}

View File

@@ -13,6 +13,7 @@ import { ModelSelectorTab } from "./ModelSelectorTab";
import { PrSection } from "./PrSection"; import { PrSection } from "./PrSection";
import { TaskComments } from "./TaskComments"; import { TaskComments } from "./TaskComments";
import { MergeDetails } from "./MergeDetails"; import { MergeDetails } from "./MergeDetails";
import { TaskChangesTab } from "./TaskChangesTab";
interface ModelSelection { interface ModelSelection {
provider?: string; provider?: string;
@@ -105,7 +106,7 @@ export function TaskDetailModal({
addToast, addToast,
githubTokenConfigured, githubTokenConfigured,
}: TaskDetailModalProps) { }: TaskDetailModalProps) {
const [activeTab, setActiveTab] = useState<"definition" | "activity" | "agent-log" | "steering" | "comments" | "model">("definition"); const [activeTab, setActiveTab] = useState<"definition" | "activity" | "agent-log" | "changes" | "steering" | "comments" | "model">("definition");
const [attachments, setAttachments] = useState<TaskAttachment[]>(task.attachments || []); const [attachments, setAttachments] = useState<TaskAttachment[]>(task.attachments || []);
const [uploading, setUploading] = useState(false); const [uploading, setUploading] = useState(false);
const [dependencies, setDependencies] = useState<string[]>(task.dependencies || []); const [dependencies, setDependencies] = useState<string[]>(task.dependencies || []);
@@ -671,6 +672,14 @@ export function TaskDetailModal({
> >
Agent Log Agent Log
</button> </button>
{(task.column === "in-progress" || task.column === "in-review" || task.column === "done") && (
<button
className={`detail-tab${activeTab === "changes" ? " detail-tab-active" : ""}`}
onClick={() => setActiveTab("changes")}
>
Changes
</button>
)}
<button <button
className={`detail-tab${activeTab === "steering" ? " detail-tab-active" : ""}`} className={`detail-tab${activeTab === "steering" ? " detail-tab-active" : ""}`}
onClick={() => setActiveTab("steering")} onClick={() => setActiveTab("steering")}
@@ -703,6 +712,8 @@ export function TaskDetailModal({
validatorModel={getValidatorSelection(task)} validatorModel={getValidatorSelection(task)}
/> />
</div> </div>
) : activeTab === "changes" ? (
<TaskChangesTab taskId={task.id} worktree={task.worktree} />
) : activeTab === "steering" ? ( ) : activeTab === "steering" ? (
<SteeringTab task={task} addToast={addToast} /> <SteeringTab task={task} addToast={addToast} />
) : activeTab === "comments" ? ( ) : activeTab === "comments" ? (

View File

@@ -11054,3 +11054,134 @@ html .column.drag-over * {
[data-theme="light"] .gm-load-more:hover { [data-theme="light"] .gm-load-more:hover {
background: rgba(0, 0, 0, 0.03); background: rgba(0, 0, 0, 0.03);
} }
/* ── Task Changes Tab Styles ─────────────────────────────────────────────── */
.task-changes-tab {
padding: 16px;
}
.changes-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
}
.changes-header h4 {
margin: 0;
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
font-weight: 500;
}
.changes-file-list {
border: 1px solid var(--border, #30363d);
border-radius: 8px;
overflow: hidden;
}
.changes-file-item {
border-bottom: 1px solid var(--border, #30363d);
}
.changes-file-item:last-child {
border-bottom: none;
}
.changes-file-item.expanded {
background: var(--bg-secondary, #161b22);
}
.changes-file-header {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 12px;
background: none;
border: none;
width: 100%;
text-align: left;
cursor: pointer;
color: var(--text-primary, #c9d1d9);
font-size: 13px;
transition: background 0.15s;
}
.changes-file-header:hover {
background: var(--bg-hover, #1f242c);
}
.changes-file-toggle {
display: flex;
align-items: center;
color: var(--text-secondary, #8b949e);
flex-shrink: 0;
}
.changes-file-status {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
flex-shrink: 0;
}
.changes-file-path {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
}
.changes-file-stat {
color: var(--text-secondary, #8b949e);
font-size: 11px;
flex-shrink: 0;
margin-left: 8px;
}
.changes-file-content {
border-top: 1px solid var(--border, #30363d);
background: var(--bg-primary, #0d1117);
}
.changes-diff-patch {
margin: 0;
padding: 12px;
font-size: 12px;
line-height: 1.5;
overflow-x: auto;
white-space: pre;
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
color: var(--text-primary, #c9d1d9);
}
.changes-diff-patch code {
background: none;
padding: 0;
}
/* Syntax highlighting for diff */
.changes-diff-patch .diff-add,
.changes-diff-patch [data-prefix="+"] {
color: #3fb950;
}
.changes-diff-patch .diff-del,
.changes-diff-patch [data-prefix="-"] {
color: #f85149;
}
.changes-diff-patch .diff-hunk,
.changes-diff-patch [data-prefix="@@"] {
color: #58a6ff;
}

View File

@@ -25,6 +25,8 @@ import type {
FeatureCreateInput, FeatureCreateInput,
MissionStatus, MissionStatus,
MilestoneStatus, MilestoneStatus,
SliceStatus,
FeatureStatus,
InterviewState, InterviewState,
} from "@fusion/core"; } from "@fusion/core";
import { import {
@@ -41,20 +43,29 @@ function validateUuid(id: string): boolean {
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id); return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);
} }
function validateMissionId(id: string): boolean { function validateMissionId(id: string | string[]): boolean {
return /^M-\d+$/.test(id); const str = Array.isArray(id) ? id[0] : id;
return /^M-\d+$/.test(str);
} }
function validateMilestoneId(id: string): boolean { function validateMilestoneId(id: string | string[]): boolean {
return /^MS-\d+$/.test(id); const str = Array.isArray(id) ? id[0] : id;
return /^MS-\d+$/.test(str);
} }
function validateSliceId(id: string): boolean { function validateSliceId(id: string | string[]): boolean {
return /^SL-\d+$/.test(id); const str = Array.isArray(id) ? id[0] : id;
return /^SL-\d+$/.test(str);
} }
function validateFeatureId(id: string): boolean { function validateFeatureId(id: string | string[]): boolean {
return /^F-\d+$/.test(id); const str = Array.isArray(id) ? id[0] : id;
return /^F-\d+$/.test(str);
}
/** Helper to extract string from Express param (handles string | string[]) */
function paramString(value: string | string[]): string {
return Array.isArray(value) ? value[0] : value;
} }
function validateTitle(title: unknown): string { function validateTitle(title: unknown): string {
@@ -174,7 +185,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.get( router.get(
"/:missionId", "/:missionId",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { missionId } = req.params; const missionId = paramString(req.params.missionId);
if (!validateMissionId(missionId)) { if (!validateMissionId(missionId)) {
res.status(400).json({ error: "Invalid mission ID format" }); res.status(400).json({ error: "Invalid mission ID format" });
@@ -198,7 +209,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.patch( router.patch(
"/:missionId", "/:missionId",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { missionId } = req.params; const missionId = paramString(req.params.missionId);
const { title, description, status } = req.body; const { title, description, status } = req.body;
if (!validateMissionId(missionId)) { if (!validateMissionId(missionId)) {
@@ -243,7 +254,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.delete( router.delete(
"/:missionId", "/:missionId",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { missionId } = req.params; const missionId = paramString(req.params.missionId);
if (!validateMissionId(missionId)) { if (!validateMissionId(missionId)) {
res.status(400).json({ error: "Invalid mission ID format" }); res.status(400).json({ error: "Invalid mission ID format" });
@@ -268,7 +279,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.get( router.get(
"/:missionId/status", "/:missionId/status",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { missionId } = req.params; const missionId = paramString(req.params.missionId);
if (!validateMissionId(missionId)) { if (!validateMissionId(missionId)) {
res.status(400).json({ error: "Invalid mission ID format" }); res.status(400).json({ error: "Invalid mission ID format" });
@@ -295,7 +306,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.get( router.get(
"/:missionId/interview-state", "/:missionId/interview-state",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { missionId } = req.params; const missionId = paramString(req.params.missionId);
if (!validateMissionId(missionId)) { if (!validateMissionId(missionId)) {
res.status(400).json({ error: "Invalid mission ID format" }); res.status(400).json({ error: "Invalid mission ID format" });
@@ -319,7 +330,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.post( router.post(
"/:missionId/interview-state", "/:missionId/interview-state",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { missionId } = req.params; const missionId = paramString(req.params.missionId);
const { state } = req.body; const { state } = req.body;
if (!validateMissionId(missionId)) { if (!validateMissionId(missionId)) {
@@ -351,7 +362,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.get( router.get(
"/:missionId/milestones", "/:missionId/milestones",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { missionId } = req.params; const missionId = paramString(req.params.missionId);
if (!validateMissionId(missionId)) { if (!validateMissionId(missionId)) {
res.status(400).json({ error: "Invalid mission ID format" }); res.status(400).json({ error: "Invalid mission ID format" });
@@ -378,7 +389,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.post( router.post(
"/:missionId/milestones", "/:missionId/milestones",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { missionId } = req.params; const missionId = paramString(req.params.missionId);
const { title, description, dependencies } = req.body; const { title, description, dependencies } = req.body;
if (!validateMissionId(missionId)) { if (!validateMissionId(missionId)) {
@@ -414,7 +425,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.post( router.post(
"/:missionId/milestones/reorder", "/:missionId/milestones/reorder",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { missionId } = req.params; const missionId = paramString(req.params.missionId);
if (!validateMissionId(missionId)) { if (!validateMissionId(missionId)) {
res.status(400).json({ error: "Invalid mission ID format" }); res.status(400).json({ error: "Invalid mission ID format" });
@@ -456,7 +467,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.get( router.get(
"/milestones/:milestoneId", "/milestones/:milestoneId",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { milestoneId } = req.params; const milestoneId = paramString(req.params.milestoneId);
if (!validateMilestoneId(milestoneId)) { if (!validateMilestoneId(milestoneId)) {
res.status(400).json({ error: "Invalid milestone ID format" }); res.status(400).json({ error: "Invalid milestone ID format" });
@@ -480,7 +491,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.patch( router.patch(
"/milestones/:milestoneId", "/milestones/:milestoneId",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { milestoneId } = req.params; const milestoneId = paramString(req.params.milestoneId);
const { title, description, status, dependencies } = req.body; const { title, description, status, dependencies } = req.body;
if (!validateMilestoneId(milestoneId)) { if (!validateMilestoneId(milestoneId)) {
@@ -528,7 +539,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.delete( router.delete(
"/milestones/:milestoneId", "/milestones/:milestoneId",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { milestoneId } = req.params; const milestoneId = paramString(req.params.milestoneId);
if (!validateMilestoneId(milestoneId)) { if (!validateMilestoneId(milestoneId)) {
res.status(400).json({ error: "Invalid milestone ID format" }); res.status(400).json({ error: "Invalid milestone ID format" });
@@ -555,7 +566,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.get( router.get(
"/milestones/:milestoneId/interview-state", "/milestones/:milestoneId/interview-state",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { milestoneId } = req.params; const milestoneId = paramString(req.params.milestoneId);
if (!validateMilestoneId(milestoneId)) { if (!validateMilestoneId(milestoneId)) {
res.status(400).json({ error: "Invalid milestone ID format" }); res.status(400).json({ error: "Invalid milestone ID format" });
@@ -579,7 +590,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.post( router.post(
"/milestones/:milestoneId/interview-state", "/milestones/:milestoneId/interview-state",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { milestoneId } = req.params; const milestoneId = paramString(req.params.milestoneId);
const { state } = req.body; const { state } = req.body;
if (!validateMilestoneId(milestoneId)) { if (!validateMilestoneId(milestoneId)) {
@@ -611,7 +622,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.get( router.get(
"/milestones/:milestoneId/slices", "/milestones/:milestoneId/slices",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { milestoneId } = req.params; const milestoneId = paramString(req.params.milestoneId);
if (!validateMilestoneId(milestoneId)) { if (!validateMilestoneId(milestoneId)) {
res.status(400).json({ error: "Invalid milestone ID format" }); res.status(400).json({ error: "Invalid milestone ID format" });
@@ -638,7 +649,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.post( router.post(
"/milestones/:milestoneId/slices", "/milestones/:milestoneId/slices",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { milestoneId } = req.params; const milestoneId = paramString(req.params.milestoneId);
const { title, description } = req.body; const { title, description } = req.body;
if (!validateMilestoneId(milestoneId)) { if (!validateMilestoneId(milestoneId)) {
@@ -672,7 +683,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.post( router.post(
"/milestones/:milestoneId/slices/reorder", "/milestones/:milestoneId/slices/reorder",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { milestoneId } = req.params; const milestoneId = paramString(req.params.milestoneId);
if (!validateMilestoneId(milestoneId)) { if (!validateMilestoneId(milestoneId)) {
res.status(400).json({ error: "Invalid milestone ID format" }); res.status(400).json({ error: "Invalid milestone ID format" });
@@ -714,7 +725,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.get( router.get(
"/slices/:sliceId", "/slices/:sliceId",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { sliceId } = req.params; const sliceId = paramString(req.params.sliceId);
if (!validateSliceId(sliceId)) { if (!validateSliceId(sliceId)) {
res.status(400).json({ error: "Invalid slice ID format" }); res.status(400).json({ error: "Invalid slice ID format" });
@@ -738,7 +749,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.patch( router.patch(
"/slices/:sliceId", "/slices/:sliceId",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { sliceId } = req.params; const sliceId = paramString(req.params.sliceId);
const { title, description, status } = req.body; const { title, description, status } = req.body;
if (!validateSliceId(sliceId)) { if (!validateSliceId(sliceId)) {
@@ -783,7 +794,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.delete( router.delete(
"/slices/:sliceId", "/slices/:sliceId",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { sliceId } = req.params; const sliceId = paramString(req.params.sliceId);
if (!validateSliceId(sliceId)) { if (!validateSliceId(sliceId)) {
res.status(400).json({ error: "Invalid slice ID format" }); res.status(400).json({ error: "Invalid slice ID format" });
@@ -808,7 +819,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.post( router.post(
"/slices/:sliceId/activate", "/slices/:sliceId/activate",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { sliceId } = req.params; const sliceId = paramString(req.params.sliceId);
if (!validateSliceId(sliceId)) { if (!validateSliceId(sliceId)) {
res.status(400).json({ error: "Invalid slice ID format" }); res.status(400).json({ error: "Invalid slice ID format" });
@@ -837,7 +848,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.get( router.get(
"/slices/:sliceId/features", "/slices/:sliceId/features",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { sliceId } = req.params; const sliceId = paramString(req.params.sliceId);
if (!validateSliceId(sliceId)) { if (!validateSliceId(sliceId)) {
res.status(400).json({ error: "Invalid slice ID format" }); res.status(400).json({ error: "Invalid slice ID format" });
@@ -862,7 +873,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.post( router.post(
"/slices/:sliceId/features", "/slices/:sliceId/features",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { sliceId } = req.params; const sliceId = paramString(req.params.sliceId);
const { title, description, acceptanceCriteria } = req.body; const { title, description, acceptanceCriteria } = req.body;
if (!validateSliceId(sliceId)) { if (!validateSliceId(sliceId)) {
@@ -898,7 +909,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.get( router.get(
"/features/:featureId", "/features/:featureId",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { featureId } = req.params; const featureId = paramString(req.params.featureId);
if (!validateFeatureId(featureId)) { if (!validateFeatureId(featureId)) {
res.status(400).json({ error: "Invalid feature ID format" }); res.status(400).json({ error: "Invalid feature ID format" });
@@ -922,7 +933,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.patch( router.patch(
"/features/:featureId", "/features/:featureId",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { featureId } = req.params; const featureId = paramString(req.params.featureId);
const { title, description, acceptanceCriteria, status } = req.body; const { title, description, acceptanceCriteria, status } = req.body;
if (!validateFeatureId(featureId)) { if (!validateFeatureId(featureId)) {
@@ -970,7 +981,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.delete( router.delete(
"/features/:featureId", "/features/:featureId",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { featureId } = req.params; const featureId = paramString(req.params.featureId);
if (!validateFeatureId(featureId)) { if (!validateFeatureId(featureId)) {
res.status(400).json({ error: "Invalid feature ID format" }); res.status(400).json({ error: "Invalid feature ID format" });
@@ -995,7 +1006,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.post( router.post(
"/features/:featureId/link-task", "/features/:featureId/link-task",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { featureId } = req.params; const featureId = paramString(req.params.featureId);
const { taskId } = req.body; const { taskId } = req.body;
if (!validateFeatureId(featureId)) { if (!validateFeatureId(featureId)) {
@@ -1034,7 +1045,7 @@ export function createMissionRouter(store: TaskStore): Router {
router.post( router.post(
"/features/:featureId/unlink-task", "/features/:featureId/unlink-task",
asyncHandler(async (req, res) => { asyncHandler(async (req, res) => {
const { featureId } = req.params; const featureId = paramString(req.params.featureId);
if (!validateFeatureId(featureId)) { if (!validateFeatureId(featureId)) {
res.status(400).json({ error: "Invalid feature ID format" }); res.status(400).json({ error: "Invalid feature ID format" });

View File

@@ -1841,6 +1841,82 @@ export function createApiRoutes(store: TaskStore, options?: ServerOptions): Rout
} }
}); });
/**
* GET /api/tasks/:id/diff
* Get detailed diff information for files modified during task execution.
* Returns: { files: string[]; diffs: Record<string, { stat: string; patch: string }> }
*/
router.get("/tasks/:id/diff", async (req, res) => {
try {
const task = await store.getTask(req.params.id);
// Only tasks with worktrees can have diffs
if (!task.worktree || !existsSync(task.worktree)) {
res.json({ files: [], diffs: {} });
return;
}
// Use stored modifiedFiles if available, otherwise compute on-the-fly
let files = task.modifiedFiles;
if (!files || files.length === 0) {
// Fallback: compute files using git diff
try {
const baseRef = task.baseCommitSha ?? "HEAD~1";
const output = execSync(`git diff --name-only ${baseRef}..HEAD`, {
cwd: task.worktree,
encoding: "utf-8",
timeout: 5000,
}).trim();
files = output ? output.split("\n").filter(Boolean) : [];
} catch {
files = [];
}
}
if (files.length === 0) {
res.json({ files: [], diffs: {} });
return;
}
// Compute diffs for each file
const diffs: Record<string, { stat: string; patch: string }> = {};
const baseRef = task.baseCommitSha ?? "HEAD~1";
for (const file of files) {
try {
// Get stat for this file
const stat = execSync(`git diff --stat ${baseRef}..HEAD -- "${file}"`, {
cwd: task.worktree,
encoding: "utf-8",
timeout: 5000,
}).trim();
// Get patch for this file
const patch = execSync(`git diff ${baseRef}..HEAD -- "${file}"`, {
cwd: task.worktree,
encoding: "utf-8",
timeout: 10000,
});
diffs[file] = { stat, patch };
} catch (err: any) {
// Log error but continue with other files
console.warn(`Failed to get diff for ${file}:`, err.message);
diffs[file] = { stat: "", patch: "" };
}
}
res.json({ files, diffs });
} catch (err: any) {
if (err.code === "ENOENT") {
res.status(404).json({ error: `Task ${req.params.id} not found` });
} else {
res.status(500).json({ error: err.message || "Internal server error" });
}
}
});
/** /**
* GET /api/tasks/:id/workflow-results * GET /api/tasks/:id/workflow-results
* Get workflow step execution results for a task. * Get workflow step execution results for a task.

View File

@@ -455,6 +455,23 @@ export class TaskExecutor {
worktreePath = await this.createWorktree(branchName, worktreePath, task.id); worktreePath = await this.createWorktree(branchName, worktreePath, task.id);
} }
// Capture the base commit SHA for diff computation
// This is done after worktree creation when we're on the new branch
if (!task.baseCommitSha) {
try {
const baseCommitSha = execSync("git rev-parse HEAD", {
cwd: worktreePath,
stdio: "pipe",
encoding: "utf-8",
}).trim();
await this.store.updateTask(task.id, { baseCommitSha });
executorLog.log(`${task.id}: captured baseCommitSha ${baseCommitSha.slice(0, 7)}`);
} catch (err: any) {
executorLog.log(`Failed to capture baseCommitSha for ${task.id}: ${err.message}`);
// Non-fatal: task can continue without baseCommitSha
}
}
this.activeWorktrees.set(task.id, worktreePath); this.activeWorktrees.set(task.id, worktreePath);
this.options.onStart?.(task, worktreePath); this.options.onStart?.(task, worktreePath);
@@ -569,6 +586,14 @@ export class TaskExecutor {
} }
if (taskDone) { if (taskDone) {
// Capture modified files before running workflow steps
const updatedTask = await this.store.getTask(task.id);
const modifiedFiles = this.captureModifiedFiles(worktreePath, updatedTask.baseCommitSha);
if (modifiedFiles.length > 0) {
await this.store.updateTask(task.id, { modifiedFiles });
executorLog.log(`${task.id}: captured ${modifiedFiles.length} modified files`);
}
// Run workflow steps before moving to in-review // Run workflow steps before moving to in-review
const workflowSuccess = await this.runWorkflowSteps(task, worktreePath, settings); const workflowSuccess = await this.runWorkflowSteps(task, worktreePath, settings);
if (!workflowSuccess) { if (!workflowSuccess) {
@@ -1065,6 +1090,61 @@ export class TaskExecutor {
await this.store.logEntry(taskId, "Execution stopped — work discarded, moved to triage for re-specification"); await this.store.logEntry(taskId, "Execution stopped — work discarded, moved to triage for re-specification");
} }
/**
* Capture the list of files modified during agent execution.
* Uses git diff against the stored baseCommitSha to determine what changed.
* Returns an empty array if no changes or if git commands fail.
*/
private captureModifiedFiles(worktreePath: string, baseCommitSha?: string): string[] {
try {
// Determine the base reference for diff
// If baseCommitSha is stored, use it; otherwise fall back to merge-base with HEAD
let baseRef = baseCommitSha;
if (!baseRef) {
// Try to find merge-base with main/master as fallback
try {
baseRef = execSync("git merge-base HEAD origin/main 2>/dev/null || git merge-base HEAD main", {
cwd: worktreePath,
stdio: "pipe",
encoding: "utf-8",
}).trim();
} catch {
// If merge-base fails, use HEAD~1 as last resort
try {
baseRef = execSync("git rev-parse HEAD~1", {
cwd: worktreePath,
stdio: "pipe",
encoding: "utf-8",
}).trim();
} catch {
executorLog.log(`Could not determine base commit for diff in ${worktreePath}`);
return [];
}
}
}
if (!baseRef) {
return [];
}
// Get list of modified files using git diff --name-only
const output = execSync(`git diff --name-only ${baseRef}..HEAD`, {
cwd: worktreePath,
stdio: "pipe",
encoding: "utf-8",
}).trim();
if (!output) {
return [];
}
return output.split("\n").filter(Boolean);
} catch (err: any) {
executorLog.log(`Failed to capture modified files: ${err.message}`);
return [];
}
}
// ── Worktree management ──────────────────────────────────────────── // ── Worktree management ────────────────────────────────────────────
/** /**