feat(tasks): record archive source manifests (#3905)
Co-authored-by: ayattara <alassane.yattara@savoirfairelinux.com> Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
@@ -340,7 +340,7 @@ func TestPreflightRemoteContributionPushesUsesOneBudgetForAllRepositories(t *tes
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"success": true})
|
||||
case 2:
|
||||
close(secondStarted)
|
||||
timer := time.NewTimer(70 * time.Millisecond)
|
||||
timer := time.NewTimer(650 * time.Millisecond)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
@@ -355,7 +355,7 @@ func TestPreflightRemoteContributionPushesUsesOneBudgetForAllRepositories(t *tes
|
||||
})
|
||||
|
||||
mgr := newTestManager(t)
|
||||
mgr.remoteContributionPreflightTimeout = 80 * time.Millisecond
|
||||
mgr.remoteContributionPreflightTimeout = time.Second
|
||||
execution := newContributionPreflightExecution(t, server.URL, "exec-multi-preflight-timeout", "", "",
|
||||
map[string]models.RemoteContribution{
|
||||
"a": contributionPreflightTestBinding(),
|
||||
@@ -369,7 +369,7 @@ func TestPreflightRemoteContributionPushesUsesOneBudgetForAllRepositories(t *tes
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("first contribution preflight did not start")
|
||||
}
|
||||
timer := time.NewTimer(10 * time.Millisecond)
|
||||
timer := time.NewTimer(650 * time.Millisecond)
|
||||
<-timer.C
|
||||
timer.Stop()
|
||||
releaseFirst()
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
@@ -19,6 +20,11 @@ type DirectoryHandle interface {
|
||||
VerifyPath(path string) error
|
||||
IsValidWorktree() bool
|
||||
RemoveDirectory(ctx context.Context) error
|
||||
OpenFile(name string) (io.ReadCloser, error)
|
||||
OpenSubdirectory(name string) (DirectoryHandle, error)
|
||||
LstatEntry(name string) (os.FileMode, error)
|
||||
ReadLink(name string) (string, error)
|
||||
ReadDir() ([]os.DirEntry, error)
|
||||
ReadFile(name string) ([]byte, error)
|
||||
WriteFile(name string, data []byte, mode os.FileMode) error
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package workspaces
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"unicode/utf16"
|
||||
)
|
||||
|
||||
func decodeWindowsReparsePath(data []byte, returned uint32, pathOffset int) (string, error) {
|
||||
if returned > uint32(len(data)) || int(returned) < pathOffset || pathOffset < 16 {
|
||||
return "", errors.New("reparse point data is truncated")
|
||||
}
|
||||
declaredEnd := 8 + int(binary.LittleEndian.Uint16(data[4:6]))
|
||||
if declaredEnd < pathOffset || declaredEnd > int(returned) {
|
||||
return "", errors.New("reparse point payload is truncated")
|
||||
}
|
||||
nameOffset := binary.LittleEndian.Uint16(data[8:10])
|
||||
nameLength := binary.LittleEndian.Uint16(data[10:12])
|
||||
if nameLength == 0 || nameOffset%2 != 0 || nameLength%2 != 0 {
|
||||
return "", errors.New("reparse point target name is invalid")
|
||||
}
|
||||
start := pathOffset + int(nameOffset)
|
||||
end := start + int(nameLength)
|
||||
if start < pathOffset || end > declaredEnd {
|
||||
return "", errors.New("reparse point path is invalid")
|
||||
}
|
||||
units := make([]uint16, nameLength/2)
|
||||
for index := range units {
|
||||
units[index] = binary.LittleEndian.Uint16(data[start+index*2 : start+index*2+2])
|
||||
}
|
||||
if err := validateWindowsReparseTargetUnits(units); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(utf16.Decode(units)), nil
|
||||
}
|
||||
|
||||
func validateWindowsReparseTargetUnits(units []uint16) error {
|
||||
for index := 0; index < len(units); index++ {
|
||||
unit := units[index]
|
||||
if unit == 0 {
|
||||
return errors.New("reparse point target name contains NUL")
|
||||
}
|
||||
if unit >= 0xD800 && unit <= 0xDBFF {
|
||||
if index+1 >= len(units) || units[index+1] < 0xDC00 || units[index+1] > 0xDFFF {
|
||||
return errors.New("reparse point target name contains invalid UTF-16")
|
||||
}
|
||||
index++
|
||||
continue
|
||||
}
|
||||
if unit >= 0xDC00 && unit <= 0xDFFF {
|
||||
return errors.New("reparse point target name contains invalid UTF-16")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package workspaces
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"testing"
|
||||
"unicode/utf16"
|
||||
)
|
||||
|
||||
func TestDecodeWindowsReparsePathUsesSubstituteName(t *testing.T) {
|
||||
buffer := windowsSymlinkReparseBuffer(`\??\C:\actual-target`, `C:\display-name`)
|
||||
got, err := decodeWindowsReparsePath(buffer, uint32(len(buffer)), 20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := `\??\C:\actual-target`; got != want {
|
||||
t.Fatalf("decodeWindowsReparsePath() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeWindowsReparsePathRejectsMissingSubstituteName(t *testing.T) {
|
||||
buffer := windowsSymlinkReparseBuffer("", `C:\display-name`)
|
||||
if _, err := decodeWindowsReparsePath(buffer, uint32(len(buffer)), 20); err == nil {
|
||||
t.Fatal("decodeWindowsReparsePath() accepted a display name without a target name")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeWindowsReparsePathRejectsMalformedSubstituteNameMetadata(t *testing.T) {
|
||||
t.Run("odd offset", func(t *testing.T) {
|
||||
buffer := windowsSymlinkReparseBuffer(`\??\C:\actual-target`, `C:\display-name`)
|
||||
binary.LittleEndian.PutUint16(buffer[8:10], 1)
|
||||
if _, err := decodeWindowsReparsePath(buffer, uint32(len(buffer)), 20); err == nil {
|
||||
t.Fatal("decodeWindowsReparsePath() accepted an odd UTF-16 byte offset")
|
||||
}
|
||||
})
|
||||
t.Run("outside declared payload", func(t *testing.T) {
|
||||
buffer := windowsSymlinkReparseBuffer(`\??\C:\actual-target`, `C:\display-name`)
|
||||
binary.LittleEndian.PutUint16(buffer[4:6], 12)
|
||||
if _, err := decodeWindowsReparsePath(buffer, uint32(len(buffer)), 20); err == nil {
|
||||
t.Fatal("decodeWindowsReparsePath() accepted a name outside the declared reparse payload")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestDecodeWindowsReparsePathRejectsInvalidTargetCodeUnits(t *testing.T) {
|
||||
t.Run("unpaired surrogate", func(t *testing.T) {
|
||||
buffer := windowsSymlinkReparseBuffer(`\??\C:\actual-target`, `C:\display-name`)
|
||||
binary.LittleEndian.PutUint16(buffer[20:22], 0xD800)
|
||||
if _, err := decodeWindowsReparsePath(buffer, uint32(len(buffer)), 20); err == nil {
|
||||
t.Fatal("decodeWindowsReparsePath() accepted an unpaired UTF-16 surrogate")
|
||||
}
|
||||
})
|
||||
t.Run("embedded NUL", func(t *testing.T) {
|
||||
buffer := windowsSymlinkReparseBuffer(`\??\C:\actual-target`, `C:\display-name`)
|
||||
binary.LittleEndian.PutUint16(buffer[20:22], 0)
|
||||
if _, err := decodeWindowsReparsePath(buffer, uint32(len(buffer)), 20); err == nil {
|
||||
t.Fatal("decodeWindowsReparsePath() accepted an embedded NUL")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestDecodeWindowsReparsePathAcceptsValidSurrogatePair(t *testing.T) {
|
||||
buffer := windowsSymlinkReparseBuffer(`\??\C:\target-😀`, `C:\display-name`)
|
||||
got, err := decodeWindowsReparsePath(buffer, uint32(len(buffer)), 20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := `\??\C:\target-😀`; got != want {
|
||||
t.Fatalf("decodeWindowsReparsePath() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func windowsSymlinkReparseBuffer(substituteName, printName string) []byte {
|
||||
substitute := utf16.Encode([]rune(substituteName))
|
||||
print := utf16.Encode([]rune(printName))
|
||||
pathBuffer := make([]byte, (len(substitute)+len(print))*2)
|
||||
for index, unit := range substitute {
|
||||
binary.LittleEndian.PutUint16(pathBuffer[index*2:index*2+2], unit)
|
||||
}
|
||||
printOffset := len(substitute) * 2
|
||||
for index, unit := range print {
|
||||
binary.LittleEndian.PutUint16(pathBuffer[printOffset+index*2:printOffset+index*2+2], unit)
|
||||
}
|
||||
buffer := make([]byte, 20+len(pathBuffer))
|
||||
binary.LittleEndian.PutUint16(buffer[4:6], uint16(len(buffer)-8))
|
||||
binary.LittleEndian.PutUint16(buffer[8:10], 0)
|
||||
binary.LittleEndian.PutUint16(buffer[10:12], uint16(len(substitute)*2))
|
||||
binary.LittleEndian.PutUint16(buffer[12:14], uint16(printOffset))
|
||||
binary.LittleEndian.PutUint16(buffer[14:16], uint16(len(print)*2))
|
||||
copy(buffer[20:], pathBuffer)
|
||||
return buffer
|
||||
}
|
||||
@@ -2,11 +2,81 @@ package workspaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDirectoryHandleReadsEntriesFromPinnedDirectory(t *testing.T) {
|
||||
parent := t.TempDir()
|
||||
root := filepath.Join(parent, "task")
|
||||
nested := filepath.Join(root, "cache")
|
||||
foreign := filepath.Join(root, "foreign")
|
||||
if err := os.MkdirAll(nested, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(foreign, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(nested, "data.txt"), []byte("original"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(foreign, "data.txt"), []byte("foreign"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink("original-target", filepath.Join(nested, "link")); err != nil {
|
||||
t.Skipf("symlink creation is unavailable: %v", err)
|
||||
}
|
||||
if err := os.Symlink("foreign-target", filepath.Join(foreign, "link")); err != nil {
|
||||
t.Skipf("symlink creation is unavailable: %v", err)
|
||||
}
|
||||
|
||||
rootHandle, err := OpenDirectoryNoFollow(parent, root)
|
||||
if err != nil {
|
||||
t.Fatalf("open task root: %v", err)
|
||||
}
|
||||
defer func() { _ = rootHandle.Close() }()
|
||||
handle, err := rootHandle.OpenSubdirectory("cache")
|
||||
if err != nil {
|
||||
t.Fatalf("open cache directory: %v", err)
|
||||
}
|
||||
defer func() { _ = handle.Close() }()
|
||||
|
||||
pinned := nested + ".pinned"
|
||||
if err := os.Rename(nested, pinned); err != nil {
|
||||
t.Fatalf("rename pinned directory: %v", err)
|
||||
}
|
||||
if err := os.Symlink(foreign, nested); err != nil {
|
||||
t.Fatalf("replace directory with foreign symlink: %v", err)
|
||||
}
|
||||
|
||||
target, err := handle.ReadLink("link")
|
||||
if err != nil || target != "original-target" {
|
||||
t.Fatalf("pinned link target = %q, err = %v; want original target", target, err)
|
||||
}
|
||||
mode, err := handle.LstatEntry("link")
|
||||
if err != nil || mode&os.ModeSymlink == 0 {
|
||||
t.Fatalf("pinned link mode = %v, err = %v; want symlink", mode, err)
|
||||
}
|
||||
entries, err := handle.ReadDir()
|
||||
if err != nil {
|
||||
t.Fatalf("read pinned directory: %v", err)
|
||||
}
|
||||
if len(entries) != 2 {
|
||||
t.Fatalf("pinned directory entries = %d, want 2", len(entries))
|
||||
}
|
||||
file, err := handle.OpenFile("data.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("open pinned file: %v", err)
|
||||
}
|
||||
content, readErr := io.ReadAll(file)
|
||||
closeErr := file.Close()
|
||||
if readErr != nil || closeErr != nil || string(content) != "original" {
|
||||
t.Fatalf("pinned file content = %q, read err = %v, close err = %v", content, readErr, closeErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectoryHandlePinsWorktreeAcrossPathReplacement(t *testing.T) {
|
||||
parent := t.TempDir()
|
||||
original := filepath.Join(parent, "original")
|
||||
|
||||
@@ -159,6 +159,19 @@ func (h *unixDirectoryHandle) RemoveDirectory(ctx context.Context) error {
|
||||
}
|
||||
|
||||
func (h *unixDirectoryHandle) ReadFile(name string) ([]byte, error) {
|
||||
file, err := h.OpenFile(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
content, readErr := io.ReadAll(file)
|
||||
closeErr := file.Close()
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
return content, closeErr
|
||||
}
|
||||
|
||||
func (h *unixDirectoryHandle) OpenFile(name string) (io.ReadCloser, error) {
|
||||
if h == nil || h.targetFD < 0 {
|
||||
return nil, errors.New("directory handle is closed")
|
||||
}
|
||||
@@ -183,9 +196,111 @@ func (h *unixDirectoryHandle) ReadFile(name string) ([]byte, error) {
|
||||
_ = file.Close()
|
||||
return nil, fmt.Errorf("directory entry is not a regular file: %s", name)
|
||||
}
|
||||
content, readErr := io.ReadAll(file)
|
||||
_ = file.Close()
|
||||
return content, readErr
|
||||
return file, nil
|
||||
}
|
||||
|
||||
func (h *unixDirectoryHandle) OpenSubdirectory(name string) (DirectoryHandle, error) {
|
||||
if h == nil || h.targetFD < 0 {
|
||||
return nil, errors.New("directory handle is closed")
|
||||
}
|
||||
if err := validateDirectoryEntryName(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rootFD, err := unix.Dup(h.targetFD)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parentFD, err := unix.Dup(h.targetFD)
|
||||
if err != nil {
|
||||
_ = unix.Close(rootFD)
|
||||
return nil, err
|
||||
}
|
||||
targetFD, err := unix.Openat(h.targetFD, name, dependencyDirectoryOpenFlags, 0)
|
||||
if err != nil {
|
||||
_ = unix.Close(parentFD)
|
||||
_ = unix.Close(rootFD)
|
||||
return nil, err
|
||||
}
|
||||
return &unixDirectoryHandle{rootFD: rootFD, parentFD: parentFD, targetFD: targetFD, target: name}, nil
|
||||
}
|
||||
|
||||
func (h *unixDirectoryHandle) LstatEntry(name string) (os.FileMode, error) {
|
||||
if h == nil || h.targetFD < 0 {
|
||||
return 0, errors.New("directory handle is closed")
|
||||
}
|
||||
if err := validateDirectoryEntryName(name); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var info unix.Stat_t
|
||||
if err := unix.Fstatat(h.targetFD, name, &info, unix.AT_SYMLINK_NOFOLLOW); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
mode := os.FileMode(info.Mode & 0o777)
|
||||
switch info.Mode & unix.S_IFMT {
|
||||
case unix.S_IFDIR:
|
||||
mode |= os.ModeDir
|
||||
case unix.S_IFLNK:
|
||||
mode |= os.ModeSymlink
|
||||
case unix.S_IFIFO:
|
||||
mode |= os.ModeNamedPipe
|
||||
case unix.S_IFSOCK:
|
||||
mode |= os.ModeSocket
|
||||
case unix.S_IFCHR:
|
||||
mode |= os.ModeDevice | os.ModeCharDevice
|
||||
case unix.S_IFBLK:
|
||||
mode |= os.ModeDevice
|
||||
}
|
||||
if info.Mode&0o4000 != 0 {
|
||||
mode |= os.ModeSetuid
|
||||
}
|
||||
if info.Mode&0o2000 != 0 {
|
||||
mode |= os.ModeSetgid
|
||||
}
|
||||
if info.Mode&0o1000 != 0 {
|
||||
mode |= os.ModeSticky
|
||||
}
|
||||
return mode, nil
|
||||
}
|
||||
|
||||
func (h *unixDirectoryHandle) ReadLink(name string) (string, error) {
|
||||
if h == nil || h.targetFD < 0 {
|
||||
return "", errors.New("directory handle is closed")
|
||||
}
|
||||
if err := validateDirectoryEntryName(name); err != nil {
|
||||
return "", err
|
||||
}
|
||||
buffer := make([]byte, 256)
|
||||
for {
|
||||
n, err := unix.Readlinkat(h.targetFD, name, buffer)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if n < len(buffer) {
|
||||
return string(buffer[:n]), nil
|
||||
}
|
||||
buffer = make([]byte, len(buffer)*2)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *unixDirectoryHandle) ReadDir() ([]os.DirEntry, error) {
|
||||
if h == nil || h.targetFD < 0 {
|
||||
return nil, errors.New("directory handle is closed")
|
||||
}
|
||||
fd, err := unix.Openat(h.targetFD, ".", dependencyDirectoryOpenFlags, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
directory := os.NewFile(uintptr(fd), "worktree-directory")
|
||||
if directory == nil {
|
||||
_ = unix.Close(fd)
|
||||
return nil, errors.New("create directory reader from handle")
|
||||
}
|
||||
entries, readErr := directory.ReadDir(-1)
|
||||
closeErr := directory.Close()
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
return entries, closeErr
|
||||
}
|
||||
|
||||
func (h *unixDirectoryHandle) WriteFile(name string, data []byte, mode os.FileMode) error {
|
||||
|
||||
@@ -4,6 +4,7 @@ package workspaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -207,6 +208,19 @@ func windowsDependencyHandlesSameFile(a, b windows.Handle) (bool, error) {
|
||||
}
|
||||
|
||||
func (h *windowsDirectoryHandle) ReadFile(name string) ([]byte, error) {
|
||||
file, err := h.OpenFile(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
content, readErr := io.ReadAll(file)
|
||||
closeErr := file.Close()
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
return content, closeErr
|
||||
}
|
||||
|
||||
func (h *windowsDirectoryHandle) OpenFile(name string) (io.ReadCloser, error) {
|
||||
if h == nil || h.targetHandle == 0 {
|
||||
return nil, errors.New("directory handle is closed")
|
||||
}
|
||||
@@ -238,9 +252,131 @@ func (h *windowsDirectoryHandle) ReadFile(name string) ([]byte, error) {
|
||||
_ = file.Close()
|
||||
return nil, fmt.Errorf("directory entry is not a regular file: %s", name)
|
||||
}
|
||||
content, readErr := io.ReadAll(file)
|
||||
_ = file.Close()
|
||||
return content, readErr
|
||||
return file, nil
|
||||
}
|
||||
|
||||
func (h *windowsDirectoryHandle) OpenSubdirectory(name string) (DirectoryHandle, error) {
|
||||
if h == nil || h.targetHandle == 0 {
|
||||
return nil, errors.New("directory handle is closed")
|
||||
}
|
||||
if err := validateDirectoryEntryName(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
targetHandle, err := openWindowsDependencyDirectoryRelative(h.targetHandle, name, windowsDependencyReadAccess)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if reparse, err := windowsDependencyHandleIsReparsePoint(targetHandle); err != nil {
|
||||
_ = windows.CloseHandle(targetHandle)
|
||||
return nil, err
|
||||
} else if reparse {
|
||||
_ = windows.CloseHandle(targetHandle)
|
||||
return nil, fmt.Errorf("directory entry is a reparse point: %s", name)
|
||||
}
|
||||
rootHandle, err := duplicateWindowsDependencyHandle(h.targetHandle)
|
||||
if err != nil {
|
||||
_ = windows.CloseHandle(targetHandle)
|
||||
return nil, err
|
||||
}
|
||||
parentHandle, err := duplicateWindowsDependencyHandle(h.targetHandle)
|
||||
if err != nil {
|
||||
_ = windows.CloseHandle(targetHandle)
|
||||
_ = windows.CloseHandle(rootHandle)
|
||||
return nil, err
|
||||
}
|
||||
return &windowsDirectoryHandle{
|
||||
rootHandle: rootHandle, parentHandle: parentHandle, targetHandle: targetHandle, target: name,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *windowsDirectoryHandle) LstatEntry(name string) (os.FileMode, error) {
|
||||
if h == nil || h.targetHandle == 0 {
|
||||
return 0, errors.New("directory handle is closed")
|
||||
}
|
||||
if err := validateDirectoryEntryName(name); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
handle, err := openWindowsDependencyHandle(h.targetHandle, name, windowsDependencyReadAccess, 0)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if reparse, err := windowsDependencyHandleIsReparsePoint(handle); err != nil {
|
||||
_ = windows.CloseHandle(handle)
|
||||
return 0, err
|
||||
} else if reparse {
|
||||
_ = windows.CloseHandle(handle)
|
||||
return os.ModeSymlink, nil
|
||||
}
|
||||
file := os.NewFile(uintptr(handle), filepath.Join("worktree-directory", name))
|
||||
if file == nil {
|
||||
_ = windows.CloseHandle(handle)
|
||||
return 0, errors.New("create file info from directory entry handle")
|
||||
}
|
||||
info, err := file.Stat()
|
||||
closeErr := file.Close()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return info.Mode(), closeErr
|
||||
}
|
||||
|
||||
func (h *windowsDirectoryHandle) ReadLink(name string) (string, error) {
|
||||
if h == nil || h.targetHandle == 0 {
|
||||
return "", errors.New("directory handle is closed")
|
||||
}
|
||||
if err := validateDirectoryEntryName(name); err != nil {
|
||||
return "", err
|
||||
}
|
||||
handle, err := openWindowsDependencyHandle(h.targetHandle, name, windowsDependencyReadAccess, 0)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = windows.CloseHandle(handle) }()
|
||||
buffer := make([]byte, windows.MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
|
||||
var returned uint32
|
||||
if err := windows.DeviceIoControl(
|
||||
handle, windows.FSCTL_GET_REPARSE_POINT, nil, 0, &buffer[0], uint32(len(buffer)), &returned, nil,
|
||||
); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if returned < 16 {
|
||||
return "", errors.New("reparse point data is truncated")
|
||||
}
|
||||
tag := binary.LittleEndian.Uint32(buffer[:4])
|
||||
pathOffset := 16
|
||||
switch tag {
|
||||
case windows.IO_REPARSE_TAG_SYMLINK:
|
||||
if returned < 20 {
|
||||
return "", errors.New("symbolic link data is truncated")
|
||||
}
|
||||
pathOffset = 20
|
||||
case windows.IO_REPARSE_TAG_MOUNT_POINT:
|
||||
pathOffset = 16
|
||||
default:
|
||||
return "", errors.New("reparse point is not a symbolic link or junction")
|
||||
}
|
||||
return decodeWindowsReparsePath(buffer, returned, pathOffset)
|
||||
}
|
||||
|
||||
func (h *windowsDirectoryHandle) ReadDir() ([]os.DirEntry, error) {
|
||||
if h == nil || h.targetHandle == 0 {
|
||||
return nil, errors.New("directory handle is closed")
|
||||
}
|
||||
handle, err := duplicateWindowsDependencyHandle(h.targetHandle)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
directory := os.NewFile(uintptr(handle), "worktree-directory")
|
||||
if directory == nil {
|
||||
_ = windows.CloseHandle(handle)
|
||||
return nil, errors.New("create directory reader from handle")
|
||||
}
|
||||
entries, readErr := directory.ReadDir(-1)
|
||||
closeErr := directory.Close()
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
return entries, closeErr
|
||||
}
|
||||
|
||||
func (h *windowsDirectoryHandle) WriteFile(name string, data []byte, _ os.FileMode) error {
|
||||
|
||||
@@ -196,6 +196,7 @@ func (h *TaskHandlers) registerHTTP(router *gin.Engine) {
|
||||
api.GET("/workspaces/:id/tasks/by-external-id", h.httpGetTaskByExternalID)
|
||||
api.DELETE("/workspaces/:id/tasks/by-external-id", h.httpReleaseTaskExternalID)
|
||||
api.GET("/tasks/:id", h.httpGetTask)
|
||||
api.GET("/tasks/:id/archive-source-manifest", h.httpGetArchiveSourceManifest)
|
||||
api.GET("/tasks/:id/context", h.httpGetTaskContext)
|
||||
api.GET("/task-sessions/:id", h.httpGetTaskSession)
|
||||
api.POST("/task-sessions/:id/last-agent-error/dismiss", h.httpDismissLastAgentError)
|
||||
|
||||
@@ -467,6 +467,21 @@ func (h *TaskHandlers) httpGetTask(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, dtos[0])
|
||||
}
|
||||
|
||||
// httpGetArchiveSourceManifest exposes only durable archive-time evidence.
|
||||
// Service authorization binds each decoded cleanup snapshot to its workspace.
|
||||
func (h *TaskHandlers) httpGetArchiveSourceManifest(c *gin.Context) {
|
||||
manifest, err := h.service.GetArchiveSourceManifest(c.Request.Context(), c.Param("id"))
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrTaskSourceManifestNotFound) {
|
||||
handleNotFound(c, h.logger, taskrepo.ErrTaskNotFound, "archive source manifest not found")
|
||||
return
|
||||
}
|
||||
handleNotFound(c, h.logger, err, "archive source manifest not found")
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"worktrees": manifest})
|
||||
}
|
||||
|
||||
func (h *TaskHandlers) httpListTaskSessions(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
sessions, err := h.service.ListTaskSessions(ctx, c.Param("id"))
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/kandev/kandev/internal/auth/authn"
|
||||
"github.com/kandev/kandev/internal/task/dto"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
taskrepository "github.com/kandev/kandev/internal/task/repository"
|
||||
"github.com/kandev/kandev/internal/task/service"
|
||||
)
|
||||
|
||||
@@ -21,6 +22,7 @@ import (
|
||||
// the HTTP list/count routes need, recording the arguments they receive.
|
||||
type httpTaskRepo struct {
|
||||
wsTaskRepo
|
||||
taskrepository.TaskResourceCleanupRepository
|
||||
|
||||
listedWorkspaceID string
|
||||
listedPage int
|
||||
@@ -35,6 +37,57 @@ type httpTaskRepo struct {
|
||||
stepCountErr error
|
||||
countedWorkflowID string
|
||||
countedStepID string
|
||||
cleanupJobs []*models.TaskResourceCleanupJob
|
||||
cleanupJobsByOp map[string]*models.TaskResourceCleanupJob
|
||||
}
|
||||
|
||||
func (r *httpTaskRepo) CreateTaskResourceCleanupJob(
|
||||
_ context.Context, job *models.TaskResourceCleanupJob,
|
||||
) error {
|
||||
if r.cleanupJobsByOp == nil {
|
||||
r.cleanupJobsByOp = make(map[string]*models.TaskResourceCleanupJob)
|
||||
}
|
||||
r.cleanupJobsByOp[job.OperationID] = job
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *httpTaskRepo) GetTaskResourceCleanupJobByOperationID(
|
||||
_ context.Context, operationID string,
|
||||
) (*models.TaskResourceCleanupJob, error) {
|
||||
return r.cleanupJobsByOp[operationID], nil
|
||||
}
|
||||
|
||||
func (r *httpTaskRepo) UpdateTaskResourceCleanupSnapshot(
|
||||
_ context.Context, operationID, snapshot string,
|
||||
) error {
|
||||
if job := r.cleanupJobsByOp[operationID]; job != nil {
|
||||
job.ResourceSnapshot = snapshot
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *httpTaskRepo) StartPreparedTaskResourceCleanupJob(
|
||||
_ context.Context, id string,
|
||||
) (bool, error) {
|
||||
for _, job := range r.cleanupJobsByOp {
|
||||
if job.ID == id && job.State == models.TaskResourceCleanupStatePrepared {
|
||||
job.State = models.TaskResourceCleanupStatePending
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (r *httpTaskRepo) ListTaskResourceCleanupJobs(
|
||||
_ context.Context, taskID string,
|
||||
) ([]*models.TaskResourceCleanupJob, error) {
|
||||
jobs := make([]*models.TaskResourceCleanupJob, 0, len(r.cleanupJobs))
|
||||
for _, job := range r.cleanupJobs {
|
||||
if job != nil && job.TaskID == taskID {
|
||||
jobs = append(jobs, job)
|
||||
}
|
||||
}
|
||||
return jobs, nil
|
||||
}
|
||||
|
||||
func (r *httpTaskRepo) ListTasksByWorkspace(
|
||||
@@ -70,7 +123,7 @@ func newHTTPTaskHandlers(t *testing.T, repo *httpTaskRepo) *TaskHandlers {
|
||||
Workflows: repo, Messages: repo, Turns: repo,
|
||||
Sessions: repo, GitSnapshots: repo, RepoEntities: repo,
|
||||
Executors: repo, Environments: repo, TaskEnvironments: repo,
|
||||
Reviews: repo,
|
||||
Reviews: repo, ResourceCleanups: repo,
|
||||
}, nil, log, service.RepositoryDiscoveryConfig{})
|
||||
return &TaskHandlers{service: svc, logger: log}
|
||||
}
|
||||
@@ -141,6 +194,54 @@ func TestHTTPGetTaskDeniesForeignTask(t *testing.T) {
|
||||
require.Contains(t, ownerRec.Body.String(), "Victim", "the owner must still get their task")
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.5
|
||||
func TestHTTPGetArchiveSourceManifestDeniesForeignWorkspace(t *testing.T) {
|
||||
repo := &httpTaskRepo{cleanupJobs: []*models.TaskResourceCleanupJob{{
|
||||
ID: "cleanup-b", TaskID: "task-b",
|
||||
ResourceSnapshot: `{"workspace_id":"ws-b","worktrees":[{"id":"wt-b","task_id":"task-b","repository_id":"repo-b"}],"archive_source_manifest":[{"task_id":"task-b","cleanup_job_id":"cleanup-b","worktree_id":"wt-b","repository_id":"repo-b"}]}`,
|
||||
}}}
|
||||
h := newHTTPTaskHandlers(t, repo)
|
||||
|
||||
foreignCtx, foreignRec := taskRequestAs(t, "user-a", http.MethodGet,
|
||||
"/api/v1/tasks/task-b/archive-source-manifest", "task-b")
|
||||
h.httpGetArchiveSourceManifest(foreignCtx)
|
||||
require.Equal(t, http.StatusNotFound, foreignRec.Code)
|
||||
require.JSONEq(t, `{"error":"archive source manifest not found"}`, foreignRec.Body.String())
|
||||
|
||||
ownerCtx, ownerRec := taskRequestAs(t, "user-b", http.MethodGet,
|
||||
"/api/v1/tasks/task-b/archive-source-manifest", "task-b")
|
||||
h.httpGetArchiveSourceManifest(ownerCtx)
|
||||
require.Equal(t, http.StatusOK, ownerRec.Code)
|
||||
require.Contains(t, ownerRec.Body.String(), `"worktree_id":"wt-b"`)
|
||||
|
||||
missingCtx, missingRec := taskRequestAs(t, "user-b", http.MethodGet,
|
||||
"/api/v1/tasks/task-b/archive-source-manifest", "task-b")
|
||||
newHTTPTaskHandlers(t, &httpTaskRepo{}).httpGetArchiveSourceManifest(missingCtx)
|
||||
require.Equal(t, http.StatusNotFound, missingRec.Code)
|
||||
require.JSONEq(t, `{"error":"archive source manifest not found"}`, missingRec.Body.String())
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.5
|
||||
func TestHTTPGetArchiveSourceManifestReturnsAllCleanupGenerations(t *testing.T) {
|
||||
repo := &httpTaskRepo{cleanupJobs: []*models.TaskResourceCleanupJob{
|
||||
{
|
||||
ID: "cleanup-first", TaskID: "task-b",
|
||||
ResourceSnapshot: `{"workspace_id":"ws-b","worktrees":[{"id":"wt-first","task_id":"task-b","repository_id":"repo-b"}],"archive_source_manifest":[{"task_id":"task-b","cleanup_job_id":"cleanup-first","worktree_id":"wt-first","repository_id":"repo-b"}]}`,
|
||||
},
|
||||
{
|
||||
ID: "cleanup-second", TaskID: "task-b",
|
||||
ResourceSnapshot: `{"workspace_id":"ws-b","worktrees":[{"id":"wt-second","task_id":"task-b","repository_id":"repo-b"}],"archive_source_manifest":[{"task_id":"task-b","cleanup_job_id":"cleanup-second","worktree_id":"wt-second","repository_id":"repo-b"}]}`,
|
||||
},
|
||||
}}
|
||||
h := newHTTPTaskHandlers(t, repo)
|
||||
ownerCtx, ownerRec := taskRequestAs(t, "user-b", http.MethodGet,
|
||||
"/api/v1/tasks/task-b/archive-source-manifest", "task-b")
|
||||
h.httpGetArchiveSourceManifest(ownerCtx)
|
||||
require.Equal(t, http.StatusOK, ownerRec.Code)
|
||||
require.Contains(t, ownerRec.Body.String(), `"cleanup_job_id":"cleanup-first"`)
|
||||
require.Contains(t, ownerRec.Body.String(), `"cleanup_job_id":"cleanup-second"`)
|
||||
}
|
||||
|
||||
func TestHTTPGetTaskReturnsNotFoundForUnknownTask(t *testing.T) {
|
||||
h := newHTTPTaskHandlers(t, &httpTaskRepo{})
|
||||
c, rec := taskRequestAs(t, "", http.MethodGet, "/api/v1/tasks/nope", "nope")
|
||||
|
||||
@@ -147,6 +147,32 @@ func (r *Repository) ListArchiveTaskResourceCleanupJobs(
|
||||
return jobs, rows.Err()
|
||||
}
|
||||
|
||||
// ListTaskResourceCleanupJobs returns every durable cleanup generation for one
|
||||
// task, including delete generations that outlive the task row itself.
|
||||
func (r *Repository) ListTaskResourceCleanupJobs(
|
||||
ctx context.Context, taskID string,
|
||||
) ([]*models.TaskResourceCleanupJob, error) {
|
||||
rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(`
|
||||
SELECT `+taskResourceCleanupColumns+`
|
||||
FROM task_resource_cleanup_jobs
|
||||
WHERE task_id = ?
|
||||
ORDER BY created_at ASC
|
||||
`), taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
jobs := make([]*models.TaskResourceCleanupJob, 0)
|
||||
for rows.Next() {
|
||||
job, scanErr := scanTaskResourceCleanupJob(rows)
|
||||
if scanErr != nil {
|
||||
return nil, scanErr
|
||||
}
|
||||
jobs = append(jobs, job)
|
||||
}
|
||||
return jobs, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) ListPreparedTaskResourceCleanupJobs(ctx context.Context) ([]*models.TaskResourceCleanupJob, error) {
|
||||
rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(`
|
||||
SELECT `+taskResourceCleanupColumns+`
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -109,6 +110,12 @@ func TestArchiveTaskCleanupPreservesTaskEnvironmentIdentity(t *testing.T) {
|
||||
if err := repo.UpdateTaskSession(ctx, session); err != nil {
|
||||
t.Fatalf("UpdateTaskSession: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(wt.Path, "README.md"), []byte("changed before archive\n"), 0o644); err != nil {
|
||||
t.Fatalf("write tracked change: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(wt.Path, "untracked.txt"), []byte("untracked before archive\n"), 0o644); err != nil {
|
||||
t.Fatalf("write untracked change: %v", err)
|
||||
}
|
||||
|
||||
svc.SetWorktreeCleanup(mgr)
|
||||
svc.SetEnvironmentDestroyer(&archiveManagerEnvironmentDestroyer{mgr: mgr})
|
||||
@@ -129,6 +136,55 @@ func TestArchiveTaskCleanupPreservesTaskEnvironmentIdentity(t *testing.T) {
|
||||
if cleanupState != models.TaskResourceCleanupStateSucceeded {
|
||||
t.Fatalf("cleanup state = %q, want %q", cleanupState, models.TaskResourceCleanupStateSucceeded)
|
||||
}
|
||||
var encodedSnapshot string
|
||||
if err := repo.DB().QueryRowContext(ctx, `
|
||||
SELECT resource_snapshot FROM task_resource_cleanup_jobs
|
||||
WHERE task_id = ? AND trigger = 'archive'
|
||||
ORDER BY created_at DESC LIMIT 1
|
||||
`, taskID).Scan(&encodedSnapshot); err != nil {
|
||||
t.Fatalf("load archive cleanup snapshot: %v", err)
|
||||
}
|
||||
var snapshot struct {
|
||||
ArchiveSourceManifest []struct {
|
||||
TaskID string `json:"task_id"`
|
||||
CleanupJobID string `json:"cleanup_job_id"`
|
||||
WorktreeID string `json:"worktree_id"`
|
||||
RepositoryID string `json:"repository_id"`
|
||||
HeadOID string `json:"head_oid"`
|
||||
IndexStateSHA256 string `json:"index_state_sha256"`
|
||||
Entries []struct {
|
||||
Path string `json:"path"`
|
||||
ContentSHA256 string `json:"content_sha256"`
|
||||
} `json:"entries"`
|
||||
} `json:"archive_source_manifest"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(encodedSnapshot), &snapshot); err != nil {
|
||||
t.Fatalf("decode archive source manifest: %v", err)
|
||||
}
|
||||
if len(snapshot.ArchiveSourceManifest) != 1 {
|
||||
t.Fatalf("archive source manifest = %#v, want one worktree", snapshot.ArchiveSourceManifest)
|
||||
}
|
||||
manifest := snapshot.ArchiveSourceManifest[0]
|
||||
if manifest.TaskID != taskID || manifest.CleanupJobID == "" || manifest.WorktreeID != wt.ID || manifest.RepositoryID != repositoryID {
|
||||
t.Fatalf("archive source manifest identity = %+v, want task/job/worktree/repository binding", manifest)
|
||||
}
|
||||
if manifest.HeadOID == "" || manifest.IndexStateSHA256 == "" {
|
||||
t.Fatalf("archive source manifest lacks git identities: %+v", manifest)
|
||||
}
|
||||
entries := make(map[string]string, len(manifest.Entries))
|
||||
for _, entry := range manifest.Entries {
|
||||
entries[entry.Path] = entry.ContentSHA256
|
||||
}
|
||||
if entries["README.md"] == "" || entries["untracked.txt"] == "" {
|
||||
t.Fatalf("archive source manifest entries = %#v, want tracked and untracked content identities", entries)
|
||||
}
|
||||
retrieved, err := svc.GetArchiveSourceManifest(ctx, taskID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetArchiveSourceManifest: %v", err)
|
||||
}
|
||||
if len(retrieved) != 1 || retrieved[0].CleanupJobID != manifest.CleanupJobID || retrieved[0].WorktreeID != wt.ID {
|
||||
t.Fatalf("retrieved archive source manifest = %#v, want persisted task-scoped evidence", retrieved)
|
||||
}
|
||||
|
||||
env, err := repo.GetTaskEnvironment(ctx, environmentID)
|
||||
if err != nil {
|
||||
|
||||
@@ -55,7 +55,9 @@ func TestDurableDeleteCleanupRemovesTaskAttachments(t *testing.T) {
|
||||
TaskID: taskID, Trigger: models.TaskResourceCleanupTriggerCascadeDelete,
|
||||
State: models.TaskResourceCleanupStateRunning,
|
||||
}
|
||||
if err := taskSvc.executeTaskResourceCleanupJob(ctx, job, &taskResourceCleanupSnapshot{}); err != nil {
|
||||
if err := taskSvc.executeTaskResourceCleanupJob(ctx, job, &taskResourceCleanupSnapshot{
|
||||
ArchiveSourceManifestCaptured: true,
|
||||
}); err != nil {
|
||||
t.Fatalf("executeTaskResourceCleanupJob: %v", err)
|
||||
}
|
||||
if _, err := repo.GetMessageAttachment(ctx, attachment.ID); !errors.Is(err, ErrAttachmentNotFound) {
|
||||
@@ -101,6 +103,9 @@ func TestWorkspaceDeleteCleanupSnapshotsAttachments(t *testing.T) {
|
||||
if err := json.Unmarshal([]byte(cleanup.cleanupJob.ResourceSnapshot), &snapshot); err != nil {
|
||||
t.Fatalf("decode cleanup snapshot: %v", err)
|
||||
}
|
||||
if snapshot.WorkspaceID != taskResult.Task.WorkspaceID {
|
||||
t.Fatalf("snapshot workspace ID = %q, want %q", snapshot.WorkspaceID, taskResult.Task.WorkspaceID)
|
||||
}
|
||||
if len(snapshot.Attachments) != 1 ||
|
||||
snapshot.Attachments[0].ID != attachment.ID ||
|
||||
snapshot.Attachments[0].StorageKey != attachment.StorageKey {
|
||||
|
||||
@@ -26,6 +26,7 @@ const (
|
||||
const taskResourceCleanupMutationOutcomeUnknown = "task mutation outcome requires reconciliation"
|
||||
|
||||
var ErrCleanupCancellationRace = errors.New("cleanup cancellation lost lifecycle race")
|
||||
var ErrTaskSourceManifestNotFound = errors.New("task source manifest not found")
|
||||
|
||||
type taskResourceCleanupCancellationCAS interface {
|
||||
CancelTaskResourceCleanupJobIfPending(ctx context.Context, id string) (bool, error)
|
||||
@@ -35,6 +36,10 @@ type taskResourceCleanupArchiveInspector interface {
|
||||
ListArchiveTaskResourceCleanupJobs(ctx context.Context, taskID string) ([]*models.TaskResourceCleanupJob, error)
|
||||
}
|
||||
|
||||
type taskResourceCleanupTaskInspector interface {
|
||||
ListTaskResourceCleanupJobs(ctx context.Context, taskID string) ([]*models.TaskResourceCleanupJob, error)
|
||||
}
|
||||
|
||||
var taskResourceCleanupRetryDelays = []time.Duration{
|
||||
time.Minute,
|
||||
5 * time.Minute,
|
||||
@@ -95,7 +100,23 @@ type taskResourceCleanupSnapshot struct {
|
||||
OrphanReapRecords []orphanReapCandidateRecord `json:"orphan_reap_records,omitempty"`
|
||||
// OrphanReapSkips carries a root-level or phase-level skip that has no
|
||||
// per-candidate record to attach its reason to.
|
||||
OrphanReapSkips []orphanReapSkipRecord `json:"orphan_reap_skips,omitempty"`
|
||||
OrphanReapSkips []orphanReapSkipRecord `json:"orphan_reap_skips,omitempty"`
|
||||
ArchiveSourceManifest []ArchiveSourceManifest `json:"archive_source_manifest,omitempty"`
|
||||
ArchiveSourceManifestCaptured bool `json:"archive_source_manifest_captured,omitempty"`
|
||||
}
|
||||
|
||||
// ArchiveSourceManifest is the task-scoped evidence retained before an archive
|
||||
// removes its registered worktree. It contains identities and digests only.
|
||||
type ArchiveSourceManifest struct {
|
||||
TaskID string `json:"task_id"`
|
||||
CleanupJobID string `json:"cleanup_job_id"`
|
||||
TaskEnvironmentID string `json:"task_environment_id,omitempty"`
|
||||
WorktreeID string `json:"worktree_id"`
|
||||
RepositoryID string `json:"repository_id"`
|
||||
HeadOID string `json:"head_oid"`
|
||||
IndexStateSHA256 string `json:"index_state_sha256"`
|
||||
PathPresent bool `json:"path_present"`
|
||||
Entries []worktree.ArchiveSourceManifestEntry `json:"entries,omitempty"`
|
||||
}
|
||||
|
||||
type taskResourceCleanupRun struct {
|
||||
@@ -127,6 +148,7 @@ func (s *Service) persistTaskResourceCleanup(
|
||||
if operationID == "" {
|
||||
operationID = newTaskResourceCleanupOperationID(trigger, taskID)
|
||||
}
|
||||
jobID := uuid.NewString()
|
||||
worktreeHeadOIDs, err := s.captureWorktreeCleanupHeadOIDs(ctx, worktrees)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -172,7 +194,7 @@ func (s *Service) persistTaskResourceCleanup(
|
||||
state = models.TaskResourceCleanupStatePrepared
|
||||
}
|
||||
job := &models.TaskResourceCleanupJob{
|
||||
OperationID: operationID, TaskID: taskID, Trigger: trigger,
|
||||
ID: jobID, OperationID: operationID, TaskID: taskID, Trigger: trigger,
|
||||
State: state, ResourceSnapshot: string(encoded),
|
||||
}
|
||||
if err := s.resourceCleanups.CreateTaskResourceCleanupJob(ctx, job); err != nil {
|
||||
@@ -198,6 +220,102 @@ func (s *Service) captureWorktreeCleanupHeadOIDs(
|
||||
return identities, nil
|
||||
}
|
||||
|
||||
func (s *Service) captureArchiveSourceManifest(
|
||||
ctx context.Context, jobID, taskID string, worktrees []*worktree.Worktree,
|
||||
) ([]ArchiveSourceManifest, error) {
|
||||
if len(worktrees) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
provider, ok := s.worktreeCleanup.(WorktreeArchiveSourceManifestProvider)
|
||||
if !ok {
|
||||
return nil, errors.New("worktree cleanup does not support archive source manifest capture")
|
||||
}
|
||||
captured, err := provider.CaptureArchiveSourceManifests(ctx, worktrees)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
manifests := make([]ArchiveSourceManifest, 0, len(worktrees))
|
||||
for _, wt := range worktrees {
|
||||
if wt == nil {
|
||||
continue
|
||||
}
|
||||
manifest, found := captured[wt.ID]
|
||||
if !found || manifest.TaskID != taskID || manifest.TaskEnvironmentID != wt.TaskEnvironmentID ||
|
||||
manifest.WorktreeID != wt.ID || manifest.RepositoryID != wt.RepositoryID {
|
||||
return nil, fmt.Errorf("archive source manifest does not match owned worktree %s", wt.ID)
|
||||
}
|
||||
manifests = append(manifests, ArchiveSourceManifest{
|
||||
TaskID: manifest.TaskID, CleanupJobID: jobID, TaskEnvironmentID: manifest.TaskEnvironmentID,
|
||||
WorktreeID: manifest.WorktreeID, RepositoryID: manifest.RepositoryID,
|
||||
HeadOID: manifest.HeadOID, IndexStateSHA256: manifest.IndexStateSHA256,
|
||||
Entries: manifest.Entries,
|
||||
PathPresent: manifest.PathPresent,
|
||||
})
|
||||
}
|
||||
return manifests, nil
|
||||
}
|
||||
|
||||
// GetTaskSourceManifest returns every retained archive/delete evidence
|
||||
// generation after authorizing each generation's persisted workspace identity.
|
||||
// This keeps delete evidence readable after its task row has been removed.
|
||||
func (s *Service) GetTaskSourceManifest(ctx context.Context, taskID string) ([]ArchiveSourceManifest, error) {
|
||||
inspector, ok := s.resourceCleanups.(taskResourceCleanupTaskInspector)
|
||||
if !ok {
|
||||
return nil, errors.New("task source manifest retrieval is unavailable")
|
||||
}
|
||||
jobs, err := inspector.ListTaskResourceCleanupJobs(ctx, taskID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list task cleanup jobs: %w", err)
|
||||
}
|
||||
manifests := make([]ArchiveSourceManifest, 0)
|
||||
for _, job := range jobs {
|
||||
if job == nil || job.TaskID != taskID {
|
||||
return nil, errors.New("task source manifest cleanup job identity is invalid")
|
||||
}
|
||||
var snapshot taskResourceCleanupSnapshot
|
||||
if err := json.Unmarshal([]byte(job.ResourceSnapshot), &snapshot); err != nil {
|
||||
return nil, fmt.Errorf("decode archive source manifest: %w", err)
|
||||
}
|
||||
if len(snapshot.ArchiveSourceManifest) == 0 {
|
||||
continue
|
||||
}
|
||||
if snapshot.WorkspaceID == "" {
|
||||
return nil, errors.New("task source manifest lacks workspace identity")
|
||||
}
|
||||
if err := s.AuthorizeWorkspaceAccess(ctx, snapshot.WorkspaceID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, manifest := range snapshot.ArchiveSourceManifest {
|
||||
if manifest.TaskID != taskID || manifest.CleanupJobID != job.ID {
|
||||
return nil, errors.New("archive source manifest identity does not match cleanup job")
|
||||
}
|
||||
if !sourceManifestMatchesSnapshotWorktree(manifest, snapshot.Worktrees) {
|
||||
return nil, errors.New("task source manifest does not match cleanup worktree inventory")
|
||||
}
|
||||
}
|
||||
manifests = append(manifests, snapshot.ArchiveSourceManifest...)
|
||||
}
|
||||
if len(manifests) == 0 {
|
||||
return nil, ErrTaskSourceManifestNotFound
|
||||
}
|
||||
return manifests, nil
|
||||
}
|
||||
|
||||
func sourceManifestMatchesSnapshotWorktree(manifest ArchiveSourceManifest, worktrees []*worktree.Worktree) bool {
|
||||
for _, wt := range worktrees {
|
||||
if wt != nil && manifest.WorktreeID == wt.ID && manifest.RepositoryID == wt.RepositoryID &&
|
||||
manifest.TaskEnvironmentID == wt.TaskEnvironmentID && manifest.TaskID == wt.TaskID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// GetArchiveSourceManifest is retained for the initial audit endpoint name.
|
||||
func (s *Service) GetArchiveSourceManifest(ctx context.Context, taskID string) ([]ArchiveSourceManifest, error) {
|
||||
return s.GetTaskSourceManifest(ctx, taskID)
|
||||
}
|
||||
|
||||
func captureWorktreeTaskDirNames(worktrees []*worktree.Worktree) map[string]string {
|
||||
if len(worktrees) == 0 {
|
||||
return nil
|
||||
@@ -671,6 +789,9 @@ func (s *Service) executeTaskResourceCleanupJob(
|
||||
if cancelled, err := s.cancelIfTaskUnarchived(ctx, job); err != nil || cancelled {
|
||||
return err
|
||||
}
|
||||
if err := s.captureAndPersistTaskSourceManifest(ctx, job, snapshot, len(failedStops)); err != nil {
|
||||
return err
|
||||
}
|
||||
var errs []error
|
||||
if taskResourceCleanupDeletesTask(job.Trigger) && s.attachmentSvc != nil {
|
||||
var attachmentErr error
|
||||
@@ -752,6 +873,41 @@ func (s *Service) executeTaskResourceCleanupJob(
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func (s *Service) captureAndPersistTaskSourceManifest(
|
||||
ctx context.Context,
|
||||
job *models.TaskResourceCleanupJob,
|
||||
snapshot *taskResourceCleanupSnapshot,
|
||||
runtimeStopFailures int,
|
||||
) error {
|
||||
if !taskResourceCleanupCapturesSourceManifest(job.Trigger) || snapshot.ArchiveSourceManifestCaptured ||
|
||||
len(snapshot.ArchiveSourceManifest) > 0 {
|
||||
return nil
|
||||
}
|
||||
if runtimeStopFailures > 0 {
|
||||
return fmt.Errorf("%d runtime stop operations failed; defer source manifest capture and cleanup", runtimeStopFailures)
|
||||
}
|
||||
manifest, err := s.captureArchiveSourceManifest(ctx, job.ID, job.TaskID, snapshot.Worktrees)
|
||||
if err != nil {
|
||||
return fmt.Errorf("capture archive source manifest: %w", err)
|
||||
}
|
||||
snapshot.ArchiveSourceManifest = manifest
|
||||
snapshot.ArchiveSourceManifestCaptured = true
|
||||
encoded, err := json.Marshal(snapshot)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode archive source manifest: %w", err)
|
||||
}
|
||||
updated, err := s.resourceCleanups.UpdateClaimedTaskResourceCleanupSnapshot(
|
||||
ctx, job.ID, job.Attempts, string(encoded),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("persist archive source manifest before cleanup: %w", err)
|
||||
}
|
||||
if !updated {
|
||||
return fmt.Errorf("persist archive source manifest before cleanup: cleanup claim changed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) hasLegacyWorktreeCleanup() bool {
|
||||
if s.worktreeCleanup == nil {
|
||||
return false
|
||||
@@ -1020,6 +1176,10 @@ func (s *Service) PrepareTaskResourceCleanupWithOptions(
|
||||
if job.State != models.TaskResourceCleanupStatePrepared {
|
||||
return nil
|
||||
}
|
||||
task, err := s.tasks.GetTask(ctx, taskID)
|
||||
if err != nil {
|
||||
return cancelPrepared(fmt.Errorf("load task for cleanup source manifest: %w", err))
|
||||
}
|
||||
sessions, err := s.sessions.ListTaskSessions(ctx, taskID)
|
||||
if err != nil {
|
||||
return cancelPrepared(fmt.Errorf("list task sessions for cleanup snapshot: %w", err))
|
||||
@@ -1058,6 +1218,7 @@ func (s *Service) PrepareTaskResourceCleanupWithOptions(
|
||||
DiscardWorktreeChanges: discardWorktreeChanges,
|
||||
LegacyWorktreeCleanup: s.hasLegacyWorktreeCleanup(),
|
||||
SSHTaskDirs: sshTaskDirs,
|
||||
WorkspaceID: task.WorkspaceID,
|
||||
}
|
||||
encoded, err := json.Marshal(snapshot)
|
||||
if err != nil {
|
||||
@@ -1069,6 +1230,20 @@ func (s *Service) PrepareTaskResourceCleanupWithOptions(
|
||||
return nil
|
||||
}
|
||||
|
||||
func taskResourceCleanupCapturesSourceManifest(trigger models.TaskResourceCleanupTrigger) bool {
|
||||
switch trigger {
|
||||
case models.TaskResourceCleanupTriggerArchive,
|
||||
models.TaskResourceCleanupTriggerDelete,
|
||||
models.TaskResourceCleanupTriggerCascadeArchive,
|
||||
models.TaskResourceCleanupTriggerCascadeDelete,
|
||||
models.TaskResourceCleanupTriggerWorkspaceDelete,
|
||||
models.TaskResourceCleanupTriggerQuickChatExpire:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) StartPreparedTaskResourceCleanup(ctx context.Context, operationID string) error {
|
||||
if s.resourceCleanups == nil {
|
||||
return nil
|
||||
|
||||
@@ -124,6 +124,12 @@ type activityCleanupBarrier struct {
|
||||
maintenanceErr chan error
|
||||
}
|
||||
|
||||
func (b *activityCleanupBarrier) CaptureArchiveSourceManifests(
|
||||
ctx context.Context, worktrees []*worktree.Worktree,
|
||||
) (map[string]worktree.ArchiveSourceManifest, error) {
|
||||
return (&recordingWorktreeCleanup{}).CaptureArchiveSourceManifests(ctx, worktrees)
|
||||
}
|
||||
|
||||
type blockingResumeCleanupRepository struct {
|
||||
repository.TaskResourceCleanupRepository
|
||||
entered chan struct{}
|
||||
@@ -385,6 +391,12 @@ func (c *cancellableCleanupBarrier) GetAllByTaskID(context.Context, string) ([]*
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c *cancellableCleanupBarrier) CaptureArchiveSourceManifests(
|
||||
ctx context.Context, worktrees []*worktree.Worktree,
|
||||
) (map[string]worktree.ArchiveSourceManifest, error) {
|
||||
return (&recordingWorktreeCleanup{}).CaptureArchiveSourceManifests(ctx, worktrees)
|
||||
}
|
||||
|
||||
func (c *cancellableCleanupBarrier) CleanupWorktrees(ctx context.Context, _ []*worktree.Worktree) error {
|
||||
c.once.Do(func() { close(c.started) })
|
||||
defer close(c.stopped)
|
||||
@@ -1066,6 +1078,11 @@ func TestPreparedCleanupIsNotRunnableUntilStarted(t *testing.T) {
|
||||
|
||||
func TestCancelPreparedTaskResourceCleanupIgnoresCallerCancellation(t *testing.T) {
|
||||
taskSvc, repo := setupOfficeTest(t)
|
||||
if err := repo.CreateTask(context.Background(), &models.Task{
|
||||
ID: "task-prepared-cancel", WorkspaceID: "ws-1", Title: "Prepared cancel",
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateTask: %v", err)
|
||||
}
|
||||
operationID := "cascade_cancel:prepared-cancel"
|
||||
if err := taskSvc.PrepareTaskResourceCleanup(context.Background(), "task-prepared-cancel",
|
||||
models.TaskResourceCleanupTriggerCascadeDelete, operationID, true); err != nil {
|
||||
@@ -1090,6 +1107,11 @@ func TestPrepareTaskResourceCleanupReadmitsCancelledIntent(t *testing.T) {
|
||||
taskSvc, repo := setupOfficeTest(t)
|
||||
taskSvc.StopTaskResourceCleanupWorker()
|
||||
ctx := context.Background()
|
||||
if err := repo.CreateTask(ctx, &models.Task{
|
||||
ID: "task-retry-cancelled", WorkspaceID: "ws-1", Title: "Retry cancelled",
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateTask: %v", err)
|
||||
}
|
||||
operationID := "cascade_archive:retry-cancelled-intent"
|
||||
if err := taskSvc.PrepareTaskResourceCleanup(
|
||||
ctx, "task-retry-cancelled", models.TaskResourceCleanupTriggerCascadeArchive,
|
||||
@@ -1147,6 +1169,11 @@ func TestTaskResourceCleanupRetriesCompletionPersistenceFailure(t *testing.T) {
|
||||
}
|
||||
func TestCancelPreparedTaskResourceCleanupIgnoresExpiredDeadline(t *testing.T) {
|
||||
taskSvc, repo := setupOfficeTest(t)
|
||||
if err := repo.CreateTask(context.Background(), &models.Task{
|
||||
ID: "task-expired-deadline", WorkspaceID: "ws-1", Title: "Expired deadline",
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateTask: %v", err)
|
||||
}
|
||||
operationID := "cascade_cancel:expired-deadline"
|
||||
if err := taskSvc.PrepareTaskResourceCleanup(context.Background(), "task-expired-deadline",
|
||||
models.TaskResourceCleanupTriggerCascadeDelete, operationID, true); err != nil {
|
||||
|
||||
@@ -3,12 +3,14 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository/repoerrors"
|
||||
sqliterepo "github.com/kandev/kandev/internal/task/repository/sqlite"
|
||||
"github.com/kandev/kandev/internal/worktree"
|
||||
)
|
||||
@@ -142,7 +144,14 @@ func TestTaskLifecycleCleanup_MissingWorktree(t *testing.T) {
|
||||
if err := taskSvc.processTaskResourceCleanupJob(ctx, job.ID); err != nil {
|
||||
t.Fatalf("processTaskResourceCleanupJob: %v", err)
|
||||
}
|
||||
job, err := repo.GetTaskResourceCleanupJob(ctx, job.ID)
|
||||
manifest, err := taskSvc.GetTaskSourceManifest(ctx, fixture.taskID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetTaskSourceManifest after lifecycle cleanup: %v", err)
|
||||
}
|
||||
if len(manifest) != 2 {
|
||||
t.Fatalf("task source manifest entries = %d, want both worktrees", len(manifest))
|
||||
}
|
||||
job, err = repo.GetTaskResourceCleanupJob(ctx, job.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("reload cleanup job: %v", err)
|
||||
}
|
||||
@@ -172,6 +181,51 @@ func TestTaskLifecycleCleanup_MissingWorktree(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.3
|
||||
func TestWorkspaceDeleteSourceManifestIsCoordinatorReadableButScopedCallsFailClosed(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
taskSvc, repo := setupOfficeTest(t)
|
||||
taskSvc.StopTaskResourceCleanupWorker()
|
||||
fixture := newMissingWorktreeCleanupFixture(t, repo, "task-workspace-delete-source-manifest")
|
||||
taskSvc.SetWorktreeCleanup(fixture.manager)
|
||||
taskSvc.SetEnvironmentDestroyer(&managerEnvironmentDestroyer{mgr: fixture.manager})
|
||||
|
||||
workspaceID := "ws-" + fixture.taskID
|
||||
task, err := repo.GetTask(ctx, fixture.taskID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetTask: %v", err)
|
||||
}
|
||||
cleanup, err := taskSvc.prepareWorkspaceDeleteTaskCleanup(ctx, task)
|
||||
if err != nil {
|
||||
t.Fatalf("prepareWorkspaceDeleteTaskCleanup: %v", err)
|
||||
}
|
||||
if err := repo.DeleteWorkspace(ctx, workspaceID); err != nil {
|
||||
t.Fatalf("DeleteWorkspace cascade: %v", err)
|
||||
}
|
||||
if err := taskSvc.StartPreparedTaskResourceCleanup(ctx, cleanup.cleanupJob.OperationID); err != nil {
|
||||
t.Fatalf("StartPreparedTaskResourceCleanup: %v", err)
|
||||
}
|
||||
job := latestCleanupJob(t, repo, fixture.taskID, models.TaskResourceCleanupTriggerWorkspaceDelete)
|
||||
if err := taskSvc.processTaskResourceCleanupJob(ctx, job.ID); err != nil {
|
||||
t.Fatalf("processTaskResourceCleanupJob: %v", err)
|
||||
}
|
||||
job = latestCleanupJob(t, repo, fixture.taskID, models.TaskResourceCleanupTriggerWorkspaceDelete)
|
||||
if job.State != models.TaskResourceCleanupStateSucceeded {
|
||||
t.Fatalf("workspace cleanup state = %q, want succeeded", job.State)
|
||||
}
|
||||
|
||||
manifest, err := taskSvc.GetTaskSourceManifest(ctx, fixture.taskID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetTaskSourceManifest as coordinator: %v", err)
|
||||
}
|
||||
if len(manifest) != 2 {
|
||||
t.Fatalf("coordinator source manifest entries = %d, want both worktrees", len(manifest))
|
||||
}
|
||||
if _, err := taskSvc.GetTaskSourceManifest(ctxAs("user-a"), fixture.taskID); !errors.Is(err, repoerrors.ErrWorkspaceNotFound) {
|
||||
t.Fatalf("scoped source manifest error = %v, want ErrWorkspaceNotFound after workspace deletion", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskLifecycleCleanup_MissingWorktree_ReplacementBranchStaysRetryable(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
taskSvc, repo := setupOfficeTest(t)
|
||||
|
||||
@@ -64,7 +64,8 @@ func TestOrphanReapEndToEndKillsRealChildAfterQuickChatDirRemoval(t *testing.T)
|
||||
State: models.TaskResourceCleanupStatePending,
|
||||
}
|
||||
snapshot := &taskResourceCleanupSnapshot{
|
||||
Sessions: []*models.TaskSession{{ID: sessionID, TaskID: "task-reap-e2e"}},
|
||||
ArchiveSourceManifestCaptured: true,
|
||||
Sessions: []*models.TaskSession{{ID: sessionID, TaskID: "task-reap-e2e"}},
|
||||
}
|
||||
|
||||
err := taskSvc.executeTaskResourceCleanupJob(ctx, job, snapshot)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/agentruntime"
|
||||
@@ -65,12 +66,15 @@ func TestExecuteTaskResourceCleanupJobSkipsReapPhaseOnFailedStop(t *testing.T) {
|
||||
job := &models.TaskResourceCleanupJob{
|
||||
ID: "job-failed-stop", TaskID: taskID, Trigger: models.TaskResourceCleanupTriggerDelete,
|
||||
}
|
||||
snapshot := &taskResourceCleanupSnapshot{}
|
||||
snapshot := &taskResourceCleanupSnapshot{ArchiveSourceManifestCaptured: true}
|
||||
err := svc.executeTaskResourceCleanupJob(ctx, job, snapshot)
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("expected an error reporting the failed runtime stop")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "runtime stop operations failed") {
|
||||
t.Fatalf("cleanup error = %v, want the stable runtime stop failure description", err)
|
||||
}
|
||||
if len(snapshot.OrphanReapRoots) != 0 {
|
||||
t.Fatalf("expected no reap roots recorded when a stop failed, got %+v", snapshot.OrphanReapRoots)
|
||||
}
|
||||
@@ -82,13 +86,8 @@ func TestExecuteTaskResourceCleanupJobSkipsReapPhaseOnFailedStop(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// AC-TASKS-ORPHAN-REAP-001.1: recording a removed path as a reap root is not
|
||||
// gated on a clean overall stop — only the reap phase's signal-sending is
|
||||
// (AC-TASKS-ORPHAN-REAP-006.2). A multi-session task with a mixed stop
|
||||
// outcome removes every non-preserved session's directory on this attempt
|
||||
// regardless of the failure elsewhere; a directory actually removed here must
|
||||
// still be recorded, since it will no longer exist to re-derive candidacy
|
||||
// from on a later attempt once the failing session's stop succeeds.
|
||||
// AC-TASKS-ORPHAN-REAP-006.2: completed session cleanup still runs after a
|
||||
// partial stop, while the running session and orphan reap phase are gated.
|
||||
func TestExecuteTaskResourceCleanupJobRecordsReapRootForSucceededSessionDespiteMixedStopOutcome(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
@@ -116,15 +115,12 @@ func TestExecuteTaskResourceCleanupJobRecordsReapRootForSucceededSessionDespiteM
|
||||
svc.orphanReapHostSnapshotter = poisonOrphanReapHostSnapshotter{t: t}
|
||||
|
||||
okDir := filepath.Join(quickChatDir, okSessionID)
|
||||
// Resolve while the directory still exists — resolveOrphanReapPathBestEffort
|
||||
// falls back to an unresolved absolute path once it is gone, so the
|
||||
// resolved form must be captured before the cleanup below removes it.
|
||||
wantRoot := resolveOrphanReapPathBestEffort(okDir)
|
||||
|
||||
job := &models.TaskResourceCleanupJob{
|
||||
ID: "job-mixed-stop", TaskID: taskID, Trigger: models.TaskResourceCleanupTriggerDelete,
|
||||
}
|
||||
snapshot := &taskResourceCleanupSnapshot{}
|
||||
snapshot := &taskResourceCleanupSnapshot{ArchiveSourceManifestCaptured: true}
|
||||
err := svc.executeTaskResourceCleanupJob(ctx, job, snapshot)
|
||||
|
||||
if err == nil {
|
||||
@@ -143,8 +139,7 @@ func TestExecuteTaskResourceCleanupJobRecordsReapRootForSucceededSessionDespiteM
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("expected the removed directory %q to be recorded as a reap root even though the "+
|
||||
"reap phase's signal-sending step is gated off this attempt; got roots=%+v", wantRoot, snapshot.OrphanReapRoots)
|
||||
t.Fatalf("expected the removed session directory to be recorded as a reap root, got %+v", snapshot.OrphanReapRoots)
|
||||
}
|
||||
// The signal-sending phase itself is still gated off this attempt
|
||||
// (AC-TASKS-ORPHAN-REAP-006.2): no candidate records or skips yet, and
|
||||
@@ -168,6 +163,11 @@ func (c *cancellingWorktreeCleanup) OnTaskDeleted(context.Context, string) error
|
||||
func (c *cancellingWorktreeCleanup) GetAllByTaskID(context.Context, string) ([]*worktree.Worktree, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (c *cancellingWorktreeCleanup) CaptureArchiveSourceManifests(
|
||||
ctx context.Context, worktrees []*worktree.Worktree,
|
||||
) (map[string]worktree.ArchiveSourceManifest, error) {
|
||||
return (&recordingWorktreeCleanup{}).CaptureArchiveSourceManifests(ctx, worktrees)
|
||||
}
|
||||
func (c *cancellingWorktreeCleanup) CleanupWorktrees(_ context.Context, _ []*worktree.Worktree) error {
|
||||
if err := os.RemoveAll(c.realPath); err != nil {
|
||||
return err
|
||||
@@ -209,7 +209,8 @@ func TestExecuteTaskResourceCleanupJobRecordsReapRootDespiteCancellationDuringCl
|
||||
ID: "job-cancel-during-cleanup", TaskID: taskID, Trigger: models.TaskResourceCleanupTriggerDelete,
|
||||
}
|
||||
snapshot := &taskResourceCleanupSnapshot{
|
||||
Worktrees: []*worktree.Worktree{{ID: "wt-cancel-during-cleanup", TaskID: taskID, Path: wtPath}},
|
||||
ArchiveSourceManifestCaptured: true,
|
||||
Worktrees: []*worktree.Worktree{{ID: "wt-cancel-during-cleanup", TaskID: taskID, Path: wtPath}},
|
||||
}
|
||||
err := svc.executeTaskResourceCleanupJob(ctx, job, snapshot)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
@@ -247,6 +248,11 @@ func (c *cancellingWorktreeCleanupParent) OnTaskDeleted(context.Context, string)
|
||||
func (c *cancellingWorktreeCleanupParent) GetAllByTaskID(context.Context, string) ([]*worktree.Worktree, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (c *cancellingWorktreeCleanupParent) CaptureArchiveSourceManifests(
|
||||
ctx context.Context, worktrees []*worktree.Worktree,
|
||||
) (map[string]worktree.ArchiveSourceManifest, error) {
|
||||
return (&recordingWorktreeCleanup{}).CaptureArchiveSourceManifests(ctx, worktrees)
|
||||
}
|
||||
func (c *cancellingWorktreeCleanupParent) CleanupWorktrees(_ context.Context, _ []*worktree.Worktree) error {
|
||||
if err := os.RemoveAll(c.realPath); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/worktree"
|
||||
)
|
||||
|
||||
type manifestBoundaryStopper struct {
|
||||
stopped bool
|
||||
}
|
||||
|
||||
func (s *manifestBoundaryStopper) StopTask(context.Context, string, string, bool) error { return nil }
|
||||
func (s *manifestBoundaryStopper) StopSession(context.Context, string, string, bool) error {
|
||||
return nil
|
||||
}
|
||||
func (s *manifestBoundaryStopper) StopExecution(context.Context, string, string, bool) error {
|
||||
s.stopped = true
|
||||
return nil
|
||||
}
|
||||
func (*manifestBoundaryStopper) RegisterExecutionStopOwner(string, string, bool) {}
|
||||
|
||||
type manifestBoundaryCleanup struct {
|
||||
WorktreeCleanup
|
||||
repo interface {
|
||||
GetTaskResourceCleanupJob(context.Context, string) (*models.TaskResourceCleanupJob, error)
|
||||
}
|
||||
stopper *manifestBoundaryStopper
|
||||
captureErr error
|
||||
captureCount int
|
||||
cleanupErr error
|
||||
cleanupCalled bool
|
||||
}
|
||||
|
||||
func TestCaptureManifestDefersOnRuntimeStopFailureWithStableReason(t *testing.T) {
|
||||
svc, _ := setupOfficeTest(t)
|
||||
snapshot := &taskResourceCleanupSnapshot{}
|
||||
err := svc.captureAndPersistTaskSourceManifest(
|
||||
context.Background(),
|
||||
&models.TaskResourceCleanupJob{Trigger: models.TaskResourceCleanupTriggerDelete},
|
||||
snapshot,
|
||||
1,
|
||||
)
|
||||
if err == nil || !strings.Contains(err.Error(), "runtime stop operations failed") {
|
||||
t.Fatalf("capture error = %v, want stable runtime stop failure description", err)
|
||||
}
|
||||
if snapshot.ArchiveSourceManifestCaptured {
|
||||
t.Fatal("manifest marked captured after an incomplete runtime stop")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *manifestBoundaryCleanup) GetAllByTaskID(context.Context, string) ([]*worktree.Worktree, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c *manifestBoundaryCleanup) CaptureArchiveSourceManifests(
|
||||
_ context.Context, worktrees []*worktree.Worktree,
|
||||
) (map[string]worktree.ArchiveSourceManifest, error) {
|
||||
c.captureCount++
|
||||
if !c.stopper.stopped {
|
||||
return nil, errors.New("capture ran before runtime stop")
|
||||
}
|
||||
if c.captureErr != nil {
|
||||
return nil, c.captureErr
|
||||
}
|
||||
result := make(map[string]worktree.ArchiveSourceManifest, len(worktrees))
|
||||
for _, wt := range worktrees {
|
||||
result[wt.ID] = worktree.ArchiveSourceManifest{
|
||||
TaskID: wt.TaskID, WorktreeID: wt.ID, RepositoryID: wt.RepositoryID,
|
||||
TaskEnvironmentID: wt.TaskEnvironmentID, HeadOID: "head", IndexStateSHA256: "index",
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *manifestBoundaryCleanup) CleanupWorktrees(context.Context, []*worktree.Worktree) error {
|
||||
c.cleanupCalled = true
|
||||
job, err := c.repo.GetTaskResourceCleanupJob(context.Background(), "manifest-boundary-job")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var snapshot taskResourceCleanupSnapshot
|
||||
if err := json.Unmarshal([]byte(job.ResourceSnapshot), &snapshot); err != nil {
|
||||
return err
|
||||
}
|
||||
if !snapshot.ArchiveSourceManifestCaptured || len(snapshot.ArchiveSourceManifest) != 1 {
|
||||
return errors.New("cleanup began before source manifest was durably persisted")
|
||||
}
|
||||
return c.cleanupErr
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.1
|
||||
func TestCleanupRetryReusesPersistedSourceManifest(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := setupOfficeTest(t)
|
||||
svc.StopTaskResourceCleanupWorker()
|
||||
stopper := &manifestBoundaryStopper{}
|
||||
cleanup := &manifestBoundaryCleanup{repo: repo, stopper: stopper, cleanupErr: errors.New("partial cleanup")}
|
||||
svc.SetWorktreeCleanup(cleanup)
|
||||
svc.SetExecutionStopper(stopper)
|
||||
snapshot, err := json.Marshal(taskResourceCleanupSnapshot{
|
||||
Worktrees: []*worktree.Worktree{{ID: "wt", TaskID: "task", RepositoryID: "repo"}},
|
||||
StopTargets: []persistedTaskStopTarget{{SessionID: "session", ExecutionID: "execution"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job := &models.TaskResourceCleanupJob{
|
||||
ID: "manifest-boundary-job", OperationID: "delete:manifest-boundary",
|
||||
TaskID: "task", Trigger: models.TaskResourceCleanupTriggerDelete,
|
||||
State: models.TaskResourceCleanupStatePending, ResourceSnapshot: string(snapshot),
|
||||
}
|
||||
if err := repo.CreateTaskResourceCleanupJob(ctx, job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := svc.processTaskResourceCleanupJob(ctx, job.ID); err == nil {
|
||||
t.Fatal("first cleanup attempt succeeded; expected partial cleanup failure")
|
||||
}
|
||||
cleanup.cleanupErr = nil
|
||||
if err := svc.processTaskResourceCleanupJob(ctx, job.ID); err != nil {
|
||||
t.Fatalf("retry cleanup: %v", err)
|
||||
}
|
||||
if cleanup.captureCount != 1 || !cleanup.cleanupCalled {
|
||||
t.Fatalf("capture count=%d cleanup called=%v, want one capture reused on retry", cleanup.captureCount, cleanup.cleanupCalled)
|
||||
}
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.1
|
||||
func TestCleanupPersistsSourceManifestAfterStopBeforeWorktreeRemoval(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := setupOfficeTest(t)
|
||||
svc.StopTaskResourceCleanupWorker()
|
||||
stopper := &manifestBoundaryStopper{}
|
||||
cleanup := &manifestBoundaryCleanup{repo: repo, stopper: stopper}
|
||||
svc.SetWorktreeCleanup(cleanup)
|
||||
svc.SetExecutionStopper(stopper)
|
||||
|
||||
snapshot, err := json.Marshal(taskResourceCleanupSnapshot{
|
||||
Worktrees: []*worktree.Worktree{{ID: "wt", TaskID: "task", RepositoryID: "repo"}},
|
||||
StopTargets: []persistedTaskStopTarget{{SessionID: "session", ExecutionID: "execution"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job := &models.TaskResourceCleanupJob{
|
||||
ID: "manifest-boundary-job", OperationID: "delete:manifest-boundary",
|
||||
TaskID: "task", Trigger: models.TaskResourceCleanupTriggerDelete,
|
||||
State: models.TaskResourceCleanupStatePending, ResourceSnapshot: string(snapshot),
|
||||
}
|
||||
if err := repo.CreateTaskResourceCleanupJob(ctx, job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := svc.processTaskResourceCleanupJob(ctx, job.ID); err != nil {
|
||||
t.Fatalf("process cleanup: %v", err)
|
||||
}
|
||||
if !stopper.stopped || !cleanup.cleanupCalled {
|
||||
t.Fatalf("stop=%v cleanup=%v, want stop then cleanup", stopper.stopped, cleanup.cleanupCalled)
|
||||
}
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.1
|
||||
func TestDeleteCleanupTriggersPersistSourceManifestBeforeWorktreeRemoval(t *testing.T) {
|
||||
for _, trigger := range []models.TaskResourceCleanupTrigger{
|
||||
models.TaskResourceCleanupTriggerWorkspaceDelete,
|
||||
models.TaskResourceCleanupTriggerQuickChatExpire,
|
||||
} {
|
||||
t.Run(string(trigger), func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := setupOfficeTest(t)
|
||||
svc.StopTaskResourceCleanupWorker()
|
||||
stopper := &manifestBoundaryStopper{}
|
||||
cleanup := &manifestBoundaryCleanup{repo: repo, stopper: stopper}
|
||||
svc.SetWorktreeCleanup(cleanup)
|
||||
svc.SetExecutionStopper(stopper)
|
||||
|
||||
snapshot, err := json.Marshal(taskResourceCleanupSnapshot{
|
||||
Worktrees: []*worktree.Worktree{{ID: "wt", TaskID: "task", RepositoryID: "repo"}},
|
||||
StopTargets: []persistedTaskStopTarget{{SessionID: "session", ExecutionID: "execution"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job := &models.TaskResourceCleanupJob{
|
||||
ID: "manifest-boundary-job", OperationID: string(trigger) + ":manifest-boundary",
|
||||
TaskID: "task", Trigger: trigger,
|
||||
State: models.TaskResourceCleanupStatePending, ResourceSnapshot: string(snapshot),
|
||||
}
|
||||
if err := repo.CreateTaskResourceCleanupJob(ctx, job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := svc.processTaskResourceCleanupJob(ctx, job.ID); err != nil {
|
||||
t.Fatalf("process %s cleanup: %v", trigger, err)
|
||||
}
|
||||
if !stopper.stopped || cleanup.captureCount != 1 || !cleanup.cleanupCalled {
|
||||
t.Fatalf("stop=%v captures=%d cleanup=%v, want manifest persisted before removal",
|
||||
stopper.stopped, cleanup.captureCount, cleanup.cleanupCalled)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.4
|
||||
func TestCleanupCaptureFailureBlocksWorktreeRemoval(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc, repo := setupOfficeTest(t)
|
||||
svc.StopTaskResourceCleanupWorker()
|
||||
stopper := &manifestBoundaryStopper{}
|
||||
captureErr := errors.New("capture unavailable")
|
||||
cleanup := &manifestBoundaryCleanup{repo: repo, stopper: stopper, captureErr: captureErr}
|
||||
svc.SetWorktreeCleanup(cleanup)
|
||||
svc.SetExecutionStopper(stopper)
|
||||
|
||||
snapshot, err := json.Marshal(taskResourceCleanupSnapshot{
|
||||
Worktrees: []*worktree.Worktree{{ID: "wt", TaskID: "task", RepositoryID: "repo"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job := &models.TaskResourceCleanupJob{
|
||||
ID: "manifest-boundary-job", OperationID: "delete:manifest-boundary",
|
||||
TaskID: "task", Trigger: models.TaskResourceCleanupTriggerDelete,
|
||||
State: models.TaskResourceCleanupStatePending, ResourceSnapshot: string(snapshot),
|
||||
}
|
||||
if err := repo.CreateTaskResourceCleanupJob(ctx, job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := svc.processTaskResourceCleanupJob(ctx, job.ID); err == nil {
|
||||
t.Fatal("cleanup succeeded after source capture failed")
|
||||
}
|
||||
if cleanup.cleanupCalled {
|
||||
t.Fatal("worktree cleanup ran after source capture failed")
|
||||
}
|
||||
}
|
||||
@@ -545,8 +545,9 @@ func TestSSHReclaimRetryReRunsTheProbe(t *testing.T) {
|
||||
|
||||
taskID, env := newReclaimTask(t, taskSvc, "Retrying task")
|
||||
snapshot := taskResourceCleanupSnapshot{
|
||||
TaskEnvironment: env,
|
||||
SSHTaskDirs: []sshReclaimTarget{enabledReclaimTarget()},
|
||||
TaskEnvironment: env,
|
||||
SSHTaskDirs: []sshReclaimTarget{enabledReclaimTarget()},
|
||||
ArchiveSourceManifestCaptured: true,
|
||||
}
|
||||
job := newReclaimJob(t, repo, taskID, models.TaskResourceCleanupTriggerDelete, snapshot)
|
||||
|
||||
|
||||
@@ -146,6 +146,17 @@ func TestDeleteTaskWithDiscardConsentPersistsAndCleansDirtyWorktree(t *testing.T
|
||||
}); err != nil {
|
||||
t.Fatalf("delete task with discard consent: %v", err)
|
||||
}
|
||||
var jobID string
|
||||
if err := repo.DB().QueryRowContext(ctx, `
|
||||
SELECT id FROM task_resource_cleanup_jobs
|
||||
WHERE task_id = ? AND trigger = 'delete'
|
||||
ORDER BY created_at DESC LIMIT 1
|
||||
`, taskID).Scan(&jobID); err != nil {
|
||||
t.Fatalf("load delete cleanup job: %v", err)
|
||||
}
|
||||
if err := svc.processTaskResourceCleanupJob(ctx, jobID); err != nil {
|
||||
t.Fatalf("process delete cleanup job: %v", err)
|
||||
}
|
||||
var encodedSnapshot string
|
||||
if err := repo.DB().QueryRowContext(ctx, `
|
||||
SELECT resource_snapshot FROM task_resource_cleanup_jobs
|
||||
@@ -161,16 +172,15 @@ func TestDeleteTaskWithDiscardConsentPersistsAndCleansDirtyWorktree(t *testing.T
|
||||
if !snapshot.DiscardWorktreeChanges {
|
||||
t.Fatal("cleanup snapshot omitted discard consent")
|
||||
}
|
||||
var jobID string
|
||||
if err := repo.DB().QueryRowContext(ctx, `
|
||||
SELECT id FROM task_resource_cleanup_jobs
|
||||
WHERE task_id = ? AND trigger = 'delete'
|
||||
ORDER BY created_at DESC LIMIT 1
|
||||
`, taskID).Scan(&jobID); err != nil {
|
||||
t.Fatalf("load delete cleanup job: %v", err)
|
||||
if len(snapshot.ArchiveSourceManifest) != 1 || snapshot.ArchiveSourceManifest[0].WorktreeID != wt.ID {
|
||||
t.Fatalf("delete cleanup snapshot omitted task worktree source evidence: %+v", snapshot.ArchiveSourceManifest)
|
||||
}
|
||||
if err := svc.processTaskResourceCleanupJob(ctx, jobID); err != nil {
|
||||
t.Fatalf("process delete cleanup job: %v", err)
|
||||
retrieved, err := svc.GetTaskSourceManifest(ctx, taskID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetTaskSourceManifest after delete: %v", err)
|
||||
}
|
||||
if len(retrieved) != 1 || retrieved[0].CleanupJobID == "" || retrieved[0].WorktreeID != wt.ID {
|
||||
t.Fatalf("retrieved delete source manifest = %+v, want durable task evidence", retrieved)
|
||||
}
|
||||
if _, statErr := os.Stat(wt.Path); !os.IsNotExist(statErr) {
|
||||
t.Fatalf("consented cleanup left worktree on disk: %s (stat err = %v)", wt.Path, statErr)
|
||||
@@ -185,6 +195,12 @@ func (dirtyWorktreeCleanupFailure) GetAllByTaskID(context.Context, string) ([]*w
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (dirtyWorktreeCleanupFailure) CaptureArchiveSourceManifests(
|
||||
ctx context.Context, worktrees []*worktree.Worktree,
|
||||
) (map[string]worktree.ArchiveSourceManifest, error) {
|
||||
return (&recordingWorktreeCleanup{}).CaptureArchiveSourceManifests(ctx, worktrees)
|
||||
}
|
||||
|
||||
func (dirtyWorktreeCleanupFailure) CleanupWorktrees(context.Context, []*worktree.Worktree) error {
|
||||
return fmt.Errorf("cleanup worktrees: %w", worktree.ErrDirtyWorktreeCleanup)
|
||||
}
|
||||
|
||||
@@ -74,6 +74,12 @@ type WorktreeCleanupIdentityProvider interface {
|
||||
CaptureCleanupHeadOIDs(ctx context.Context, worktrees []*worktree.Worktree) (map[string]string, error)
|
||||
}
|
||||
|
||||
// WorktreeArchiveSourceManifestProvider captures the archive-time source
|
||||
// evidence required before an owned checkout can be removed.
|
||||
type WorktreeArchiveSourceManifestProvider interface {
|
||||
CaptureArchiveSourceManifests(ctx context.Context, worktrees []*worktree.Worktree) (map[string]worktree.ArchiveSourceManifest, error)
|
||||
}
|
||||
|
||||
// WorktreeDirtyInspector reports local changes before a task deletion mutates
|
||||
// task rows or persists a cleanup job.
|
||||
type WorktreeDirtyInspector interface {
|
||||
|
||||
@@ -520,7 +520,7 @@ func (s *Service) prepareWorkspaceDeleteTaskCleanup(ctx context.Context, task *m
|
||||
ctx, task.ID, models.TaskResourceCleanupTriggerWorkspaceDelete,
|
||||
newTaskResourceCleanupOperationID(models.TaskResourceCleanupTriggerWorkspaceDelete, task.ID),
|
||||
cleanup.sessions, cleanup.worktrees, cleanup.stopTargets, cleanup.attachments,
|
||||
taskEnvironmentCleanup{env: cleanup.taskEnv, deleteRow: false}, true, true, "",
|
||||
taskEnvironmentCleanup{env: cleanup.taskEnv, deleteRow: false}, true, true, task.WorkspaceID,
|
||||
)
|
||||
return cleanup, err
|
||||
}
|
||||
|
||||
@@ -2439,7 +2439,7 @@ func (s *Service) ArchiveTask(ctx context.Context, id string) error {
|
||||
envCleanup := taskEnvironmentCleanup{env: taskEnv, deleteRow: false, preserveBranches: true}
|
||||
cleanupJob, err := s.persistTaskResourceCleanup(
|
||||
archiveCtx, id, models.TaskResourceCleanupTriggerArchive, "",
|
||||
sessions, worktrees, stopTargets, nil, envCleanup, true, true, "",
|
||||
sessions, worktrees, stopTargets, nil, envCleanup, true, true, task.WorkspaceID,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -3108,7 +3108,7 @@ func (s *Service) deleteTaskWithReasonAndDBDelete(
|
||||
env: taskEnv, deleteRow: false, discardWorktreeChanges: options.DiscardWorktreeChanges,
|
||||
}
|
||||
cleanupJob, err := s.persistTaskResourceCleanup(
|
||||
operationCtx, id, trigger, "", sessions, worktrees, stopTargets, attachments, envCleanup, true, true, "",
|
||||
operationCtx, id, trigger, "", sessions, worktrees, stopTargets, attachments, envCleanup, true, true, task.WorkspaceID,
|
||||
)
|
||||
if err != nil {
|
||||
return false, err
|
||||
|
||||
@@ -1759,7 +1759,7 @@ func TestService_DeleteTaskPreservesExecutorRunningWhenStopFails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestService_DeleteTaskCleansSuccessfulSessionResourcesOnPartialStopFailure(t *testing.T) {
|
||||
func TestService_DeleteTaskDefersResourceCleanupOnPartialStopFailure(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
stopper := newRecordingTaskExecutionStopper()
|
||||
@@ -1828,21 +1828,21 @@ func TestService_DeleteTaskCleansSuccessfulSessionResourcesOnPartialStopFailure(
|
||||
t.Fatalf("unexpected StopExecution calls: %#v", calls)
|
||||
}
|
||||
waitForCleanupDone(t, svc)
|
||||
if _, err := os.Stat(filepath.Join(quickChatDir, "session-ok")); !os.IsNotExist(err) {
|
||||
t.Fatalf("successful session quick-chat directory should be removed, got %v", err)
|
||||
if _, err := os.Stat(filepath.Join(quickChatDir, "session-ok")); err != nil {
|
||||
t.Fatalf("successful session quick-chat directory should remain until retry, got %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(quickChatDir, "session-failed")); err != nil {
|
||||
t.Fatalf("failed session quick-chat directory should remain: %v", err)
|
||||
}
|
||||
cleanedIDs := cleanup.cleanedIDs()
|
||||
if len(cleanedIDs) != 1 || cleanedIDs[0] != "wt-ok" {
|
||||
t.Fatalf("expected only successful session worktree cleanup, got %#v", cleanedIDs)
|
||||
if len(cleanedIDs) != 0 {
|
||||
t.Fatalf("worktrees should remain until source capture can retry, got %#v", cleanedIDs)
|
||||
}
|
||||
if _, err := repo.GetExecutorRunningBySessionID(ctx, "session-failed"); err != nil {
|
||||
t.Fatalf("failed session executor row should remain retryable: %v", err)
|
||||
}
|
||||
if _, err := repo.GetExecutorRunningBySessionID(ctx, "session-ok"); err == nil {
|
||||
t.Fatal("successful session executor row should be removed")
|
||||
if _, err := repo.GetExecutorRunningBySessionID(ctx, "session-ok"); err != nil {
|
||||
t.Fatalf("successful session executor row should remain retryable until cleanup completes: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2818,6 +2818,23 @@ func (c *recordingWorktreeCleanup) GetAllByTaskID(_ context.Context, taskID stri
|
||||
return c.worktrees, nil
|
||||
}
|
||||
|
||||
func (c *recordingWorktreeCleanup) CaptureArchiveSourceManifests(
|
||||
_ context.Context, worktrees []*worktree.Worktree,
|
||||
) (map[string]worktree.ArchiveSourceManifest, error) {
|
||||
manifests := make(map[string]worktree.ArchiveSourceManifest, len(worktrees))
|
||||
for _, wt := range worktrees {
|
||||
if wt == nil {
|
||||
continue
|
||||
}
|
||||
manifests[wt.ID] = worktree.ArchiveSourceManifest{
|
||||
TaskID: wt.TaskID, TaskEnvironmentID: wt.TaskEnvironmentID,
|
||||
WorktreeID: wt.ID, RepositoryID: wt.RepositoryID,
|
||||
HeadOID: "test-head", IndexStateSHA256: "test-index", PathPresent: true,
|
||||
}
|
||||
}
|
||||
return manifests, nil
|
||||
}
|
||||
|
||||
func (c *recordingWorktreeCleanup) CleanupWorktrees(_ context.Context, worktrees []*worktree.Worktree) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
package worktree
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
storageworkspaces "github.com/kandev/kandev/internal/system/storage/workspaces"
|
||||
)
|
||||
|
||||
// ArchiveSourceManifest is the content-identity record captured before an
|
||||
// archived worktree is removed. It deliberately stores digests, never file
|
||||
// contents, so durable cleanup evidence cannot retain source secrets.
|
||||
type ArchiveSourceManifest struct {
|
||||
TaskID string `json:"task_id"`
|
||||
TaskEnvironmentID string `json:"task_environment_id,omitempty"`
|
||||
WorktreeID string `json:"worktree_id"`
|
||||
RepositoryID string `json:"repository_id"`
|
||||
HeadOID string `json:"head_oid"`
|
||||
IndexStateSHA256 string `json:"index_state_sha256"`
|
||||
PathPresent bool `json:"path_present"`
|
||||
Entries []ArchiveSourceManifestEntry `json:"entries,omitempty"`
|
||||
}
|
||||
|
||||
// ArchiveSourceManifestEntry identifies one changed path without retaining its
|
||||
// source bytes. A missing digest represents a deleted path.
|
||||
type ArchiveSourceManifestEntry struct {
|
||||
Path string `json:"path"`
|
||||
Status string `json:"status"`
|
||||
ContentSHA256 string `json:"content_sha256,omitempty"`
|
||||
}
|
||||
|
||||
// CaptureArchiveSourceManifests reads the git state of exact registered
|
||||
// worktrees before archive cleanup. Any uncertain ownership, git metadata, or
|
||||
// filesystem read fails the caller closed.
|
||||
func (m *Manager) CaptureArchiveSourceManifests(
|
||||
ctx context.Context, worktrees []*Worktree,
|
||||
) (map[string]ArchiveSourceManifest, error) {
|
||||
manifests := make(map[string]ArchiveSourceManifest, len(worktrees))
|
||||
for _, wt := range worktrees {
|
||||
if wt == nil {
|
||||
continue
|
||||
}
|
||||
if wt.ID == "" || wt.TaskID == "" || wt.RepositoryID == "" || wt.Path == "" || wt.RepositoryPath == "" {
|
||||
return nil, fmt.Errorf("archive source manifest has incomplete worktree identity")
|
||||
}
|
||||
pathPresent, err := cleanupPathPresent(wt.Path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("inspect archive source worktree path for %s: %w", wt.ID, err)
|
||||
}
|
||||
if !pathPresent {
|
||||
manifest, captureErr := m.captureAbsentArchiveSourceManifest(ctx, wt)
|
||||
if captureErr != nil {
|
||||
return nil, captureErr
|
||||
}
|
||||
manifests[wt.ID] = manifest
|
||||
continue
|
||||
}
|
||||
manifest, captureErr := m.capturePresentArchiveSourceManifest(ctx, wt)
|
||||
if captureErr != nil {
|
||||
return nil, captureErr
|
||||
}
|
||||
manifests[wt.ID] = manifest
|
||||
}
|
||||
return manifests, nil
|
||||
}
|
||||
|
||||
func (m *Manager) captureAbsentArchiveSourceManifest(ctx context.Context, wt *Worktree) (ArchiveSourceManifest, error) {
|
||||
manifest := ArchiveSourceManifest{TaskID: wt.TaskID, TaskEnvironmentID: wt.TaskEnvironmentID, WorktreeID: wt.ID, RepositoryID: wt.RepositoryID}
|
||||
branch := strings.TrimSpace(wt.Branch)
|
||||
if branch == "" {
|
||||
return manifest, nil
|
||||
}
|
||||
oid, found, err := m.captureCleanupBranchOID(ctx, wt.RepositoryPath, "refs/heads/"+branch)
|
||||
if err != nil {
|
||||
return ArchiveSourceManifest{}, fmt.Errorf("capture absent archive source branch for %s: %w", wt.ID, err)
|
||||
}
|
||||
if found {
|
||||
manifest.HeadOID = oid
|
||||
}
|
||||
return manifest, nil
|
||||
}
|
||||
|
||||
func (m *Manager) capturePresentArchiveSourceManifest(ctx context.Context, wt *Worktree) (ArchiveSourceManifest, error) {
|
||||
if err := m.validateExistingWorktreePathOwner(wt.Path, wt); err != nil {
|
||||
return ArchiveSourceManifest{}, fmt.Errorf("validate archive source manifest owner for %s: %w", wt.ID, err)
|
||||
}
|
||||
gitDir, err := m.runBoundedGitInspect(ctx, wt.Path, "rev-parse", "--git-dir")
|
||||
if err != nil {
|
||||
return ArchiveSourceManifest{}, fmt.Errorf("verify archive source worktree registration for %s: %w", wt.ID, err)
|
||||
}
|
||||
if filepath.Clean(strings.TrimSpace(gitDir)) == ".git" {
|
||||
return ArchiveSourceManifest{}, fmt.Errorf("archive source manifest path is a primary repository, not a registered worktree")
|
||||
}
|
||||
if err := m.validateArchiveWorktreeRegistration(ctx, wt); err != nil {
|
||||
return ArchiveSourceManifest{}, fmt.Errorf("validate archive source worktree registration for %s: %w", wt.ID, err)
|
||||
}
|
||||
head, err := m.runBoundedGitInspect(ctx, wt.Path, "rev-parse", "--verify", "HEAD^{commit}")
|
||||
if err != nil {
|
||||
return ArchiveSourceManifest{}, fmt.Errorf("capture archive source HEAD for %s: %w", wt.ID, err)
|
||||
}
|
||||
indexStage, err := m.runBoundedGitInspect(ctx, wt.Path, "ls-files", "--stage", "-z")
|
||||
if err != nil {
|
||||
return ArchiveSourceManifest{}, fmt.Errorf("capture archive source index for %s: %w", wt.ID, err)
|
||||
}
|
||||
indexState := sha256.Sum256([]byte(indexStage))
|
||||
status, err := m.runBoundedGitInspect(ctx, wt.Path, "status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching")
|
||||
if err != nil {
|
||||
return ArchiveSourceManifest{}, fmt.Errorf("capture archive source status for %s: %w", wt.ID, err)
|
||||
}
|
||||
entries, err := archiveSourceManifestEntries(wt.Path, status)
|
||||
if err != nil {
|
||||
return ArchiveSourceManifest{}, fmt.Errorf("capture archive source entries for %s: %w", wt.ID, err)
|
||||
}
|
||||
return ArchiveSourceManifest{TaskID: wt.TaskID, TaskEnvironmentID: wt.TaskEnvironmentID, WorktreeID: wt.ID, RepositoryID: wt.RepositoryID, HeadOID: strings.TrimSpace(head), IndexStateSHA256: fmt.Sprintf("%x", indexState), PathPresent: true, Entries: entries}, nil
|
||||
}
|
||||
|
||||
func (m *Manager) validateArchiveWorktreeRegistration(ctx context.Context, wt *Worktree) error {
|
||||
if err := validateArchiveWorktreeGitDirBackpointer(wt.Path, ctx, m); err != nil {
|
||||
return err
|
||||
}
|
||||
worktreeCommonDir, err := m.runBoundedGitInspect(ctx, wt.Path, "rev-parse", "--path-format=absolute", "--git-common-dir")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repositoryCommonDir, err := m.runBoundedGitInspect(ctx, wt.RepositoryPath, "rev-parse", "--path-format=absolute", "--git-common-dir")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if filepath.Clean(strings.TrimSpace(worktreeCommonDir)) != filepath.Clean(strings.TrimSpace(repositoryCommonDir)) {
|
||||
return fmt.Errorf("worktree belongs to a different repository")
|
||||
}
|
||||
registered, err := m.runBoundedGitInspect(ctx, wt.RepositoryPath, "worktree", "list", "--porcelain", "-z")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
want, err := filepath.Abs(wt.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, field := range strings.Split(registered, "\x00") {
|
||||
if strings.HasPrefix(field, "worktree ") && filepath.Clean(strings.TrimPrefix(field, "worktree ")) == filepath.Clean(want) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("worktree path is not registered in the recorded repository")
|
||||
}
|
||||
|
||||
func validateArchiveWorktreeGitDirBackpointer(worktreePath string, ctx context.Context, manager *Manager) error {
|
||||
gitDir, err := manager.runBoundedGitInspect(ctx, worktreePath, "rev-parse", "--path-format=absolute", "--git-dir")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gitDir = filepath.Clean(strings.TrimSpace(gitDir))
|
||||
worktreeRoot, err := openArchiveSourceDirectory(filepath.Dir(worktreePath), worktreePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open registered worktree: %w", err)
|
||||
}
|
||||
marker, err := readArchiveSourcePointerFile(worktreeRoot, ".git")
|
||||
closeErr := worktreeRoot.Close()
|
||||
if err != nil {
|
||||
return fmt.Errorf("read worktree gitdir pointer: %w", err)
|
||||
}
|
||||
if closeErr != nil {
|
||||
return fmt.Errorf("close worktree gitdir pointer: %w", closeErr)
|
||||
}
|
||||
pointedGitDir, ok := archiveSourceGitDirPointer(string(marker), worktreePath)
|
||||
if !ok || pointedGitDir != gitDir {
|
||||
return fmt.Errorf("worktree gitdir pointer does not match git metadata")
|
||||
}
|
||||
|
||||
gitMetadata, err := openArchiveSourceDirectory(filepath.Dir(gitDir), gitDir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open worktree git metadata: %w", err)
|
||||
}
|
||||
defer func() { _ = gitMetadata.Close() }()
|
||||
backpointer, err := readArchiveSourcePointerFile(gitMetadata, "gitdir")
|
||||
if err != nil {
|
||||
return fmt.Errorf("read worktree git metadata backpointer: %w", err)
|
||||
}
|
||||
pointedWorktreeGitFile, ok := archiveSourceResolvePath(string(backpointer), filepath.Dir(gitDir))
|
||||
wantWorktreeGitFile, absErr := filepath.Abs(filepath.Join(worktreePath, ".git"))
|
||||
if absErr != nil {
|
||||
return absErr
|
||||
}
|
||||
if !ok || pointedWorktreeGitFile != filepath.Clean(wantWorktreeGitFile) {
|
||||
return fmt.Errorf("worktree git metadata belongs to a different worktree path")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readArchiveSourcePointerFile(directory storageworkspaces.DirectoryHandle, name string) ([]byte, error) {
|
||||
mode, err := directory.LstatEntry(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !mode.IsRegular() {
|
||||
return nil, fmt.Errorf("%s is not a regular file", name)
|
||||
}
|
||||
return directory.ReadFile(name)
|
||||
}
|
||||
|
||||
func archiveSourceGitDirPointer(content, relativeTo string) (string, bool) {
|
||||
content = strings.TrimSpace(content)
|
||||
if !strings.HasPrefix(content, "gitdir: ") {
|
||||
return "", false
|
||||
}
|
||||
pointer := strings.TrimSpace(strings.TrimPrefix(content, "gitdir: "))
|
||||
if pointer == "" {
|
||||
return "", false
|
||||
}
|
||||
return archiveSourceResolvePath(pointer, relativeTo)
|
||||
}
|
||||
|
||||
func archiveSourceResolvePath(pointer, relativeTo string) (string, bool) {
|
||||
pointer = strings.TrimSpace(pointer)
|
||||
if pointer == "" {
|
||||
return "", false
|
||||
}
|
||||
if !filepath.IsAbs(pointer) {
|
||||
pointer = filepath.Join(relativeTo, pointer)
|
||||
}
|
||||
abs, err := filepath.Abs(pointer)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
return filepath.Clean(abs), true
|
||||
}
|
||||
|
||||
func archiveSourceManifestEntries(root, output string) ([]ArchiveSourceManifestEntry, error) {
|
||||
fields := strings.Split(output, "\x00")
|
||||
entries := make([]ArchiveSourceManifestEntry, 0, len(fields))
|
||||
for index := 0; index < len(fields); index++ {
|
||||
if fields[index] == "" {
|
||||
continue
|
||||
}
|
||||
entry, consumed, err := archiveSourceManifestEntry(root, fields, index)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries = append(entries, entry)
|
||||
index += consumed
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func archiveSourceManifestEntry(root string, fields []string, index int) (ArchiveSourceManifestEntry, int, error) {
|
||||
field := fields[index]
|
||||
if len(field) < 4 || field[2] != ' ' {
|
||||
return ArchiveSourceManifestEntry{}, 0, fmt.Errorf("invalid git status record")
|
||||
}
|
||||
path := field[3:]
|
||||
consumed := 0
|
||||
if field[0] == 'R' || field[0] == 'C' || field[1] == 'R' || field[1] == 'C' {
|
||||
if index+1 >= len(fields) || fields[index+1] == "" {
|
||||
return ArchiveSourceManifestEntry{}, 0, fmt.Errorf("git rename or copy record lacks its original path")
|
||||
}
|
||||
consumed = 1
|
||||
}
|
||||
if err := archiveSourceManifestPath(root, path); err != nil {
|
||||
return ArchiveSourceManifestEntry{}, 0, err
|
||||
}
|
||||
entry := ArchiveSourceManifestEntry{Path: path, Status: field[:2]}
|
||||
digest, err := archiveSourceManifestDigest(root, path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) && (field[0] == 'D' || field[1] == 'D') {
|
||||
return entry, consumed, nil
|
||||
}
|
||||
if os.IsNotExist(err) {
|
||||
return ArchiveSourceManifestEntry{}, 0, fmt.Errorf("source path disappeared before content identity was captured")
|
||||
}
|
||||
return ArchiveSourceManifestEntry{}, 0, err
|
||||
}
|
||||
entry.ContentSHA256 = digest
|
||||
return entry, consumed, nil
|
||||
}
|
||||
|
||||
func archiveSourceManifestPath(root, path string) error {
|
||||
if path == "" || filepath.IsAbs(path) {
|
||||
return fmt.Errorf("invalid source path")
|
||||
}
|
||||
rel, err := filepath.Rel(root, filepath.Join(root, path))
|
||||
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
||||
return fmt.Errorf("source path escapes worktree")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func archiveSourceManifestDigest(root, path string) (string, error) {
|
||||
parent, name, err := archiveSourceManifestOpenParent(root, path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = parent.Close() }()
|
||||
mode, err := parent.LstatEntry(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if mode&os.ModeSymlink != 0 {
|
||||
target, readErr := parent.ReadLink(name)
|
||||
if readErr != nil {
|
||||
return "", readErr
|
||||
}
|
||||
sum := sha256.Sum256([]byte("symlink:\x00" + target))
|
||||
return fmt.Sprintf("%x", sum), nil
|
||||
}
|
||||
if !mode.IsRegular() {
|
||||
if !mode.IsDir() {
|
||||
return "", fmt.Errorf("source path is not a regular file or directory")
|
||||
}
|
||||
directory, err := parent.OpenSubdirectory(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = directory.Close() }()
|
||||
digest, err := archiveSourceManifestDirectoryDigestHandle(directory)
|
||||
return digest, err
|
||||
}
|
||||
f, err := parent.OpenFile(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return archiveSourceManifestReadDigest(f)
|
||||
}
|
||||
|
||||
type archiveSourceManifestDirectoryRecord struct {
|
||||
path string
|
||||
kind string
|
||||
digest string
|
||||
target string
|
||||
}
|
||||
|
||||
const (
|
||||
archiveSourceManifestKindSymlink = "symlink"
|
||||
archiveSourceManifestKindDirectory = "directory"
|
||||
archiveSourceManifestKindFile = "file"
|
||||
)
|
||||
|
||||
func archiveSourceManifestDirectoryDigestHandle(root storageworkspaces.DirectoryHandle) (string, error) {
|
||||
records := make([]archiveSourceManifestDirectoryRecord, 0)
|
||||
if err := archiveSourceManifestCollectDirectory(root, "", &records); err != nil {
|
||||
return "", err
|
||||
}
|
||||
sort.Slice(records, func(i, j int) bool { return records[i].path < records[j].path })
|
||||
h := sha256.New()
|
||||
for _, record := range records {
|
||||
_, _ = io.WriteString(h, record.path+"\x00")
|
||||
switch record.kind {
|
||||
case archiveSourceManifestKindSymlink:
|
||||
_, _ = io.WriteString(h, "symlink:\x00"+record.target+"\x00")
|
||||
case archiveSourceManifestKindDirectory:
|
||||
_, _ = io.WriteString(h, "directory\x00")
|
||||
case archiveSourceManifestKindFile:
|
||||
_, _ = io.WriteString(h, "file:\x00"+record.digest+"\x00")
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("%x", h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func archiveSourceManifestCollectDirectory(
|
||||
directory storageworkspaces.DirectoryHandle,
|
||||
prefix string,
|
||||
records *[]archiveSourceManifestDirectoryRecord,
|
||||
) error {
|
||||
entries, err := directory.ReadDir()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
|
||||
for _, entry := range entries {
|
||||
name := entry.Name()
|
||||
if name == ".git" {
|
||||
continue
|
||||
}
|
||||
mode, err := directory.LstatEntry(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
path := name
|
||||
if prefix != "" {
|
||||
path = filepath.Join(prefix, name)
|
||||
}
|
||||
if err := archiveSourceManifestCollectEntry(directory, name, path, mode, records); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func archiveSourceManifestCollectEntry(
|
||||
directory storageworkspaces.DirectoryHandle,
|
||||
name, path string,
|
||||
mode os.FileMode,
|
||||
records *[]archiveSourceManifestDirectoryRecord,
|
||||
) error {
|
||||
switch {
|
||||
case mode&os.ModeSymlink != 0:
|
||||
target, err := directory.ReadLink(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*records = append(*records, archiveSourceManifestDirectoryRecord{
|
||||
path: path, kind: archiveSourceManifestKindSymlink, target: target,
|
||||
})
|
||||
case mode.IsDir():
|
||||
return archiveSourceManifestCollectSubdirectory(directory, name, path, records)
|
||||
case mode.IsRegular():
|
||||
return archiveSourceManifestCollectFile(directory, name, path, records)
|
||||
default:
|
||||
return fmt.Errorf("directory source path is not a regular file, directory, or symlink")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func archiveSourceManifestCollectSubdirectory(
|
||||
directory storageworkspaces.DirectoryHandle,
|
||||
name, path string,
|
||||
records *[]archiveSourceManifestDirectoryRecord,
|
||||
) error {
|
||||
*records = append(*records, archiveSourceManifestDirectoryRecord{
|
||||
path: path, kind: archiveSourceManifestKindDirectory,
|
||||
})
|
||||
child, err := directory.OpenSubdirectory(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
collectErr := archiveSourceManifestCollectDirectory(child, path, records)
|
||||
closeErr := child.Close()
|
||||
if collectErr != nil {
|
||||
return collectErr
|
||||
}
|
||||
return closeErr
|
||||
}
|
||||
|
||||
func archiveSourceManifestCollectFile(
|
||||
directory storageworkspaces.DirectoryHandle,
|
||||
name, path string,
|
||||
records *[]archiveSourceManifestDirectoryRecord,
|
||||
) error {
|
||||
file, err := directory.OpenFile(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
digest, err := archiveSourceManifestReadDigest(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*records = append(*records, archiveSourceManifestDirectoryRecord{
|
||||
path: path, kind: archiveSourceManifestKindFile, digest: digest,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func archiveSourceManifestOpenParent(
|
||||
root, path string,
|
||||
) (storageworkspaces.DirectoryHandle, string, error) {
|
||||
if err := archiveSourceManifestPath(root, path); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
absolute, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
directory, err := openArchiveSourceDirectory(filepath.Dir(absolute), absolute)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
components := strings.Split(filepath.ToSlash(filepath.Clean(path)), "/")
|
||||
for _, component := range components[:len(components)-1] {
|
||||
child, err := directory.OpenSubdirectory(component)
|
||||
if err != nil {
|
||||
_ = directory.Close()
|
||||
return nil, "", err
|
||||
}
|
||||
_ = directory.Close()
|
||||
directory = child
|
||||
}
|
||||
return directory, components[len(components)-1], nil
|
||||
}
|
||||
|
||||
func archiveSourceManifestFileDigest(root, path string) (string, error) {
|
||||
rootPath, err := filepath.Rel(root, filepath.Dir(path))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
parent, err := openArchiveSourceDirectory(filepath.Dir(root), filepath.Join(root, rootPath))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = parent.Close() }()
|
||||
mode, err := parent.LstatEntry(filepath.Base(path))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !mode.IsRegular() {
|
||||
return "", fmt.Errorf("source path is not a regular file")
|
||||
}
|
||||
f, err := parent.OpenFile(filepath.Base(path))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return archiveSourceManifestReadDigest(f)
|
||||
}
|
||||
|
||||
func openArchiveSourceDirectory(root, target string) (storageworkspaces.DirectoryHandle, error) {
|
||||
return storageworkspaces.OpenDirectoryNoFollow(root, target)
|
||||
}
|
||||
|
||||
func archiveSourceManifestReadDigest(f io.ReadCloser) (string, error) {
|
||||
h := sha256.New()
|
||||
_, copyErr := io.Copy(h, f)
|
||||
closeErr := f.Close()
|
||||
if copyErr != nil {
|
||||
return "", copyErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return "", closeErr
|
||||
}
|
||||
return fmt.Sprintf("%x", h.Sum(nil)), nil
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
package worktree
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestArchiveManifestRejectsForeignRepositoryPath(t *testing.T) {
|
||||
foreignRepo := initGitRepoForWorktreeTest(t)
|
||||
if err := os.WriteFile(filepath.Join(foreignRepo, "foreign-secret.txt"), []byte("secret"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest, err := mgr.CaptureArchiveSourceManifests(context.Background(), []*Worktree{{
|
||||
ID: "recorded-worktree", TaskID: "recorded-task", RepositoryID: "recorded-repository",
|
||||
Path: foreignRepo, RepositoryPath: foreignRepo,
|
||||
}})
|
||||
if err == nil {
|
||||
t.Fatalf("accepted foreign repository path as task worktree: %+v", manifest)
|
||||
}
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.4
|
||||
func TestArchiveManifestRejectsMissingGitMetadata(t *testing.T) {
|
||||
repo := initGitRepoForWorktreeTest(t)
|
||||
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = mgr.CaptureArchiveSourceManifests(context.Background(), []*Worktree{{
|
||||
ID: "wt", TaskID: "task", RepositoryID: "repo", Path: t.TempDir(), RepositoryPath: repo,
|
||||
}})
|
||||
if err == nil {
|
||||
t.Fatal("captured a worktree path without Git metadata")
|
||||
}
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.2
|
||||
func TestArchiveManifestRejectsForeignLinkedWorktree(t *testing.T) {
|
||||
recordedRepo := initGitRepoForWorktreeTest(t)
|
||||
foreignRepo := initGitRepoForWorktreeTest(t)
|
||||
foreignWorktree := filepath.Join(t.TempDir(), "foreign-worktree")
|
||||
runGit(t, foreignRepo, "worktree", "add", foreignWorktree, "feature/pr-branch")
|
||||
if err := os.WriteFile(filepath.Join(foreignWorktree, "foreign-secret.txt"), []byte("secret"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest, err := mgr.CaptureArchiveSourceManifests(context.Background(), []*Worktree{{
|
||||
ID: "recorded-worktree", TaskID: "recorded-task", RepositoryID: "recorded-repository",
|
||||
Path: foreignWorktree, RepositoryPath: recordedRepo,
|
||||
}})
|
||||
if err == nil {
|
||||
t.Fatalf("accepted foreign linked worktree as task source: %+v", manifest)
|
||||
}
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.2
|
||||
func TestArchiveManifestRejectsSiblingWorktreeGitdir(t *testing.T) {
|
||||
repo := initGitRepoForWorktreeTest(t)
|
||||
firstPath := filepath.Join(t.TempDir(), "task-one")
|
||||
secondPath := filepath.Join(t.TempDir(), "task-two")
|
||||
runGit(t, repo, "worktree", "add", "-b", "feature/task-one", firstPath)
|
||||
runGit(t, repo, "worktree", "add", "-b", "feature/task-two", secondPath)
|
||||
if err := os.WriteFile(filepath.Join(secondPath, "task-two-only.txt"), []byte("task two"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, secondPath, "add", "task-two-only.txt")
|
||||
runGit(t, secondPath, "commit", "-m", "add task two file")
|
||||
secondGitPointer, err := os.ReadFile(filepath.Join(secondPath, ".git"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(firstPath, ".git"), secondGitPointer, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifest, err := mgr.CaptureArchiveSourceManifests(context.Background(), []*Worktree{{
|
||||
ID: "task-one-worktree", TaskID: "task-one", RepositoryID: "repo",
|
||||
Path: firstPath, RepositoryPath: repo,
|
||||
}})
|
||||
if err == nil {
|
||||
t.Fatalf("captured sibling worktree state under task-one identity: %+v", manifest)
|
||||
}
|
||||
}
|
||||
|
||||
func TestArchiveManifestRejectsDisappearedUntrackedPath(t *testing.T) {
|
||||
entries, err := archiveSourceManifestEntries(t.TempDir(), "?? disappeared.txt\x00")
|
||||
if err == nil {
|
||||
t.Fatalf("accepted disappeared untracked path without content identity: %+v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.3
|
||||
func TestArchiveManifestCapturesIgnoredUntrackedFile(t *testing.T) {
|
||||
repo := initGitRepoForWorktreeTest(t)
|
||||
if err := os.WriteFile(filepath.Join(repo, ".gitignore"), []byte("ignored.env\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, repo, "add", ".gitignore")
|
||||
runGit(t, repo, "commit", "-m", "ignore generated file")
|
||||
worktreePath := filepath.Join(t.TempDir(), "task-worktree")
|
||||
runGit(t, repo, "worktree", "add", "-b", "feature/task", worktreePath)
|
||||
if err := os.WriteFile(filepath.Join(worktreePath, "ignored.env"), []byte("local value"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifests, err := mgr.CaptureArchiveSourceManifests(context.Background(), []*Worktree{{
|
||||
ID: "wt", TaskID: "task", RepositoryID: "repo", Path: worktreePath, RepositoryPath: repo,
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("capture ignored untracked source: %v", err)
|
||||
}
|
||||
runGit(t, repo, "worktree", "remove", "--force", worktreePath)
|
||||
if _, err := os.Stat(worktreePath); !os.IsNotExist(err) {
|
||||
t.Fatalf("worktree after cleanup: %v, want removed", err)
|
||||
}
|
||||
for _, entry := range manifests["wt"].Entries {
|
||||
if entry.Path == "ignored.env" && entry.ContentSHA256 != "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("ignored untracked file has no path and digest in manifest: %+v", manifests["wt"].Entries)
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.3
|
||||
func TestArchiveManifestCapturesIgnoredDirectoryContents(t *testing.T) {
|
||||
repo := initGitRepoForWorktreeTest(t)
|
||||
if err := os.WriteFile(filepath.Join(repo, ".gitignore"), []byte("cache/\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, repo, "add", ".gitignore")
|
||||
runGit(t, repo, "commit", "-m", "ignore generated directory")
|
||||
worktreePath := filepath.Join(t.TempDir(), "task-worktree")
|
||||
runGit(t, repo, "worktree", "add", "-b", "feature/task", worktreePath)
|
||||
cachePath := filepath.Join(worktreePath, "cache")
|
||||
if err := os.Mkdir(cachePath, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(cachePath, "data.txt"), []byte("local value"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status := runGit(t, worktreePath, "status", "--porcelain"); status != "" {
|
||||
t.Fatalf("fixture must be Git-clean, status = %q", status)
|
||||
}
|
||||
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifests, err := mgr.CaptureArchiveSourceManifests(context.Background(), []*Worktree{{
|
||||
ID: "wt", TaskID: "task", RepositoryID: "repo", Path: worktreePath, RepositoryPath: repo,
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("capture ignored directory source: %v", err)
|
||||
}
|
||||
runGit(t, repo, "worktree", "remove", "--force", worktreePath)
|
||||
if _, err := os.Stat(worktreePath); !os.IsNotExist(err) {
|
||||
t.Fatalf("worktree after cleanup: %v, want removed", err)
|
||||
}
|
||||
for _, entry := range manifests["wt"].Entries {
|
||||
if (entry.Path == "cache/" || entry.Path == "cache/data.txt") && entry.ContentSHA256 != "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("ignored directory has no path and content identity in manifest: %+v", manifests["wt"].Entries)
|
||||
}
|
||||
|
||||
func TestArchiveManifestFileDigestRejectsSymlink(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
outside := filepath.Join(t.TempDir(), "outside.txt")
|
||||
if err := os.WriteFile(outside, []byte("outside"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(root, "source.txt")
|
||||
if err := os.Symlink(outside, path); err != nil {
|
||||
t.Skipf("symlink creation is unavailable: %v", err)
|
||||
}
|
||||
if _, err := archiveSourceManifestFileDigest(root, path); err == nil {
|
||||
t.Fatal("archive source digest followed a symlink")
|
||||
}
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.6
|
||||
func TestArchiveManifestRejectsSymlinkedPathAncestor(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
foreign := t.TempDir()
|
||||
if err := os.Symlink("outside-target", filepath.Join(foreign, "secret-link")); err != nil {
|
||||
t.Skipf("symlink creation is unavailable: %v", err)
|
||||
}
|
||||
if err := os.Symlink(foreign, filepath.Join(root, "cache")); err != nil {
|
||||
t.Skipf("symlink creation is unavailable: %v", err)
|
||||
}
|
||||
// The status was captured before cache was replaced by a symlink.
|
||||
_, err := archiveSourceManifestEntries(root, "?? cache/secret-link\x00")
|
||||
if err == nil {
|
||||
t.Fatal("archive source manifest captured a path through a symlinked ancestor")
|
||||
}
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.3
|
||||
func TestArchiveManifestHandlesDeletedRenameDestination(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(root, "next.txt"), []byte("next"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries, err := archiveSourceManifestEntries(root, "RD renamed.txt\x00original.txt\x00?? next.txt\x00")
|
||||
if err != nil {
|
||||
t.Fatalf("parse staged rename with deleted destination: %v", err)
|
||||
}
|
||||
if len(entries) != 2 || entries[0].Path != "renamed.txt" || entries[0].Status != "RD" || entries[1].Path != "next.txt" {
|
||||
t.Fatalf("rename evidence = %+v, want one deleted destination", entries)
|
||||
}
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.3
|
||||
func TestArchiveManifestCapturesUnmergedIndex(t *testing.T) {
|
||||
repo := initGitRepoForWorktreeTest(t)
|
||||
if err := os.WriteFile(filepath.Join(repo, "conflict.txt"), []byte("base\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, repo, "add", "conflict.txt")
|
||||
runGit(t, repo, "commit", "-m", "base")
|
||||
worktreePath := filepath.Join(t.TempDir(), "task-worktree")
|
||||
runGit(t, repo, "worktree", "add", "-b", "feature/task", worktreePath)
|
||||
runGit(t, repo, "checkout", "-b", "feature/upstream")
|
||||
if err := os.WriteFile(filepath.Join(worktreePath, "conflict.txt"), []byte("task\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, worktreePath, "commit", "-am", "task")
|
||||
if err := os.WriteFile(filepath.Join(repo, "conflict.txt"), []byte("upstream\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, repo, "commit", "-am", "upstream")
|
||||
merge := exec.Command("git", "merge", "feature/conflict")
|
||||
merge.Dir = repo
|
||||
if err := merge.Run(); err == nil {
|
||||
t.Fatal("merge succeeded; expected an unmerged index")
|
||||
}
|
||||
merge = exec.Command("git", "merge", "feature/upstream")
|
||||
merge.Dir = worktreePath
|
||||
if err := merge.Run(); err == nil {
|
||||
t.Fatal("merge succeeded; expected an unmerged index")
|
||||
}
|
||||
|
||||
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manifests, err := mgr.CaptureArchiveSourceManifests(context.Background(), []*Worktree{{
|
||||
ID: "wt", TaskID: "task", RepositoryID: "repo", Path: worktreePath, RepositoryPath: repo,
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("capture unmerged index: %v", err)
|
||||
}
|
||||
manifest := manifests["wt"]
|
||||
if len(manifest.IndexStateSHA256) != 64 {
|
||||
t.Fatalf("unmerged index state digest = %q", manifest.IndexStateSHA256)
|
||||
}
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.4
|
||||
func TestArchiveManifestRejectsCorruptIndex(t *testing.T) {
|
||||
repo := initGitRepoForWorktreeTest(t)
|
||||
worktreePath := filepath.Join(t.TempDir(), "task-worktree")
|
||||
runGit(t, repo, "worktree", "add", "-b", "feature/task", worktreePath)
|
||||
indexPath := strings.TrimSpace(runGit(t, worktreePath, "rev-parse", "--path-format=absolute", "--git-path", "index"))
|
||||
if err := os.WriteFile(indexPath, []byte("corrupt index"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := mgr.CaptureArchiveSourceManifests(context.Background(), []*Worktree{{
|
||||
ID: "wt", TaskID: "task", RepositoryID: "repo", Path: worktreePath, RepositoryPath: repo,
|
||||
}}); err == nil {
|
||||
t.Fatal("captured source state with a corrupt Git index")
|
||||
}
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.3
|
||||
func TestArchiveManifestInspectionDoesNotWriteGitObjects(t *testing.T) {
|
||||
repo := initGitRepoForWorktreeTest(t)
|
||||
worktreePath := filepath.Join(t.TempDir(), "task-worktree")
|
||||
runGit(t, repo, "worktree", "add", "-b", "feature/task", worktreePath)
|
||||
if err := os.WriteFile(filepath.Join(worktreePath, "staged.txt"), []byte("staged"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, worktreePath, "add", "staged.txt")
|
||||
before := gitLooseObjectCount(t, repo)
|
||||
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := mgr.CaptureArchiveSourceManifests(context.Background(), []*Worktree{{
|
||||
ID: "wt", TaskID: "task", RepositoryID: "repo", Path: worktreePath, RepositoryPath: repo,
|
||||
}}); err != nil {
|
||||
t.Fatalf("capture staged source state: %v", err)
|
||||
}
|
||||
if after := gitLooseObjectCount(t, repo); after != before {
|
||||
t.Fatalf("capture wrote Git objects: count before=%d after=%d", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func gitLooseObjectCount(t *testing.T, repo string) int {
|
||||
t.Helper()
|
||||
output := runGit(t, repo, "count-objects", "-v")
|
||||
for _, line := range strings.Split(output, "\n") {
|
||||
if value, found := strings.CutPrefix(line, "count: "); found {
|
||||
count, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
}
|
||||
t.Fatal("git count-objects omitted the loose object count")
|
||||
return 0
|
||||
}
|
||||
|
||||
// @covers AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.3
|
||||
func TestArchiveManifestHashesDirtySubmoduleDirectory(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
submodule := filepath.Join(root, "module")
|
||||
if err := os.MkdirAll(submodule, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(submodule, ".git"), []byte("gitdir: ../.git/modules/module\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(submodule, "tracked.txt"), []byte("changed"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries, err := archiveSourceManifestEntries(root, " M module\x00")
|
||||
if err != nil {
|
||||
t.Fatalf("hash dirty submodule: %v", err)
|
||||
}
|
||||
if len(entries) != 1 || entries[0].ContentSHA256 == "" {
|
||||
t.Fatalf("submodule evidence = %+v", entries)
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,14 @@ package worktree
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
storageworkspaces "github.com/kandev/kandev/internal/system/storage/workspaces"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
)
|
||||
|
||||
@@ -69,6 +71,26 @@ func (h *postRemovalSwapDirectoryHandle) ReadFile(string) ([]byte, error) {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
|
||||
func (h *postRemovalSwapDirectoryHandle) OpenFile(string) (io.ReadCloser, error) {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
|
||||
func (h *postRemovalSwapDirectoryHandle) OpenSubdirectory(string) (storageworkspaces.DirectoryHandle, error) {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
|
||||
func (h *postRemovalSwapDirectoryHandle) LstatEntry(string) (os.FileMode, error) {
|
||||
return 0, os.ErrNotExist
|
||||
}
|
||||
|
||||
func (h *postRemovalSwapDirectoryHandle) ReadLink(string) (string, error) {
|
||||
return "", os.ErrNotExist
|
||||
}
|
||||
|
||||
func (h *postRemovalSwapDirectoryHandle) ReadDir() ([]os.DirEntry, error) {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
|
||||
func (h *postRemovalSwapDirectoryHandle) WriteFile(string, []byte, os.FileMode) error {
|
||||
return errors.New("fake directory handle does not support writes")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
status: done
|
||||
requirements:
|
||||
- REQ-TASKS-ARCHIVE-SOURCE-MANIFEST-001
|
||||
system_design:
|
||||
- ../../specs/tasks/system-design/archive-source-manifest.md
|
||||
---
|
||||
|
||||
# Implementation Plan: Task Cleanup Source Manifest
|
||||
|
||||
## Overview
|
||||
|
||||
Retain task-scoped Git source evidence at the cleanup boundary for archive and
|
||||
delete operations. Capture happens after runtime stop and is durably written
|
||||
through the cleanup job claim before destructive worktree cleanup. The manifest
|
||||
contains content identities, not source bytes, and remains retrievable through
|
||||
the authorized task audit route.
|
||||
|
||||
## Work order
|
||||
|
||||
- [Task 01: Capture and expose task cleanup source evidence](task-01-capture-task-cleanup-source-evidence.md)
|
||||
|
||||
## Risks and decisions
|
||||
|
||||
- Worktree identity is checked against both Git's common directory and its
|
||||
registration list for the persisted repository.
|
||||
- A successful empty inventory is distinguished from a not-yet-captured retry.
|
||||
- Staged-index records are hashed through Git's read-only listing command,
|
||||
including unmerged stages. Dirty submodules use a
|
||||
digest over sorted working-tree paths and identities.
|
||||
- Older archived cleanup rows are not reconstructed or described as clean.
|
||||
|
||||
## Verification strategy
|
||||
|
||||
- Run focused worktree capture and service cleanup lifecycle tests.
|
||||
- Run the task handler authorization test for the retrieval route.
|
||||
- Run docs specification validation and linked-delivery coverage.
|
||||
|
||||
## Verification Results
|
||||
|
||||
Local implementation checks passed; PR #3905 receives a fresh CI and review
|
||||
snapshot after the fixup commit is pushed.
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: "01-capture-task-cleanup-source-evidence"
|
||||
title: "Capture task cleanup source evidence"
|
||||
status: done
|
||||
wave: 1
|
||||
depends_on: []
|
||||
plan: "plan.md"
|
||||
requirements:
|
||||
- REQ-TASKS-ARCHIVE-SOURCE-MANIFEST-001
|
||||
acceptance_criteria:
|
||||
- AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.1
|
||||
- AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.2
|
||||
- AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.3
|
||||
- AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.4
|
||||
- AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.5
|
||||
- AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.6
|
||||
system_design:
|
||||
- ../../specs/tasks/system-design/archive-source-manifest.md
|
||||
---
|
||||
|
||||
# Task 01: Capture and expose task cleanup source evidence
|
||||
|
||||
## Outcome
|
||||
|
||||
Archive and delete cleanup persists a task-bound source manifest after runtime
|
||||
stop and before worktree removal. Authorized workspace callers can retrieve
|
||||
the retained evidence after task deletion.
|
||||
|
||||
## Scope
|
||||
|
||||
- Verify exact repository and registered worktree identity before capture.
|
||||
- Record Git and changed-path identities without storing source bytes, including
|
||||
read-only staged-index records, unmerged indexes, dirty submodules, symlinks,
|
||||
and rename status.
|
||||
- Persist the completed manifest under the claimed cleanup job before
|
||||
destructive work and reuse it on retries.
|
||||
- Keep the task-scoped route authorized and test its foreign-workspace denial.
|
||||
|
||||
## Exclusions
|
||||
|
||||
- Backfilling old cleanup records or asserting historical task cleanliness.
|
||||
- Public documentation or user-facing UI for the internal Coordinator audit
|
||||
route.
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
cd apps/backend && go test -count=1 -run '^TestArchiveManifest' ./internal/worktree
|
||||
cd apps/backend && go test -count=1 -run 'TestArchiveTaskCleanupPreservesTaskEnvironmentIdentity|TestDeleteTaskWithDiscardConsentPersistsAndCleansDirtyWorktree|TestTaskLifecycleCleanup_MissingWorktree' ./internal/task/service
|
||||
cd apps/backend && go test -count=1 -run '^TestHTTPGetArchiveSourceManifestDeniesForeignWorkspace$' ./internal/task/handlers
|
||||
python3 scripts/list-docs.py validate
|
||||
python3 scripts/lint-spec-files.py --all
|
||||
```
|
||||
|
||||
## Results
|
||||
|
||||
Completed in the PR fixup.
|
||||
|
||||
- Passed: `cd apps/backend && go test -count=1 -run '^TestArchiveManifest' ./internal/worktree`.
|
||||
This includes a staged-file regression that verifies inspection does not
|
||||
increase the repository's loose Git object count.
|
||||
- Passed: `cd apps/backend && go test -count=1 -run 'TestArchiveTaskCleanupPreservesTaskEnvironmentIdentity|TestDeleteTaskWithDiscardConsentPersistsAndCleansDirtyWorktree|TestTaskLifecycleCleanup_MissingWorktree|TestCleanupPersistsSourceManifestAfterStopBeforeWorktreeRemoval|TestCleanupCaptureFailureBlocksWorktreeRemoval|TestCleanupRetryReusesPersistedSourceManifest' ./internal/task/service`.
|
||||
- Passed: `cd apps/backend && go test -count=1 -run 'TestHTTPGetArchiveSourceManifestDeniesForeignWorkspace' ./internal/task/handlers`.
|
||||
- Passed under the race detector: the `TestArchiveManifest` worktree cases and the three cleanup boundary/retry cases above.
|
||||
- Passed: `cd apps/backend && golangci-lint run ./internal/worktree ./internal/task/service ./internal/task/handlers --new-from-rev=25271b6e7fc04344e3e8e851bc73257dd783e538 --timeout=5m`.
|
||||
- Passed: `python3 scripts/list-docs.py validate`,
|
||||
`python3 scripts/lint-spec-files.py --all`, and `git diff --check`.
|
||||
- Passed: `.github/scripts/pr-docs.cjs` `validateCoverage` accepted this changed
|
||||
work order for the backend cleanup and route paths.
|
||||
- The historical archived task rows are not represented as reconstructed or
|
||||
confirmed-clean evidence.
|
||||
@@ -94,6 +94,7 @@ signals, and task-scoped scheduling contracts.
|
||||
- [Task Terminal Persistence](requirements/task-terminal-persistence.md)
|
||||
- [Runtime Task-State Publication Order](requirements/runtime-state-publication-order.md)
|
||||
- [Session Delete Preserves Task Workspaces](requirements/session-delete-resource-cleanup.md)
|
||||
- [Task Cleanup Source Manifest](requirements/archive-source-manifest.md)
|
||||
- [Restart-Orphaned Session Terminalization](requirements/restart-orphaned-session-terminalization.md)
|
||||
- [Sidebar Task Editing](requirements/sidebar-task-edit.md)
|
||||
- [Task Actions Menu on Preview and Detail Surfaces](requirements/task-actions-menu.md)
|
||||
@@ -194,6 +195,7 @@ signals, and task-scoped scheduling contracts.
|
||||
- [Queued Run Scheduling](system-design/run-scheduling.md)
|
||||
- [Resume prompt queue](system-design/resume-prompt-queue.md)
|
||||
- [Session Delete Preserves Task Workspaces](system-design/session-delete-resource-cleanup.md)
|
||||
- [Task Cleanup Source Manifest](system-design/archive-source-manifest.md)
|
||||
- [Task Dependencies and Auto-Start Chains](system-design/task-dependencies.md)
|
||||
- [Dependency Gate Skip Visibility](system-design/dependency-gate-skip-visibility.md)
|
||||
- [Edit task dependencies](system-design/task-dependency-detail-editing.md)
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
status: active
|
||||
system: tasks
|
||||
created: 2026-09-24
|
||||
owners:
|
||||
- kandev
|
||||
---
|
||||
|
||||
# Task Cleanup Source Manifest Requirements
|
||||
|
||||
## Overview
|
||||
|
||||
Archive and delete cleanup removes task worktrees. The task system must retain
|
||||
evidence of the source state that existed immediately before removal so a
|
||||
Coordinator can audit the task's terminal integrity after the checkout is gone.
|
||||
The task system owns the cleanup lifecycle and durable task association; the
|
||||
workspace system continues to own Git worktree registration and file capture.
|
||||
|
||||
## Terminology
|
||||
|
||||
- **Source manifest:** A task-scoped record of Git identities and changed-path
|
||||
content hashes captured for a cleanup job.
|
||||
- **Cleanup boundary:** The point after all recorded runtime stop operations
|
||||
succeed and before cleanup removes any task worktree.
|
||||
|
||||
## Requirements
|
||||
|
||||
### REQ-TASKS-ARCHIVE-SOURCE-MANIFEST-001: Preserve task source evidence
|
||||
|
||||
**Intent:** Preserve verifiable, secret-free evidence for task source state at
|
||||
the cleanup boundary.
|
||||
|
||||
**User story:** As a Coordinator, I want to inspect the source state associated
|
||||
with an archived or deleted task, so that I can audit its terminal integrity.
|
||||
|
||||
#### Acceptance criteria
|
||||
|
||||
- **AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.1:** Before archive or delete cleanup
|
||||
removes any worktree, the cleanup job shall durably persist the source
|
||||
manifest for every captured task worktree. A retry shall reuse persisted
|
||||
evidence, and a failed capture or persistence shall leave the worktree intact.
|
||||
- **AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.2:** Each manifest shall bind the exact
|
||||
task, cleanup job, environment, worktree, and repository identities. Capture
|
||||
shall verify that the path is a registered worktree of the recorded
|
||||
repository; uncertain or foreign ownership shall block cleanup.
|
||||
- **AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.3:** Evidence shall include HEAD,
|
||||
a digest of Git's staged-index records, tracked and untracked status, and
|
||||
content digests for changed paths. It shall retain no source bytes or
|
||||
dereferenced symlink data. The staged-index digest shall include unmerged
|
||||
stages without writing Git objects. Dirty submodules shall have a stable
|
||||
digest of their working-tree contents.
|
||||
- **AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.4:** Git metadata, index, status, path,
|
||||
or content capture failures shall be recorded as a recoverable cleanup error
|
||||
and shall block destructive cleanup. A disappeared untracked path shall not
|
||||
be recorded as a deletion.
|
||||
- **AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.5:** An authorized workspace member
|
||||
shall be able to retrieve retained source manifests for a task, including
|
||||
after task deletion. A foreign workspace caller shall receive the existing
|
||||
task-not-found response.
|
||||
- **AC-TASKS-ARCHIVE-SOURCE-MANIFEST-001.6:** Captures shall not combine or
|
||||
attribute content from another task or repository.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Reconstructing source state for tasks archived before this requirement was
|
||||
implemented.
|
||||
- Retaining source file contents or changing normal clean-task lifecycle
|
||||
behavior after successful evidence capture.
|
||||
@@ -0,0 +1,107 @@
|
||||
---
|
||||
status: current
|
||||
system: tasks
|
||||
requirements:
|
||||
- REQ-TASKS-ARCHIVE-SOURCE-MANIFEST-001
|
||||
---
|
||||
|
||||
# Task Cleanup Source Manifest System Design
|
||||
|
||||
## Purpose and boundaries
|
||||
|
||||
The task cleanup worker owns when manifest evidence becomes durable and whether
|
||||
filesystem cleanup may proceed. The worktree manager owns Git registration
|
||||
validation and source-state inspection. Workspace authorization owns read
|
||||
access to retained cleanup evidence.
|
||||
|
||||
## Requirement mapping
|
||||
|
||||
| Requirement | Design section |
|
||||
| --- | --- |
|
||||
| `REQ-TASKS-ARCHIVE-SOURCE-MANIFEST-001` | [Control flow](#control-flow), [Persistence](#persistence), and [Security](#security) |
|
||||
|
||||
## Components and responsibilities
|
||||
|
||||
- `Service.persistTaskResourceCleanup` and cascade preparation persist the
|
||||
cleanup inventory and lifecycle barrier before task-row mutation. They do not
|
||||
capture source contents while a runtime can still write.
|
||||
- `Service.executeTaskResourceCleanupJob` refreshes and stops runtime targets,
|
||||
then captures and compare-and-set persists the manifest before invoking any
|
||||
destructive task cleanup.
|
||||
- `worktree.Manager.CaptureArchiveSourceManifests` verifies the checkout path
|
||||
is registered with the recorded repository, reads Git state, and hashes
|
||||
changed content without retaining source bytes.
|
||||
- `Service.GetTaskSourceManifest` validates job and worktree identities and
|
||||
authorizes through the cleanup snapshot's persisted workspace identity.
|
||||
- `GET /api/v1/tasks/:id/archive-source-manifest` returns the service result
|
||||
with the task handler's existing not-found behavior for inaccessible tasks.
|
||||
|
||||
## Data and contracts
|
||||
|
||||
The cleanup snapshot contains one manifest per owned task worktree. A manifest
|
||||
binds task ID, cleanup-job ID, task-environment ID, worktree ID, and repository
|
||||
ID. It records HEAD and the SHA-256 digest of `git ls-files --stage -z`, which
|
||||
includes unmerged stages and does not write Git objects. Changed paths contain
|
||||
porcelain status and a SHA-256 identity. Symlink identities hash the link
|
||||
target. Dirty submodule identities hash sorted relative paths and file/link
|
||||
identities while omitting Git administrative metadata.
|
||||
|
||||
The existing `archive_source_manifest` field remains additive and
|
||||
backward-compatible in cleanup snapshots. A capture-complete marker
|
||||
distinguishes a successful empty inventory from a not-yet-captured retry.
|
||||
|
||||
## Control flow
|
||||
|
||||
1. A direct or cascade lifecycle operation persists a cleanup job and blocks
|
||||
new task resource admission.
|
||||
2. The worker reloads the exact snapshot and stops every recorded runtime.
|
||||
Failed stop operations defer source capture and filesystem cleanup for a
|
||||
retry.
|
||||
3. The worker captures all source manifests from the snapshot's worktree
|
||||
inventory. The worktree manager compares Git common directories and checks
|
||||
that each exact path appears in `git worktree list` for the recorded
|
||||
repository.
|
||||
4. The worker writes the manifest and capture-complete marker through the
|
||||
claimed-job snapshot compare-and-set. A lost claim or failed write aborts
|
||||
before destructive cleanup.
|
||||
5. Only then does the worker remove worktrees and other task resources. A later
|
||||
retry reuses the already persisted manifest.
|
||||
6. Retrieval loads cleanup generations for the requested task, checks manifest
|
||||
IDs against the persisted worktree inventory, and authorizes the persisted
|
||||
workspace before returning evidence.
|
||||
|
||||
## Failure and recovery
|
||||
|
||||
Missing or malformed Git state, unreadable indexes, unsafe paths, disappearing
|
||||
untracked files, unreadable file content, unregistered or foreign worktrees,
|
||||
and snapshot persistence failures produce a retryable cleanup error. No
|
||||
worktree removal follows that failure. Unmerged indexes are represented by the
|
||||
same staged-index digest as resolved indexes. A dirty submodule is represented
|
||||
by a recursive digest of its working tree rather than rejected as a directory.
|
||||
|
||||
If the process crashes before the manifest compare-and-set, the worker has not
|
||||
entered worktree cleanup. If it crashes after the compare-and-set, retries use
|
||||
the stored evidence and continue cleanup without recapturing a potentially
|
||||
changed or partially removed checkout.
|
||||
|
||||
## Persistence
|
||||
|
||||
Evidence is stored inside the existing durable task cleanup job snapshot; no
|
||||
separate table or retention policy is introduced. Existing cleanup-job
|
||||
retention governs manifest retention. The cleanup-job claim attempt protects
|
||||
the manifest update from stale workers.
|
||||
|
||||
## Security
|
||||
|
||||
Manifests store identifiers, Git object IDs, status values, relative paths, and
|
||||
SHA-256 digests only. Source bytes are streamed into hashes. Symlinks are
|
||||
identified by their link target and never followed. Retrieval is authorized
|
||||
against the persisted workspace so deleted task rows do not erase the audit
|
||||
access boundary. Worktree registration and repository identity checks prevent
|
||||
cross-task source attribution.
|
||||
|
||||
## Observability
|
||||
|
||||
Capture and persistence failures are returned to the cleanup job, which records
|
||||
its retryable error using the existing cleanup lifecycle. No source bytes or
|
||||
task-controlled content is added to logs or metric labels.
|
||||
Reference in New Issue
Block a user