feat(task): add task_environment_repos schema and model for multi-repo support
Phase 0 of multi-repository task support: introduces the per-repository child table and model alongside legacy single-repo fields (dual-write, no behavior change). Lays the foundation for the orchestrator/lifecycle refactor in subsequent phases. - New task_environment_repos table with FK CASCADE on task_environments. - New task_dir_name column on task_environments (idempotent ALTER). - TaskEnvironmentRepo model + Repos slice + RepoFor helper on TaskEnvironment. - CRUD methods + interface extension; env getters preload Repos. - Idempotent backfill from legacy single-repo task_environments rows. - Tests cover round-trip, CRUD, preload ordering, embedded create, cascade delete, and backfill from a legacy-shaped row. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -352,6 +352,21 @@ func (m *mockRepository) DeleteTaskEnvironment(ctx context.Context, id string) e
|
||||
func (m *mockRepository) DeleteTaskEnvironmentsByTask(ctx context.Context, taskID string) error {
|
||||
return nil
|
||||
}
|
||||
func (m *mockRepository) CreateTaskEnvironmentRepo(ctx context.Context, repo *models.TaskEnvironmentRepo) error {
|
||||
return nil
|
||||
}
|
||||
func (m *mockRepository) ListTaskEnvironmentRepos(ctx context.Context, envID string) ([]*models.TaskEnvironmentRepo, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *mockRepository) UpdateTaskEnvironmentRepo(ctx context.Context, repo *models.TaskEnvironmentRepo) error {
|
||||
return nil
|
||||
}
|
||||
func (m *mockRepository) DeleteTaskEnvironmentRepo(ctx context.Context, id string) error {
|
||||
return nil
|
||||
}
|
||||
func (m *mockRepository) DeleteTaskEnvironmentReposByEnv(ctx context.Context, envID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Git Snapshot operations
|
||||
func (m *mockRepository) CreateGitSnapshot(ctx context.Context, snapshot *models.GitSnapshot) error {
|
||||
|
||||
@@ -535,7 +535,7 @@ const (
|
||||
type TaskEnvironment struct {
|
||||
ID string `json:"id"`
|
||||
TaskID string `json:"task_id"`
|
||||
RepositoryID string `json:"repository_id"`
|
||||
RepositoryID string `json:"repository_id"` // Deprecated: use Repos. Kept for dual-write/backwards compat.
|
||||
ExecutorType string `json:"executor_type"`
|
||||
ExecutorID string `json:"executor_id"`
|
||||
ExecutorProfileID string `json:"executor_profile_id"`
|
||||
@@ -543,18 +543,57 @@ type TaskEnvironment struct {
|
||||
ControlPort int `json:"control_port"` // agentctl control port
|
||||
Status TaskEnvironmentStatus `json:"status"`
|
||||
|
||||
// Type-specific fields
|
||||
WorktreeID string `json:"worktree_id,omitempty"`
|
||||
WorktreePath string `json:"worktree_path,omitempty"`
|
||||
WorktreeBranch string `json:"worktree_branch,omitempty"`
|
||||
// Type-specific fields. The single worktree fields below are legacy: with
|
||||
// multi-repo tasks, the per-repo worktrees live on Repos. WorkspacePath
|
||||
// continues to point at the agent workspace root (the task root when
|
||||
// TaskDirName is set, otherwise the single repo's worktree path).
|
||||
WorktreeID string `json:"worktree_id,omitempty"` // Deprecated: use Repos[i].WorktreeID
|
||||
WorktreePath string `json:"worktree_path,omitempty"` // Deprecated: use Repos[i].WorktreePath
|
||||
WorktreeBranch string `json:"worktree_branch,omitempty"` // Deprecated: use Repos[i].WorktreeBranch
|
||||
WorkspacePath string `json:"workspace_path,omitempty"`
|
||||
ContainerID string `json:"container_id,omitempty"`
|
||||
SandboxID string `json:"sandbox_id,omitempty"`
|
||||
|
||||
// TaskDirName is the semantic directory name for the task (e.g. "fix-bug_ab12").
|
||||
// Set when the task uses the multi-repo task-directory layout
|
||||
// (~/.kandev/tasks/{TaskDirName}/{RepoName}/).
|
||||
TaskDirName string `json:"task_dir_name,omitempty"`
|
||||
|
||||
// Repos contains one entry per repository associated with this environment.
|
||||
// Populated by repository getters. Empty for environments created before the
|
||||
// multi-repo backfill ran with no legacy repository_id.
|
||||
Repos []*TaskEnvironmentRepo `json:"repos,omitempty"`
|
||||
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// RepoFor returns the per-repo environment row for repositoryID, or nil if not present.
|
||||
func (te *TaskEnvironment) RepoFor(repositoryID string) *TaskEnvironmentRepo {
|
||||
for _, r := range te.Repos {
|
||||
if r.RepositoryID == repositoryID {
|
||||
return r
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TaskEnvironmentRepo represents the per-repository state of a task environment.
|
||||
// One row per repository associated with the task: each carries its own worktree
|
||||
// reference and any per-repo preparation error.
|
||||
type TaskEnvironmentRepo struct {
|
||||
ID string `json:"id"`
|
||||
TaskEnvironmentID string `json:"task_environment_id"`
|
||||
RepositoryID string `json:"repository_id"`
|
||||
WorktreeID string `json:"worktree_id,omitempty"`
|
||||
WorktreePath string `json:"worktree_path,omitempty"`
|
||||
WorktreeBranch string `json:"worktree_branch,omitempty"`
|
||||
Position int `json:"position"`
|
||||
ErrorMessage string `json:"error_message,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// ToAPI converts internal TaskEnvironment to API map.
|
||||
func (te *TaskEnvironment) ToAPI() map[string]interface{} {
|
||||
result := map[string]interface{}{
|
||||
@@ -590,9 +629,44 @@ func (te *TaskEnvironment) ToAPI() map[string]interface{} {
|
||||
if te.SandboxID != "" {
|
||||
result["sandbox_id"] = te.SandboxID
|
||||
}
|
||||
if te.TaskDirName != "" {
|
||||
result["task_dir_name"] = te.TaskDirName
|
||||
}
|
||||
if len(te.Repos) > 0 {
|
||||
repos := make([]map[string]interface{}, 0, len(te.Repos))
|
||||
for _, repo := range te.Repos {
|
||||
repos = append(repos, repo.ToAPI())
|
||||
}
|
||||
result["repos"] = repos
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ToAPI converts internal TaskEnvironmentRepo to API map.
|
||||
func (r *TaskEnvironmentRepo) ToAPI() map[string]interface{} {
|
||||
out := map[string]interface{}{
|
||||
"id": r.ID,
|
||||
"task_environment_id": r.TaskEnvironmentID,
|
||||
"repository_id": r.RepositoryID,
|
||||
"position": r.Position,
|
||||
"created_at": r.CreatedAt,
|
||||
"updated_at": r.UpdatedAt,
|
||||
}
|
||||
if r.WorktreeID != "" {
|
||||
out["worktree_id"] = r.WorktreeID
|
||||
}
|
||||
if r.WorktreePath != "" {
|
||||
out["worktree_path"] = r.WorktreePath
|
||||
}
|
||||
if r.WorktreeBranch != "" {
|
||||
out["worktree_branch"] = r.WorktreeBranch
|
||||
}
|
||||
if r.ErrorMessage != "" {
|
||||
out["error_message"] = r.ErrorMessage
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TaskPlan represents a plan associated with a task
|
||||
type TaskPlan struct {
|
||||
ID string `json:"id"`
|
||||
|
||||
@@ -180,7 +180,8 @@ type EnvironmentRepository interface {
|
||||
ListEnvironments(ctx context.Context) ([]*models.Environment, error)
|
||||
}
|
||||
|
||||
// TaskEnvironmentRepository handles per-task execution environment instances.
|
||||
// TaskEnvironmentRepository handles per-task execution environment instances
|
||||
// and their per-repository child rows.
|
||||
type TaskEnvironmentRepository interface {
|
||||
CreateTaskEnvironment(ctx context.Context, env *models.TaskEnvironment) error
|
||||
GetTaskEnvironment(ctx context.Context, id string) (*models.TaskEnvironment, error)
|
||||
@@ -188,6 +189,11 @@ type TaskEnvironmentRepository interface {
|
||||
UpdateTaskEnvironment(ctx context.Context, env *models.TaskEnvironment) error
|
||||
DeleteTaskEnvironment(ctx context.Context, id string) error
|
||||
DeleteTaskEnvironmentsByTask(ctx context.Context, taskID string) error
|
||||
CreateTaskEnvironmentRepo(ctx context.Context, repo *models.TaskEnvironmentRepo) error
|
||||
ListTaskEnvironmentRepos(ctx context.Context, envID string) ([]*models.TaskEnvironmentRepo, error)
|
||||
UpdateTaskEnvironmentRepo(ctx context.Context, repo *models.TaskEnvironmentRepo) error
|
||||
DeleteTaskEnvironmentRepo(ctx context.Context, id string) error
|
||||
DeleteTaskEnvironmentReposByEnv(ctx context.Context, envID string) error
|
||||
}
|
||||
|
||||
// ReviewRepository handles session file review records.
|
||||
|
||||
@@ -109,6 +109,9 @@ func (r *Repository) initSchema() error {
|
||||
if err := r.backfillTaskEnvironments(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.backfillTaskEnvironmentRepos(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.ensureWorkspaceIndexes(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -160,6 +163,8 @@ func (r *Repository) runMigrations() error {
|
||||
_, _ = r.db.Exec(`ALTER TABLE workflows ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0`)
|
||||
// Add agent_profile_id column to workflows for per-workflow agent profile override (ignore error if already exists)
|
||||
_, _ = r.db.Exec(`ALTER TABLE workflows ADD COLUMN agent_profile_id TEXT DEFAULT ''`)
|
||||
// Add task_dir_name column to task_environments for multi-repo task root layout (ignore error if already exists)
|
||||
_, _ = r.db.Exec(`ALTER TABLE task_environments ADD COLUMN task_dir_name TEXT DEFAULT ''`)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -396,6 +401,67 @@ func (r *Repository) backfillSingleTask(tx *sql.Tx, row backfillRow) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// backfillTaskEnvironmentRepos populates task_environment_repos from the legacy
|
||||
// single-repo fields on task_environments. One row per environment that has a
|
||||
// non-empty repository_id and no existing task_environment_repos row.
|
||||
// Idempotent.
|
||||
func (r *Repository) backfillTaskEnvironmentRepos() error {
|
||||
rows, err := r.db.Query(`
|
||||
SELECT te.id,
|
||||
te.repository_id,
|
||||
COALESCE(te.worktree_id, ''),
|
||||
COALESCE(te.worktree_path, ''),
|
||||
COALESCE(te.worktree_branch, ''),
|
||||
te.created_at
|
||||
FROM task_environments te
|
||||
LEFT JOIN task_environment_repos ter ON ter.task_environment_id = te.id
|
||||
WHERE te.repository_id != '' AND ter.id IS NULL
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("backfill repos: query: %w", err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
type envRepoRow struct {
|
||||
envID, repoID, wtID, wtPath, wtBranch, createdAt string
|
||||
}
|
||||
var pending []envRepoRow
|
||||
for rows.Next() {
|
||||
var row envRepoRow
|
||||
if err := rows.Scan(&row.envID, &row.repoID, &row.wtID, &row.wtPath, &row.wtBranch, &row.createdAt); err != nil {
|
||||
return fmt.Errorf("backfill repos: scan: %w", err)
|
||||
}
|
||||
pending = append(pending, row)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("backfill repos: rows: %w", err)
|
||||
}
|
||||
if len(pending) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
tx, err := r.db.Begin()
|
||||
if err != nil {
|
||||
return fmt.Errorf("backfill repos: begin tx: %w", err)
|
||||
}
|
||||
defer tx.Rollback() //nolint:errcheck
|
||||
|
||||
for _, row := range pending {
|
||||
if _, err := tx.Exec(`
|
||||
INSERT INTO task_environment_repos (
|
||||
id, task_environment_id, repository_id,
|
||||
worktree_id, worktree_path, worktree_branch,
|
||||
position, error_message, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, 0, '', ?, ?)
|
||||
`, uuid.New().String(), row.envID, row.repoID,
|
||||
row.wtID, row.wtPath, row.wtBranch,
|
||||
row.createdAt, row.createdAt); err != nil {
|
||||
return fmt.Errorf("backfill repos: insert env %s: %w", row.envID, err)
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (r *Repository) initCoreSchema() error {
|
||||
if err := r.initInfraSchema(); err != nil {
|
||||
return err
|
||||
@@ -697,6 +763,7 @@ func (r *Repository) initSessionWorktreeSchema() error {
|
||||
workspace_path TEXT DEFAULT '',
|
||||
container_id TEXT DEFAULT '',
|
||||
sandbox_id TEXT DEFAULT '',
|
||||
task_dir_name TEXT DEFAULT '',
|
||||
created_at TIMESTAMP NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (task_id) REFERENCES tasks(id) ON DELETE CASCADE
|
||||
@@ -705,6 +772,24 @@ func (r *Repository) initSessionWorktreeSchema() error {
|
||||
CREATE INDEX IF NOT EXISTS idx_task_environments_task_id ON task_environments(task_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_task_environments_status ON task_environments(status);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS task_environment_repos (
|
||||
id TEXT PRIMARY KEY,
|
||||
task_environment_id TEXT NOT NULL,
|
||||
repository_id TEXT NOT NULL,
|
||||
worktree_id TEXT DEFAULT '',
|
||||
worktree_path TEXT DEFAULT '',
|
||||
worktree_branch TEXT DEFAULT '',
|
||||
position INTEGER DEFAULT 0,
|
||||
error_message TEXT DEFAULT '',
|
||||
created_at TIMESTAMP NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (task_environment_id) REFERENCES task_environments(id) ON DELETE CASCADE,
|
||||
UNIQUE(task_environment_id, repository_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_task_environment_repos_env_id ON task_environment_repos(task_environment_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_task_environment_repos_repository_id ON task_environment_repos(repository_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS task_session_worktrees (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
)
|
||||
|
||||
// CreateTaskEnvironment creates a new task environment record.
|
||||
// If env.Repos is non-empty, the per-repo rows are inserted in the same transaction.
|
||||
func (r *Repository) CreateTaskEnvironment(ctx context.Context, env *models.TaskEnvironment) error {
|
||||
if env.ID == "" {
|
||||
env.ID = uuid.New().String()
|
||||
@@ -20,25 +21,41 @@ func (r *Repository) CreateTaskEnvironment(ctx context.Context, env *models.Task
|
||||
env.CreatedAt = now
|
||||
env.UpdatedAt = now
|
||||
|
||||
_, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
if _, err := tx.ExecContext(ctx, r.db.Rebind(`
|
||||
INSERT INTO task_environments (
|
||||
id, task_id, repository_id, executor_type, executor_id, executor_profile_id,
|
||||
agent_execution_id, control_port, status,
|
||||
worktree_id, worktree_path, worktree_branch, workspace_path,
|
||||
container_id, sandbox_id,
|
||||
container_id, sandbox_id, task_dir_name,
|
||||
created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`),
|
||||
env.ID, env.TaskID, env.RepositoryID, env.ExecutorType, env.ExecutorID, env.ExecutorProfileID,
|
||||
env.AgentExecutionID, env.ControlPort, string(env.Status),
|
||||
env.WorktreeID, env.WorktreePath, env.WorktreeBranch, env.WorkspacePath,
|
||||
env.ContainerID, env.SandboxID,
|
||||
env.ContainerID, env.SandboxID, env.TaskDirName,
|
||||
env.CreatedAt, env.UpdatedAt,
|
||||
)
|
||||
return err
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, repo := range env.Repos {
|
||||
repo.TaskEnvironmentID = env.ID
|
||||
if err := r.insertTaskEnvironmentRepoTx(ctx, tx, repo); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// GetTaskEnvironment retrieves a task environment by ID.
|
||||
// GetTaskEnvironment retrieves a task environment by ID, including per-repo rows.
|
||||
func (r *Repository) GetTaskEnvironment(ctx context.Context, id string) (*models.TaskEnvironment, error) {
|
||||
env := &models.TaskEnvironment{}
|
||||
var status string
|
||||
@@ -47,14 +64,14 @@ func (r *Repository) GetTaskEnvironment(ctx context.Context, id string) (*models
|
||||
SELECT id, task_id, repository_id, executor_type, executor_id, executor_profile_id,
|
||||
agent_execution_id, control_port, status,
|
||||
worktree_id, worktree_path, worktree_branch, workspace_path,
|
||||
container_id, sandbox_id,
|
||||
container_id, sandbox_id, COALESCE(task_dir_name, ''),
|
||||
created_at, updated_at
|
||||
FROM task_environments WHERE id = ?
|
||||
`), id).Scan(
|
||||
&env.ID, &env.TaskID, &env.RepositoryID, &env.ExecutorType, &env.ExecutorID, &env.ExecutorProfileID,
|
||||
&env.AgentExecutionID, &env.ControlPort, &status,
|
||||
&env.WorktreeID, &env.WorktreePath, &env.WorktreeBranch, &env.WorkspacePath,
|
||||
&env.ContainerID, &env.SandboxID,
|
||||
&env.ContainerID, &env.SandboxID, &env.TaskDirName,
|
||||
&env.CreatedAt, &env.UpdatedAt,
|
||||
)
|
||||
if err == sql.ErrNoRows {
|
||||
@@ -64,10 +81,17 @@ func (r *Repository) GetTaskEnvironment(ctx context.Context, id string) (*models
|
||||
return nil, err
|
||||
}
|
||||
env.Status = models.TaskEnvironmentStatus(status)
|
||||
|
||||
repos, err := r.ListTaskEnvironmentRepos(ctx, env.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
env.Repos = repos
|
||||
return env, nil
|
||||
}
|
||||
|
||||
// GetTaskEnvironmentByTaskID retrieves the active task environment for a task.
|
||||
// GetTaskEnvironmentByTaskID retrieves the active task environment for a task,
|
||||
// including per-repo rows.
|
||||
func (r *Repository) GetTaskEnvironmentByTaskID(ctx context.Context, taskID string) (*models.TaskEnvironment, error) {
|
||||
env := &models.TaskEnvironment{}
|
||||
var status string
|
||||
@@ -76,14 +100,14 @@ func (r *Repository) GetTaskEnvironmentByTaskID(ctx context.Context, taskID stri
|
||||
SELECT id, task_id, repository_id, executor_type, executor_id, executor_profile_id,
|
||||
agent_execution_id, control_port, status,
|
||||
worktree_id, worktree_path, worktree_branch, workspace_path,
|
||||
container_id, sandbox_id,
|
||||
container_id, sandbox_id, COALESCE(task_dir_name, ''),
|
||||
created_at, updated_at
|
||||
FROM task_environments WHERE task_id = ? ORDER BY created_at DESC LIMIT 1
|
||||
`), taskID).Scan(
|
||||
&env.ID, &env.TaskID, &env.RepositoryID, &env.ExecutorType, &env.ExecutorID, &env.ExecutorProfileID,
|
||||
&env.AgentExecutionID, &env.ControlPort, &status,
|
||||
&env.WorktreeID, &env.WorktreePath, &env.WorktreeBranch, &env.WorkspacePath,
|
||||
&env.ContainerID, &env.SandboxID,
|
||||
&env.ContainerID, &env.SandboxID, &env.TaskDirName,
|
||||
&env.CreatedAt, &env.UpdatedAt,
|
||||
)
|
||||
if err == sql.ErrNoRows {
|
||||
@@ -93,10 +117,17 @@ func (r *Repository) GetTaskEnvironmentByTaskID(ctx context.Context, taskID stri
|
||||
return nil, err
|
||||
}
|
||||
env.Status = models.TaskEnvironmentStatus(status)
|
||||
|
||||
repos, err := r.ListTaskEnvironmentRepos(ctx, env.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
env.Repos = repos
|
||||
return env, nil
|
||||
}
|
||||
|
||||
// UpdateTaskEnvironment updates an existing task environment.
|
||||
// Per-repo rows are not touched; use the TaskEnvironmentRepo CRUD methods.
|
||||
func (r *Repository) UpdateTaskEnvironment(ctx context.Context, env *models.TaskEnvironment) error {
|
||||
env.UpdatedAt = time.Now().UTC()
|
||||
|
||||
@@ -105,14 +136,14 @@ func (r *Repository) UpdateTaskEnvironment(ctx context.Context, env *models.Task
|
||||
repository_id = ?, executor_type = ?, executor_id = ?, executor_profile_id = ?,
|
||||
agent_execution_id = ?, control_port = ?, status = ?,
|
||||
worktree_id = ?, worktree_path = ?, worktree_branch = ?, workspace_path = ?,
|
||||
container_id = ?, sandbox_id = ?,
|
||||
container_id = ?, sandbox_id = ?, task_dir_name = ?,
|
||||
updated_at = ?
|
||||
WHERE id = ?
|
||||
`),
|
||||
env.RepositoryID, env.ExecutorType, env.ExecutorID, env.ExecutorProfileID,
|
||||
env.AgentExecutionID, env.ControlPort, string(env.Status),
|
||||
env.WorktreeID, env.WorktreePath, env.WorktreeBranch, env.WorkspacePath,
|
||||
env.ContainerID, env.SandboxID,
|
||||
env.ContainerID, env.SandboxID, env.TaskDirName,
|
||||
env.UpdatedAt,
|
||||
env.ID,
|
||||
)
|
||||
@@ -127,6 +158,7 @@ func (r *Repository) UpdateTaskEnvironment(ctx context.Context, env *models.Task
|
||||
}
|
||||
|
||||
// DeleteTaskEnvironment deletes a task environment by ID.
|
||||
// Per-repo rows are removed via ON DELETE CASCADE.
|
||||
func (r *Repository) DeleteTaskEnvironment(ctx context.Context, id string) error {
|
||||
result, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
DELETE FROM task_environments WHERE id = ?
|
||||
@@ -148,3 +180,135 @@ func (r *Repository) DeleteTaskEnvironmentsByTask(ctx context.Context, taskID st
|
||||
`), taskID)
|
||||
return err
|
||||
}
|
||||
|
||||
// CreateTaskEnvironmentRepo inserts a single per-repo environment row.
|
||||
func (r *Repository) CreateTaskEnvironmentRepo(ctx context.Context, repo *models.TaskEnvironmentRepo) error {
|
||||
if repo.TaskEnvironmentID == "" {
|
||||
return fmt.Errorf("task_environment_id is required")
|
||||
}
|
||||
if repo.RepositoryID == "" {
|
||||
return fmt.Errorf("repository_id is required")
|
||||
}
|
||||
if repo.ID == "" {
|
||||
repo.ID = uuid.New().String()
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
repo.CreatedAt = now
|
||||
repo.UpdatedAt = now
|
||||
|
||||
_, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
INSERT INTO task_environment_repos (
|
||||
id, task_environment_id, repository_id,
|
||||
worktree_id, worktree_path, worktree_branch,
|
||||
position, error_message, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`),
|
||||
repo.ID, repo.TaskEnvironmentID, repo.RepositoryID,
|
||||
repo.WorktreeID, repo.WorktreePath, repo.WorktreeBranch,
|
||||
repo.Position, repo.ErrorMessage, repo.CreatedAt, repo.UpdatedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
// insertTaskEnvironmentRepoTx is the in-transaction variant of CreateTaskEnvironmentRepo.
|
||||
func (r *Repository) insertTaskEnvironmentRepoTx(ctx context.Context, tx *sql.Tx, repo *models.TaskEnvironmentRepo) error {
|
||||
if repo.RepositoryID == "" {
|
||||
return fmt.Errorf("repository_id is required")
|
||||
}
|
||||
if repo.ID == "" {
|
||||
repo.ID = uuid.New().String()
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
repo.CreatedAt = now
|
||||
repo.UpdatedAt = now
|
||||
|
||||
_, err := tx.ExecContext(ctx, r.db.Rebind(`
|
||||
INSERT INTO task_environment_repos (
|
||||
id, task_environment_id, repository_id,
|
||||
worktree_id, worktree_path, worktree_branch,
|
||||
position, error_message, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`),
|
||||
repo.ID, repo.TaskEnvironmentID, repo.RepositoryID,
|
||||
repo.WorktreeID, repo.WorktreePath, repo.WorktreeBranch,
|
||||
repo.Position, repo.ErrorMessage, repo.CreatedAt, repo.UpdatedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
// ListTaskEnvironmentRepos returns all per-repo rows for an environment, ordered by position.
|
||||
func (r *Repository) ListTaskEnvironmentRepos(ctx context.Context, envID string) ([]*models.TaskEnvironmentRepo, error) {
|
||||
rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(`
|
||||
SELECT id, task_environment_id, repository_id,
|
||||
worktree_id, worktree_path, worktree_branch,
|
||||
position, error_message, created_at, updated_at
|
||||
FROM task_environment_repos
|
||||
WHERE task_environment_id = ?
|
||||
ORDER BY position ASC, created_at ASC
|
||||
`), envID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var out []*models.TaskEnvironmentRepo
|
||||
for rows.Next() {
|
||||
repo := &models.TaskEnvironmentRepo{}
|
||||
if err := rows.Scan(
|
||||
&repo.ID, &repo.TaskEnvironmentID, &repo.RepositoryID,
|
||||
&repo.WorktreeID, &repo.WorktreePath, &repo.WorktreeBranch,
|
||||
&repo.Position, &repo.ErrorMessage, &repo.CreatedAt, &repo.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, repo)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// UpdateTaskEnvironmentRepo updates an existing per-repo row.
|
||||
func (r *Repository) UpdateTaskEnvironmentRepo(ctx context.Context, repo *models.TaskEnvironmentRepo) error {
|
||||
repo.UpdatedAt = time.Now().UTC()
|
||||
|
||||
result, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
UPDATE task_environment_repos SET
|
||||
worktree_id = ?, worktree_path = ?, worktree_branch = ?,
|
||||
position = ?, error_message = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`),
|
||||
repo.WorktreeID, repo.WorktreePath, repo.WorktreeBranch,
|
||||
repo.Position, repo.ErrorMessage, repo.UpdatedAt,
|
||||
repo.ID,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows, _ := result.RowsAffected()
|
||||
if rows == 0 {
|
||||
return fmt.Errorf("task environment repo not found: %s", repo.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteTaskEnvironmentRepo removes a single per-repo row.
|
||||
func (r *Repository) DeleteTaskEnvironmentRepo(ctx context.Context, id string) error {
|
||||
result, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
DELETE FROM task_environment_repos WHERE id = ?
|
||||
`), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows, _ := result.RowsAffected()
|
||||
if rows == 0 {
|
||||
return fmt.Errorf("task environment repo not found: %s", id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteTaskEnvironmentReposByEnv removes all per-repo rows for an environment.
|
||||
func (r *Repository) DeleteTaskEnvironmentReposByEnv(ctx context.Context, envID string) error {
|
||||
_, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
DELETE FROM task_environment_repos WHERE task_environment_id = ?
|
||||
`), envID)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/kandev/kandev/internal/db"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository/sqlite"
|
||||
"github.com/kandev/kandev/internal/worktree"
|
||||
)
|
||||
|
||||
// Phase 0 tests for the multi-repo TaskEnvironment / TaskEnvironmentRepo schema.
|
||||
|
||||
func newEnv(t *testing.T, repo *sqlite.Repository, taskID, envID string) *models.TaskEnvironment {
|
||||
t.Helper()
|
||||
env := &models.TaskEnvironment{
|
||||
ID: envID,
|
||||
TaskID: taskID,
|
||||
ExecutorType: "local_pc",
|
||||
Status: models.TaskEnvironmentStatusReady,
|
||||
TaskDirName: "fix-bug_ab12",
|
||||
}
|
||||
if err := repo.CreateTaskEnvironment(context.Background(), env); err != nil {
|
||||
t.Fatalf("create env: %v", err)
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func newTaskWithRepo(t *testing.T, repo *sqlite.Repository, taskID string) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
wf := &models.Workflow{ID: "wf-env", Name: "Env Workflow"}
|
||||
_ = repo.CreateWorkflow(ctx, wf)
|
||||
task := &models.Task{ID: taskID, WorkflowID: wf.ID, Title: "Env Task"}
|
||||
if err := repo.CreateTask(ctx, task); err != nil {
|
||||
t.Fatalf("create task: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskEnvironment_TaskDirNameRoundTrip(t *testing.T) {
|
||||
repo, cleanup := createTestSQLiteRepo(t)
|
||||
defer cleanup()
|
||||
|
||||
newTaskWithRepo(t, repo, "task-env-1")
|
||||
env := newEnv(t, repo, "task-env-1", "env-1")
|
||||
|
||||
got, err := repo.GetTaskEnvironment(context.Background(), env.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("get env: %v", err)
|
||||
}
|
||||
if got.TaskDirName != "fix-bug_ab12" {
|
||||
t.Errorf("expected task_dir_name persisted; got %q", got.TaskDirName)
|
||||
}
|
||||
if len(got.Repos) != 0 {
|
||||
t.Errorf("expected 0 repos, got %d", len(got.Repos))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskEnvironmentRepo_CRUD(t *testing.T) {
|
||||
repo, cleanup := createTestSQLiteRepo(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
newTaskWithRepo(t, repo, "task-env-2")
|
||||
env := newEnv(t, repo, "task-env-2", "env-2")
|
||||
|
||||
er := &models.TaskEnvironmentRepo{
|
||||
TaskEnvironmentID: env.ID,
|
||||
RepositoryID: "repo-frontend",
|
||||
WorktreeID: "wt-1",
|
||||
WorktreePath: "/tmp/tasks/x/frontend",
|
||||
WorktreeBranch: "feature/x",
|
||||
Position: 0,
|
||||
}
|
||||
if err := repo.CreateTaskEnvironmentRepo(ctx, er); err != nil {
|
||||
t.Fatalf("create env repo: %v", err)
|
||||
}
|
||||
if er.ID == "" {
|
||||
t.Fatal("expected ID to be assigned")
|
||||
}
|
||||
|
||||
list, err := repo.ListTaskEnvironmentRepos(ctx, env.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("list: %v", err)
|
||||
}
|
||||
if len(list) != 1 || list[0].RepositoryID != "repo-frontend" {
|
||||
t.Fatalf("unexpected list: %+v", list)
|
||||
}
|
||||
|
||||
er.WorktreeBranch = "feature/x-renamed"
|
||||
er.ErrorMessage = "fetch failed"
|
||||
if err := repo.UpdateTaskEnvironmentRepo(ctx, er); err != nil {
|
||||
t.Fatalf("update: %v", err)
|
||||
}
|
||||
list, _ = repo.ListTaskEnvironmentRepos(ctx, env.ID)
|
||||
if list[0].WorktreeBranch != "feature/x-renamed" || list[0].ErrorMessage != "fetch failed" {
|
||||
t.Errorf("update did not persist: %+v", list[0])
|
||||
}
|
||||
|
||||
if err := repo.DeleteTaskEnvironmentRepo(ctx, er.ID); err != nil {
|
||||
t.Fatalf("delete: %v", err)
|
||||
}
|
||||
list, _ = repo.ListTaskEnvironmentRepos(ctx, env.ID)
|
||||
if len(list) != 0 {
|
||||
t.Errorf("expected empty list after delete, got %d", len(list))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskEnvironmentRepo_PreloadOnGet(t *testing.T) {
|
||||
repo, cleanup := createTestSQLiteRepo(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
newTaskWithRepo(t, repo, "task-env-3")
|
||||
env := newEnv(t, repo, "task-env-3", "env-3")
|
||||
|
||||
rows := []*models.TaskEnvironmentRepo{
|
||||
{TaskEnvironmentID: env.ID, RepositoryID: "repo-backend", Position: 1, WorktreePath: "/b"},
|
||||
{TaskEnvironmentID: env.ID, RepositoryID: "repo-frontend", Position: 0, WorktreePath: "/f"},
|
||||
}
|
||||
for _, r := range rows {
|
||||
if err := repo.CreateTaskEnvironmentRepo(ctx, r); err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
got, err := repo.GetTaskEnvironment(ctx, env.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
if len(got.Repos) != 2 {
|
||||
t.Fatalf("expected 2 repos, got %d", len(got.Repos))
|
||||
}
|
||||
if got.Repos[0].RepositoryID != "repo-frontend" {
|
||||
t.Errorf("expected position-ordered list, frontend (pos=0) first; got %s", got.Repos[0].RepositoryID)
|
||||
}
|
||||
if got.RepoFor("repo-backend") == nil {
|
||||
t.Error("expected RepoFor lookup to find repo-backend")
|
||||
}
|
||||
if got.RepoFor("missing") != nil {
|
||||
t.Error("expected RepoFor to return nil for unknown repo")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskEnvironmentRepo_CreateWithEmbeddedRepos(t *testing.T) {
|
||||
repo, cleanup := createTestSQLiteRepo(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
newTaskWithRepo(t, repo, "task-env-4")
|
||||
env := &models.TaskEnvironment{
|
||||
ID: "env-4",
|
||||
TaskID: "task-env-4",
|
||||
ExecutorType: "local_pc",
|
||||
Status: models.TaskEnvironmentStatusReady,
|
||||
Repos: []*models.TaskEnvironmentRepo{
|
||||
{RepositoryID: "repo-a", Position: 0, WorktreePath: "/a"},
|
||||
{RepositoryID: "repo-b", Position: 1, WorktreePath: "/b"},
|
||||
},
|
||||
}
|
||||
if err := repo.CreateTaskEnvironment(ctx, env); err != nil {
|
||||
t.Fatalf("create env with repos: %v", err)
|
||||
}
|
||||
got, err := repo.GetTaskEnvironment(ctx, env.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
if len(got.Repos) != 2 {
|
||||
t.Fatalf("expected 2 repos persisted, got %d", len(got.Repos))
|
||||
}
|
||||
for _, r := range got.Repos {
|
||||
if r.TaskEnvironmentID != env.ID {
|
||||
t.Errorf("expected env id wired; got %q", r.TaskEnvironmentID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskEnvironmentRepo_CascadeDeleteOnEnvDelete(t *testing.T) {
|
||||
repo, cleanup := createTestSQLiteRepo(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
newTaskWithRepo(t, repo, "task-env-5")
|
||||
env := newEnv(t, repo, "task-env-5", "env-5")
|
||||
er := &models.TaskEnvironmentRepo{TaskEnvironmentID: env.ID, RepositoryID: "repo-x"}
|
||||
if err := repo.CreateTaskEnvironmentRepo(ctx, er); err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
if err := repo.DeleteTaskEnvironment(ctx, env.ID); err != nil {
|
||||
t.Fatalf("delete env: %v", err)
|
||||
}
|
||||
list, err := repo.ListTaskEnvironmentRepos(ctx, env.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("list after delete: %v", err)
|
||||
}
|
||||
if len(list) != 0 {
|
||||
t.Errorf("expected cascade delete to remove per-repo rows, got %d", len(list))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskEnvironmentRepo_BackfillFromLegacyEnv(t *testing.T) {
|
||||
// Backfill is run by initSchema. Simulate a "legacy" environment by inserting
|
||||
// directly into task_environments with repository_id set, then re-opening the
|
||||
// repository so initSchema re-runs the backfill on the existing data.
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := filepath.Join(tmpDir, "backfill.db")
|
||||
|
||||
dbConn, err := db.OpenSQLite(dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("open db: %v", err)
|
||||
}
|
||||
sqlxDB := sqlx.NewDb(dbConn, "sqlite3")
|
||||
repo, err := sqlite.NewWithDB(sqlxDB, sqlxDB)
|
||||
if err != nil {
|
||||
t.Fatalf("new repo: %v", err)
|
||||
}
|
||||
if _, err := worktree.NewSQLiteStore(sqlxDB, sqlxDB); err != nil {
|
||||
t.Fatalf("worktree store: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
newTaskWithRepo(t, repo, "task-env-6")
|
||||
|
||||
// Insert a legacy-shaped env (no per-repo row exists).
|
||||
if _, err := sqlxDB.Exec(`
|
||||
INSERT INTO task_environments (
|
||||
id, task_id, repository_id, executor_type, executor_id, executor_profile_id,
|
||||
agent_execution_id, control_port, status,
|
||||
worktree_id, worktree_path, worktree_branch, workspace_path,
|
||||
container_id, sandbox_id, task_dir_name,
|
||||
created_at, updated_at
|
||||
) VALUES ('legacy-env', 'task-env-6', 'repo-legacy', 'local_pc', '', '',
|
||||
'', 0, 'ready',
|
||||
'wt-legacy', '/wt/legacy', 'main', '',
|
||||
'', '', '',
|
||||
datetime('now'), datetime('now'))
|
||||
`); err != nil {
|
||||
t.Fatalf("insert legacy env: %v", err)
|
||||
}
|
||||
|
||||
// Verify no per-repo row yet.
|
||||
list, err := repo.ListTaskEnvironmentRepos(ctx, "legacy-env")
|
||||
if err != nil {
|
||||
t.Fatalf("list: %v", err)
|
||||
}
|
||||
if len(list) != 0 {
|
||||
t.Fatalf("expected 0 per-repo rows pre-backfill, got %d", len(list))
|
||||
}
|
||||
|
||||
// Re-open the repository to retrigger initSchema → backfill.
|
||||
if err := repo.Close(); err != nil {
|
||||
t.Fatalf("close: %v", err)
|
||||
}
|
||||
dbConn2, err := db.OpenSQLite(dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("reopen db: %v", err)
|
||||
}
|
||||
sqlxDB2 := sqlx.NewDb(dbConn2, "sqlite3")
|
||||
repo2, err := sqlite.NewWithDB(sqlxDB2, sqlxDB2)
|
||||
if err != nil {
|
||||
t.Fatalf("reopen repo: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
_ = repo2.Close()
|
||||
_ = sqlxDB2.Close()
|
||||
}()
|
||||
|
||||
list, err = repo2.ListTaskEnvironmentRepos(ctx, "legacy-env")
|
||||
if err != nil {
|
||||
t.Fatalf("list after reopen: %v", err)
|
||||
}
|
||||
if len(list) != 1 {
|
||||
t.Fatalf("expected 1 backfilled row, got %d", len(list))
|
||||
}
|
||||
got := list[0]
|
||||
if got.RepositoryID != "repo-legacy" || got.WorktreeID != "wt-legacy" || got.WorktreeBranch != "main" {
|
||||
t.Errorf("backfilled row mismatch: %+v", got)
|
||||
}
|
||||
|
||||
// Idempotency: a second backfill must not duplicate rows.
|
||||
list, _ = repo2.ListTaskEnvironmentRepos(ctx, "legacy-env")
|
||||
if len(list) != 1 {
|
||||
t.Errorf("expected backfill to be idempotent, got %d rows", len(list))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user