feat(worker): build merge-helper interactive launch spec

This commit is contained in:
mika kuns
2026-07-24 14:21:26 +02:00
parent c7d64e9c9b
commit 78d4e1a46b
3 changed files with 236 additions and 4 deletions
@@ -157,6 +157,101 @@ public sealed class InteractiveLaunchSpecService : IInteractiveLaunchSpecService
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)
// if the task has neither a title nor a description.
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
/// directory doesn't exist.</summary>
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/&lt;guid&gt; 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);
}