feat(KB-617): add diff viewer tab to task detail modal

- Add modifiedFiles and baseCommitSha tracking during task execution
- Create GET /tasks/:id/diff API endpoint for file list and patches
- Build TaskChangesTab component with expandable file diffs
- Integrate Changes tab into TaskDetailModal for in-progress, in-review, and done tasks
- Add database columns and types for diff tracking
- Update executor to capture modified files during agent sessions
This commit is contained in:
gsxdsm
2026-03-31 23:31:04 -07:00
parent 7eca797c0f
commit e5c598122f
12 changed files with 386 additions and 28 deletions

View File

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

View File

@@ -86,7 +86,7 @@ describe("Database", () => {
});
it("seeds schema version", () => {
expect(db.getSchemaVersion()).toBe(3);
expect(db.getSchemaVersion()).toBe(4);
});
it("seeds lastModified", () => {
@@ -109,7 +109,7 @@ describe("Database", () => {
it("is idempotent - calling init() twice does not fail", () => {
expect(() => db.init()).not.toThrow();
expect(db.getSchemaVersion()).toBe(3);
expect(db.getSchemaVersion()).toBe(4);
});
it("does not overwrite existing config on re-init", () => {
@@ -683,8 +683,8 @@ describe("schema migrations", () => {
// Now run init() which should trigger migration
db.init();
// Verify version bumped to 3 (includes both v1→v2 and v2→v3 migrations)
expect(db.getSchemaVersion()).toBe(3);
// Verify version bumped to 4 (includes v1→v2, v2→v3, and v3→v4 migrations)
expect(db.getSchemaVersion()).toBe(4);
// Verify new columns exist and existing data is intact
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);
db.init();
expect(db.getSchemaVersion()).toBe(3);
expect(db.getSchemaVersion()).toBe(4);
// Re-init should not fail
db.init();
expect(db.getSchemaVersion()).toBe(3);
expect(db.getSchemaVersion()).toBe(4);
db.close();
});
@@ -804,11 +804,11 @@ describe("schema migrations", () => {
// 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')`);
// Now run init() which should trigger v2→v3 migration
// Now run init() which should trigger migrations v2→v3→v4
db.init();
// Verify version bumped to 3
expect(db.getSchemaVersion()).toBe(3);
// Verify version bumped to 4
expect(db.getSchemaVersion()).toBe(4);
// Verify new columns exist and existing data is intact
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
@@ -864,7 +864,7 @@ describe("createDatabase factory", () => {
const db = createDatabase(kbDir);
db.init();
expect(db.getSchemaVersion()).toBe(3);
expect(db.getSchemaVersion()).toBe(4);
expect(db.getLastModified()).toBeGreaterThan(0);
db.close();

View File

@@ -58,7 +58,7 @@ export function fromJson<T>(json: string | null | undefined): T | undefined {
// ── Schema Definition ────────────────────────────────────────────────
const SCHEMA_VERSION = 3;
const SCHEMA_VERSION = 4;
const SCHEMA_SQL = `
-- Tasks table with JSON columns for nested data
@@ -75,6 +75,7 @@ CREATE TABLE IF NOT EXISTS tasks (
blockedBy TEXT,
paused INTEGER DEFAULT 0,
baseBranch TEXT,
baseCommitSha TEXT,
modelPresetId TEXT,
modelProvider TEXT,
modelId TEXT,
@@ -99,7 +100,8 @@ CREATE TABLE IF NOT EXISTS tasks (
issueInfo TEXT,
mergeDetails TEXT,
breakIntoSubtasks INTEGER DEFAULT 0,
enabledWorkflowSteps TEXT DEFAULT '[]'
enabledWorkflowSteps TEXT DEFAULT '[]',
modifiedFiles TEXT DEFAULT '[]'
);
-- 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:
// if (version < 3) { this.applyMigration(3, () => { ... }); }
}

View File

@@ -133,6 +133,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
blockedBy: row.blockedBy || undefined,
paused: row.paused ? true : undefined,
baseBranch: row.baseBranch || undefined,
baseCommitSha: row.baseCommitSha || undefined,
modelPresetId: row.modelPresetId || undefined,
modelProvider: row.modelProvider || undefined,
modelId: row.modelId || undefined,
@@ -157,6 +158,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
mergeDetails: fromJson<import("./types.js").MergeDetails>(row.mergeDetails),
breakIntoSubtasks: row.breakIntoSubtasks ? true : 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(`
INSERT OR REPLACE INTO tasks (
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,
summary, thinkingLevel, createdAt, updatedAt, columnMovedAt,
dependencies, steps, log, attachments, steeringComments,
comments, workflowStepResults, prInfo, issueInfo, mergeDetails,
breakIntoSubtasks, enabledWorkflowSteps
breakIntoSubtasks, enabledWorkflowSteps, modifiedFiles
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)
`).run(
task.id,
@@ -190,6 +192,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
task.blockedBy ?? null,
task.paused ? 1 : 0,
task.baseBranch ?? null,
task.baseCommitSha ?? null,
task.modelPresetId ?? null,
task.modelProvider ?? null,
task.modelId ?? null,
@@ -214,6 +217,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
toJsonNullable(task.mergeDetails),
task.breakIntoSubtasks ? 1 : 0,
toJson(task.enabledWorkflowSteps || []),
toJson(task.modifiedFiles || []),
);
this.db.bumpLastModified();
}
@@ -875,7 +879,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
async updateTask(
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> {
return this.withTaskLock(id, async () => {
// 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.baseBranch !== undefined) task.baseBranch = updates.baseBranch;
if (updates.baseCommitSha !== undefined) task.baseCommitSha = updates.baseCommitSha;
if (updates.size !== undefined) task.size = updates.size;
if (updates.reviewLevel !== undefined) task.reviewLevel = updates.reviewLevel;
if (updates.mergeRetries !== undefined) task.mergeRetries = updates.mergeRetries;
@@ -963,6 +968,11 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
} else if (updates.workflowStepResults !== undefined) {
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();
await this.atomicWriteTaskJson(dir, task);
@@ -1465,8 +1475,10 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
breakIntoSubtasks: task.breakIntoSubtasks,
paused: task.paused,
baseBranch: task.baseBranch,
baseCommitSha: task.baseCommitSha,
mergeRetries: task.mergeRetries,
error: task.error,
modifiedFiles: task.modifiedFiles,
};
// Write to archivedTasks table in SQLite
@@ -2295,8 +2307,10 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
breakIntoSubtasks: task.breakIntoSubtasks,
paused: task.paused,
baseBranch: task.baseBranch,
baseCommitSha: task.baseCommitSha,
mergeRetries: task.mergeRetries,
error: task.error,
modifiedFiles: task.modifiedFiles,
};
// Write to archivedTasks table
@@ -2359,7 +2373,8 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
validatorModelProvider: entry.validatorModelProvider,
validatorModelId: entry.validatorModelId,
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

View File

@@ -387,6 +387,10 @@ export interface Task {
* unmerged branch. The executor reads this to branch from the
* dependency's branch instead of HEAD. Cleared after worktree creation. */
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[];
steeringComments?: SteeringComment[];
comments?: TaskComment[];
@@ -428,6 +432,8 @@ export interface Task {
error?: string;
/** Optional summary of what was changed/fixed when task is completed */
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.
* Used to sort cards within a column so that recently-moved cards appear at the top. */
columnMovedAt?: string;
@@ -523,6 +529,9 @@ export interface GlobalSettings {
/** 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. */
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,
ntfyEnabled: false,
ntfyTopic: undefined,
defaultProjectId: undefined,
};
/** Default values for project-level settings. */
@@ -740,6 +750,7 @@ export const GLOBAL_SETTINGS_KEYS: ReadonlyArray<keyof GlobalSettings> = [
"defaultThinkingLevel",
"ntfyEnabled",
"ntfyTopic",
"defaultProjectId",
] as const;
/** Keys that belong to the project settings scope. */
@@ -861,8 +872,11 @@ export interface ArchivedTaskEntry {
breakIntoSubtasks?: boolean;
paused?: boolean;
baseBranch?: string;
baseCommitSha?: string;
mergeRetries?: number;
error?: string;
/** Files modified during agent execution, captured at task completion time */
modifiedFiles?: string[];
}
/** Type of planning question presented to the user */

View File

@@ -1868,3 +1868,14 @@ export function fetchProjectTasks(projectId: string, limit?: number, offset?: nu
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

@@ -396,7 +396,7 @@ export function SetupWizard({ isOpen, onClose, onProjectCreated, onRegisterProje
<button
className="btn btn-primary"
onClick={handleValidate}
disabled={state.isValidating || state.validationError}
disabled={state.isValidating || !!state.validationError}
>
{state.isValidating ? (
<>

View File

@@ -13,6 +13,7 @@ import { ModelSelectorTab } from "./ModelSelectorTab";
import { PrSection } from "./PrSection";
import { TaskComments } from "./TaskComments";
import { MergeDetails } from "./MergeDetails";
import { TaskChangesTab } from "./TaskChangesTab";
interface ModelSelection {
provider?: string;
@@ -105,7 +106,7 @@ export function TaskDetailModal({
addToast,
githubTokenConfigured,
}: 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 [uploading, setUploading] = useState(false);
const [dependencies, setDependencies] = useState<string[]>(task.dependencies || []);
@@ -671,6 +672,14 @@ export function TaskDetailModal({
>
Agent Log
</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
className={`detail-tab${activeTab === "steering" ? " detail-tab-active" : ""}`}
onClick={() => setActiveTab("steering")}
@@ -703,6 +712,8 @@ export function TaskDetailModal({
validatorModel={getValidatorSelection(task)}
/>
</div>
) : activeTab === "changes" ? (
<TaskChangesTab taskId={task.id} worktree={task.worktree} />
) : activeTab === "steering" ? (
<SteeringTab task={task} addToast={addToast} />
) : activeTab === "comments" ? (

View File

@@ -11812,3 +11812,134 @@ html .column.drag-over * {
[data-theme="light"] .gm-load-more:hover {
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

@@ -51,20 +51,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);
}
function validateMissionId(id: string): boolean {
return /^M-\d+$/.test(id);
function validateMissionId(id: string | string[]): boolean {
const str = Array.isArray(id) ? id[0] : id;
return /^M-\d+$/.test(str);
}
function validateMilestoneId(id: string): boolean {
return /^MS-\d+$/.test(id);
function validateMilestoneId(id: string | string[]): boolean {
const str = Array.isArray(id) ? id[0] : id;
return /^MS-\d+$/.test(str);
}
function validateSliceId(id: string): boolean {
return /^SL-\d+$/.test(id);
function validateSliceId(id: string | string[]): boolean {
const str = Array.isArray(id) ? id[0] : id;
return /^SL-\d+$/.test(str);
}
function validateFeatureId(id: string): boolean {
return /^F-\d+$/.test(id);
function validateFeatureId(id: string | string[]): boolean {
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 {

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 workflow step execution results for a task.

View File

@@ -457,6 +457,23 @@ export class TaskExecutor {
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.options.onStart?.(task, worktreePath);
@@ -571,6 +588,14 @@ export class TaskExecutor {
}
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
const workflowSuccess = await this.runWorkflowSteps(task, worktreePath, settings);
if (!workflowSuccess) {
@@ -1067,6 +1092,61 @@ export class TaskExecutor {
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 ────────────────────────────────────────────
/**