Skip to content

feat(worktrees): clean up worktrees by policy and manage them per thread - #82

Merged
nixuuu merged 1 commit into
feat/worktrees-1from
feat/worktrees-2
Nov 4, 2026
Merged

nixuuu merged 1 commit into
feat/worktrees-1from
feat/worktrees-2

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 4, 2026

Copy link
Copy Markdown
Member

Stage 2 of git worktree support (on top of #74).

  • Cleanup policies in Settings → Worktrees with the stage 1 scopes: with deleted threads, merged branches (git ancestry after fetch), inactive for N days, settled threads, only unchanged worktrees vs. keeping those with local changes. Dirty or unpushed worktrees are never removed without explicit confirmation.
  • Cleanup engine on the gateway schedule, executed on the owning worker; dry-run preview in Settings; every removal audited; durable retries when the worker is offline; path containment (never the main checkout or anything outside worktree roots).
  • Per-worktree status (branch, ahead/behind, dirty files, last activity) and actions (copy path / reveal, remove) from the thread and a Worktrees list in Settings.
  • Composer picker row now wraps as a group with aligned controls at desktop and phone widths.
  • Migration 0065 (both worktree migrations will be renumbered after feat(workers): edit worker tags when adding and in the workers view #75's 0064 before the stack merges).

Known gap: squash-merged branches are not detected as merged by git ancestry; handled in the next stage.

Checks: install, gen:check, typecheck, lint, format:check, check:tmp (972 pass, 152 skip, 0 fail), web build. Browser checked light/dark at desktop and phone widths.

Draft until the whole stack is done.

@nixuuu
nixuuu added this pull request to stack #83 November 4, 2026 18:09
@nixuuu
nixuuu marked this pull request as ready for review November 4, 2026 19:02
@nixuuu
nixuuu merged commit 5be451d into dev Nov 4, 2026
10 checks passed
@nixuuu
nixuuu deleted the feat/worktrees-2 branch November 4, 2026 19:02
nixuuu added a commit that referenced this pull request Nov 4, 2026
Stage 3 (final for now) of git worktree support, on top of #82.

- **Squash-merge detection** for the "merged" cleanup policy and status:
a branch counts as merged when its PR is merged (owner-scoped GitHub
connector, checked in the gateway, no credentials on the worker) or,
without a connector, when all its commits are patch-equivalent to the
base or its changes are fully contained in the base after fetch. Covers
squash-merged and rebased branches; partially merged ones stay.
- **Worktrees for automation:** agent-spawned threads (`spawn_thread`),
bots running code tasks and scheduled tasks follow the scoped worktree
settings, with an explicit option (current checkout / new worktree /
inherit). Side threads inherit their parent's worktree by default.
Cleanup policies cover them.
- Linked-computer threads keep a clear refusal (linked computers are
desktop-only, #88); worktrees across linked computers are a later,
separate change.
- Migration `0068_worktree_automation`. The whole stack was rebased onto
current dev with migrations 0066–0068.

Known limitation: if thread creation fails after its worktree was
created, the worktree stays on disk until cleanup.

Checks per stage: install, gen:check, typecheck, lint, format:check,
shard check. Top: check:tmp (1,035 pass, 153 skip, 0 fail), web build;
composer and Settings → Worktrees checked in light/dark at desktop and
phone widths.
nixuuu added a commit that referenced this pull request Nov 6, 2026
Stage 3 of 4, mobile parity round 2: where a thread runs.

**Changed**
- **Linked computers:** the overview state keeps `computers` and handles
`computer`, `computer_removed` and `computer_snapshot`. The phone's
snapshot already carries the linked computers' workers, projects and
threads.
- **Worker picker** of a new thread, as on the web:
- workers grouped by computer: "This computer" first, then linked
computers by name;
- a worker on a linked computer this one cannot reach is greyed out with
its status ("Unreachable") and reason ("Studio Mac is unreachable since
6:45 AM.");
- the worker pill shows "worker · computer" for a linked one, and the
blocker uses the same reason.
- The presence rules (`computerName`, `sharesThreads`, `awayReason`, …)
move from the web to `@canopy/domain/computer-presence`, and the web
imports them from there. The web formats times with its own clock
settings.
- **Worktrees** (as #74, #82, #90): when the worker offers worktrees and
the folder is a git repository (`ListGitRefs`), the new thread shows:
- a workspace pill: Current checkout, New worktree, or a previous
worktree;
- the branch: read-only for the checkout and earlier worktrees, a base
ref picker (Branches, Remote branches) for a new worktree.
- The worktree settings' default mode applies until you pick.
`CreateThread` gets `workspace_mode`, `base_ref` and `worktree_id`.

**Checked**
- Gates clean, as in stage 1. Web typecheck covers the moved presence
rules.
- Android emulator, light and dark, unfolded and phone width:
- workspace and base ref pickers with a long branch name, against a
scripted worker that lists refs;
- the worker picker grouped by computer, with one reachable and one
unreachable linked computer. These came from overview data injected
locally for the check; no real link between two gateways.
- **Not checked on the device:** creating a thread in a new worktree end
to end (the scripted worker reports no agents for new threads).

**Copy audit (§8)**
- "This computer", "Unreachable" and the reasons ("‹Name› is unreachable
since 7:42 PM."): the web's text.
- "Workspace", "Current checkout", "Works in the project's directory",
"New worktree", "A new branch in its own directory", "Previous
worktrees", "Created 2 days ago", "Base ref", "Branches", "Remote
branches", "Default", "Current": from the web pickers.
nixuuu added a commit that referenced this pull request Nov 17, 2026
Ignore Git-ignored files during cleanup scans. Enabled archived/deleted thread rules authorize discarding local files and removing the checkout despite unpushed or squash-diverged commits, while retaining its local branch. Recheck that authorization atomically before persisting removal and fence reopening against cleanup.

Fixes: #82
nixuuu added a commit that referenced this pull request Nov 17, 2026
Archived worktrees remained on disk because ignored dependencies/build
output counted as local changes, and cleanup still required manual
confirmation after squash merges or remote branch deletion.

Exclude Git-ignored files from cleanup status. Enabling Archived threads
or Deleted threads authorizes removing the checkout and discarding local
files once all sharing threads meet that rule, even when Git reports
unpushed commits. Preserve the local branch whenever ordinary local
changes or unpushed commits exist. Other cleanup rules and manual
removal retain their confirmation requirements.

Validate closed-thread authorization under the reservation transaction's
locks before persisting a removal command. Block unarchive/restore
during removal, keep worker activity/HEAD/path checks, and stop treating
paused goals of closed threads as active work. Update settings copy and
the worktree documentation.

Fixes: #82

## Validation

- 59 affected integration tests passed across worktree lifecycle,
closed-thread cleanup, squash/rebase cleanup, automation and archive
resource cleanup. Corrected lifecycle and automation tests were rerun
selectively; passing files with unchanged inputs were reused. The
`check:tmp` runs left no test temporary files.
- Gateway, worker, mobile and integration package typechecks passed.
Lint passed on all edited source/test files; edited supported files were
formatted.
- Web settings inspected at 1440 px and 390 px in light/dark, with no
horizontal overflow. Native layouts were unchanged; mobile copy was
reviewed and typechecked.
- Full generation, repository checks and builds remain with CI. No
protobuf or migration changes.

## Copy audit (§8)

- 1–2: Archived/Deleted descriptions now explicitly say “discard local
files”; mobile “Settled threads” becomes “Archived threads”. Changed
sentences use plain English, sentence case, glossary terms and stay
within length limits.
- 3–4: The mobile cleanup confirmation now asks “Clean up worktrees?”
and states the actual effect. The new reopen error explains the blocker
and retry action.
- 5–8: Removed misleading “Local changes stay” and blanket local-work
protection promises. No empty-state changes, repeated effects, new
jargon or humor.
- 9–10: Fixed setting descriptions inspected in the browser at
desktop/phone widths and light/dark; no changed text interpolates user
names. Meaning is explicit text and does not rely on color or icons.
nixuuu added a commit that referenced this pull request Nov 26, 2026
## Incident

Five gateway updates spent 217–453 seconds waiting for background jobs
during shutdown. In the latest case, 148 worktree scans completed during
five full minutes of the 390-second wait. The new gateway was listening
about two seconds after the wait ended. Local Desktop runs the same
cleanup scheduler.

## Changes

- Stop the scheduled inventory scan on shutdown. Cancel outstanding
reads from workers and merge checks, and leave the remaining worktrees
for the next pass.
- Once a removal is reserved, finish the worker command and persist its
result. Report the individual background job if shutdown takes more than
five seconds.
- Manual cleanup and preview keep their existing behavior.

## Verification

The integration regression reproduced the hang on the base revision with
a worker reply held open. The fixed gateway stops while that reply is
held. A separate integration test holds a removal acknowledgement and
verifies its database result after shutdown.

Locally, 36 focused tests, gateway typechecking, and lint on the changed
files passed. A separate Linux Local Desktop check exercised worker,
gateway and PostgreSQL shutdown. Native macOS and Windows installer
timing was not measured. Full repository checks run in CI.

Fixes: #82
nixuuu added a commit that referenced this pull request Nov 26, 2026
## Change

The hourly cleanup, startup scan and worker reconnect used to fetch and
inspect each managed checkout on an available worker. A read-only
production snapshot on November 26 had 287 live entries. After external
entries and offline workers, 276 could receive a scan. Of those, 1 was
busy, 40 were protected by recent archival and 208 could not match the
enabled policy. The remaining 27 shared one worker, repository path and
remote. Worker availability in this estimate uses the database lease.

The gateway now checks the owner-scoped inventory and effective policy
before sending a scheduled scan. A scope snapshot only filters
candidates. Each admitted candidate uses current settings and its own
checkout status. After one successful scan, later candidates for the
same repository path and remote reuse fetched refs on that worker
connection for the rest of the pass. The worker also skips a duplicate
merge check when both ref names are identical.

Reserved commands retain their replay path. The worker fetches again and
checks the expected HEAD, local changes and required merge evidence
before removing a checkout. Manual preview and execution still scan each
managed checkout in scope. A newly merged branch can be picked up at the
following refresh.

## Isolated measurement

Three alternating pairs of runs through the global scheduler tick, using
a fresh PostgreSQL database, a real gateway, a WorkerHost and local bare
remotes per run. The baseline has the same source tree as the merged
shutdown fix in #1320. Each of three projects had 12 worktrees on one
worker with 512 tracked files per repository. The policies were merged,
all rules disabled, and archived or 30 days inactive. The fixture
included busy threads, recent and older archives, dirty files and
unpushed commits.

| Per pass, median of three runs | Before | After |
| --- | ---: | ---: |
| Wall time | 6.403 s | 2.312 s |
| Scan RPCs / cumulative time | 36 / 5.164 s | 10 / 1.179 s |
| Removal RPCs / cumulative time | 5 / 1.056 s | 5 / 0.966 s |
| Top-level worker Git processes / cumulative Git time | 980 / 3.013 s |
351 / 0.950 s |
| Fetch | 41 / 855 ms | 7 / 153 ms |
| Status | 41 / 439 ms | 15 / 136 ms |
| Git commands during merge verification | 258 / 591 ms | 79 / 185 ms |
| SQL executions / cumulative client time | 168 / 243 ms | 107 / 159 ms
|

All runs removed the same five checkouts on disk and in PostgreSQL. The
seven remaining fetches comprise two candidate-repository refreshes and
five pre-removal rechecks. RPC durations include worker execution, so
the Git timings overlap them. The local remotes exercise Git merge
detection without network latency or a GitHub API account. The
measurement harness runs outside required CI.

## Verification

68 integration tests passed locally across worktree-lifecycle,
worktree-merged, worktree-closed-cleanup and worktree-github, with a
clean check:tmp result. New regressions exercise the skipped scan RPC
plus full manual preview, and the loss of the remote between the first
removal and the next candidate. In the latter case the worker rejects
the reserved removal and the gateway releases the reservation. The suite
also covers reconnect replay, cancellation during a read, settlement
after shutdown begins, and owner/project-scoped merge proof.

Lint and formatting passed on the six edited TypeScript files. The
repository-wide typecheck, builds and remaining tests run in CI.

The first CI run (733fe3e) exposed a Git-version difference in the new
regression fixture. Pushing by URL had already advanced the worker’s
tracking ref on the runner. The fixture now advances the bare repository
from the other side, leaving that tracking ref stale until the scheduled
fetch. All seven worktree-merged tests passed locally with the adjusted
fixture. The first run also rejected the skill preview in
config-sync-environment.test.ts with a stale-report error on shard 8.
That focused linked-computer test passed locally on the original
revision.

Fixes: #82

Related: #1320
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant