@@ -631,6 +631,107 @@ func TestCutover_PrefersFlatMetadataForSameWorktree(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCutover_IgnoresTerminalWorktreeDifferentFromFlatOwner proves that
|
||||
// terminal session history cannot replace the surviving flat environment
|
||||
// owner for the same repository and empty branch slot.
|
||||
func TestCutover_IgnoresTerminalWorktreeDifferentFromFlatOwner(t *testing.T) {
|
||||
for _, state := range []string{"COMPLETED", "FAILED", "CANCELLED"} {
|
||||
t.Run(state, func(t *testing.T) {
|
||||
db := openLegacyDB(t)
|
||||
now := time.Now().UTC().Truncate(time.Second)
|
||||
seed := legacySeed{envID: "env-flat-terminal", taskID: "task-flat-terminal", repoID: "repo-flat-terminal", sessionID: "sess-flat-terminal"}
|
||||
seedLegacyTask(t, db, seed, now)
|
||||
if _, err := db.Exec(db.Rebind(`UPDATE task_sessions SET state = ? WHERE id = ?`), state, seed.sessionID); err != nil {
|
||||
t.Fatalf("set session state: %v", err)
|
||||
}
|
||||
seedLegacyFlatEnv(t, db, seed, "wt-flat-current", "/tasks/flat-terminal/repo", "feature/current", now)
|
||||
seedLegacySessionWorktree(t, db, seed.sessionID, "wt-flat-old", seed.repoID, "", "/tasks/flat-terminal/old", "feature/old", "active", now)
|
||||
|
||||
repo, err := NewWithDB(db, db, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("cutover: %v", err)
|
||||
}
|
||||
env, err := repo.GetTaskEnvironment(context.Background(), seed.envID)
|
||||
if err != nil {
|
||||
t.Fatalf("get task environment: %v", err)
|
||||
}
|
||||
if len(env.Repos) != 1 || env.Repos[0].WorktreeID != "wt-flat-current" {
|
||||
t.Fatalf("flat environment owner = %+v", env.Repos)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCutover_PreservesTerminalWorktreeOutsideFlatOwnerSlot proves that flat
|
||||
// source precedence does not discard a different repository or branch slot.
|
||||
func TestCutover_PreservesTerminalWorktreeOutsideFlatOwnerSlot(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
sessionRepoID string
|
||||
sessionBranchSlug string
|
||||
}{
|
||||
{name: "different repository", sessionRepoID: "repo-flat-terminal-other"},
|
||||
{name: "non-empty branch", sessionRepoID: "repo-flat-terminal", sessionBranchSlug: "feature/old"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
db := openLegacyDB(t)
|
||||
now := time.Now().UTC().Truncate(time.Second)
|
||||
seed := legacySeed{envID: "env-flat-terminal", taskID: "task-flat-terminal", repoID: "repo-flat-terminal", sessionID: "sess-flat-terminal"}
|
||||
seedLegacyTask(t, db, seed, now)
|
||||
seedLegacyFlatEnv(t, db, seed, "wt-flat-current", "/tasks/flat-terminal/repo", "feature/current", now)
|
||||
seedLegacySessionWorktree(t, db, seed.sessionID, "wt-flat-old", tc.sessionRepoID, tc.sessionBranchSlug, "/tasks/flat-terminal/old", "feature/old", "active", now)
|
||||
|
||||
repo, err := NewWithDB(db, db, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("cutover: %v", err)
|
||||
}
|
||||
env, err := repo.GetTaskEnvironment(context.Background(), seed.envID)
|
||||
if err != nil {
|
||||
t.Fatalf("get task environment: %v", err)
|
||||
}
|
||||
|
||||
slots := make(map[string]string, len(env.Repos))
|
||||
for _, envRepo := range env.Repos {
|
||||
slots[envRepo.RepositoryID+"\x00"+envRepo.BranchSlug] = envRepo.WorktreeID
|
||||
}
|
||||
flatSlot := seed.repoID + "\x00"
|
||||
sessionSlot := tc.sessionRepoID + "\x00" + tc.sessionBranchSlug
|
||||
if len(env.Repos) != 2 || slots[flatSlot] != "wt-flat-current" || slots[sessionSlot] != "wt-flat-old" {
|
||||
t.Fatalf("preserved repository slots = %+v", env.Repos)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCutover_RejectsLiveWorktreeDifferentFromFlatOwner proves that a
|
||||
// non-terminal session with a different physical identity still fails closed.
|
||||
func TestCutover_RejectsLiveWorktreeDifferentFromFlatOwner(t *testing.T) {
|
||||
for _, state := range []string{"RUNNING", "WAITING_FOR_INPUT"} {
|
||||
t.Run(state, func(t *testing.T) {
|
||||
db := openLegacyDB(t)
|
||||
now := time.Now().UTC().Truncate(time.Second)
|
||||
seed := legacySeed{envID: "env-flat-live", taskID: "task-flat-live", repoID: "repo-flat-live", sessionID: "sess-flat-live"}
|
||||
seedLegacyTask(t, db, seed, now)
|
||||
if _, err := db.Exec(db.Rebind(`UPDATE task_sessions SET state = ? WHERE id = ?`), state, seed.sessionID); err != nil {
|
||||
t.Fatalf("set session state: %v", err)
|
||||
}
|
||||
seedLegacyFlatEnv(t, db, seed, "wt-flat-current", "/tasks/flat-live/repo", "feature/current", now)
|
||||
seedLegacySessionWorktree(t, db, seed.sessionID, "wt-flat-live", seed.repoID, "", "/tasks/flat-live/old", "feature/live", "active", now)
|
||||
|
||||
_, err := NewWithDB(db, db, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected live worktree conflict")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "conflict") {
|
||||
t.Fatalf("error must describe the conflict, got: %v", err)
|
||||
}
|
||||
if !legacyTableExists(t, db, "task_session_worktrees") {
|
||||
t.Fatal("legacy table must survive a failed cutover")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCutover_IgnoresDeletedHistoricalSessionConflict proves that a deleted
|
||||
// session reference cannot override an existing task-owned repository row.
|
||||
func TestCutover_IgnoresDeletedHistoricalSessionConflict(t *testing.T) {
|
||||
|
||||
@@ -491,14 +491,17 @@ func (c *worktreeCutover) isSupersededSessionWorktree(wt legacySessionWorktree)
|
||||
case hasSession && c.authoritativeWorktreeIDs[authoritativeWorktreeKey(ownerTaskID, wt.worktreeID)]:
|
||||
superseded = true
|
||||
case hasSession && isLegacyHistoricalSession(session.state):
|
||||
for _, row := range c.envRepos {
|
||||
env, ok := c.envs[row.envID]
|
||||
if !ok || env.taskID != ownerTaskID || row.worktreeID == "" {
|
||||
continue
|
||||
}
|
||||
if row.repositoryID == wt.repositoryID && row.branchSlug == wt.branchSlug {
|
||||
superseded = true
|
||||
break
|
||||
superseded = c.flatEnvironmentSupersedesSessionWorktree(wt, session, ownerTaskID)
|
||||
if !superseded {
|
||||
for _, row := range c.envRepos {
|
||||
env, ok := c.envs[row.envID]
|
||||
if !ok || env.taskID != ownerTaskID || row.worktreeID == "" {
|
||||
continue
|
||||
}
|
||||
if row.repositoryID == wt.repositoryID && row.branchSlug == wt.branchSlug {
|
||||
superseded = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -506,6 +509,24 @@ func (c *worktreeCutover) isSupersededSessionWorktree(wt legacySessionWorktree)
|
||||
return superseded
|
||||
}
|
||||
|
||||
// flatEnvironmentSupersedesSessionWorktree reports whether a surviving flat
|
||||
// environment owns the session's repository slot. Terminal history may carry
|
||||
// an older physical identity, but only for the task that owns the session's
|
||||
// environment and the legacy empty branch slot.
|
||||
func (c *worktreeCutover) flatEnvironmentSupersedesSessionWorktree(
|
||||
wt legacySessionWorktree, session *legacySession, ownerTaskID string,
|
||||
) bool {
|
||||
if !isLegacyHistoricalSession(session.state) || wt.branchSlug != "" {
|
||||
return false
|
||||
}
|
||||
envID, ok := c.taskEnvIDs[ownerTaskID]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
env, ok := c.envs[envID]
|
||||
return ok && env.taskID == ownerTaskID && env.repositoryID == wt.repositoryID && env.worktreeID != ""
|
||||
}
|
||||
|
||||
// sessionOwnerTaskID returns the task that owns the environment a session
|
||||
// resolves to. A session does not always run in an environment owned by its
|
||||
// own task: workspace-group members, subtasks inheriting their parent's
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
---
|
||||
spec: docs/specs/session-delete-resource-cleanup/spec.md
|
||||
created: 2026-08-10
|
||||
status: complete
|
||||
---
|
||||
|
||||
# Fix Plan: Normalize Terminal Worktree History
|
||||
|
||||
## Overview
|
||||
|
||||
Issue #2505 reports a startup error during the task-worktree ownership cutover.
|
||||
The repair extends the existing source precedence for terminal session history.
|
||||
The cutover will keep the surviving flat environment owner for the same
|
||||
repository slot, even when the terminal row has an older worktree ID.
|
||||
|
||||
## Root Cause
|
||||
|
||||
The cutover loads the surviving flat environment before legacy session rows.
|
||||
`isSupersededSessionWorktree` discards a terminal row with a different worktree
|
||||
ID only when `task_environment_repos` owns the same repository slot. It does not
|
||||
apply this rule when the surviving flat environment owns that slot. Therefore,
|
||||
`mergeSessionWorktree` tries to claim the terminal row and returns the exact
|
||||
`worktree A conflicts with B` error from issue #2505.
|
||||
|
||||
A focused temporary test reproduced the reported error. The fixture used a
|
||||
`COMPLETED` session, an older session worktree, and a newer flat environment
|
||||
worktree for the same repository slot. The temporary test passed because it
|
||||
expected the current startup error, and it was then removed.
|
||||
|
||||
## Backend
|
||||
|
||||
### Terminal history classification
|
||||
|
||||
Update
|
||||
`apps/backend/internal/task/repository/sqlite/worktree_ownership_normalize.go`.
|
||||
Extend `isSupersededSessionWorktree` with one source-precedence helper. The
|
||||
helper must recognize the surviving flat environment as the owner only when all
|
||||
of these conditions are true:
|
||||
|
||||
- The session state is `COMPLETED`, `FAILED`, or `CANCELLED`.
|
||||
- The flat environment belongs to the task that owns the session environment.
|
||||
- The repository ID matches the session row.
|
||||
- The legacy session row uses an empty `branchSlug`. The flat environment has
|
||||
no `branchSlug` field.
|
||||
- The flat environment has a non-empty worktree ID.
|
||||
|
||||
Keep the current canonical repository-row rule. Keep deleted-row handling and
|
||||
same-identity precedence unchanged. Non-terminal rows with different physical
|
||||
IDs must still stop the migration.
|
||||
|
||||
The existing `isSupersededSessionWorktree` predicate is also used by inventory
|
||||
and owner validation. Therefore, merge and validation will use the same rule.
|
||||
|
||||
## Tests
|
||||
|
||||
- **What:** A terminal session row with an older worktree ID does not override
|
||||
the surviving flat environment for the same repository slot.
|
||||
**File:**
|
||||
`apps/backend/internal/task/repository/sqlite/worktree_ownership_migration_test.go`.
|
||||
**How:** Use a table-driven SQLite migration test for `COMPLETED`, `FAILED`,
|
||||
and `CANCELLED`. Assert that startup succeeds and retains the flat owner.
|
||||
- **What:** A resumable session row with a different worktree ID still stops
|
||||
the migration.
|
||||
**File:** the same migration test file.
|
||||
**How:** Seed `RUNNING` and `WAITING_FOR_INPUT` states against a flat owner.
|
||||
Assert the conflict and the complete legacy rollback.
|
||||
- **What:** Terminal history outside the flat repository slot remains.
|
||||
**File:** the same migration test file.
|
||||
**How:** Use a different repository ID or a non-empty `branchSlug`. Assert
|
||||
that the migration retains both worktrees.
|
||||
- **What:** Existing cutover precedence, inventory, rollback, and replay
|
||||
behavior remains valid.
|
||||
**File:** the existing SQLite repository test package.
|
||||
**How:** Run the focused tests, all cutover tests, and the package tests.
|
||||
|
||||
## Verification Results
|
||||
|
||||
- TDD red: `TestCutover_IgnoresTerminalWorktreeDifferentFromFlatOwner` failed
|
||||
for `COMPLETED`, `FAILED`, and `CANCELLED` with the reported flat-owner
|
||||
worktree conflict before the production change.
|
||||
- The shared supersession predicate now recognizes a surviving flat environment
|
||||
for the owning task, matching repository ID and the legacy empty branch slot,
|
||||
only for terminal session history. Canonical repository precedence remains
|
||||
unchanged, and live sessions still fail closed.
|
||||
- Focused regressions passed: `8 passed`.
|
||||
- All cutover tests passed: `41 passed`.
|
||||
- SQLite repository package passed: `385 passed`.
|
||||
- `git diff --check` passed.
|
||||
- Changed files are limited to the cutover predicate, its migration tests, the
|
||||
amended repair spec, and this plan/task package. No temporary reproduction
|
||||
files remain.
|
||||
|
||||
## Implementation Waves And Parallel Candidates
|
||||
|
||||
Wave 1, sequential:
|
||||
|
||||
- [x] [task-01-normalize-terminal-history](task-01-normalize-terminal-history.md)
|
||||
|
||||
No task is parallel-safe. The classification and migration tests share one
|
||||
persistence boundary.
|
||||
|
||||
## Risks
|
||||
|
||||
- A broad terminal-state bypass can discard a worktree from another repository
|
||||
or branch slot. The helper must match the exact slot.
|
||||
- A non-terminal bypass can hide two active physical owners. The current
|
||||
fail-closed rule must remain.
|
||||
- Merge and inventory rules can diverge. Both paths must use the existing shared
|
||||
supersession predicate.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Manual changes to an affected database.
|
||||
- File-system or Git reconciliation during startup.
|
||||
- Changes to task or session behavior after the one-time cutover.
|
||||
- Public recovery documentation. The current backup guidance remains correct.
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
---
|
||||
id: "01-normalize-terminal-history"
|
||||
title: "Normalize terminal worktree history"
|
||||
status: done
|
||||
wave: 1
|
||||
depends_on: []
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/session-delete-resource-cleanup/spec.md"
|
||||
---
|
||||
|
||||
# Task 01: Normalize Terminal Worktree History
|
||||
|
||||
## Acceptance
|
||||
|
||||
- Terminal session history cannot override the surviving flat environment for
|
||||
the same repository and empty branch slot.
|
||||
- Terminal history for a different repository or non-empty branch slot remains.
|
||||
- `RUNNING` and `WAITING_FOR_INPUT` sessions with different physical worktree
|
||||
IDs still stop the cutover and preserve the legacy database.
|
||||
- Merge, inventory, rollback, and replay tests pass with one shared
|
||||
supersession rule.
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
make -C apps/backend test GOFLAGS="-v -run=TestCutover_(IgnoresTerminalWorktreeDifferentFromFlatOwner|PreservesTerminalWorktreeOutsideFlatOwnerSlot|RejectsLiveWorktreeDifferentFromFlatOwner|ConflictingWorktreesFailClosed) -count=1"
|
||||
make -C apps/backend test GOFLAGS="-v -run=TestCutover -count=1"
|
||||
make -C apps/backend test GOFLAGS="-v -count=1"
|
||||
```
|
||||
|
||||
## Files Likely Touched
|
||||
|
||||
- `apps/backend/internal/task/repository/sqlite/worktree_ownership_normalize.go`
|
||||
- `apps/backend/internal/task/repository/sqlite/worktree_ownership_migration_test.go`
|
||||
- `docs/specs/session-delete-resource-cleanup/spec.md`
|
||||
- `docs/plans/task-owned-worktree-cutover-terminal-history/plan.md`
|
||||
- `docs/plans/task-owned-worktree-cutover-terminal-history/task-01-normalize-terminal-history.md`
|
||||
|
||||
## Dependencies
|
||||
|
||||
None.
|
||||
|
||||
## Parallelism
|
||||
|
||||
Sequential. The source classification and migration tests share one
|
||||
persistence boundary.
|
||||
|
||||
## Inputs
|
||||
|
||||
- The schema-normalization and failure-mode sections of the repair spec.
|
||||
- The root-cause section of `plan.md`.
|
||||
- Existing `isSupersededSessionWorktree`, `mergeSessionWorktree`, and
|
||||
`legacyWorktreeInventory` behavior.
|
||||
- Existing terminal-history, physical-identity, rollback, and replay tests.
|
||||
- Issue #2505 and the temporary reproduction result in `plan.md`.
|
||||
|
||||
## Output Contract
|
||||
|
||||
Report the classification change, files changed, and exact test results. Report
|
||||
all temporary-file cleanup. Update this task and `plan.md` in the same
|
||||
conversation.
|
||||
|
||||
## Results
|
||||
|
||||
- **RED:**
|
||||
`go test ./internal/task/repository/sqlite -run
|
||||
'TestCutover_IgnoresTerminalWorktreeDifferentFromFlatOwner' -count=1`
|
||||
failed for all three terminal states with `worktree wt-flat-old conflicts
|
||||
with wt-flat-current`.
|
||||
- **Implementation:** extended `isSupersededSessionWorktree` with a shared
|
||||
flat-environment source-precedence helper. The helper uses the task's direct
|
||||
environment lookup. It requires a matching repository ID, the legacy empty
|
||||
branch slot, a non-empty flat worktree ID, and a terminal session state.
|
||||
Canonical repository-row precedence and live-session fail-closed behavior
|
||||
remain unchanged.
|
||||
- **Focused regressions:**
|
||||
`make -C apps/backend test GOFLAGS="-v -run=TestCutover_(IgnoresTerminalWorktreeDifferentFromFlatOwner|PreservesTerminalWorktreeOutsideFlatOwnerSlot|RejectsLiveWorktreeDifferentFromFlatOwner|ConflictingWorktreesFailClosed) -count=1"`
|
||||
passed with `11 passed`.
|
||||
- **Cutover suite:**
|
||||
`make -C apps/backend test GOFLAGS="-v -run=TestCutover -count=1"` passed
|
||||
with `44 passed`.
|
||||
- **Backend suite:** `make -C apps/backend test GOFLAGS="-v -count=1"` passed.
|
||||
- **Hygiene:** `git diff --check` passed. The temporary reproduction test in
|
||||
`plan.md` was removed. No temporary reproduction files remain.
|
||||
@@ -120,10 +120,14 @@ environment across tasks. Such a borrowing task gains no environment of its
|
||||
own, and the shared physical worktree keeps exactly one owner.
|
||||
Legacy session rows marked `deleted` (or carrying `deleted_at`) and stale
|
||||
references from terminal sessions are historical evidence, not additional
|
||||
owners, and bypass validation only when a canonical repository owner exists.
|
||||
A terminal-only reference without a canonical owner, a non-terminal session,
|
||||
or a worktree that has no canonical owner still requires compatible identity,
|
||||
path, branch, and repository data; unresolved ownership fails closed with a
|
||||
owners. A terminal reference bypasses validation when a higher-precedence
|
||||
task-owned source exists for the same repository and branch slot. This source
|
||||
can be a canonical repository row or the surviving flat environment row. The
|
||||
higher-precedence source remains the owner when the terminal reference carries
|
||||
a different physical `worktree_id`. A terminal-only reference without a
|
||||
higher-precedence owner still requires compatible identity, path, branch, and
|
||||
repository data. A non-terminal session with a different physical identity
|
||||
also requires compatible data. Unresolved ownership fails closed with a
|
||||
diagnostic.
|
||||
|
||||
After backfill validation, the same upgrade drops `task_session_worktrees` and
|
||||
@@ -220,8 +224,9 @@ remain the authorization boundary for physical cleanup.
|
||||
closed, the transaction rolls back, and the pre-upgrade database remains
|
||||
authoritative instead of authorizing future deletion from ambiguous data.
|
||||
- Historical deleted session-worktree rows and stale references from terminal
|
||||
sessions do not block migration when a canonical task-owned repository row
|
||||
exists; the canonical row remains authoritative.
|
||||
sessions do not block migration when a higher-precedence task-owned source
|
||||
exists for the same repository and branch slot. The higher-precedence source
|
||||
remains authoritative.
|
||||
- A legacy session row that repeats a higher-precedence physical `worktree_id`
|
||||
cannot block migration solely because its path or branch metadata is stale,
|
||||
including when the session is resumable. The higher-precedence repository or
|
||||
@@ -297,6 +302,10 @@ remain the authorization boundary for physical cleanup.
|
||||
repeats the surviving task environment's `worktree_id` with stale path or
|
||||
branch metadata, **WHEN** the new binary starts, **THEN** the flat environment
|
||||
metadata is retained and the cutover completes.
|
||||
- **GIVEN** a terminal legacy session references an older physical worktree for
|
||||
the surviving flat environment's repository slot, **WHEN** the new binary
|
||||
starts, **THEN** the flat environment remains the owner and the cutover
|
||||
completes.
|
||||
- **GIVEN** a legacy session of one task is bound to another task's environment
|
||||
and carries a session-worktree row for that shared workspace, **WHEN** the new
|
||||
binary starts, **THEN** the worktree is normalized onto the owning task's
|
||||
|
||||
Reference in New Issue
Block a user