feat(worker): build merge-helper interactive launch spec
This commit is contained in:
@@ -157,6 +157,101 @@ public sealed class InteractiveLaunchSpecService : IInteractiveLaunchSpecService
|
|||||||
return Task.FromResult(new LaunchSpec(directory, resolvedClaude, Array.Empty<string>(), env));
|
return Task.FromResult(new LaunchSpec(directory, resolvedClaude, Array.Empty<string>(), env));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Tools the merge helper may use without prompting: the claudedo MCP surface (run, poll,
|
||||||
|
// diff, review/merge, continue/abort merge), read/search, Edit + Bash for hand-resolving
|
||||||
|
// conflict markers the MCP tools left behind, and web/skill lookups.
|
||||||
|
private const string MergeHelperAllowedTools =
|
||||||
|
"mcp__claudedo__*,Read,Grep,Glob,Edit,Bash,WebFetch,WebSearch,Skill";
|
||||||
|
|
||||||
|
public async Task<LaunchSpec> BuildForMergeHelperAsync(IReadOnlyList<string> taskIds, string? listId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (taskIds.Count == 0)
|
||||||
|
throw new InvalidOperationException("No tasks selected for the merge helper.");
|
||||||
|
|
||||||
|
await using var ctx = await _dbFactory.CreateDbContextAsync(ct);
|
||||||
|
var taskRepo = new TaskRepository(ctx);
|
||||||
|
var listRepo = new ListRepository(ctx);
|
||||||
|
|
||||||
|
var listsById = new Dictionary<string, ListEntity?>();
|
||||||
|
var briefLines = new List<string>();
|
||||||
|
var repoDirs = new List<string>(); // distinct, existing, in first-seen order
|
||||||
|
|
||||||
|
foreach (var id in taskIds)
|
||||||
|
{
|
||||||
|
var task = await taskRepo.GetByIdAsync(id, ct)
|
||||||
|
?? throw new KeyNotFoundException($"Task not found: {id}");
|
||||||
|
if (!listsById.TryGetValue(task.ListId, out var list))
|
||||||
|
listsById[task.ListId] = list = await listRepo.GetByIdAsync(task.ListId, ct);
|
||||||
|
|
||||||
|
var workingDir = list?.WorkingDir;
|
||||||
|
if (!string.IsNullOrEmpty(workingDir) && Directory.Exists(workingDir) && !repoDirs.Contains(workingDir))
|
||||||
|
repoDirs.Add(workingDir);
|
||||||
|
|
||||||
|
briefLines.Add(
|
||||||
|
$"- [{task.Status}] {task.Title} (id: {task.Id}, list: {list?.Name ?? "—"}, " +
|
||||||
|
$"repo: {(string.IsNullOrEmpty(workingDir) ? "—" : workingDir)})");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (repoDirs.Count == 0)
|
||||||
|
throw new InvalidOperationException("none of the selected tasks are in a working directory");
|
||||||
|
|
||||||
|
string scopeLabel;
|
||||||
|
string cwd;
|
||||||
|
if (listId is not null)
|
||||||
|
{
|
||||||
|
var scopeList = await listRepo.GetByIdAsync(listId, ct)
|
||||||
|
?? throw new KeyNotFoundException($"List not found: {listId}");
|
||||||
|
scopeLabel = $"List: {scopeList.Name}";
|
||||||
|
cwd = scopeList.WorkingDir is { Length: > 0 } wd && Directory.Exists(wd) ? wd : repoDirs[0];
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
scopeLabel = "All lists";
|
||||||
|
cwd = repoDirs[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
var sessionDir = Path.Combine(Paths.AppDataRoot(), "merge-helper-sessions", Guid.NewGuid().ToString());
|
||||||
|
Directory.CreateDirectory(sessionDir);
|
||||||
|
|
||||||
|
var systemPromptPath = Path.Combine(sessionDir, "system-prompt.md");
|
||||||
|
await File.WriteAllTextAsync(systemPromptPath, PromptFiles.ReadOrDefault(PromptKind.MergeHelper), ct);
|
||||||
|
|
||||||
|
var briefPath = Path.Combine(sessionDir, "brief.md");
|
||||||
|
await File.WriteAllTextAsync(briefPath, PromptFiles.Render(PromptKind.MergeHelperInitial,
|
||||||
|
new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["scope"] = scopeLabel,
|
||||||
|
["tasks"] = string.Join("\n", briefLines),
|
||||||
|
}), ct);
|
||||||
|
|
||||||
|
var resolvedClaude = WindowsTerminalLauncher.Resolve(_claudePath)
|
||||||
|
?? throw new InvalidOperationException($"claude executable not found: {_claudePath}");
|
||||||
|
|
||||||
|
// Mirrors WindowsTerminalLauncher.BuildPlanningStartArgs ordering: variadic flags
|
||||||
|
// (--allowedTools, --add-dir) first, then a single-value flag, then the single-line
|
||||||
|
// positional kickoff LAST — a multi-line positional prompt truncates at the first
|
||||||
|
// newline, so the full multi-line brief travels via the file exposed through --add-dir.
|
||||||
|
var args = new List<string>
|
||||||
|
{
|
||||||
|
"--permission-mode", "default",
|
||||||
|
"--allowedTools", MergeHelperAllowedTools,
|
||||||
|
"--add-dir", sessionDir,
|
||||||
|
};
|
||||||
|
args.AddRange(repoDirs);
|
||||||
|
args.Add("--append-system-prompt-file");
|
||||||
|
args.Add(systemPromptPath);
|
||||||
|
args.Add(
|
||||||
|
$"Read the file {briefPath} first. It lists the tasks you must merge and their status. " +
|
||||||
|
"After reading it, begin the merge-helper session as your instructions describe.");
|
||||||
|
|
||||||
|
var env = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["MCP_TOOL_TIMEOUT"] = "200000",
|
||||||
|
};
|
||||||
|
|
||||||
|
return new LaunchSpec(cwd, resolvedClaude, args, env);
|
||||||
|
}
|
||||||
|
|
||||||
// The positional prompt claude opens the interactive session on. Empty (no positional arg)
|
// The positional prompt claude opens the interactive session on. Empty (no positional arg)
|
||||||
// if the task has neither a title nor a description.
|
// if the task has neither a title nor a description.
|
||||||
private static IReadOnlyList<string> BuildFreshPromptArgs(TaskEntity task)
|
private static IReadOnlyList<string> BuildFreshPromptArgs(TaskEntity task)
|
||||||
|
|||||||
@@ -26,4 +26,12 @@ public interface IInteractiveLaunchSpecService
|
|||||||
/// no task, no worktree, no session-skills seeding. Throws InvalidOperationException if the
|
/// no task, no worktree, no session-skills seeding. Throws InvalidOperationException if the
|
||||||
/// directory doesn't exist.</summary>
|
/// directory doesn't exist.</summary>
|
||||||
Task<LaunchSpec> BuildForDirectoryAsync(string directory, CancellationToken ct);
|
Task<LaunchSpec> BuildForDirectoryAsync(string directory, CancellationToken ct);
|
||||||
|
|
||||||
|
/// <summary>Builds a LaunchSpec for an embedded ConPTY "merge helper" session that drives the
|
||||||
|
/// given tasks to a merged/Done state via the mcp__claudedo__* tools. Writes a per-session
|
||||||
|
/// system prompt + task brief under ~/.todo-app/merge-helper-sessions/<guid> and exposes
|
||||||
|
/// that dir plus every distinct existing repo dir via --add-dir. listId scopes the brief label
|
||||||
|
/// and the cwd to that list; null means all lists (cwd = first existing repo dir). Throws
|
||||||
|
/// InvalidOperationException if taskIds is empty or no task has an existing working directory.</summary>
|
||||||
|
Task<LaunchSpec> BuildForMergeHelperAsync(IReadOnlyList<string> taskIds, string? listId, CancellationToken ct);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,6 +52,8 @@ public sealed class InteractiveLaunchSpecServiceTests : IDisposable
|
|||||||
_db.Dispose();
|
_db.Dispose();
|
||||||
foreach (var f in _gitFixtures) f.Dispose();
|
foreach (var f in _gitFixtures) f.Dispose();
|
||||||
try { Directory.Delete(_tempDir, true); } catch { /* best effort */ }
|
try { Directory.Delete(_tempDir, true); } catch { /* best effort */ }
|
||||||
|
foreach (var d in _mergeHelperSessionDirs)
|
||||||
|
try { Directory.Delete(d, true); } catch { /* best effort */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed class FakeSessionSkillRegistry : ISessionSkillRegistry
|
private sealed class FakeSessionSkillRegistry : ISessionSkillRegistry
|
||||||
@@ -70,23 +72,23 @@ public sealed class InteractiveLaunchSpecServiceTests : IDisposable
|
|||||||
new WorktreeManager(new GitService(), _db.CreateFactory(), new WorkerConfig(), NullLogger<WorktreeManager>.Instance),
|
new WorktreeManager(new GitService(), _db.CreateFactory(), new WorkerConfig(), NullLogger<WorktreeManager>.Instance),
|
||||||
new WorkerConfig { ClaudeBin = _claudeStubPath });
|
new WorkerConfig { ClaudeBin = _claudeStubPath });
|
||||||
|
|
||||||
private async Task<string> SeedListAsync(string? workingDir = null)
|
private async Task<string> SeedListAsync(string? workingDir = null, string name = "L")
|
||||||
{
|
{
|
||||||
var listId = Guid.NewGuid().ToString();
|
var listId = Guid.NewGuid().ToString();
|
||||||
using var ctx = _db.CreateContext();
|
using var ctx = _db.CreateContext();
|
||||||
await new ListRepository(ctx).AddAsync(new ListEntity
|
await new ListRepository(ctx).AddAsync(new ListEntity
|
||||||
{
|
{
|
||||||
Id = listId, Name = "L", WorkingDir = workingDir ?? _tempDir, CreatedAt = DateTime.UtcNow,
|
Id = listId, Name = name, WorkingDir = workingDir ?? _tempDir, CreatedAt = DateTime.UtcNow,
|
||||||
});
|
});
|
||||||
return listId;
|
return listId;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task SeedTaskAsync(string taskId, string listId, TaskStatus status, string? sessionSkillsJson = null)
|
private async Task SeedTaskAsync(string taskId, string listId, TaskStatus status, string? sessionSkillsJson = null, string title = "T")
|
||||||
{
|
{
|
||||||
using var ctx = _db.CreateContext();
|
using var ctx = _db.CreateContext();
|
||||||
await new TaskRepository(ctx).AddAsync(new TaskEntity
|
await new TaskRepository(ctx).AddAsync(new TaskEntity
|
||||||
{
|
{
|
||||||
Id = taskId, ListId = listId, Title = "T", Status = status,
|
Id = taskId, ListId = listId, Title = title, Status = status,
|
||||||
CreatedAt = DateTime.UtcNow, SessionSkills = sessionSkillsJson,
|
CreatedAt = DateTime.UtcNow, SessionSkills = sessionSkillsJson,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -344,6 +346,133 @@ public sealed class InteractiveLaunchSpecServiceTests : IDisposable
|
|||||||
() => svc.BuildForDirectoryAsync(Path.Combine(_tempDir, "does-not-exist"), CancellationToken.None));
|
() => svc.BuildForDirectoryAsync(Path.Combine(_tempDir, "does-not-exist"), CancellationToken.None));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Merge helper ──
|
||||||
|
|
||||||
|
private readonly List<string> _mergeHelperSessionDirs = new();
|
||||||
|
|
||||||
|
/// The session dir is the value right after --add-dir; register it for cleanup
|
||||||
|
/// (BuildForMergeHelperAsync writes under the real ~/.todo-app).
|
||||||
|
private string TrackSessionDir(LaunchSpec spec)
|
||||||
|
{
|
||||||
|
var args = spec.Args.ToList();
|
||||||
|
var dir = args[args.IndexOf("--add-dir") + 1];
|
||||||
|
_mergeHelperSessionDirs.Add(dir);
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task BuildForMergeHelperAsync_EmptyTaskIds_ThrowsInvalidOperation()
|
||||||
|
{
|
||||||
|
var svc = BuildService();
|
||||||
|
await Assert.ThrowsAsync<InvalidOperationException>(
|
||||||
|
() => svc.BuildForMergeHelperAsync(Array.Empty<string>(), null, CancellationToken.None));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task BuildForMergeHelperAsync_NoExistingWorkingDirs_ThrowsInvalidOperation()
|
||||||
|
{
|
||||||
|
var listId = await SeedListAsync(workingDir: Path.Combine(_tempDir, "gone"));
|
||||||
|
var taskId = Guid.NewGuid().ToString();
|
||||||
|
await SeedTaskAsync(taskId, listId, TaskStatus.WaitingForReview);
|
||||||
|
|
||||||
|
var svc = BuildService();
|
||||||
|
var ex = await Assert.ThrowsAsync<InvalidOperationException>(
|
||||||
|
() => svc.BuildForMergeHelperAsync(new[] { taskId }, null, CancellationToken.None));
|
||||||
|
Assert.Contains("working directory", ex.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task BuildForMergeHelperAsync_TasksAcrossTwoRepos_BuildsGlobalScopeSpec()
|
||||||
|
{
|
||||||
|
var repoA = Path.Combine(_tempDir, "repoA");
|
||||||
|
var repoB = Path.Combine(_tempDir, "repoB");
|
||||||
|
Directory.CreateDirectory(repoA);
|
||||||
|
Directory.CreateDirectory(repoB);
|
||||||
|
|
||||||
|
var listA = await SeedListAsync(workingDir: repoA, name: "Alpha");
|
||||||
|
var listB = await SeedListAsync(workingDir: repoB, name: "Beta");
|
||||||
|
var t1 = Guid.NewGuid().ToString();
|
||||||
|
var t2 = Guid.NewGuid().ToString();
|
||||||
|
var t3 = Guid.NewGuid().ToString();
|
||||||
|
await SeedTaskAsync(t1, listA, TaskStatus.WaitingForReview, title: "First task");
|
||||||
|
await SeedTaskAsync(t2, listB, TaskStatus.Idle, title: "Second task");
|
||||||
|
await SeedTaskAsync(t3, listA, TaskStatus.Failed, title: "Third task"); // same repo as t1 -> distinct
|
||||||
|
|
||||||
|
var svc = BuildService();
|
||||||
|
var spec = await svc.BuildForMergeHelperAsync(new[] { t1, t2, t3 }, null, CancellationToken.None);
|
||||||
|
var sessionDir = TrackSessionDir(spec);
|
||||||
|
|
||||||
|
// cwd: no listId -> first existing repo dir.
|
||||||
|
Assert.Equal(repoA, spec.Cwd);
|
||||||
|
Assert.Equal(_claudeStubPath, spec.Exe);
|
||||||
|
|
||||||
|
var args = spec.Args.ToList();
|
||||||
|
|
||||||
|
// --permission-mode default
|
||||||
|
var pmIdx = args.IndexOf("--permission-mode");
|
||||||
|
Assert.True(pmIdx >= 0);
|
||||||
|
Assert.Equal("default", args[pmIdx + 1]);
|
||||||
|
|
||||||
|
// allowedTools string for the merge helper
|
||||||
|
var atIdx = args.IndexOf("--allowedTools");
|
||||||
|
Assert.Equal("mcp__claudedo__*,Read,Grep,Glob,Edit,Bash,WebFetch,WebSearch,Skill", args[atIdx + 1]);
|
||||||
|
|
||||||
|
// --add-dir: session dir + BOTH distinct repo dirs (repoA only once)
|
||||||
|
var addIdx = args.IndexOf("--add-dir");
|
||||||
|
var appendIdx = args.IndexOf("--append-system-prompt-file");
|
||||||
|
var addDirs = args.GetRange(addIdx + 1, appendIdx - addIdx - 1);
|
||||||
|
Assert.Equal(new[] { sessionDir, repoA, repoB }, addDirs);
|
||||||
|
|
||||||
|
// system prompt file follows --append-system-prompt-file
|
||||||
|
var systemPromptPath = args[appendIdx + 1];
|
||||||
|
Assert.Equal(Path.Combine(sessionDir, "system-prompt.md"), systemPromptPath);
|
||||||
|
Assert.True(File.Exists(systemPromptPath));
|
||||||
|
|
||||||
|
// kickoff is the LAST arg (positional), single line, points at brief.md
|
||||||
|
var kickoff = args[^1];
|
||||||
|
var briefPath = Path.Combine(sessionDir, "brief.md");
|
||||||
|
Assert.Contains(briefPath, kickoff);
|
||||||
|
Assert.DoesNotContain('\n', kickoff);
|
||||||
|
|
||||||
|
// brief exists, carries the scope label and every task's title
|
||||||
|
Assert.True(File.Exists(briefPath));
|
||||||
|
var brief = File.ReadAllText(briefPath);
|
||||||
|
Assert.Contains("Scope: All lists", brief);
|
||||||
|
Assert.Contains("First task", brief);
|
||||||
|
Assert.Contains("Second task", brief);
|
||||||
|
Assert.Contains("Third task", brief);
|
||||||
|
|
||||||
|
Assert.Equal("200000", spec.Env["MCP_TOOL_TIMEOUT"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task BuildForMergeHelperAsync_WithListId_UsesListWorkingDirAsCwdAndListScope()
|
||||||
|
{
|
||||||
|
var repoA = Path.Combine(_tempDir, "repoA2");
|
||||||
|
var repoB = Path.Combine(_tempDir, "repoB2");
|
||||||
|
Directory.CreateDirectory(repoA);
|
||||||
|
Directory.CreateDirectory(repoB);
|
||||||
|
|
||||||
|
var listA = await SeedListAsync(workingDir: repoA, name: "Alpha");
|
||||||
|
var listB = await SeedListAsync(workingDir: repoB, name: "Beta");
|
||||||
|
var t1 = Guid.NewGuid().ToString();
|
||||||
|
var t2 = Guid.NewGuid().ToString();
|
||||||
|
await SeedTaskAsync(t1, listA, TaskStatus.WaitingForReview, title: "Task in Alpha");
|
||||||
|
await SeedTaskAsync(t2, listB, TaskStatus.WaitingForReview, title: "Task in Beta");
|
||||||
|
|
||||||
|
var svc = BuildService();
|
||||||
|
// Scope on listB even though listA's task comes first: cwd must be listB's repo.
|
||||||
|
var spec = await svc.BuildForMergeHelperAsync(new[] { t1, t2 }, listB, CancellationToken.None);
|
||||||
|
var sessionDir = TrackSessionDir(spec);
|
||||||
|
|
||||||
|
Assert.Equal(repoB, spec.Cwd);
|
||||||
|
|
||||||
|
var brief = File.ReadAllText(Path.Combine(sessionDir, "brief.md"));
|
||||||
|
Assert.Contains("Scope: List: Beta", brief);
|
||||||
|
Assert.Contains("Task in Alpha", brief);
|
||||||
|
Assert.Contains("Task in Beta", brief);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void BuildPlanningStart_MapsPlanningArgsAndEnv()
|
public void BuildPlanningStart_MapsPlanningArgsAndEnv()
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in New Issue
Block a user