Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-3281: Add daemon skill bundle refs (#4445)

Bohan Jiang5038c983c076
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index a969a8830f..0aa744948b 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -503,6 +503,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/workspaces/{workspaceId}/runtime-profiles", h.DaemonListRuntimeProfiles)
r.Post("/runtimes/{runtimeId}/tasks/claim", h.ClaimTaskByRuntime)
+ r.Post("/runtimes/{runtimeId}/tasks/{taskId}/prepare-lease", h.ExtendTaskPrepareLease)
+ r.Post("/runtimes/{runtimeId}/tasks/{taskId}/skill-bundles/resolve", h.ResolveTaskSkillBundles)
r.Get("/runtimes/{runtimeId}/tasks/pending", h.ListPendingTasksByRuntime)
r.Post("/runtimes/{runtimeId}/update/{updateId}/result", h.ReportUpdateResult)
r.Post("/runtimes/{runtimeId}/models/{requestId}/result", h.ReportModelListResult)
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 7c329c85c2..8516fab6bf 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -141,6 +141,7 @@ func (c *Client) setIdentityHeaders(req *http.Request) {
if c.os != "" {
req.Header.Set("X-Client-OS", c.os)
}
+ req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilitySkillBundlesV1)
}
// SetToken sets the auth token for authenticated requests.
@@ -163,6 +164,22 @@ func (c *Client) ClaimTask(ctx context.Context, runtimeID string) (*Task, error)
return resp.Task, nil
}
+func (c *Client) ResolveSkillBundles(ctx context.Context, runtimeID, taskID string, refs []SkillRefData) ([]SkillData, error) {
+ var resp struct {
+ Bundles []SkillData `json:"bundles"`
+ }
+ if err := c.postJSON(ctx, fmt.Sprintf("/api/daemon/runtimes/%s/tasks/%s/skill-bundles/resolve", runtimeID, taskID), map[string]any{
+ "skills": refs,
+ }, &resp); err != nil {
+ return nil, err
+ }
+ return resp.Bundles, nil
+}
+
+func (c *Client) ExtendTaskPrepareLease(ctx context.Context, runtimeID, taskID string) error {
+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/runtimes/%s/tasks/%s/prepare-lease", runtimeID, taskID), map[string]any{}, nil)
+}
+
func (c *Client) StartTask(ctx context.Context, taskID string) error {
return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/start", taskID), map[string]any{}, nil)
}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index f253306ae6..d436e7bd1e 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -22,6 +22,7 @@ import (
"github.com/multica-ai/multica/server/internal/daemon/execenv"
"github.com/multica-ai/multica/server/internal/daemon/repocache"
"github.com/multica-ai/multica/server/pkg/agent"
+ "github.com/multica-ai/multica/server/pkg/skillbundle"
"github.com/multica-ai/multica/server/pkg/taskfailure"
)
@@ -48,6 +49,11 @@ const (
taskSlotCapacityBackoff = 5 * time.Second
)
+var (
+ taskPrepareLeaseRefresh = 15 * time.Second
+ taskPrepareLeaseTimeout = 10 * time.Second
+)
+
func taskScopedAuthToken(task Task) (string, error) {
token := strings.TrimSpace(task.AuthToken)
if token == "" {
@@ -141,10 +147,11 @@ type repoCacheBackend interface {
// Daemon is the local agent runtime that polls for and executes tasks.
type Daemon struct {
- cfg Config
- client *Client
- repoCache repoCacheBackend
- logger *slog.Logger
+ cfg Config
+ client *Client
+ repoCache repoCacheBackend
+ skillCache *SkillBundleCache
+ logger *slog.Logger
mu sync.Mutex
workspaces map[string]*workspaceState
@@ -230,6 +237,7 @@ type profileLaunchSpec struct {
// New creates a new Daemon instance.
func New(cfg Config, logger *slog.Logger) *Daemon {
cacheRoot := filepath.Join(cfg.WorkspacesRoot, ".repos")
+ skillCacheRoot := filepath.Join(cfg.WorkspacesRoot, ".skill-cache", "v1")
client := NewClient(cfg.ServerBaseURL)
// Tag every daemon HTTP request with the daemon's CLI version so the
// server can split logs/metrics by client version (parallel to the CLI).
@@ -238,6 +246,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {
cfg: cfg,
client: client,
repoCache: repocache.New(cacheRoot, logger),
+ skillCache: NewSkillBundleCache(skillCacheRoot),
logger: logger,
workspaces: make(map[string]*workspaceState),
runtimeIndex: make(map[string]Runtime),
@@ -2917,9 +2926,16 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tas
pollInterval = 5 * time.Second
}
var (
- watcherOnce sync.Once
- cancelledByPoll <-chan struct{}
+ watcherOnce sync.Once
+ prepareLeaseOnce sync.Once
+ cancelledByPoll <-chan struct{}
+ stopPrepareLease func()
)
+ defer func() {
+ if stopPrepareLease != nil {
+ stopPrepareLease()
+ }
+ }()
onWait := func(holder string) {
reason := fmt.Sprintf("local_directory %s", assignment.AbsPath)
@@ -2933,6 +2949,9 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tas
// The UI just won't see the explicit "waiting" badge.
taskLog.Warn("local_directory: mark waiting status failed", "error", waitErr)
}
+ prepareLeaseOnce.Do(func() {
+ stopPrepareLease = d.startTaskPrepareLeaseExtender(waitCtx, task, taskLog)
+ })
// Start polling once we actually park. shouldInterruptAgent inside
// watchTaskCancellation already handles both server-side terminal
// states (completed/failed/cancelled) and the row-deleted
@@ -3116,6 +3135,123 @@ func gateResumeToReusedWorkdir(task *Task, taskCtx *execenv.TaskContextForEnv, e
return reused
}
+func (d *Daemon) ensureTaskSkillBundles(ctx context.Context, task *Task) error {
+ if task == nil || task.Agent == nil || len(task.Agent.SkillRefs) == 0 {
+ return nil
+ }
+ resolved := make(map[string]SkillData, len(task.Agent.SkillRefs))
+ misses := make([]SkillRefData, 0)
+ for _, ref := range task.Agent.SkillRefs {
+ ref := ref
+ var bundle SkillData
+ if err := d.skillCache.WithRefLock(task.WorkspaceID, ref, func() error {
+ if cached, ok := d.skillCache.Load(task.WorkspaceID, ref); ok {
+ bundle = cached
+ return nil
+ }
+ misses = append(misses, ref)
+ return nil
+ }); err != nil {
+ return fmt.Errorf("load skill bundle cache: %w", err)
+ }
+ if bundle.ID != "" {
+ resolved[skillRefKey(ref.Source, ref.ID)] = bundle
+ }
+ }
+
+ if len(misses) > 0 {
+ bundles, err := d.client.ResolveSkillBundles(ctx, task.RuntimeID, task.ID, misses)
+ if err != nil {
+ return fmt.Errorf("resolve skill bundles: %w", err)
+ }
+ for _, bundle := range bundles {
+ ref := skillRefFromBundle(bundle)
+ if !validateSkillBundle(ref, bundle) {
+ return fmt.Errorf("resolve skill bundle returned invalid bundle: skill_id=%s source=%s hash=%s", bundle.ID, bundle.Source, bundle.Hash)
+ }
+ if err := d.skillCache.WithRefLock(task.WorkspaceID, ref, func() error {
+ return d.skillCache.Store(task.WorkspaceID, bundle)
+ }); err != nil {
+ return fmt.Errorf("store skill bundle cache: %w", err)
+ }
+ resolved[skillRefKey(bundle.Source, bundle.ID)] = bundle
+ }
+ }
+
+ skills := make([]SkillData, 0, len(task.Agent.SkillRefs))
+ for _, ref := range task.Agent.SkillRefs {
+ bundle, ok := resolved[skillRefKey(ref.Source, ref.ID)]
+ if !ok {
+ return fmt.Errorf("skill bundle missing after resolve: skill_id=%s source=%s hash=%s", ref.ID, ref.Source, ref.Hash)
+ }
+ skills = append(skills, bundle)
+ }
+ task.Agent.Skills = skills
+ return nil
+}
+
+func (d *Daemon) startTaskPrepareLeaseExtender(ctx context.Context, task Task, taskLog *slog.Logger) func() {
+ leaseCtx, cancel := context.WithCancel(ctx)
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ ticker := time.NewTicker(taskPrepareLeaseRefresh)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-leaseCtx.Done():
+ return
+ case <-ticker.C:
+ reqCtx, reqCancel := context.WithTimeout(leaseCtx, taskPrepareLeaseTimeout)
+ err := d.client.ExtendTaskPrepareLease(reqCtx, task.RuntimeID, task.ID)
+ reqCancel()
+ if err != nil {
+ taskLog.Warn("extend task prepare lease failed", "error", err)
+ }
+ }
+ }
+ }()
+
+ var once sync.Once
+ return func() {
+ once.Do(func() {
+ cancel()
+ <-done
+ })
+ }
+}
+
+func skillRefKey(source, id string) string {
+ return source + "\x00" + id
+}
+
+func skillRefFromBundle(bundle SkillData) SkillRefData {
+ files := make([]skillbundle.File, 0, len(bundle.Files))
+ for _, file := range bundle.Files {
+ files = append(files, skillbundle.File{Path: file.Path, Content: file.Content})
+ }
+ manifest := skillbundle.BuildManifest(skillbundle.Skill{
+ ID: bundle.ID,
+ Source: bundle.Source,
+ Name: bundle.Name,
+ Description: bundle.Description,
+ Content: bundle.Content,
+ Files: files,
+ })
+ fileRefs := make([]SkillFileRefData, 0, len(manifest.Files))
+ for _, file := range manifest.Files {
+ fileRefs = append(fileRefs, SkillFileRefData{Path: file.Path, SHA256: file.SHA256, SizeBytes: file.SizeBytes})
+ }
+ return SkillRefData{
+ ID: bundle.ID,
+ Source: bundle.Source,
+ Hash: manifest.Hash,
+ SizeBytes: manifest.SizeBytes,
+ FileCount: manifest.FileCount,
+ Files: fileRefs,
+ }
+}
+
func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot int, taskLog *slog.Logger) (TaskResult, error) {
// Refuse to spawn an agent without a workspace. An empty workspace_id
// here would make MULTICA_WORKSPACE_ID empty in the agent env, and the
@@ -3156,6 +3292,13 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
return TaskResult{}, fmt.Errorf("no agent configured for provider %q", provider)
}
+ stopPrepareLease := d.startTaskPrepareLeaseExtender(ctx, task, taskLog)
+ defer stopPrepareLease()
+
+ if err := d.ensureTaskSkillBundles(ctx, &task); err != nil {
+ return TaskResult{}, err
+ }
+
agentName := "agent"
var agentID string
var skills []SkillData
@@ -3300,8 +3443,10 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// "start task failed: <…>" string and the same failure_reason
// taxonomy as before — see MUL-2946 for the classifier contract.
if err := d.client.StartTask(ctx, task.ID); err != nil {
+ stopPrepareLease()
return TaskResult{}, fmt.Errorf("start task failed: %w", err)
}
+ stopPrepareLease()
_ = d.client.ReportProgress(ctx, task.ID, fmt.Sprintf("Launching %s", provider), 1, 2)
reused := gateResumeToReusedWorkdir(&task, &taskCtx, env.WorkDir, taskLog)
diff --git a/server/internal/daemon/skill_cache.go b/server/internal/daemon/skill_cache.go
new file mode 100644
index 0000000000..9c288bbb4b
--- /dev/null
+++ b/server/internal/daemon/skill_cache.go
@@ -0,0 +1,173 @@
+package daemon
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+ "sync"
+
+ "github.com/multica-ai/multica/server/pkg/skillbundle"
+)
+
+type SkillBundleCache struct {
+ root string
+ mu sync.Mutex
+ locks map[string]*sync.Mutex
+}
+
+func NewSkillBundleCache(root string) *SkillBundleCache {
+ return &SkillBundleCache{root: root, locks: make(map[string]*sync.Mutex)}
+}
+
+func (c *SkillBundleCache) Load(workspaceID string, ref SkillRefData) (SkillData, bool) {
+ if c == nil || c.root == "" {
+ return SkillData{}, false
+ }
+ keyPath := c.bundlePath(workspaceID, ref)
+ data, err := os.ReadFile(keyPath)
+ if err != nil {
+ return SkillData{}, false
+ }
+ var bundle SkillData
+ if err := json.Unmarshal(data, &bundle); err != nil || !validateSkillBundle(ref, bundle) {
+ _ = os.Remove(keyPath)
+ return SkillData{}, false
+ }
+ return bundle, true
+}
+
+func (c *SkillBundleCache) Store(workspaceID string, bundle SkillData) error {
+ if c == nil || c.root == "" {
+ return nil
+ }
+ ref := SkillRefData{ID: bundle.ID, Source: bundle.Source, Hash: bundle.Hash}
+ dir := filepath.Dir(c.bundlePath(workspaceID, ref))
+ tmp, err := os.MkdirTemp(filepath.Dir(dir), ".bundle-*")
+ if err != nil {
+ if mkErr := os.MkdirAll(filepath.Dir(dir), 0o755); mkErr != nil {
+ return mkErr
+ }
+ tmp, err = os.MkdirTemp(filepath.Dir(dir), ".bundle-*")
+ if err != nil {
+ return err
+ }
+ }
+ defer os.RemoveAll(tmp)
+
+ data, err := json.Marshal(bundle)
+ if err != nil {
+ return err
+ }
+ if err := os.WriteFile(filepath.Join(tmp, "bundle.json"), data, 0o644); err != nil {
+ return err
+ }
+ _ = os.RemoveAll(dir)
+ if err := os.Rename(tmp, dir); err != nil {
+ return err
+ }
+ return nil
+}
+
+func (c *SkillBundleCache) WithRefLock(workspaceID string, ref SkillRefData, fn func() error) error {
+ if c == nil {
+ return fn()
+ }
+ key := workspaceID + "\x00" + ref.Source + "\x00" + ref.ID + "\x00" + ref.Hash
+ lock := c.lockForKey(key)
+ lock.Lock()
+ defer lock.Unlock()
+ return fn()
+}
+
+func (c *SkillBundleCache) lockForKey(key string) *sync.Mutex {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if lock := c.locks[key]; lock != nil {
+ return lock
+ }
+ lock := &sync.Mutex{}
+ c.locks[key] = lock
+ return lock
+}
+
+func (c *SkillBundleCache) bundlePath(workspaceID string, ref SkillRefData) string {
+ return filepath.Join(
+ c.root,
+ safeCacheSegment(workspaceID),
+ safeCacheSegment(ref.Source),
+ safeCacheSegment(ref.ID),
+ safeCacheSegment(ref.Hash),
+ "bundle.json",
+ )
+}
+
+func validateSkillBundle(ref SkillRefData, bundle SkillData) bool {
+ if bundle.ID != ref.ID || bundle.Source != ref.Source || bundle.Hash != ref.Hash {
+ return false
+ }
+ if len(bundle.Files) != ref.FileCount {
+ return false
+ }
+ files := make([]skillbundle.File, 0, len(bundle.Files))
+ for _, file := range bundle.Files {
+ if !safeSkillFilePath(file.Path) {
+ return false
+ }
+ files = append(files, skillbundle.File{Path: file.Path, Content: file.Content})
+ }
+ manifest := skillbundle.BuildManifest(skillbundle.Skill{
+ ID: bundle.ID,
+ Source: bundle.Source,
+ Name: bundle.Name,
+ Description: bundle.Description,
+ Content: bundle.Content,
+ Files: files,
+ })
+ if manifest.Hash != ref.Hash {
+ return false
+ }
+ if ref.SizeBytes > 0 && manifest.SizeBytes != ref.SizeBytes {
+ return false
+ }
+ return true
+}
+
+func safeSkillFilePath(p string) bool {
+ if p == "" || strings.Contains(p, "\x00") || strings.HasPrefix(p, "/") || strings.Contains(p, "\\") {
+ return false
+ }
+ clean := path.Clean(p)
+ if clean == "." || clean != p || strings.HasPrefix(clean, "../") || clean == ".." {
+ return false
+ }
+ return true
+}
+
+func safeCacheSegment(s string) string {
+ var b strings.Builder
+ if s == "" {
+ return "_"
+ }
+ for _, r := range s {
+ switch {
+ case r >= 'a' && r <= 'z':
+ b.WriteRune(r)
+ case r >= 'A' && r <= 'Z':
+ b.WriteRune(r)
+ case r >= '0' && r <= '9':
+ b.WriteRune(r)
+ case r == '-' || r == '_' || r == '.':
+ b.WriteRune(r)
+ default:
+ b.WriteByte('_')
+ }
+ }
+ out := b.String()
+ if out == "." || out == ".." {
+ return fmt.Sprintf("_%s", out)
+ }
+ return out
+}
diff --git a/server/internal/daemon/skill_cache_test.go b/server/internal/daemon/skill_cache_test.go
new file mode 100644
index 0000000000..f688286bd5
--- /dev/null
+++ b/server/internal/daemon/skill_cache_test.go
@@ -0,0 +1,59 @@
+package daemon
+
+import (
+ "os"
+ "testing"
+)
+
+func TestSkillBundleCacheLoadStore(t *testing.T) {
+ cache := NewSkillBundleCache(t.TempDir())
+ bundle := testSkillBundle()
+ ref := skillRefFromBundle(bundle)
+
+ if err := cache.Store("ws-1", bundle); err != nil {
+ t.Fatalf("Store: %v", err)
+ }
+ got, ok := cache.Load("ws-1", ref)
+ if !ok {
+ t.Fatal("expected cache hit")
+ }
+ if got.Content != bundle.Content || len(got.Files) != 1 || got.Files[0].Content != "rules" {
+ t.Fatalf("unexpected bundle: %+v", got)
+ }
+}
+
+func TestSkillBundleCacheRejectsCorruptBundle(t *testing.T) {
+ cache := NewSkillBundleCache(t.TempDir())
+ bundle := testSkillBundle()
+ ref := skillRefFromBundle(bundle)
+ if err := cache.Store("ws-1", bundle); err != nil {
+ t.Fatalf("Store: %v", err)
+ }
+
+ path := cache.bundlePath("ws-1", ref)
+ if err := os.WriteFile(path, []byte(`{"id":"skill-1","source":"workspace","hash":"sha256:bad","content":"tampered"}`), 0o644); err != nil {
+ t.Fatalf("tamper cache: %v", err)
+ }
+ if _, ok := cache.Load("ws-1", ref); ok {
+ t.Fatal("expected corrupt cache miss")
+ }
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("expected corrupt cache file to be removed, stat err=%v", err)
+ }
+}
+
+func testSkillBundle() SkillData {
+ bundle := SkillData{
+ ID: "skill-1",
+ Source: "workspace",
+ Name: "deploy",
+ Content: "main",
+ Files: []SkillFileData{{Path: "rules.md", Content: "rules"}},
+ }
+ ref := skillRefFromBundle(bundle)
+ bundle.Hash = ref.Hash
+ bundle.SizeBytes = ref.SizeBytes
+ bundle.Files[0].SHA256 = ref.Files[0].SHA256
+ bundle.Files[0].SizeBytes = ref.Files[0].SizeBytes
+ return bundle
+}
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 52184ede60..bb5bef94f0 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -130,7 +130,8 @@ type AgentData struct {
ID string `json:"id"`
Name string `json:"name"`
Instructions string `json:"instructions"`
- Skills []SkillData `json:"skills"`
+ Skills []SkillData `json:"skills,omitempty"`
+ SkillRefs []SkillRefData `json:"skill_refs,omitempty"`
CustomEnv map[string]string `json:"custom_env,omitempty"`
CustomArgs []string `json:"custom_args,omitempty"`
McpConfig json.RawMessage `json:"mcp_config,omitempty"`
@@ -146,16 +147,38 @@ type AgentData struct {
// SkillData represents a structured skill for task execution.
type SkillData struct {
ID string `json:"id"`
+ Source string `json:"source,omitempty"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
+ Hash string `json:"hash,omitempty"`
+ SizeBytes int64 `json:"size_bytes,omitempty"`
Content string `json:"content"`
Files []SkillFileData `json:"files,omitempty"`
}
// SkillFileData represents a supporting file within a skill.
type SkillFileData struct {
- Path string `json:"path"`
- Content string `json:"content"`
+ Path string `json:"path"`
+ Content string `json:"content"`
+ SHA256 string `json:"sha256,omitempty"`
+ SizeBytes int64 `json:"size_bytes,omitempty"`
+}
+
+type SkillRefData struct {
+ ID string `json:"id"`
+ Source string `json:"source"`
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ Hash string `json:"hash"`
+ SizeBytes int64 `json:"size_bytes"`
+ FileCount int `json:"file_count"`
+ Files []SkillFileRefData `json:"files,omitempty"`
+}
+
+type SkillFileRefData struct {
+ Path string `json:"path"`
+ SHA256 string `json:"sha256"`
+ SizeBytes int64 `json:"size_bytes"`
}
// TaskUsageEntry represents token usage for a single model during a task execution.
diff --git a/server/internal/daemon/workdir_race_test.go b/server/internal/daemon/workdir_race_test.go
index ee79031b2e..d76c310906 100644
--- a/server/internal/daemon/workdir_race_test.go
+++ b/server/internal/daemon/workdir_race_test.go
@@ -9,6 +9,7 @@ import (
"os"
"path/filepath"
"strings"
+ "sync"
"sync/atomic"
"testing"
"time"
@@ -95,9 +96,9 @@ func TestRunTask_StartTaskCalledAfterWorkdirOnDisk(t *testing.T) {
expectedWorkDir := filepath.Join(expectedEnvRoot, "workdir")
var (
- startCalled atomic.Bool
- workdirOnDisk atomic.Bool
- envRootOnDisk atomic.Bool
+ startCalled atomic.Bool
+ workdirOnDisk atomic.Bool
+ envRootOnDisk atomic.Bool
)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -156,6 +157,81 @@ func TestRunTask_StartTaskCalledAfterWorkdirOnDisk(t *testing.T) {
}
}
+func TestRunTask_ExtendsPrepareLeaseDuringStartTask(t *testing.T) {
+ oldRefresh := taskPrepareLeaseRefresh
+ oldTimeout := taskPrepareLeaseTimeout
+ taskPrepareLeaseRefresh = 10 * time.Millisecond
+ taskPrepareLeaseTimeout = 500 * time.Millisecond
+ t.Cleanup(func() {
+ taskPrepareLeaseRefresh = oldRefresh
+ taskPrepareLeaseTimeout = oldTimeout
+ })
+
+ workspacesRoot := t.TempDir()
+ workspaceID := "ws-runtask-start-lease"
+ taskID := "task-runtask-start-lease"
+ var (
+ startEntered atomic.Bool
+ leaseDuringStart atomic.Bool
+ closeLeaseOnce sync.Once
+ )
+ leaseSeenDuringStart := make(chan struct{})
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/prepare-lease"):
+ if startEntered.Load() {
+ leaseDuringStart.Store(true)
+ closeLeaseOnce.Do(func() { close(leaseSeenDuringStart) })
+ }
+ w.WriteHeader(http.StatusOK)
+ case strings.HasSuffix(r.URL.Path, "/start"):
+ startEntered.Store(true)
+ select {
+ case <-leaseSeenDuringStart:
+ case <-time.After(2 * time.Second):
+ }
+ w.WriteHeader(http.StatusOK)
+ default:
+ w.WriteHeader(http.StatusOK)
+ }
+ }))
+ t.Cleanup(srv.Close)
+
+ missingBin := filepath.Join(t.TempDir(), "definitely-not-claude")
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ workspaces: make(map[string]*workspaceState),
+ runtimeIndex: map[string]Runtime{"rt-1": {ID: "rt-1", Provider: "claude"}},
+ activeEnvRoots: make(map[string]int),
+ cfg: Config{
+ WorkspacesRoot: workspacesRoot,
+ Agents: map[string]AgentEntry{
+ "claude": {Path: missingBin, Model: ""},
+ },
+ },
+ }
+
+ task := Task{
+ ID: taskID,
+ WorkspaceID: workspaceID,
+ RuntimeID: "rt-1",
+ IssueID: "issue-runtask-start-lease",
+ Agent: &AgentData{Name: "test-agent"},
+ }
+
+ taskLog := slog.New(slog.NewTextHandler(io.Discard, nil))
+ _, _ = d.runTask(context.Background(), task, "claude", 0, taskLog)
+
+ if !startEntered.Load() {
+ t.Fatal("runTask did not call /start")
+ }
+ if !leaseDuringStart.Load() {
+ t.Fatal("prepare lease was not extended while /start was still in flight")
+ }
+}
+
// TestHandleTask_KeepsEnvRootActiveAcrossCompletion is the regression guard
// for issue #3999 race B. After runner.run returns, the in-process active
// guard installed inside runTask (defer unmarkActiveEnvRoot at the
@@ -178,7 +254,7 @@ func TestHandleTask_KeepsEnvRootActiveAcrossCompletion(t *testing.T) {
expectedEnvRoot := execenv.PredictRootDir(workspacesRoot, workspaceID, taskID)
var (
- completeCalled atomic.Bool
+ completeCalled atomic.Bool
activeAtComplete atomic.Bool
)
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 2d0e1174a8..f01b823f03 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -343,15 +343,16 @@ type ChatAttachmentMeta struct {
// TaskAgentData holds agent info included in claim responses so the daemon
// can set up the execution environment (branch naming, skill files, instructions).
type TaskAgentData struct {
- ID string `json:"id"`
- Name string `json:"name"`
- Instructions string `json:"instructions"`
- Skills []service.AgentSkillData `json:"skills,omitempty"`
- CustomEnv map[string]string `json:"custom_env,omitempty"`
- CustomArgs []string `json:"custom_args,omitempty"`
- McpConfig json.RawMessage `json:"mcp_config,omitempty"`
- Model string `json:"model,omitempty"`
- ThinkingLevel string `json:"thinking_level,omitempty"`
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Instructions string `json:"instructions"`
+ Skills []service.AgentSkillData `json:"skills,omitempty"`
+ SkillRefs []service.AgentSkillRefData `json:"skill_refs,omitempty"`
+ CustomEnv map[string]string `json:"custom_env,omitempty"`
+ CustomArgs []string `json:"custom_args,omitempty"`
+ McpConfig json.RawMessage `json:"mcp_config,omitempty"`
+ Model string `json:"model,omitempty"`
+ ThinkingLevel string `json:"thinking_level,omitempty"`
// RuntimeConfig is the agent's saved runtime_config JSON as-is. The
// daemon decodes it per-provider — e.g. the openclaw backend reads
// `mode` + `gateway.*` to choose between embedded and gateway routing
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index b1ae824e27..0a43b6ed11 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1213,6 +1213,15 @@ func logClaimEndpointSlow(runtimeID, outcome string, start time.Time, authMs, cl
)
}
+func requestHasDaemonCapability(r *http.Request, capability string) bool {
+ for _, part := range strings.Split(r.Header.Get("X-Client-Capabilities"), ",") {
+ if strings.TrimSpace(part) == capability {
+ return true
+ }
+ }
+ return false
+}
+
// ClaimTaskByRuntime atomically claims the next queued task for a runtime.
// The response includes the agent's name and skills, fetched fresh from the DB.
func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
@@ -1272,14 +1281,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
// Build response with fresh agent data (name + skills + custom_env + custom_args).
resp := taskToResponse(*task, runtimeWorkspaceID)
if agent, err := h.Queries.GetAgent(r.Context(), task.AgentID); err == nil {
- // Workspace-bound skills first, then platform built-in skills. Built-in
- // names carry a "multica-" prefix so their on-disk slugs never collide
- // with a user-authored workspace skill (see writeSkillFiles).
- skills := h.TaskService.LoadAgentSkills(r.Context(), task.AgentID)
- agentSkillCount = len(skills)
- builtinSkills := h.TaskService.BuiltinSkills()
- builtinSkillCount = len(builtinSkills)
- skills = append(skills, builtinSkills...)
+ useSkillRefs := requestHasDaemonCapability(r, protocol.DaemonCapabilitySkillBundlesV1)
var customEnv map[string]string
if agent.CustomEnv != nil {
if err := json.Unmarshal(agent.CustomEnv, &customEnv); err != nil {
@@ -1308,7 +1310,6 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
ID: uuidToString(agent.ID),
Name: agent.Name,
Instructions: agent.Instructions,
- Skills: skills,
CustomEnv: customEnv,
CustomArgs: customArgs,
McpConfig: mcpConfig,
@@ -1316,6 +1317,18 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
ThinkingLevel: agent.ThinkingLevel.String,
RuntimeConfig: runtimeConfig,
}
+ if useSkillRefs {
+ _, skillRefs := h.TaskService.LoadAgentSkillBundles(r.Context(), task.AgentID)
+ agentSkillCount = len(skillRefs)
+ resp.Agent.SkillRefs = skillRefs
+ } else {
+ skills := h.TaskService.LoadAgentSkills(r.Context(), task.AgentID)
+ agentSkillCount = len(skills)
+ builtinSkills := h.TaskService.BuiltinSkills()
+ builtinSkillCount = len(builtinSkills)
+ skills = append(skills, builtinSkills...)
+ resp.Agent.Skills = skills
+ }
}
// Resolve the runtime owner's profile description so the daemon can
@@ -1880,10 +1893,86 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
if skillPayload, err := json.Marshal(resp.Agent.Skills); err == nil {
skillPayloadBytes = len(skillPayload)
}
+ } else if resp.Agent != nil && len(resp.Agent.SkillRefs) > 0 {
+ if skillPayload, err := json.Marshal(resp.Agent.SkillRefs); err == nil {
+ skillPayloadBytes = len(skillPayload)
+ }
}
payloadBytes, _ = writeMeasuredJSON(w, http.StatusOK, map[string]any{"task": resp})
}
+type resolveSkillBundlesRequest struct {
+ Skills []resolveSkillBundleRef `json:"skills"`
+}
+
+type resolveSkillBundleRef struct {
+ ID string `json:"id"`
+ Source string `json:"source"`
+ Hash string `json:"hash"`
+}
+
+// ResolveTaskSkillBundles returns full skill content for refs from a slim
+// claim. The daemon calls this after claim and before execenv.Prepare so
+// runtimes still see complete local skill files at startup.
+//
+// If a requested hash no longer matches the agent's current skill bundle, the
+// endpoint returns the current bundle and hash. Stage 1 does not snapshot skill
+// content at claim time; the daemon validates the returned bundle before
+// writing it to cache and materializing it.
+func (h *Handler) ResolveTaskSkillBundles(w http.ResponseWriter, r *http.Request) {
+ runtimeID := chi.URLParam(r, "runtimeId")
+ taskID := chi.URLParam(r, "taskId")
+
+ runtime, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID)
+ if !ok {
+ return
+ }
+ task, taskWorkspaceID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, taskID)
+ if !ok {
+ return
+ }
+ if taskWorkspaceID != uuidToString(runtime.WorkspaceID) || uuidToString(task.RuntimeID) != runtimeID {
+ writeError(w, http.StatusNotFound, "task not found")
+ return
+ }
+ if task.Status != "dispatched" && task.Status != "waiting_local_directory" {
+ writeError(w, http.StatusConflict, "task is not preparing")
+ return
+ }
+
+ var req resolveSkillBundlesRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if len(req.Skills) == 0 {
+ writeJSON(w, http.StatusOK, map[string]any{"bundles": []service.AgentSkillData{}})
+ return
+ }
+
+ bundles, _ := h.TaskService.LoadAgentSkillBundles(r.Context(), task.AgentID)
+ allowed := make(map[string]service.AgentSkillData, len(bundles))
+ for _, bundle := range bundles {
+ allowed[bundle.Source+"\x00"+bundle.ID] = bundle
+ }
+
+ resolved := make([]service.AgentSkillData, 0, len(req.Skills))
+ for _, ref := range req.Skills {
+ if ref.ID == "" || ref.Source == "" || ref.Hash == "" {
+ writeError(w, http.StatusBadRequest, "invalid skill ref")
+ return
+ }
+ bundle, ok := allowed[ref.Source+"\x00"+ref.ID]
+ if !ok {
+ writeError(w, http.StatusNotFound, "skill bundle not found")
+ return
+ }
+ resolved = append(resolved, bundle)
+ }
+
+ writeJSON(w, http.StatusOK, map[string]any{"bundles": resolved})
+}
+
// trailingUserMessages returns the run of user messages after the last
// assistant message in a chronologically-ordered chat history — the set the
// agent has NOT yet replied to. The agent resumes its prior session and only
@@ -1932,6 +2021,35 @@ func (h *Handler) ListPendingTasksByRuntime(w http.ResponseWriter, r *http.Reque
// Task Lifecycle (called by daemon)
// ---------------------------------------------------------------------------
+// ExtendTaskPrepareLease keeps a dispatched task protected while the daemon is
+// resolving startup inputs and preparing the execution environment.
+func (h *Handler) ExtendTaskPrepareLease(w http.ResponseWriter, r *http.Request) {
+ runtimeID := chi.URLParam(r, "runtimeId")
+ taskID := chi.URLParam(r, "taskId")
+
+ runtime, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID)
+ if !ok {
+ return
+ }
+ task, taskWorkspaceID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, taskID)
+ if !ok {
+ return
+ }
+ if taskWorkspaceID != uuidToString(runtime.WorkspaceID) || uuidToString(task.RuntimeID) != runtimeID {
+ writeError(w, http.StatusNotFound, "task not found")
+ return
+ }
+
+ updated, err := h.TaskService.ExtendTaskPrepareLease(r.Context(), parseUUID(taskID), parseUUID(runtimeID))
+ if err != nil {
+ slog.Warn("extend task prepare lease failed", "task_id", taskID, "runtime_id", runtimeID, "error", err)
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+
+ writeJSON(w, http.StatusOK, taskToResponse(*updated, taskWorkspaceID))
+}
+
// StartTask marks a dispatched task as running.
func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {
taskID := chi.URLParam(r, "taskId")
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index 2746cf3c2f..91c4c148a7 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -19,6 +19,7 @@ import (
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/daemonws"
"github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -189,6 +190,17 @@ func createDispatchedClaimFixtureTask(t *testing.T, ctx context.Context, agentID
return taskID
}
+func setTaskPrepareLeaseForTest(t *testing.T, ctx context.Context, taskID, expiresIn string) {
+ t.Helper()
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent_task_queue
+ SET prepare_lease_expires_at = now() + ($2::interval)
+ WHERE id = $1
+ `, taskID, expiresIn); err != nil {
+ t.Fatalf("setup: set prepare lease: %v", err)
+ }
+}
+
func claimTaskByRuntimeForTest(t *testing.T, runtimeID string) (*struct {
ID string `json:"id"`
}, string) {
@@ -274,6 +286,109 @@ func TestClaimTaskByRuntime_DoesNotReclaimFreshDispatchedTask(t *testing.T) {
}
}
+func TestClaimTaskByRuntime_DoesNotReclaimActivePrepareLease(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Active prepare lease runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Active prepare lease agent")
+ taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "240 seconds", false)
+ setTaskPrepareLeaseForTest(t, ctx, taskID, "30 seconds")
+
+ task, body := claimTaskByRuntimeForTest(t, runtimeID)
+ if task != nil {
+ t.Fatalf("expected actively leased dispatched task %s not to be reclaimed, got %s in %s", taskID, task.ID, body)
+ }
+
+ var leaseActive bool
+ if err := testPool.QueryRow(ctx, `
+ SELECT prepare_lease_expires_at > now()
+ FROM agent_task_queue
+ WHERE id = $1
+ `, taskID).Scan(&leaseActive); err != nil {
+ t.Fatalf("load active prepare lease: %v", err)
+ }
+ if !leaseActive {
+ t.Fatal("expected prepare lease to remain active")
+ }
+}
+
+func TestClaimTaskByRuntime_ReclaimsExpiredPrepareLease(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Expired prepare lease runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Expired prepare lease agent")
+ taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "240 seconds", false)
+ setTaskPrepareLeaseForTest(t, ctx, taskID, "-5 seconds")
+
+ task, body := claimTaskByRuntimeForTest(t, runtimeID)
+ if task == nil {
+ t.Fatalf("expected expired leased task %s to be reclaimed, got nil response: %s", taskID, body)
+ }
+ if task.ID != taskID {
+ t.Fatalf("reclaimed task id = %s, want %s", task.ID, taskID)
+ }
+
+ var leaseRefreshed bool
+ if err := testPool.QueryRow(ctx, `
+ SELECT prepare_lease_expires_at > now()
+ FROM agent_task_queue
+ WHERE id = $1
+ `, taskID).Scan(&leaseRefreshed); err != nil {
+ t.Fatalf("load refreshed prepare lease: %v", err)
+ }
+ if !leaseRefreshed {
+ t.Fatal("expected reclaimed task to refresh prepare lease")
+ }
+}
+
+func TestExtendTaskPrepareLease(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Extend prepare lease runtime")
+ otherRuntimeID := createClaimReclaimRuntime(t, ctx, "Other prepare lease runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Extend prepare lease agent")
+ taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", false)
+
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+otherRuntimeID+"/tasks/"+taskID+"/prepare-lease", nil,
+ testWorkspaceID, "extend-prepare-lease")
+ req = withURLParams(req, "runtimeId", otherRuntimeID, "taskId", taskID)
+ testHandler.ExtendTaskPrepareLease(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("ExtendTaskPrepareLease wrong runtime: expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+
+ w = httptest.NewRecorder()
+ req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/prepare-lease", nil,
+ testWorkspaceID, "extend-prepare-lease")
+ req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
+ testHandler.ExtendTaskPrepareLease(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ExtendTaskPrepareLease: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var leaseActive bool
+ if err := testPool.QueryRow(ctx, `
+ SELECT prepare_lease_expires_at > now()
+ FROM agent_task_queue
+ WHERE id = $1
+ `, taskID).Scan(&leaseActive); err != nil {
+ t.Fatalf("load extended prepare lease: %v", err)
+ }
+ if !leaseActive {
+ t.Fatal("expected prepare lease to be extended")
+ }
+}
+
func TestClaimTaskByRuntime_DoesNotReclaimAlreadyStartedTask(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
@@ -331,6 +446,134 @@ func TestClaimTaskByRuntime_DoesNotReclaimDifferentRuntimeTask(t *testing.T) {
}
}
+func TestClaimTaskByRuntime_SkillBundleRefsAndResolve(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Skill refs runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Skill refs agent")
+
+ var skillID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO skill (workspace_id, name, description, content, config, created_by)
+ VALUES ($1, 'deploy-skill-ref-test', 'Deploy safely', 'main skill content', '{}'::jsonb, $2)
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&skillID); err != nil {
+ t.Fatalf("setup: create skill: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM agent_skill WHERE skill_id = $1`, skillID)
+ testPool.Exec(ctx, `DELETE FROM skill_file WHERE skill_id = $1`, skillID)
+ testPool.Exec(ctx, `DELETE FROM skill WHERE id = $1`, skillID)
+ })
+ if _, err := testPool.Exec(ctx, `INSERT INTO skill_file (skill_id, path, content) VALUES ($1, 'rules.md', 'rules content')`, skillID); err != nil {
+ t.Fatalf("setup: create skill file: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `INSERT INTO agent_skill (agent_id, skill_id) VALUES ($1, $2)`, agentID, skillID); err != nil {
+ t.Fatalf("setup: bind skill: %v", err)
+ }
+
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)
+ VALUES ($1, $2, $3, 'queued', 0)
+ RETURNING id
+ `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {
+ t.Fatalf("setup: create task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "skill-refs-daemon")
+ req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilitySkillBundlesV1)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.ClaimTaskByRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var claimResp struct {
+ Task *AgentTaskResponse `json:"task"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &claimResp); err != nil {
+ t.Fatalf("decode claim: %v", err)
+ }
+ if claimResp.Task == nil || claimResp.Task.Agent == nil {
+ t.Fatalf("missing task agent in response: %s", w.Body.String())
+ }
+ if len(claimResp.Task.Agent.Skills) != 0 {
+ t.Fatalf("slim claim returned full skills: %+v", claimResp.Task.Agent.Skills)
+ }
+ var ref service.AgentSkillRefData
+ for _, candidate := range claimResp.Task.Agent.SkillRefs {
+ if candidate.ID == skillID {
+ ref = candidate
+ break
+ }
+ }
+ if ref.ID == "" || ref.Hash == "" || ref.FileCount != 1 || len(ref.Files) != 1 || ref.Files[0].SHA256 == "" {
+ t.Fatalf("workspace skill ref missing manifest: %+v", ref)
+ }
+
+ staleHashBody := resolveSkillBundlesRequest{Skills: []resolveSkillBundleRef{{ID: ref.ID, Source: ref.Source, Hash: "sha256:stale"}}}
+ w = httptest.NewRecorder()
+ req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", staleHashBody, testWorkspaceID, "skill-refs-daemon")
+ req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
+ testHandler.ResolveTaskSkillBundles(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ResolveTaskSkillBundles with stale hash: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var staleHashResp struct {
+ Bundles []service.AgentSkillData `json:"bundles"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &staleHashResp); err != nil {
+ t.Fatalf("decode stale hash resolve: %v", err)
+ }
+ if len(staleHashResp.Bundles) != 1 || staleHashResp.Bundles[0].Hash != ref.Hash {
+ t.Fatalf("stale hash resolve did not return current bundle: %+v", staleHashResp.Bundles)
+ }
+
+ invalidRefBody := resolveSkillBundlesRequest{Skills: []resolveSkillBundleRef{{ID: ref.ID, Source: ref.Source}}}
+ w = httptest.NewRecorder()
+ req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", invalidRefBody, testWorkspaceID, "skill-refs-daemon")
+ req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
+ testHandler.ResolveTaskSkillBundles(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("ResolveTaskSkillBundles with invalid ref: expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+
+ resolveBody := resolveSkillBundlesRequest{Skills: []resolveSkillBundleRef{{ID: ref.ID, Source: ref.Source, Hash: ref.Hash}}}
+ w = httptest.NewRecorder()
+ req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", resolveBody, testWorkspaceID, "skill-refs-daemon")
+ req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
+ testHandler.ResolveTaskSkillBundles(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ResolveTaskSkillBundles: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resolveResp struct {
+ Bundles []service.AgentSkillData `json:"bundles"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &resolveResp); err != nil {
+ t.Fatalf("decode resolve: %v", err)
+ }
+ if len(resolveResp.Bundles) != 1 || resolveResp.Bundles[0].Content != "main skill content" || len(resolveResp.Bundles[0].Files) != 1 || resolveResp.Bundles[0].Files[0].Content != "rules content" {
+ t.Fatalf("unexpected resolved bundles: %+v", resolveResp.Bundles)
+ }
+
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'running', started_at = now() WHERE id = $1`, taskID); err != nil {
+ t.Fatalf("setup: mark task running: %v", err)
+ }
+ w = httptest.NewRecorder()
+ req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", resolveBody, testWorkspaceID, "skill-refs-daemon")
+ req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
+ testHandler.ResolveTaskSkillBundles(w, req)
+ if w.Code != http.StatusConflict {
+ t.Fatalf("ResolveTaskSkillBundles for running task: expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
// TestClaimTaskByRuntime_PopulatesWorkspaceContext verifies the claim
// response carries workspace.context so the daemon can inject the
// workspace-level system prompt into every agent brief. Regression coverage
diff --git a/server/internal/service/skill_bundle_test.go b/server/internal/service/skill_bundle_test.go
new file mode 100644
index 0000000000..ea9be58b29
--- /dev/null
+++ b/server/internal/service/skill_bundle_test.go
@@ -0,0 +1,38 @@
+package service
+
+import "testing"
+
+func TestBuildAgentSkillBundlesProducesRefsAndFullBundles(t *testing.T) {
+ bundles, refs := BuildAgentSkillBundles([]AgentSkillData{
+ {
+ ID: "skill-1",
+ Name: "deploy",
+ Description: "Deploy safely",
+ Content: "main content",
+ Files: []AgentSkillFileData{{Path: "rules.md", Content: "rules"}},
+ },
+ })
+ if len(bundles) != 1 || len(refs) != 1 {
+ t.Fatalf("counts: bundles=%d refs=%d, want 1/1", len(bundles), len(refs))
+ }
+ if bundles[0].Content == "" || bundles[0].Files[0].Content == "" {
+ t.Fatal("full bundle lost content")
+ }
+ ref := refs[0]
+ if ref.ID != "skill-1" || ref.Hash == "" || ref.SizeBytes == 0 || ref.FileCount != 1 {
+ t.Fatalf("unexpected ref: %+v", ref)
+ }
+ if len(ref.Files) != 1 || ref.Files[0].Path != "rules.md" || ref.Files[0].SHA256 == "" || ref.Files[0].SizeBytes == 0 {
+ t.Fatalf("unexpected file ref: %+v", ref.Files)
+ }
+}
+
+func TestBuildAgentSkillBundlesAssignsBuiltinID(t *testing.T) {
+ _, refs := BuildAgentSkillBundles([]AgentSkillData{{Name: "multica-working-on-issues", Content: "body"}})
+ if len(refs) != 1 {
+ t.Fatalf("refs = %d, want 1", len(refs))
+ }
+ if refs[0].ID != "builtin:multica-working-on-issues" || refs[0].Source != "builtin" {
+ t.Fatalf("builtin ref = %+v", refs[0])
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 76e679323b..79e8154394 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -21,6 +21,7 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
"github.com/multica-ai/multica/server/pkg/redact"
+ "github.com/multica-ai/multica/server/pkg/skillbundle"
"github.com/multica-ai/multica/server/pkg/taskfailure"
)
@@ -82,9 +83,11 @@ func truncateForSummary(s string, maxRunes int) string {
const (
taskAnalyticsContextCacheMax = 4096
// claimResponseRecoveryWindow must exceed daemon client.Timeout for
- // /tasks/claim (30s) plus /tasks/{id}/start (30s) plus scheduling slack, so
- // an in-flight StartTask cannot be reclaimed and double-dispatched.
+ // /tasks/claim (30s) plus /tasks/{id}/start (30s) plus scheduling slack.
+ // Longer pre-start work is protected by prepareLeaseDuration instead of
+ // stretching this global crash-recovery window.
claimResponseRecoveryWindow = 90 * time.Second
+ prepareLeaseDuration = 45 * time.Second
)
// buildCommentTriggerSummary fetches the comment content and truncates
@@ -983,7 +986,10 @@ func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.A
}
t0 = time.Now()
- task, err := s.Queries.ClaimAgentTask(ctx, agentID)
+ task, err := s.Queries.ClaimAgentTask(ctx, db.ClaimAgentTaskParams{
+ AgentID: agentID,
+ PrepareLeaseSecs: prepareLeaseDuration.Seconds(),
+ })
claimAgentMs = time.Since(t0).Milliseconds()
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@@ -1054,6 +1060,7 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
stale, err := s.Queries.ReclaimStaleDispatchedTaskForRuntime(ctx, db.ReclaimStaleDispatchedTaskForRuntimeParams{
RuntimeID: runtimeID,
ClaimRecoverySecs: claimResponseRecoveryWindow.Seconds(),
+ PrepareLeaseSecs: prepareLeaseDuration.Seconds(),
})
if err == nil {
outcome = "reclaimed_dispatched"
@@ -1171,6 +1178,20 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Ag
return &task, nil
}
+// ExtendTaskPrepareLease keeps a claimed-but-not-started task protected while
+// the daemon resolves cached inputs and prepares the execution environment.
+func (s *TaskService) ExtendTaskPrepareLease(ctx context.Context, taskID, runtimeID pgtype.UUID) (*db.AgentTaskQueue, error) {
+ task, err := s.Queries.ExtendAgentTaskPrepareLease(ctx, db.ExtendAgentTaskPrepareLeaseParams{
+ ID: taskID,
+ RuntimeID: runtimeID,
+ LeaseSecs: prepareLeaseDuration.Seconds(),
+ })
+ if err != nil {
+ return nil, fmt.Errorf("extend task prepare lease: %w", err)
+ }
+ return &task, nil
+}
+
// MarkTaskWaitingLocalDirectory parks a dispatched task in the
// waiting_local_directory state while the daemon waits for another in-flight
// task to release the project_resource path lock. reason carries a short
@@ -1180,8 +1201,9 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Ag
func (s *TaskService) MarkTaskWaitingLocalDirectory(ctx context.Context, taskID pgtype.UUID, reason string) (*db.AgentTaskQueue, error) {
reason = strings.TrimSpace(reason)
task, err := s.Queries.MarkAgentTaskWaitingLocalDirectory(ctx, db.MarkAgentTaskWaitingLocalDirectoryParams{
- ID: taskID,
- WaitReason: pgtype.Text{String: reason, Valid: reason != ""},
+ ID: taskID,
+ WaitReason: pgtype.Text{String: reason, Valid: reason != ""},
+ PrepareLeaseSecs: prepareLeaseDuration.Seconds(),
})
if err != nil {
return nil, fmt.Errorf("mark task waiting_local_directory: %w", err)
@@ -1907,19 +1929,116 @@ func (s *TaskService) LoadAgentSkills(ctx context.Context, agentID pgtype.UUID)
return result
}
+// LoadAgentSkillBundles returns every skill visible to an agent, including
+// built-ins, with stable bundle hashes and lightweight refs for slim claims.
+func (s *TaskService) LoadAgentSkillBundles(ctx context.Context, agentID pgtype.UUID) ([]AgentSkillData, []AgentSkillRefData) {
+ skills := s.LoadAgentSkills(ctx, agentID)
+ skills = append(skills, s.BuiltinSkills()...)
+ return BuildAgentSkillBundles(skills)
+}
+
+func BuildAgentSkillBundles(skills []AgentSkillData) ([]AgentSkillData, []AgentSkillRefData) {
+ bundles := make([]AgentSkillData, 0, len(skills))
+ refs := make([]AgentSkillRefData, 0, len(skills))
+ for _, skill := range skills {
+ source := skill.Source
+ id := skill.ID
+ if source == "" {
+ if id == "" {
+ source = skillbundle.SourceBuiltin
+ } else {
+ source = skillbundle.SourceWorkspace
+ }
+ }
+ if id == "" && source == skillbundle.SourceBuiltin {
+ id = "builtin:" + skill.Name
+ }
+ skill.Source = source
+ skill.ID = id
+
+ files := make([]skillbundle.File, 0, len(skill.Files))
+ for _, file := range skill.Files {
+ files = append(files, skillbundle.File{Path: file.Path, Content: file.Content})
+ }
+ manifest := skillbundle.BuildManifest(skillbundle.Skill{
+ ID: skill.ID,
+ Source: skill.Source,
+ Name: skill.Name,
+ Description: skill.Description,
+ Content: skill.Content,
+ Files: files,
+ })
+ skill.Hash = manifest.Hash
+ skill.SizeBytes = manifest.SizeBytes
+ fileRefsByPath := make(map[string]skillbundle.FileRef, len(manifest.Files))
+ for _, file := range manifest.Files {
+ fileRefsByPath[file.Path] = file
+ }
+ for i := range skill.Files {
+ if ref, ok := fileRefsByPath[skill.Files[i].Path]; ok {
+ skill.Files[i].SHA256 = ref.SHA256
+ skill.Files[i].SizeBytes = ref.SizeBytes
+ }
+ }
+ bundles = append(bundles, skill)
+
+ refFiles := make([]AgentSkillFileRefData, 0, len(manifest.Files))
+ for _, file := range manifest.Files {
+ refFiles = append(refFiles, AgentSkillFileRefData{
+ Path: file.Path,
+ SHA256: file.SHA256,
+ SizeBytes: file.SizeBytes,
+ })
+ }
+ refs = append(refs, AgentSkillRefData{
+ ID: skill.ID,
+ Source: skill.Source,
+ Name: skill.Name,
+ Description: skill.Description,
+ Hash: manifest.Hash,
+ SizeBytes: manifest.SizeBytes,
+ FileCount: manifest.FileCount,
+ Files: refFiles,
+ })
+ }
+ return bundles, refs
+}
+
// AgentSkillData represents a skill for task execution responses.
type AgentSkillData struct {
ID string `json:"id"`
+ Source string `json:"source,omitempty"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
+ Hash string `json:"hash,omitempty"`
+ SizeBytes int64 `json:"size_bytes,omitempty"`
Content string `json:"content"`
Files []AgentSkillFileData `json:"files,omitempty"`
}
// AgentSkillFileData represents a supporting file within a skill.
type AgentSkillFileData struct {
- Path string `json:"path"`
- Content string `json:"content"`
+ Path string `json:"path"`
+ Content string `json:"content"`
+ SHA256 string `json:"sha256,omitempty"`
+ SizeBytes int64 `json:"size_bytes,omitempty"`
+}
+
+type AgentSkillRefData struct {
+ ID string `json:"id"`
+ Source string `json:"source"`
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ Hash string `json:"hash"`
+ SizeBytes int64 `json:"size_bytes"`
+ FileCount int `json:"file_count"`
+ Files []AgentSkillFileRefData `json:"files,omitempty"`
+}
+
+type AgentSkillFileRefData struct {
+ Path string `json:"path"`
+ SHA256 string `json:"sha256"`
+ SizeBytes int64 `json:"size_bytes"`
}
// computeChatElapsedMs returns the wall-clock duration from task creation
diff --git a/server/migrations/124_task_prepare_lease.down.sql b/server/migrations/124_task_prepare_lease.down.sql
new file mode 100644
index 0000000000..2cafac5028
--- /dev/null
+++ b/server/migrations/124_task_prepare_lease.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE agent_task_queue
+ DROP COLUMN IF EXISTS prepare_lease_expires_at;
diff --git a/server/migrations/124_task_prepare_lease.up.sql b/server/migrations/124_task_prepare_lease.up.sql
new file mode 100644
index 0000000000..ba7c330c79
--- /dev/null
+++ b/server/migrations/124_task_prepare_lease.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE agent_task_queue
+ ADD COLUMN prepare_lease_expires_at TIMESTAMPTZ;
diff --git a/server/migrations/125_agent_task_queue_dispatched_prepare_index.down.sql b/server/migrations/125_agent_task_queue_dispatched_prepare_index.down.sql
new file mode 100644
index 0000000000..83f5193cf3
--- /dev/null
+++ b/server/migrations/125_agent_task_queue_dispatched_prepare_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_dispatched_prepare;
diff --git a/server/migrations/125_agent_task_queue_dispatched_prepare_index.up.sql b/server/migrations/125_agent_task_queue_dispatched_prepare_index.up.sql
new file mode 100644
index 0000000000..92f8e7ca84
--- /dev/null
+++ b/server/migrations/125_agent_task_queue_dispatched_prepare_index.up.sql
@@ -0,0 +1,8 @@
+-- Covers reclaim scans over dispatched tasks while allowing prepare lease checks.
+--
+-- agent_task_queue is hot, so this must stay in its own single-statement
+-- migration and must use CONCURRENTLY. Keeping CONCURRENTLY isolated avoids
+-- Postgres' implicit transaction block for multi-statement query strings.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_dispatched_prepare
+ ON agent_task_queue (runtime_id, priority DESC, dispatched_at ASC)
+ WHERE status = 'dispatched' AND started_at IS NULL;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index a86befb2ac..b45a0a6ca3 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -176,9 +176,9 @@ func (q *Queries) ArchiveAgentsByRuntime(ctx context.Context, arg ArchiveAgentsB
const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now()
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -213,15 +213,16 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now()
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -267,6 +268,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -280,9 +282,9 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :many
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now()
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
// Cancels active tasks belonging to a chat session. Called from
@@ -328,6 +330,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -341,9 +344,9 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now()
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -389,6 +392,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -402,9 +406,9 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgent :many
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now()
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
type CancelAgentTasksByIssueAndAgentParams struct {
@@ -454,6 +458,7 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -467,9 +472,9 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
const cancelAgentTasksByTriggerComment = `-- name: CancelAgentTasksByTriggerComment :many
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now()
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
// Cancels active tasks whose trigger is the given comment. Called when a
@@ -515,6 +520,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -528,7 +534,9 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
const claimAgentTask = `-- name: ClaimAgentTask :one
UPDATE agent_task_queue
-SET status = 'dispatched', dispatched_at = now()
+SET status = 'dispatched',
+ dispatched_at = now(),
+ prepare_lease_expires_at = now() + make_interval(secs => $2::double precision)
WHERE id = (
SELECT atq.id FROM agent_task_queue atq
WHERE atq.agent_id = $1 AND atq.status = 'queued'
@@ -553,9 +561,14 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
+type ClaimAgentTaskParams struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ PrepareLeaseSecs float64 `json:"prepare_lease_secs"`
+}
+
// Claims the next queued task for an agent, enforcing per-(issue, agent) serialization:
// a task is only claimable when no other task for the same issue AND same agent is
// already dispatched or running. This allows different agents to work on the same
@@ -565,8 +578,8 @@ RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, c
// "any other quick-create-shaped task" (all four FKs NULL) for the same agent —
// otherwise a user mashing the create button could fire concurrent quick-creates
// whose completion lookup would race over "most recent issue by this agent".
-func (q *Queries) ClaimAgentTask(ctx context.Context, agentID pgtype.UUID) (AgentTaskQueue, error) {
- row := q.db.QueryRow(ctx, claimAgentTask, agentID)
+func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, claimAgentTask, arg.AgentID, arg.PrepareLeaseSecs)
var i AgentTaskQueue
err := row.Scan(
&i.ID,
@@ -597,6 +610,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, agentID pgtype.UUID) (Agen
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
@@ -678,9 +692,9 @@ func (q *Queries) ClearAgentThinkingLevel(ctx context.Context, id pgtype.UUID) (
const completeAgentTask = `-- name: CompleteAgentTask :one
UPDATE agent_task_queue
-SET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4
+SET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4, prepare_lease_expires_at = NULL
WHERE id = $1 AND status = 'running'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
type CompleteAgentTaskParams struct {
@@ -727,6 +741,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
@@ -830,7 +845,7 @@ VALUES (
COALESCE($8::boolean, FALSE),
$9
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
type CreateAgentTaskParams struct {
@@ -887,6 +902,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
@@ -894,7 +910,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
const createQuickCreateTask = `-- name: CreateQuickCreateTask :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, context)
VALUES ($1, $2, NULL, 'queued', $3, $4)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
type CreateQuickCreateTaskParams struct {
@@ -944,6 +960,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
@@ -965,7 +982,7 @@ SELECT
p.is_leader_task
FROM agent_task_queue p
WHERE p.id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
// Clones a parent task into a fresh queued attempt. Carries forward the
@@ -1010,6 +1027,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
@@ -1027,12 +1045,13 @@ UPDATE agent_task_queue t
SET status = 'failed',
completed_at = now(),
error = 'task expired in queue',
- failure_reason = 'queued_expired'
+ failure_reason = 'queued_expired',
+ prepare_lease_expires_at = NULL
FROM victims v
WHERE t.id = v.id
AND t.status = 'queued'
AND t.created_at < now() - make_interval(secs => $1::double precision)
-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note
+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at
`
type ExpireStaleQueuedTasksParams struct {
@@ -1101,6 +1120,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -1112,6 +1132,63 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
return items, nil
}
+const extendAgentTaskPrepareLease = `-- name: ExtendAgentTaskPrepareLease :one
+UPDATE agent_task_queue
+SET prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)
+WHERE id = $1
+ AND runtime_id = $2
+ AND status IN ('dispatched', 'waiting_local_directory')
+ AND started_at IS NULL
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
+`
+
+type ExtendAgentTaskPrepareLeaseParams struct {
+ ID pgtype.UUID `json:"id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ LeaseSecs float64 `json:"lease_secs"`
+}
+
+// Keeps a dispatched task protected while the daemon resolves/cache/materializes
+// startup inputs before StartTask. Once the daemon stops extending this short
+// lease, the stale-dispatched reclaim path can recover the task without waiting
+// for a long global recovery window.
+func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAgentTaskPrepareLeaseParams) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, extendAgentTaskPrepareLease, arg.ID, arg.RuntimeID, arg.LeaseSecs)
+ var i AgentTaskQueue
+ err := row.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ )
+ return i, err
+}
+
const failAgentTask = `-- name: FailAgentTask :one
UPDATE agent_task_queue
SET status = 'failed',
@@ -1119,9 +1196,10 @@ SET status = 'failed',
error = $2,
failure_reason = COALESCE($3, 'agent_error'),
session_id = COALESCE($4, session_id),
- work_dir = COALESCE($5, work_dir)
+ work_dir = COALESCE($5, work_dir),
+ prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
type FailAgentTaskParams struct {
@@ -1179,6 +1257,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
@@ -1186,10 +1265,15 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
const failStaleTasks = `-- name: FailStaleTasks :many
UPDATE agent_task_queue
SET status = 'failed', completed_at = now(), error = 'task timed out',
- failure_reason = 'timeout'
-WHERE (status = 'dispatched' AND dispatched_at < now() - make_interval(secs => $1::double precision))
+ failure_reason = 'timeout',
+ prepare_lease_expires_at = NULL
+WHERE (
+ status = 'dispatched'
+ AND dispatched_at < now() - make_interval(secs => $1::double precision)
+ AND (prepare_lease_expires_at IS NULL OR prepare_lease_expires_at < now())
+ )
OR (status = 'running' AND started_at < now() - make_interval(secs => $2::double precision))
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
type FailStaleTasksParams struct {
@@ -1200,6 +1284,9 @@ type FailStaleTasksParams struct {
// Fails tasks stuck in dispatched/running beyond the given thresholds.
// Handles cases where the daemon is alive but the task is orphaned
// (e.g. agent process hung, daemon failed to report completion).
+// Dispatched tasks with an active prepare lease are excluded because the
+// daemon is still proving liveness while resolving/cache/preparing startup
+// inputs before StartTask.
// waiting_local_directory rows are intentionally excluded: the daemon owns
// the wait (with its own ctx-driven timeout) and a legitimate queue ahead
// of this task can exceed the dispatch / running timeouts without being
@@ -1243,6 +1330,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -1330,7 +1418,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa
}
const getAgentTask = `-- name: GetAgentTask :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at FROM agent_task_queue
WHERE id = $1
`
@@ -1366,12 +1454,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -1420,6 +1509,7 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
@@ -1849,7 +1939,7 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim
}
const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -1897,6 +1987,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -1909,7 +2000,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
}
const listAgentTasks = `-- name: ListAgentTasks :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -1952,6 +2043,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -2062,7 +2154,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([
}
const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -2105,6 +2197,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -2117,7 +2210,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
}
const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -2168,6 +2261,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -2180,7 +2274,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
}
const listTasksByIssue = `-- name: ListTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -2223,6 +2317,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -2235,15 +2330,15 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
}
const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
UNION ALL
-SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note FROM (
- SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note
+SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at FROM (
+ SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at
FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
@@ -2308,6 +2403,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -2321,14 +2417,17 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
const markAgentTaskWaitingLocalDirectory = `-- name: MarkAgentTaskWaitingLocalDirectory :one
UPDATE agent_task_queue
-SET status = 'waiting_local_directory', wait_reason = $2
+SET status = 'waiting_local_directory',
+ wait_reason = $2,
+ prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)
WHERE id = $1 AND status = 'dispatched'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
- ID pgtype.UUID `json:"id"`
- WaitReason pgtype.Text `json:"wait_reason"`
+ ID pgtype.UUID `json:"id"`
+ WaitReason pgtype.Text `json:"wait_reason"`
+ PrepareLeaseSecs float64 `json:"prepare_lease_secs"`
}
// Transitions a freshly-dispatched task into 'waiting_local_directory' while
@@ -2341,7 +2440,7 @@ type MarkAgentTaskWaitingLocalDirectoryParams struct {
// mark an already-running or terminal task as waiting; the StartAgentTask
// mutation handles the reverse transition once the lock is acquired.
func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg MarkAgentTaskWaitingLocalDirectoryParams) (AgentTaskQueue, error) {
- row := q.db.QueryRow(ctx, markAgentTaskWaitingLocalDirectory, arg.ID, arg.WaitReason)
+ row := q.db.QueryRow(ctx, markAgentTaskWaitingLocalDirectory, arg.ID, arg.WaitReason, arg.PrepareLeaseSecs)
var i AgentTaskQueue
err := row.Scan(
&i.ID,
@@ -2372,28 +2471,32 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
const reclaimStaleDispatchedTaskForRuntime = `-- name: ReclaimStaleDispatchedTaskForRuntime :one
UPDATE agent_task_queue
-SET dispatched_at = now()
+SET dispatched_at = now(),
+ prepare_lease_expires_at = now() + make_interval(secs => $2::double precision)
WHERE id = (
SELECT atq.id FROM agent_task_queue atq
WHERE atq.runtime_id = $1
AND atq.status = 'dispatched'
AND atq.started_at IS NULL
- AND atq.dispatched_at < now() - make_interval(secs => $2::double precision)
+ AND atq.dispatched_at < now() - make_interval(secs => $3::double precision)
+ AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())
ORDER BY atq.priority DESC, atq.dispatched_at ASC
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
RuntimeID pgtype.UUID `json:"runtime_id"`
+ PrepareLeaseSecs float64 `json:"prepare_lease_secs"`
ClaimRecoverySecs float64 `json:"claim_recovery_secs"`
}
@@ -2403,7 +2506,7 @@ type ReclaimStaleDispatchedTaskForRuntimeParams struct {
// Refresh dispatched_at so the server-side dispatch timeout measures from the
// recovered delivery attempt.
func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg ReclaimStaleDispatchedTaskForRuntimeParams) (AgentTaskQueue, error) {
- row := q.db.QueryRow(ctx, reclaimStaleDispatchedTaskForRuntime, arg.RuntimeID, arg.ClaimRecoverySecs)
+ row := q.db.QueryRow(ctx, reclaimStaleDispatchedTaskForRuntime, arg.RuntimeID, arg.PrepareLeaseSecs, arg.ClaimRecoverySecs)
var i AgentTaskQueue
err := row.Scan(
&i.ID,
@@ -2434,6 +2537,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
@@ -2444,9 +2548,10 @@ SET status = 'failed',
completed_at = now(),
error = 'daemon restarted while task was in flight',
failure_reason = 'runtime_recovery',
- wait_reason = NULL
+ wait_reason = NULL,
+ prepare_lease_expires_at = NULL
WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -2493,6 +2598,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -2583,9 +2689,12 @@ func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, erro
const startAgentTask = `-- name: StartAgentTask :one
UPDATE agent_task_queue
-SET status = 'running', started_at = now(), wait_reason = NULL
+SET status = 'running',
+ started_at = now(),
+ wait_reason = NULL,
+ prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
// Transitions a task to running. Accepts either 'dispatched' (the normal
@@ -2626,6 +2735,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index d1907b20e3..d4acf0373d 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -241,7 +241,7 @@ const createAutopilotTask = `-- name: CreateAutopilotTask :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary)
VALUES ($1, $2, NULL, 'queued', $3, $4, $5)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
type CreateAutopilotTaskParams struct {
@@ -293,6 +293,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 28d3eeb468..07e85165f2 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -90,7 +90,7 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa
const createChatTask = `-- name: CreateChatTask :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, chat_session_id, initiator_user_id)
VALUES ($1, $2, NULL, 'queued', $3, $4, $5)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
type CreateChatTaskParams struct {
@@ -139,6 +139,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 18b8b82726..a49acd4703 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -72,34 +72,35 @@ type AgentSkill struct {
}
type AgentTaskQueue struct {
- ID pgtype.UUID `json:"id"`
- AgentID pgtype.UUID `json:"agent_id"`
- IssueID pgtype.UUID `json:"issue_id"`
- Status string `json:"status"`
- Priority int32 `json:"priority"`
- DispatchedAt pgtype.Timestamptz `json:"dispatched_at"`
- StartedAt pgtype.Timestamptz `json:"started_at"`
- CompletedAt pgtype.Timestamptz `json:"completed_at"`
- Result []byte `json:"result"`
- Error pgtype.Text `json:"error"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- Context []byte `json:"context"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
- SessionID pgtype.Text `json:"session_id"`
- WorkDir pgtype.Text `json:"work_dir"`
- TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
- AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
- Attempt int32 `json:"attempt"`
- MaxAttempts int32 `json:"max_attempts"`
- ParentTaskID pgtype.UUID `json:"parent_task_id"`
- FailureReason pgtype.Text `json:"failure_reason"`
- TriggerSummary pgtype.Text `json:"trigger_summary"`
- ForceFreshSession bool `json:"force_fresh_session"`
- IsLeaderTask bool `json:"is_leader_task"`
- WaitReason pgtype.Text `json:"wait_reason"`
- InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
- HandoffNote pgtype.Text `json:"handoff_note"`
+ ID pgtype.UUID `json:"id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Status string `json:"status"`
+ Priority int32 `json:"priority"`
+ DispatchedAt pgtype.Timestamptz `json:"dispatched_at"`
+ StartedAt pgtype.Timestamptz `json:"started_at"`
+ CompletedAt pgtype.Timestamptz `json:"completed_at"`
+ Result []byte `json:"result"`
+ Error pgtype.Text `json:"error"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ Context []byte `json:"context"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ SessionID pgtype.Text `json:"session_id"`
+ WorkDir pgtype.Text `json:"work_dir"`
+ TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
+ Attempt int32 `json:"attempt"`
+ MaxAttempts int32 `json:"max_attempts"`
+ ParentTaskID pgtype.UUID `json:"parent_task_id"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ TriggerSummary pgtype.Text `json:"trigger_summary"`
+ ForceFreshSession bool `json:"force_fresh_session"`
+ IsLeaderTask bool `json:"is_leader_task"`
+ WaitReason pgtype.Text `json:"wait_reason"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ HandoffNote pgtype.Text `json:"handoff_note"`
+ PrepareLeaseExpiresAt pgtype.Timestamptz `json:"prepare_lease_expires_at"`
}
type Attachment struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 3555d57d23..bf71663198 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -16,7 +16,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -76,6 +76,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
@@ -195,7 +196,7 @@ WHERE status IN ('dispatched', 'running', 'waiting_local_directory')
AND runtime_id IN (
SELECT id FROM agent_runtime WHERE status = 'offline'
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
`
// Marks dispatched/running/waiting_local_directory tasks as failed when
@@ -239,6 +240,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ
&i.WaitReason,
&i.InitiatorUserID,
&i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.go
index 92f52d7ebe..a89661bdba 100644
--- a/server/pkg/db/generated/workspace.sql.go
+++ b/server/pkg/db/generated/workspace.sql.go
@@ -180,14 +180,8 @@ type ListWorkspacesWithReposRow struct {
Repos []byte `json:"repos"`
}
-// Workspaces that have at least one repository in their registry, returning
-// only the id and the repos JSONB. Used to route an inbound GitHub webhook to
-// the workspace that actually owns the event's repository (instead of the
-// single workspace the delivering App installation happens to be mapped to —
-// one GitHub account/installation can serve repos belonging to several
-// workspaces).
-// ORDER BY id so the multi-match tie-break in resolveWorkspaceForRepo is
-// stable across webhook replays.
+// Workspaces with a non-empty repo registry, to route a webhook to the repo's
+// owning workspace. ORDER BY id keeps the resolver's tie-break stable on replay.
func (q *Queries) ListWorkspacesWithRepos(ctx context.Context) ([]ListWorkspacesWithReposRow, error) {
rows, err := q.db.Query(ctx, listWorkspacesWithRepos)
if err != nil {
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index cd75a72517..73b46a3631 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -201,7 +201,7 @@ RETURNING *;
-- paths (issue status flips to cancelled/done, etc.) left agents stuck at
-- status="working" with no self-correction.
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now()
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
RETURNING *;
@@ -211,7 +211,7 @@ RETURNING *;
-- rerun flow so re-running the assignee doesn't collateral-cancel a
-- still-running @-mention agent on the same issue.
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now()
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
RETURNING *;
@@ -222,7 +222,7 @@ RETURNING *;
-- (also :many + RETURNING + completed_at) so the three sibling cancel paths
-- behave consistently.
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now()
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
RETURNING *;
@@ -233,7 +233,7 @@ RETURNING *;
-- because the FK ON DELETE SET NULL would otherwise nullify trigger_comment_id
-- and we'd lose the ability to find the affected tasks.
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now()
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
RETURNING *;
@@ -244,7 +244,7 @@ RETURNING *;
-- the FK ON DELETE SET NULL would otherwise nullify chat_session_id and we
-- could no longer reach those tasks.
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now()
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
RETURNING *;
@@ -275,7 +275,9 @@ WHERE atq.id = $1 AND a.workspace_id = $2;
-- otherwise a user mashing the create button could fire concurrent quick-creates
-- whose completion lookup would race over "most recent issue by this agent".
UPDATE agent_task_queue
-SET status = 'dispatched', dispatched_at = now()
+SET status = 'dispatched',
+ dispatched_at = now(),
+ prepare_lease_expires_at = now() + make_interval(secs => @prepare_lease_secs::double precision)
WHERE id = (
SELECT atq.id FROM agent_task_queue atq
WHERE atq.agent_id = $1 AND atq.status = 'queued'
@@ -309,19 +311,34 @@ RETURNING *;
-- Refresh dispatched_at so the server-side dispatch timeout measures from the
-- recovered delivery attempt.
UPDATE agent_task_queue
-SET dispatched_at = now()
+SET dispatched_at = now(),
+ prepare_lease_expires_at = now() + make_interval(secs => @prepare_lease_secs::double precision)
WHERE id = (
SELECT atq.id FROM agent_task_queue atq
WHERE atq.runtime_id = $1
AND atq.status = 'dispatched'
AND atq.started_at IS NULL
AND atq.dispatched_at < now() - make_interval(secs => @claim_recovery_secs::double precision)
+ AND (atq.prepare_lease_expires_at IS NULL OR atq.prepare_lease_expires_at < now())
ORDER BY atq.priority DESC, atq.dispatched_at ASC
LIMIT 1
FOR UPDATE SKIP LOCKED
)
RETURNING *;
+-- name: ExtendAgentTaskPrepareLease :one
+-- Keeps a dispatched task protected while the daemon resolves/cache/materializes
+-- startup inputs before StartTask. Once the daemon stops extending this short
+-- lease, the stale-dispatched reclaim path can recover the task without waiting
+-- for a long global recovery window.
+UPDATE agent_task_queue
+SET prepare_lease_expires_at = now() + make_interval(secs => @lease_secs::double precision)
+WHERE id = $1
+ AND runtime_id = $2
+ AND status IN ('dispatched', 'waiting_local_directory')
+ AND started_at IS NULL
+RETURNING *;
+
-- name: StartAgentTask :one
-- Transitions a task to running. Accepts either 'dispatched' (the normal
-- claim → run flow) or 'waiting_local_directory' (the daemon held the row in
@@ -330,7 +347,10 @@ RETURNING *;
-- the transition so a future read can't conflate "currently waiting" with
-- "previously waited".
UPDATE agent_task_queue
-SET status = 'running', started_at = now(), wait_reason = NULL
+SET status = 'running',
+ started_at = now(),
+ wait_reason = NULL,
+ prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')
RETURNING *;
@@ -345,13 +365,15 @@ RETURNING *;
-- mark an already-running or terminal task as waiting; the StartAgentTask
-- mutation handles the reverse transition once the lock is acquired.
UPDATE agent_task_queue
-SET status = 'waiting_local_directory', wait_reason = $2
+SET status = 'waiting_local_directory',
+ wait_reason = $2,
+ prepare_lease_expires_at = now() + make_interval(secs => @prepare_lease_secs::double precision)
WHERE id = $1 AND status = 'dispatched'
RETURNING *;
-- name: CompleteAgentTask :one
UPDATE agent_task_queue
-SET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4
+SET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4, prepare_lease_expires_at = NULL
WHERE id = $1 AND status = 'running'
RETURNING *;
@@ -430,7 +452,8 @@ SET status = 'failed',
error = $2,
failure_reason = COALESCE(sqlc.narg('failure_reason'), 'agent_error'),
session_id = COALESCE(sqlc.narg('session_id'), session_id),
- work_dir = COALESCE(sqlc.narg('work_dir'), work_dir)
+ work_dir = COALESCE(sqlc.narg('work_dir'), work_dir),
+ prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
RETURNING *;
@@ -456,7 +479,8 @@ SET status = 'failed',
completed_at = now(),
error = 'daemon restarted while task was in flight',
failure_reason = 'runtime_recovery',
- wait_reason = NULL
+ wait_reason = NULL,
+ prepare_lease_expires_at = NULL
WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
RETURNING *;
@@ -464,6 +488,9 @@ RETURNING *;
-- Fails tasks stuck in dispatched/running beyond the given thresholds.
-- Handles cases where the daemon is alive but the task is orphaned
-- (e.g. agent process hung, daemon failed to report completion).
+-- Dispatched tasks with an active prepare lease are excluded because the
+-- daemon is still proving liveness while resolving/cache/preparing startup
+-- inputs before StartTask.
-- waiting_local_directory rows are intentionally excluded: the daemon owns
-- the wait (with its own ctx-driven timeout) and a legitimate queue ahead
-- of this task can exceed the dispatch / running timeouts without being
@@ -471,8 +498,13 @@ RETURNING *;
-- those rows at restart.
UPDATE agent_task_queue
SET status = 'failed', completed_at = now(), error = 'task timed out',
- failure_reason = 'timeout'
-WHERE (status = 'dispatched' AND dispatched_at < now() - make_interval(secs => @dispatch_timeout_secs::double precision))
+ failure_reason = 'timeout',
+ prepare_lease_expires_at = NULL
+WHERE (
+ status = 'dispatched'
+ AND dispatched_at < now() - make_interval(secs => @dispatch_timeout_secs::double precision)
+ AND (prepare_lease_expires_at IS NULL OR prepare_lease_expires_at < now())
+ )
OR (status = 'running' AND started_at < now() - make_interval(secs => @running_timeout_secs::double precision))
RETURNING *;
@@ -511,7 +543,8 @@ UPDATE agent_task_queue t
SET status = 'failed',
completed_at = now(),
error = 'task expired in queue',
- failure_reason = 'queued_expired'
+ failure_reason = 'queued_expired',
+ prepare_lease_expires_at = NULL
FROM victims v
WHERE t.id = v.id
AND t.status = 'queued'
@@ -520,7 +553,7 @@ RETURNING t.*;
-- name: CancelAgentTask :one
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now()
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
RETURNING *;
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 0bd41b9943..ade00078ca 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -2,6 +2,10 @@ package protocol
import "encoding/json"
+const (
+ DaemonCapabilitySkillBundlesV1 = "skill-bundles-v1"
+)
+
// Message is the envelope for all WebSocket messages.
type Message struct {
Type string `json:"type"`
diff --git a/server/pkg/skillbundle/hash.go b/server/pkg/skillbundle/hash.go
new file mode 100644
index 0000000000..27a737b51e
--- /dev/null
+++ b/server/pkg/skillbundle/hash.go
@@ -0,0 +1,82 @@
+package skillbundle
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "sort"
+)
+
+const (
+ SourceWorkspace = "workspace"
+ SourceBuiltin = "builtin"
+)
+
+type File struct {
+ Path string
+ Content string
+}
+
+type Skill struct {
+ ID string
+ Source string
+ Name string
+ Description string
+ Content string
+ Files []File
+}
+
+type FileRef struct {
+ Path string
+ SHA256 string
+ SizeBytes int64
+}
+
+type Manifest struct {
+ Hash string
+ SizeBytes int64
+ FileCount int
+ Files []FileRef
+}
+
+func BuildManifest(skill Skill) Manifest {
+ files := append([]File(nil), skill.Files...)
+ sort.Slice(files, func(i, j int) bool {
+ return files[i].Path < files[j].Path
+ })
+
+ h := sha256.New()
+ writeHashPart(h, "v1")
+ writeHashPart(h, skill.Source)
+ writeHashPart(h, skill.ID)
+ writeHashPart(h, skill.Name)
+ writeHashPart(h, skill.Description)
+ writeHashPart(h, skill.Content)
+
+ size := int64(len(skill.Content))
+ refs := make([]FileRef, 0, len(files))
+ for _, file := range files {
+ fileHash := sha256.Sum256([]byte(file.Content))
+ fileDigest := "sha256:" + hex.EncodeToString(fileHash[:])
+ writeHashPart(h, file.Path)
+ writeHashPart(h, fileDigest)
+ writeHashPart(h, file.Content)
+ size += int64(len(file.Content))
+ refs = append(refs, FileRef{
+ Path: file.Path,
+ SHA256: fileDigest,
+ SizeBytes: int64(len(file.Content)),
+ })
+ }
+
+ return Manifest{
+ Hash: "sha256:" + hex.EncodeToString(h.Sum(nil)),
+ SizeBytes: size,
+ FileCount: len(files),
+ Files: refs,
+ }
+}
+
+func writeHashPart(h interface{ Write([]byte) (int, error) }, value string) {
+ _, _ = fmt.Fprintf(h, "%d:%s\n", len(value), value)
+}
diff --git a/server/pkg/skillbundle/hash_test.go b/server/pkg/skillbundle/hash_test.go
new file mode 100644
index 0000000000..2df9b0da74
--- /dev/null
+++ b/server/pkg/skillbundle/hash_test.go
@@ -0,0 +1,37 @@
+package skillbundle
+
+import "testing"
+
+func TestBuildManifestStableAcrossFileOrder(t *testing.T) {
+ a := BuildManifest(Skill{
+ ID: "skill-1",
+ Source: SourceWorkspace,
+ Name: "deploy",
+ Content: "main",
+ Files: []File{
+ {Path: "b.md", Content: "b"},
+ {Path: "a.md", Content: "a"},
+ },
+ })
+ b := BuildManifest(Skill{
+ ID: "skill-1",
+ Source: SourceWorkspace,
+ Name: "deploy",
+ Content: "main",
+ Files: []File{
+ {Path: "a.md", Content: "a"},
+ {Path: "b.md", Content: "b"},
+ },
+ })
+ if a.Hash != b.Hash {
+ t.Fatalf("hash depends on file order: %s != %s", a.Hash, b.Hash)
+ }
+}
+
+func TestBuildManifestChangesWhenContentChanges(t *testing.T) {
+ a := BuildManifest(Skill{ID: "skill-1", Source: SourceWorkspace, Name: "deploy", Content: "main"})
+ b := BuildManifest(Skill{ID: "skill-1", Source: SourceWorkspace, Name: "deploy", Content: "changed"})
+ if a.Hash == b.Hash {
+ t.Fatal("hash did not change when content changed")
+ }
+}