feat(worker): resolve and seed session skills before each run
This commit is contained in:
@@ -18,6 +18,7 @@ using ClaudeDo.Worker.Prime;
|
||||
using ClaudeDo.Worker.Refine;
|
||||
using ClaudeDo.Worker.Report;
|
||||
using ClaudeDo.Worker.Report.Interfaces;
|
||||
using ClaudeDo.Worker.Skills;
|
||||
using ClaudeDo.Worker.Worktrees;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Serilog;
|
||||
@@ -73,6 +74,9 @@ builder.Services.AddSingleton<WorktreeManager>();
|
||||
builder.Services.AddSingleton<ClaudeArgsBuilder>();
|
||||
builder.Services.AddSingleton<TaskRunTokenRegistry>();
|
||||
builder.Services.AddSingleton<PendingQuestionRegistry>();
|
||||
builder.Services.AddSingleton<IRepoCloner, GitRepoCloner>();
|
||||
builder.Services.AddSingleton<ISessionSkillRegistry, SessionSkillRegistry>();
|
||||
builder.Services.AddSingleton<ISessionSkillSeeder, SessionSkillSeeder>();
|
||||
builder.Services.AddSingleton<TaskRunner>();
|
||||
builder.Services.AddSingleton<WorktreeMaintenanceService>();
|
||||
builder.Services.AddSingleton<TaskResetService>();
|
||||
|
||||
@@ -10,8 +10,12 @@ public sealed record ClaudeRunConfig(
|
||||
int? MaxTurns = null,
|
||||
string? PermissionMode = null,
|
||||
string? McpConfigPath = null,
|
||||
string? AllowedTools = null
|
||||
);
|
||||
string? AllowedTools = null,
|
||||
IReadOnlyList<string>? SkillNames = null
|
||||
)
|
||||
{
|
||||
public IReadOnlyList<string> SkillNames { get; init; } = SkillNames ?? Array.Empty<string>();
|
||||
}
|
||||
|
||||
public sealed class ClaudeArgsBuilder
|
||||
{
|
||||
|
||||
@@ -4,6 +4,7 @@ using ClaudeDo.Data.Models;
|
||||
using ClaudeDo.Data.Repositories;
|
||||
using ClaudeDo.Worker.Config;
|
||||
using ClaudeDo.Worker.Hub;
|
||||
using ClaudeDo.Worker.Skills;
|
||||
using ClaudeDo.Worker.State;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;
|
||||
@@ -22,6 +23,7 @@ public sealed class TaskRunner
|
||||
private readonly ITaskStateService _state;
|
||||
private readonly TaskRunTokenRegistry _tokens;
|
||||
private readonly AttachmentStore _attachments;
|
||||
private readonly ISessionSkillSeeder _skillSeeder;
|
||||
|
||||
public TaskRunner(
|
||||
IClaudeProcess claude,
|
||||
@@ -33,7 +35,8 @@ public sealed class TaskRunner
|
||||
ILogger<TaskRunner> logger,
|
||||
ITaskStateService state,
|
||||
TaskRunTokenRegistry tokens,
|
||||
AttachmentStore attachments)
|
||||
AttachmentStore attachments,
|
||||
ISessionSkillSeeder skillSeeder)
|
||||
{
|
||||
_claude = claude;
|
||||
_dbFactory = dbFactory;
|
||||
@@ -45,6 +48,7 @@ public sealed class TaskRunner
|
||||
_state = state;
|
||||
_tokens = tokens;
|
||||
_attachments = attachments;
|
||||
_skillSeeder = skillSeeder;
|
||||
}
|
||||
|
||||
public async Task RunAsync(TaskEntity task, string slot, CancellationToken ct, bool alreadyClaimed = false)
|
||||
@@ -122,6 +126,8 @@ public sealed class TaskRunner
|
||||
}
|
||||
await _broadcaster.TaskStarted(slot, task.Id, now);
|
||||
|
||||
await _skillSeeder.SeedAsync(runDir, resolvedConfig.SkillNames, wtCtx is not null, ct);
|
||||
|
||||
// Build prompt: title + description + only the OPEN sub-tasks (resolved ones are dropped).
|
||||
var prompt = TaskPromptComposer.Compose(
|
||||
task.Title, task.Description,
|
||||
@@ -242,6 +248,8 @@ public sealed class TaskRunner
|
||||
}
|
||||
await _broadcaster.TaskStarted(slot, taskId, now);
|
||||
|
||||
await _skillSeeder.SeedAsync(runDir, resolvedConfig.SkillNames, wtCtx is not null, ct);
|
||||
|
||||
try
|
||||
{
|
||||
var nextRunNumber = lastRun.RunNumber + 1;
|
||||
@@ -505,13 +513,70 @@ public sealed class TaskRunner
|
||||
var instructions = MergeInstructions(
|
||||
systemFile, improvementPrompt, global.DefaultClaudeInstructions, listConfig?.SystemPrompt, task.SystemPrompt);
|
||||
|
||||
var requestedSkills = UnionSkillNames(task.SessionSkills, listConfig?.SessionSkills, global.SessionSkills);
|
||||
var skillNames = await FilterToInstalledSkillsAsync(task.Id, requestedSkills, ct);
|
||||
|
||||
return new ClaudeRunConfig(
|
||||
Model: task.Model ?? listConfig?.Model ?? global.DefaultModel,
|
||||
SystemPrompt: string.IsNullOrWhiteSpace(instructions) ? null : instructions,
|
||||
AgentPath: task.AgentPath ?? listConfig?.AgentPath,
|
||||
ResumeSessionId: resumeSessionId,
|
||||
MaxTurns: ResolveMaxTurns(task.MaxTurns, listConfig?.MaxTurns, global.DefaultMaxTurns),
|
||||
PermissionMode: global.DefaultPermissionMode);
|
||||
PermissionMode: global.DefaultPermissionMode,
|
||||
SkillNames: skillNames);
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<string>> FilterToInstalledSkillsAsync(
|
||||
string taskId, IReadOnlyList<string> requestedSkills, CancellationToken ct)
|
||||
{
|
||||
if (requestedSkills.Count == 0) return requestedSkills;
|
||||
|
||||
List<SessionSkillEntity> installed;
|
||||
using (var ctx = _dbFactory.CreateDbContext())
|
||||
{
|
||||
var skillRepo = new SessionSkillRepository(ctx);
|
||||
installed = (await skillRepo.ListAsync(ct)).ToList();
|
||||
}
|
||||
|
||||
var installedNames = installed.Select(s => s.Name).ToHashSet(StringComparer.Ordinal);
|
||||
var resolved = requestedSkills.Where(installedNames.Contains).ToList();
|
||||
var dropped = requestedSkills.Where(n => !installedNames.Contains(n)).ToList();
|
||||
if (dropped.Count > 0)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Task {TaskId}: dropped unknown session skill(s) not found in registry: {SkillNames}",
|
||||
taskId, string.Join(", ", dropped));
|
||||
}
|
||||
|
||||
return resolved;
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<string> UnionSkillNames(params string?[] jsonArrays)
|
||||
{
|
||||
var names = new List<string>();
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var json in jsonArrays)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json)) continue;
|
||||
|
||||
string[]? parsed;
|
||||
try
|
||||
{
|
||||
parsed = JsonSerializer.Deserialize<string[]>(json);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (parsed is null) continue;
|
||||
|
||||
foreach (var name in parsed)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(name) && seen.Add(name))
|
||||
names.Add(name);
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
internal static int? ResolveMaxTurns(int? taskTurns, int? listTurns, int globalDefault)
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace ClaudeDo.Worker.Skills;
|
||||
|
||||
public interface ISessionSkillSeeder
|
||||
{
|
||||
Task SeedAsync(string workingDir, IReadOnlyList<string> skillNames, bool isWorktree, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using ClaudeDo.Data;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace ClaudeDo.Worker.Skills;
|
||||
|
||||
public sealed class SessionSkillSeeder : ISessionSkillSeeder
|
||||
{
|
||||
private readonly string _skillsRoot;
|
||||
private readonly ILogger<SessionSkillSeeder> _logger;
|
||||
|
||||
public SessionSkillSeeder(ILogger<SessionSkillSeeder> logger, string? skillsRoot = null)
|
||||
{
|
||||
_logger = logger;
|
||||
_skillsRoot = skillsRoot ?? Path.Combine(Paths.AppDataRoot(), "session-skills");
|
||||
}
|
||||
|
||||
public async Task SeedAsync(string workingDir, IReadOnlyList<string> skillNames, bool isWorktree, CancellationToken ct)
|
||||
{
|
||||
if (skillNames.Count == 0) return;
|
||||
|
||||
var skillsDestRoot = Path.Combine(workingDir, ".claude", "skills");
|
||||
|
||||
foreach (var name in skillNames)
|
||||
{
|
||||
var sourceDir = Path.Combine(_skillsRoot, name);
|
||||
if (!Directory.Exists(sourceDir))
|
||||
{
|
||||
_logger.LogWarning("Session skill '{SkillName}' not found on disk at {SourceDir}; skipping", name, sourceDir);
|
||||
continue;
|
||||
}
|
||||
|
||||
var destDir = Path.Combine(skillsDestRoot, name);
|
||||
CopyDirectory(sourceDir, destDir);
|
||||
|
||||
if (isWorktree)
|
||||
await AppendExcludeLineAsync(workingDir, $"/.claude/skills/{name}/", ct);
|
||||
}
|
||||
}
|
||||
|
||||
private static void CopyDirectory(string sourceDir, string destDir)
|
||||
{
|
||||
Directory.CreateDirectory(destDir);
|
||||
foreach (var file in Directory.EnumerateFiles(sourceDir, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var relative = Path.GetRelativePath(sourceDir, file);
|
||||
var destPath = Path.Combine(destDir, relative);
|
||||
var destParent = Path.GetDirectoryName(destPath);
|
||||
if (!string.IsNullOrEmpty(destParent))
|
||||
Directory.CreateDirectory(destParent);
|
||||
File.Copy(file, destPath, overwrite: true);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task AppendExcludeLineAsync(string workingDir, string excludeLine, CancellationToken ct)
|
||||
{
|
||||
var relativeExcludePath = await RunGitCaptureAsync(workingDir, ["rev-parse", "--git-path", "info/exclude"], ct);
|
||||
var excludeFile = Path.IsPathRooted(relativeExcludePath)
|
||||
? relativeExcludePath
|
||||
: Path.GetFullPath(Path.Combine(workingDir, relativeExcludePath));
|
||||
|
||||
var excludeDir = Path.GetDirectoryName(excludeFile);
|
||||
if (!string.IsNullOrEmpty(excludeDir))
|
||||
Directory.CreateDirectory(excludeDir);
|
||||
|
||||
if (File.Exists(excludeFile))
|
||||
{
|
||||
var existingLines = await File.ReadAllLinesAsync(excludeFile, ct);
|
||||
if (existingLines.Any(l => l.Trim() == excludeLine))
|
||||
return;
|
||||
}
|
||||
|
||||
await File.AppendAllTextAsync(excludeFile, excludeLine + Environment.NewLine, ct);
|
||||
}
|
||||
|
||||
private static async Task<string> RunGitCaptureAsync(string workingDir, IEnumerable<string> args, CancellationToken ct)
|
||||
{
|
||||
var psi = new ProcessStartInfo
|
||||
{
|
||||
FileName = "git",
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
StandardOutputEncoding = Encoding.UTF8,
|
||||
StandardErrorEncoding = Encoding.UTF8,
|
||||
};
|
||||
psi.ArgumentList.Add("-C");
|
||||
psi.ArgumentList.Add(workingDir);
|
||||
foreach (var a in args) psi.ArgumentList.Add(a);
|
||||
|
||||
using var proc = new Process { StartInfo = psi };
|
||||
proc.Start();
|
||||
|
||||
await using var ctr = ct.Register(() =>
|
||||
{
|
||||
try { proc.Kill(entireProcessTree: true); }
|
||||
catch { /* already exited */ }
|
||||
});
|
||||
|
||||
var stdoutTask = proc.StandardOutput.ReadToEndAsync();
|
||||
var stderrTask = proc.StandardError.ReadToEndAsync();
|
||||
|
||||
await proc.WaitForExitAsync(CancellationToken.None);
|
||||
var stdout = await stdoutTask;
|
||||
var stderr = await stderrTask;
|
||||
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
if (proc.ExitCode != 0)
|
||||
throw new InvalidOperationException($"git rev-parse --git-path failed (exit {proc.ExitCode}): {stderr.TrimEnd()}");
|
||||
|
||||
return stdout.TrimEnd('\r', '\n');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user