Merge claudedo/ccd650a8d2b04a7092e81ed07c16dbe0

This commit is contained in:
mika kuns
2026-08-05 22:46:37 +02:00
18 changed files with 503 additions and 1 deletions
@@ -49,6 +49,7 @@ public class PromptFilesTests
{
Assert.EndsWith("merge-helper-system.md", PromptFiles.PathFor(PromptKind.MergeHelper));
Assert.EndsWith("merge-helper-initial.md", PromptFiles.PathFor(PromptKind.MergeHelperInitial));
Assert.EndsWith("merge-helper-handoff.md", PromptFiles.PathFor(PromptKind.MergeHelperHandoff));
}
[Fact]
@@ -151,4 +152,48 @@ public class PromptFilesTests
Assert.DoesNotContain("{scope}", outp);
Assert.DoesNotContain("{tasks}", outp);
}
[Fact]
public void DefaultFor_merge_helper_handoff_has_scope_repo_and_tasks_tokens()
{
var d = PromptFiles.DefaultFor(PromptKind.MergeHelperHandoff);
Assert.False(string.IsNullOrWhiteSpace(d));
Assert.Contains("{scope}", d);
Assert.Contains("{repo}", d);
Assert.Contains("{tasks}", d);
}
[Fact]
public void DefaultFor_merge_helper_handoff_points_at_phase_3()
{
var d = PromptFiles.DefaultFor(PromptKind.MergeHelperHandoff);
Assert.Contains("phase 3", d, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void RenderTemplate_merge_helper_handoff_substitutes_scope_repo_and_tasks()
{
var outp = PromptFiles.RenderTemplate(
PromptFiles.DefaultFor(PromptKind.MergeHelperHandoff),
new Dictionary<string, string>
{
["scope"] = "List: Bugs",
["repo"] = "C:\\repo",
["tasks"] = "- [WaitingForReview] T1 (id: abc)",
});
Assert.Contains("Scope: List: Bugs", outp);
Assert.Contains("Repo: C:\\repo", outp);
Assert.Contains("- [WaitingForReview] T1 (id: abc)", outp);
Assert.DoesNotContain("{scope}", outp);
Assert.DoesNotContain("{repo}", outp);
Assert.DoesNotContain("{tasks}", outp);
}
[Fact]
public void DefaultFor_merge_helper_tells_the_session_to_hand_off_after_phase_2()
{
var d = PromptFiles.DefaultFor(PromptKind.MergeHelper);
Assert.Contains("handoff_list_handler", d);
Assert.Contains("do not continue into phase 3 yourself", d, StringComparison.OrdinalIgnoreCase);
}
}
@@ -25,6 +25,7 @@ public abstract class StubWorkerClient : IWorkerClient
public event Action<WorkerLogEntry>? WorkerLogReceivedEvent;
public event Action<string, string, string>? TaskQuestionAskedEvent;
public event Action<string, string>? TaskQuestionResolvedEvent;
public event Action<string, IReadOnlyList<string>>? HandoffRequestedEvent;
public event Action? PrepStartedEvent;
public event Action<string>? PrepLineEvent;
public event Action<bool>? PrepFinishedEvent;
@@ -51,6 +52,7 @@ public abstract class StubWorkerClient : IWorkerClient
public void RaiseConnectionRestored() => ConnectionRestoredEvent?.Invoke();
public void RaiseTaskQuestionAsked(string taskId, string questionId, string question) => TaskQuestionAskedEvent?.Invoke(taskId, questionId, question);
public void RaiseTaskQuestionResolved(string taskId, string questionId) => TaskQuestionResolvedEvent?.Invoke(taskId, questionId);
public void RaiseHandoffRequested(string taskId, IReadOnlyList<string> survivingTaskIds) => HandoffRequestedEvent?.Invoke(taskId, survivingTaskIds);
public void RaisePrepStarted() => PrepStartedEvent?.Invoke();
public void RaisePrepLine(string line) => PrepLineEvent?.Invoke(line);
@@ -105,6 +107,9 @@ public abstract class StubWorkerClient : IWorkerClient
public virtual Task<string> CreateMergeHelperTaskAsync(
IReadOnlyList<string> taskIds, string listId, string title, string descriptionHeader, CancellationToken ct = default)
=> Task.FromResult(Guid.NewGuid().ToString());
public virtual Task<LaunchSpec> GetMergeHelperHandoffLaunchSpecAsync(
string taskId, IReadOnlyList<string> survivingTaskIds, CancellationToken ct = default)
=> Task.FromResult(new LaunchSpec(".", "claude", Array.Empty<string>(), new Dictionary<string, string>()));
public virtual Task<LaunchSpec> GetPlanningStartLaunchSpecAsync(string taskId, CancellationToken ct = default)
=> Task.FromResult(new LaunchSpec(".", "claude", Array.Empty<string>(), new Dictionary<string, string>()));
public virtual Task<LaunchSpec> GetPlanningResumeLaunchSpecAsync(string taskId, CancellationToken ct = default)
@@ -0,0 +1,96 @@
using ClaudeDo.Data;
using ClaudeDo.Data.Models;
using ClaudeDo.Data.Repositories;
using ClaudeDo.Worker.External;
using ClaudeDo.Worker.Hub;
using ClaudeDo.Worker.Tests.Infrastructure;
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;
namespace ClaudeDo.Worker.Tests.External;
public sealed class HandoffMcpToolsTests : IDisposable
{
private readonly DbFixture _db = new();
private readonly ClaudeDoDbContext _ctx;
private readonly TaskRepository _tasks;
private readonly ListRepository _lists;
private readonly CapturingHubContext _hubContext = new();
public HandoffMcpToolsTests()
{
_ctx = _db.CreateContext();
_tasks = new TaskRepository(_ctx);
_lists = new ListRepository(_ctx);
}
public void Dispose() { _ctx.Dispose(); _db.Dispose(); }
private HandoffMcpTools BuildSut() => new(_tasks, new HubBroadcaster(_hubContext));
private async Task<TaskEntity> SeedTaskAsync(string listId, TaskStatus status = TaskStatus.Idle, string title = "t")
{
var task = new TaskEntity
{
Id = Guid.NewGuid().ToString(), ListId = listId, Title = title,
Status = status, CreatedAt = DateTime.UtcNow, CommitType = "chore",
};
await _tasks.AddAsync(task);
return task;
}
private async Task<string> SeedListAsync()
{
var listId = Guid.NewGuid().ToString();
await _lists.AddAsync(new ListEntity { Id = listId, Name = "L", CreatedAt = DateTime.UtcNow });
return listId;
}
[Fact]
public async Task HandoffListHandler_ValidIds_BroadcastsAndReturnsCount()
{
var listId = await SeedListAsync();
var handlerTask = await SeedTaskAsync(listId, title: "List handler: Alpha");
var survivor = await SeedTaskAsync(listId, TaskStatus.WaitingForReview, title: "Survivor");
var sut = BuildSut();
var result = await sut.HandoffListHandler(handlerTask.Id, new[] { survivor.Id }, CancellationToken.None);
Assert.True(result.Requested);
Assert.Equal(handlerTask.Id, result.TaskId);
Assert.Equal(1, result.SurvivingCount);
var call = Assert.Single(_hubContext.Proxy.Calls);
Assert.Equal("HandoffRequested", call.Method);
Assert.Equal(handlerTask.Id, call.Args[0]);
}
[Fact]
public async Task HandoffListHandler_EmptySurvivingIds_Throws()
{
var listId = await SeedListAsync();
var handlerTask = await SeedTaskAsync(listId);
var sut = BuildSut();
await Assert.ThrowsAsync<InvalidOperationException>(() =>
sut.HandoffListHandler(handlerTask.Id, Array.Empty<string>(), CancellationToken.None));
}
[Fact]
public async Task HandoffListHandler_UnknownHandlerTask_Throws()
{
var sut = BuildSut();
await Assert.ThrowsAsync<InvalidOperationException>(() =>
sut.HandoffListHandler("missing", new[] { "x" }, CancellationToken.None));
}
[Fact]
public async Task HandoffListHandler_UnknownSurvivingTask_Throws()
{
var listId = await SeedListAsync();
var handlerTask = await SeedTaskAsync(listId);
var sut = BuildSut();
await Assert.ThrowsAsync<InvalidOperationException>(() =>
sut.HandoffListHandler(handlerTask.Id, new[] { "missing" }, CancellationToken.None));
}
}
@@ -26,6 +26,7 @@ public sealed class MergeHelperTaskHubTests : IDisposable
private readonly TaskRepository _tasks;
private readonly ListRepository _lists;
private readonly List<GitRepoFixture> _repos = new();
private readonly List<string> _mergeHelperSessionDirs = new();
private readonly RecordingClientProxy _proxy = new();
private static bool GitAvailable => GitRepoFixture.IsGitAvailable();
@@ -42,6 +43,8 @@ public sealed class MergeHelperTaskHubTests : IDisposable
foreach (var r in _repos) r.Dispose();
_ctx.Dispose();
_db.Dispose();
foreach (var d in _mergeHelperSessionDirs)
try { Directory.Delete(d, true); } catch { /* best effort */ }
}
private sealed class FakeSessionSkillRegistry : ISessionSkillRegistry
@@ -136,6 +139,37 @@ public sealed class MergeHelperTaskHubTests : IDisposable
() => hub.CreateMergeHelperTask(new[] { "t1" }, "no-such-list", "title", "header"));
}
// ── GetMergeHelperHandoffLaunchSpec ──
[Fact]
public async Task GetMergeHelperHandoffLaunchSpec_ReusesHandlerTaskId_NoNewTaskCreated()
{
var listId = await SeedListAsync(Path.GetTempPath(), name: "Alpha");
var handlerTask = await SeedTaskAsync(listId, TaskStatus.Idle, title: "List handler: Alpha");
var survivor = await SeedTaskAsync(listId, TaskStatus.WaitingForReview, title: "Survivor task");
var hub = CreateHub();
var spec = await hub.GetMergeHelperHandoffLaunchSpec(handlerTask.Id, new[] { survivor.Id });
var args = spec.Args.ToList();
var sessionDir = args[args.IndexOf("--add-dir") + 1];
_mergeHelperSessionDirs.Add(sessionDir);
Assert.Contains("--allowedTools", args);
Assert.Contains("mcp__claudedo__*,Read,Grep,Glob,Edit,Bash,WebFetch,WebSearch,Skill", args);
var kickoff = args[^1];
Assert.Contains(Path.Combine(sessionDir, "handoff.md"), kickoff);
}
[Fact]
public async Task GetMergeHelperHandoffLaunchSpec_UnknownHandlerTask_Throws()
{
var hub = CreateHub();
await Assert.ThrowsAsync<HubException>(
() => hub.GetMergeHelperHandoffLaunchSpec("no-such-task", new[] { "x" }));
}
// ── SubmitTaskForReview (worktree-less branch) ──
[Fact]
@@ -7,6 +7,7 @@ using ClaudeDo.Worker.Planning;
using ClaudeDo.Worker.Runner;
using ClaudeDo.Worker.Skills;
using ClaudeDo.Worker.Tests.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;
@@ -697,6 +698,108 @@ public sealed class InteractiveLaunchSpecServiceTests : IDisposable
Assert.Contains(t1, created.Description);
}
// ── BuildForMergeHelperHandoffAsync ──
[Fact]
public async Task BuildForMergeHelperHandoffAsync_EmptySurvivingTaskIds_ThrowsInvalidOperation()
{
var listId = await SeedListAsync(workingDir: _tempDir);
var handlerTaskId = Guid.NewGuid().ToString();
await SeedTaskAsync(handlerTaskId, listId, TaskStatus.Idle);
var svc = BuildService();
await Assert.ThrowsAsync<InvalidOperationException>(
() => svc.BuildForMergeHelperHandoffAsync(handlerTaskId, Array.Empty<string>(), CancellationToken.None));
}
[Fact]
public async Task BuildForMergeHelperHandoffAsync_UnknownHandlerTask_ThrowsKeyNotFound()
{
await Assert.ThrowsAsync<KeyNotFoundException>(
() => BuildService().BuildForMergeHelperHandoffAsync("no-such-task", new[] { "x" }, CancellationToken.None));
}
[Fact]
public async Task BuildForMergeHelperHandoffAsync_UnknownSurvivingTask_ThrowsKeyNotFound()
{
var listId = await SeedListAsync(workingDir: _tempDir);
var handlerTaskId = Guid.NewGuid().ToString();
await SeedTaskAsync(handlerTaskId, listId, TaskStatus.Idle);
var svc = BuildService();
await Assert.ThrowsAsync<KeyNotFoundException>(
() => svc.BuildForMergeHelperHandoffAsync(handlerTaskId, new[] { "no-such-task" }, CancellationToken.None));
}
[Fact]
public async Task BuildForMergeHelperHandoffAsync_ListWithoutExistingWorkingDir_ThrowsInvalidOperation()
{
var listId = await SeedListAsync(workingDir: Path.Combine(_tempDir, "gone"));
var handlerTaskId = Guid.NewGuid().ToString();
await SeedTaskAsync(handlerTaskId, listId, TaskStatus.Idle);
var survivor = Guid.NewGuid().ToString();
await SeedTaskAsync(survivor, listId, TaskStatus.WaitingForReview);
var svc = BuildService();
var ex = await Assert.ThrowsAsync<InvalidOperationException>(
() => svc.BuildForMergeHelperHandoffAsync(handlerTaskId, new[] { survivor }, CancellationToken.None));
Assert.Contains("working directory", ex.Message);
}
[Fact]
public async Task BuildForMergeHelperHandoffAsync_ReusesHandlerTaskId_NoNewTaskCreated()
{
var repo = Path.Combine(_tempDir, "repoHandoff");
Directory.CreateDirectory(repo);
var listId = await SeedListAsync(workingDir: repo, name: "Alpha");
var handlerTaskId = Guid.NewGuid().ToString();
await SeedTaskAsync(handlerTaskId, listId, TaskStatus.Idle, title: "List handler: Alpha");
var survivor = Guid.NewGuid().ToString();
await SeedTaskAsync(survivor, listId, TaskStatus.WaitingForReview, title: "Survivor task");
var beforeCount = await CountTasksAsync();
var svc = BuildService();
var spec = await svc.BuildForMergeHelperHandoffAsync(handlerTaskId, new[] { survivor }, CancellationToken.None);
var sessionDir = TrackSessionDir(spec);
var afterCount = await CountTasksAsync();
Assert.Equal(beforeCount, afterCount);
Assert.Equal(repo, spec.Cwd);
Assert.Equal(_claudeStubPath, spec.Exe);
var args = spec.Args.ToList();
var atIdx = args.IndexOf("--allowedTools");
Assert.Equal("mcp__claudedo__*,Read,Grep,Glob,Edit,Bash,WebFetch,WebSearch,Skill", args[atIdx + 1]);
var appendIdx = args.IndexOf("--append-system-prompt-file");
var systemPromptPath = args[appendIdx + 1];
Assert.Equal(Path.Combine(sessionDir, "system-prompt.md"), systemPromptPath);
Assert.Equal(PromptFiles.ReadOrDefault(PromptKind.MergeHelper), File.ReadAllText(systemPromptPath));
var kickoff = args[^1];
var handoffPath = Path.Combine(sessionDir, "handoff.md");
Assert.Contains(handoffPath, kickoff);
Assert.DoesNotContain('\n', kickoff);
var handoffBrief = File.ReadAllText(handoffPath);
Assert.Contains("Scope: List: Alpha", handoffBrief);
Assert.Contains($"Repo: {repo}", handoffBrief);
Assert.Contains("Survivor task", handoffBrief);
Assert.Contains(survivor, handoffBrief);
Assert.Contains("phase 3", handoffBrief, StringComparison.OrdinalIgnoreCase);
Assert.Equal("200000", spec.Env["MCP_TOOL_TIMEOUT"]);
}
private async Task<int> CountTasksAsync()
{
using var ctx = _db.CreateContext();
return await ctx.Tasks.CountAsync();
}
[Fact]
public void BuildPlanningStart_MapsPlanningArgsAndEnv()
{
@@ -36,6 +36,7 @@ sealed class FakeWorkerClient : IWorkerClient
public event Action<WorkerLogEntry>? WorkerLogReceivedEvent;
public event Action<string, string, string>? TaskQuestionAskedEvent;
public event Action<string, string>? TaskQuestionResolvedEvent;
public event Action<string, IReadOnlyList<string>>? HandoffRequestedEvent;
public void RaiseTaskUpdated(string taskId) => TaskUpdatedEvent?.Invoke(taskId);
public void RaiseWorktreeUpdated(string taskId) => WorktreeUpdatedEvent?.Invoke(taskId);
public void RaiseTaskMessage(string taskId, string line) => TaskMessageEvent?.Invoke(taskId, line);
@@ -77,6 +78,9 @@ sealed class FakeWorkerClient : IWorkerClient
public Task<string> CreateMergeHelperTaskAsync(
IReadOnlyList<string> taskIds, string listId, string title, string descriptionHeader, CancellationToken ct = default)
=> Task.FromResult(Guid.NewGuid().ToString());
public Task<LaunchSpec> GetMergeHelperHandoffLaunchSpecAsync(
string taskId, IReadOnlyList<string> survivingTaskIds, CancellationToken ct = default)
=> Task.FromResult(new LaunchSpec(".", "claude", Array.Empty<string>(), new Dictionary<string, string>()));
public Task<LaunchSpec> GetAdHocLaunchSpecAsync(string directory, CancellationToken ct = default)
=> Task.FromResult(new LaunchSpec(directory, "claude", Array.Empty<string>(), new Dictionary<string, string>()));
public int PlanningStartSpecCalls { get; private set; }