grove · worktrees

Roots and worktrees

A root is a declared repository: [roots."owner/name"] in the manifest, and roots/owner/name/ on disk — the directory holding everything grove owns for it. Its code dir is code/owner/name/, which holds checkouts and only checkouts. A worktree is a branch of that root checked out in the code dir, a direct sibling of the trunk. Roots and worktrees are declared in manifest.toml and realized in git, and convergence between the two is two-way and additive.

The manifest

$GROVE_HOME/manifest.toml is desired state, and the only durable thing grove writes besides git itself. grove_ops::manifest is its sole owner: it edits format-preservingly through toml_edit under an exclusive advisory flock on a sibling manifest.toml.lock (never the manifest itself, which every write replaces by rename), so grove's writes never clobber a human's comments.

# my repos                              # comments survive every grove write

[roots."owner/name"]
url   = "git@github.com:owner/name.git"
trunk = "canary"                        # integrates here; absent → the remote's HEAD

[roots."owner/name".pool]
size = 2                                # warm slots to keep ready; default 0

[roots."owner/name".env]
_.symlink = [".env"]                    # shared live into every worktree
_.copy = ["config/local.json"]          # seeded once per worktree

[roots."owner/name".worktrees.feature-x]
branch = "feature/x"
base = "canary"                         # absent for worktrees adopted from git

trunk names the branch grove integrates on: the one its checkout is named after, the one sync fast-forwards, and the one every share reads through. Absent — the common case — it is the remote's HEAD, whatever the clone landed on.

base is where a new branch forks from, and grove tree add without --base resolves it to the trunk branch and records it — named explicitly rather than left to git, whose own default start point is the bare's HEAD; the two differ between a trunk edit and the reconcile that applies it. A root not yet on disk resolves to nothing and the base stays unset, for the realizer to fill.

_.symlink/_.copy are TOML dotted keys nesting as env → _ → symlink, not literal "_.symlink" keys — mise's _ directive-namespace convention. _.setup, a per-worktree setup command, is reserved and not implemented.

Structure and spacing are canonicalized on every write and on every hand-edit the watcher sees: roots as standalone [roots."slug"] tables sorted by slug, each root's sub-tables regrouped, worktrees sorted by name, one blank line between tables. Canonicalization is write-if-changed, so it does not loop on its own file-change event, and a top-level table that is not under [roots] is left untouched.

Validation

Four validators guard the boundary between a declaration and a filesystem path or a git argument, applied at the declaring API and when reading a hand-edited or git-synced manifest.

validatorrule
validate_slugnon-empty relative path whose every / segment is a real name — no .., ., or empty segment, so no absolute, doubled-/ or trailing-/ spelling (o/r/ would be a second manifest and lane key for o/r); no backslash; no ASCII control characters
validate_nameexactly one Normal segment (so no /), the slug rules otherwise, and never a dotted name — no checkout can be spelled that way
validate_share_pathone or more safe segments (nesting allowed), canonical — no ., empty (//) or trailing-/ segments — no segment beginning with -, and no dotted first segment once the path nests (.env is a share; a path under a dotted entry is not)
validate_ref_arga branch, base or trunk is non-empty and does not begin with -, so a crafted declaration cannot smuggle a git flag

A root url git would read as a relative path (manifest::is_relative_path) is a doctor finding, not a refusal: it resolves against the realizer's cwd, and the daemon's is /. grove clone add never writes one — it expands owner/name to git@github.com:owner/name.git and pins any other relative path to its own cwd.

Slugs keep the case they were declared in, and manifest::add_root refuses one that differs from a declared slug only in ASCII case (Foo/bar beside foo/bar), naming the declared one: on a case-insensitive filesystem, APFS's default, the two name one directory. It refuses a slug that nests with a declared one at a segment boundary, in either direction and either case (o/r/bare or o beside o/r; never o/rr), since one root's directories would sit inside the other's: o/r/bare's root dir is o/r's bare. Re-declaring a slug already declared updates its URL, even beside a case twin a hand edit left.

The dot rule. Git refuses a ref component beginning with a dot, so no branch — and therefore no directory worktrees::name_for derives from one — is ever spelled that way. A dotted entry in a code dir is somebody else's artefact: grove neither declares nor adopts it (worktrees::is_reserved), and a dotted declaration is rejected because no adoption could read it back as a checkout.

The share-path gate is the string half of a two-gate posture; the filesystem half is the O_NOFOLLOW descent in § The worktree environment.

On-disk layout

$GROVE_HOME/
├── manifest.toml
├── manifest.toml.lock                     # serializes manifest read-modify-write
├── grove.lock · grove.pid · serve.log     # daemon custody and its log
├── code/
│   └── owner/name/                        # the code dir — checkouts, and only checkouts
│       ├── canary/                        # the trunk: the checkout of the trunk branch
│       └── feature-x/                     # a worktree — a direct sibling of the trunk
└── roots/
    └── owner/name/                        # the root — everything grove owns for it
        ├── bare/                          # the bare clone
        ├── pool/slot-0/                   # warm slots, detached at the trunk tip
        └── cloning                        # the marker, while a clone and its passes run

The binary is not in this tree: hotswap keeps it in ~/.local/share/hotswap/grove, outside $GROVE_HOME (install and upgrade).

roots::root_dir and roots::code_dir are the published definition of the two joins, roots::bare_dir of the bare, pool::pool_dir of the pool and roots::trunk of the trunk; nothing else in the tree recomputes them.

A code dir holds checkouts and only checkouts. Every entry is a git worktree of the root's bare; the one tolerated stranger is Finder's .DS_Store, the only name roots::foreign_entries skips.

One root, one directory. The bare, the warm pool and the in-flight-clone marker all live under roots/<slug>/, so a removal deletes a root completely by deleting two paths. The bare is the subdirectory bare/, never roots/<slug> itself: a bare repository at the root directory would make that directory look like a repository to every tool that walks upward, so git status under it errors and an editor opened there sees no working tree.

Checkout depth is load-bearing. Every checkout — the trunk included — is a direct child of the code dir, and shares materialize only at that canonical depth. worktrees::name_for folds a branch name's / to - (feature/x → feature-x), the one branch-to-directory rule in grove: grove tree add, the trunk and share targets all read it. worktrees::adoptable_name refuses anything more than one segment below the code dir. A warm-pool slot sits outside the code tree altogether, so it is not at canonical depth and materializes nothing while it is a slot — a relative ../<trunk>/<p> from roots/<slug>/pool/slot-N/ resolves inside the pool, not against the trunk. Promote is what puts it right, and it is one git worktree move into the code dir: worktree pointers are absolute, so crossing between the two trees costs a checkout nothing, and the links materialize correctly the moment it lands.

A root on an earlier layout generation is doctor's legacy_layout finding, and grove doctor --fix migrates it in place. Realization refuses such a root rather than cloning beside it (§ Root realization); generations: api.html § Doctor.

The trunk

The trunk is the checkout of the branch a root integrates on, named by worktrees::name_for(branch) exactly as every other checkout is (canary → canary/, release/2 → release-2/), and what tells it apart from its siblings is that the manifest points at it.

roots::trunk(home, slug) -> Trunk { branch, name, dir } is the one resolution, and nothing else spells the trunk's path. Desired state is read first — the root's trunk key when it declares one — else the bare's HEAD, which reconcile sets from that same declaration. So a root adopted off disk has a trunk too, whatever it was cloned onto, and a freshly-declared trunk resolves here before any convergence has run. A manifest that cannot be read is an error, never a fall-back: HEAD stands in only for a trunk the manifest leaves undeclared, not one it hides. trunk_reads_the_declaration_and_falls_back_to_the_bares_head pins all three.

roots::trunk_dir is the same lookup for a caller with nowhere to put a failure — a presence probe, a doctor row. A root whose bare cannot be read falls back to <code>/main, so the probe reports "missing" rather than blanking; anything able to report an error calls trunk instead.

Changing the trunk is a manifest edit

Edit trunk, reconcile, and converge_trunk brings the disk onto it in three moves, each a no-op once it has run:

  • a worktrees.<name> entry already on the trunk branch is dropped — that checkout is the trunk now, and leaving it declared would put the root's integration checkout where a tree remove deletes it;
  • the trunk's checkout is created when nothing is there, an ordinary git worktree add from the bare;
  • HEAD is moved onto the trunk branch, so actual state answers the declaration — after a share pass, since HEAD is the one record of which links went through the old trunk, and only once that pass carried every share without an error (§ Never clobber).

No trunk is ever deleted by a trunk change. The previous trunk stays checked out where it is, and the worktree reconcile that follows adopts it into worktrees.<name> — an ordinary worktree from then on. a_trunk_change_creates_the_new_checkout_and_adopts_the_old_one and a_declared_worktree_on_the_new_trunk_branch_becomes_the_trunk pin the two directions.

The branch is proved to exist before anything is written, so a typo'd trunk leaves the root exactly as it was rather than minting the typo as a branch. A declared worktree already occupying the new trunk's directory on a different branch is two checkouts asking for one path: reconcile refuses, naming both.

Reconcile is two-way and additive

worktrees::reconcile(home, slug) converges declared against actual and never deletes:

  • declared, not in git → git worktree add at <code>/<name> on the declared branch (from base when the declaration records one). A recreate git refuses is reported as failed with git's reason, not silently dropped.
  • in git, not declared → written into the manifest as adopted, with no base (the fork point is unknown).
  • both → nothing.

The trunk is never one of the three: worktrees::adoptable_name excludes the root's own checkout by name, so it is neither adopted into worktrees nor recreated as one. The checkout a trunk change left behind is not the trunk any more, so it is adopted, like any other undeclared branch-carrying checkout.

Git-level ghosts are pruned first. A worktree directory removed out of band leaves a prunable registration that makes git report it as still present (masking the declared-but-missing case, so the recreate never fires) and refuses a re-add at that path. Pruning clears both, and deletes nothing real — the working tree is already gone.

Adoption needs a branch to record, so a detached checkout is never adopted. A declared detached worktree is left entirely alone: present, so no recreate; branchless, so no adoption. worktrees::actual retains detached checkouts with branch: None.

worktrees::list is the declared ⋈ actual join a UI draws: every declared worktree with whether git has it, plus every undeclared branch-carrying one, each with its own git status drift. branch is what the manifest declares; status.branch is what is actually checked out, and the two disagreeing is drift a dashboard flags and doctor reports as a worktree/mismatch check. A git status that fails is swallowed to None — one wedged checkout must not blank the whole list.

Root realization

roots::reconcile_one(home, slug) realizes one declared root: converge the trunk, clone the declared-but-missing bare, check the trunk branch out at <code>/<trunk name>, reconcile that root's worktrees, then materialize its shares. It is idempotent — a present root re-reconciles to a no-op.

Converging the trunk comes first, or an unapplied trunk change reads as a missing trunk checkout (the trunk recovery below).

Err is reserved for not-declared and lookup faults. A clone or guard failure is an Ok(Applied { status: Failed }), so one wedged root never aborts a sweep; grove_ops::apply (the offline grove apply) relies on that to report a failed root beside its healthy neighbours.

A root that nests with another declared root — a hand edit add_root never saw — is failed naming the other before anything is claimed, created or deleted, since its directories are the other's: a clone would write into the other's bare and a failed realize's cleanup would delete it.

A root that is not already present is decided by reading both of its directories, not the manifest: a bare that is not at roots/<slug>/bare is not the same as nothing being there. Four answers, least destructive first; only the last two write:

  1. Refuse a root on an earlier layout generation. Its bare sits inside the code dir, so every probe the clone arm makes reads missing against it and a clone would lay a second root beside the first. The outcome is failed with "run grove doctor --fix to migrate it in place", and nothing is created or removed. grove_ops::layout is the one spelling of the superseded names, read by doctor's legacy_layout finding and by the realizer, so the two cannot disagree about what a legacy root is (api.html § Doctor names the generations).
  2. Refuse an occupied code dir. A code dir holds checkouts and only checkouts, so anything already in it is somebody's and a clone would interleave grove's layout with theirs: the outcome is failed naming the entries. Occupied means anything but .DS_Store. The legacy check comes first because a legacy root's own entries would trip this one with the less useful answer.
  3. Re-add the trunk when the bare is there and its checkout is gone — it vanished out of band (a stray rm, a git worktree prune), or a clone crashed between the bare and the trunk. Prune, then git worktree add from the bare, touching nothing else under the root. It is refused when the bare carries other live worktrees — a user's checkouts, possibly with uncommitted work — as failed with "recreate it, or grove clone remove the root". That check fails safe: if git worktree list errors at all, grove assumes worktrees may exist and refuses. Two exclusions keep the count honest, and they need different tests: the trunk being recovered, matched by the basename that names it in the code dir, and the warm-pool slots, matched by path — a slot is registered under roots/<slug>/pool/, where its slot-N basename names nothing in the code dir.
  4. Clone, which is a root's first realization and, when the bare cannot produce a worktree at all, its re-clone. A re-clone deletes both of the root's directories first, so it happens only if the code dir holds nothing but .DS_Store and the bare holds no branch it cannot prove pushed (a bare without remote-tracking refs proves none) and no refs/stash, and names what it would have destroyed otherwise: the one unattended rm -rf of a directory a human also writes into.

A refusal is an Applied carrying its reason, so it reads the same on both realizers: grove apply prints failed <slug>: <reason> beside the roots that converged, and the daemon degrades that root, where it waits for an operator rather than a retry clock. grove doctor --fix is what clears a legacy root — it migrates the layout in place, and the engine re-derives the root as ready from disk on the next event.

A clone in flight writes a cloning marker at roots/<slug>/cloning for the length of the clone and the worktree and share passes after it: gix materializes the bare with its origin before a byte of the transfer lands, and adoption must not read that as a discovery, or an operator's undeclare is undone and the root re-cloned. A crashed clone leaves the marker behind. The realizer holds an exclusive flock on it throughout, and a lock dies with its process, which tells a live clone from a crashed one. A second realizer (another offline CLI, a daemon booted mid-clone) that finds the lock held touches nothing, even on a root already whole: the outcome is failed with "a clone of this root is in flight". A free lock on a leftover marker is a crashed clone's (or a trunk repair's that was refused over a human's files in the code dir), and the reconcile proceeds under it, removing the marker once the root is whole; a marker grove cannot open is failed naming the file. Re-adding a missing trunk claims a fresh marker when none is left over, so two realizers never repair one root together, and a lock counts only while the marker's path still names the inode it was taken on — one taken on a marker its holder just unlinked backs off as in flight.

Worktree reconcile and share materialization are best-effort inside reconcile_one — a share hiccup must not fail the root — but a worktree the reconcile cannot recreate is surfaced on stderr (the CLI prints it, the daemon's log pipeline picks it up).

Adoption

Adoption is discovery, and it never clones.

roots::adopt(home) walks $GROVE_HOME/roots/<org>/<repo> — the tree grove owns, never the code tree — and declares any slug whose bare/ has an origin remote and is not already declared. It:

  • skips dotfile directories (a .Trash under roots/ is not an org);
  • skips a name that is not UTF-8, reporting it as skipped with a lossy rendering for the operator's eyes only — a U+FFFD-laced slug would not round-trip to the real directory, so it is never minted;
  • skips a repo with no origin (no URL to record);
  • skips a root whose cloning marker is there, lock held or not — a clone in flight, its passes, or either crashed;
  • never overwrites a declared URL;
  • is best-effort per repo — one failure does not abort the rest;
  • canonicalizes the manifest at the end, so a pure hand-edit reorder is normalized even when the pass declared nothing.

The watcher runs adopt on every manifest save and at boot, then publishes roots_changed. The engines do the realizing.

A code dir with no root directory behind it is not adoptable — no bare, no URL. Doctor reports it as orphan_code, report-only (api.html § Doctor).

Removal: declared first, then delete on disk, then undeclare

roots::remove refuses a slug that is not declared before it builds any path it would hand to remove_dir_all, since <home>/code/<slug> is a real directory whether or not grove put it there. Undeclared is not_declared (exit 3) on both paths; the route answers 404.

It then surveys the root for unsaved work — uncommitted tracked changes, or commits no remote has, in any worktree under it (warm-pool slots excluded; untracked files are not the signal, since grove materializes shares as untracked entries); any local branch in the bare carrying unpushed commits, checked out or not (a bare keeps no reflog, so a removed tree's branch dies with it); a refs/stash; and any code-dir entry that is not a registered worktree of the bare (a human's clone or notes, what foreign_entries refuses to clone over) — and refuses with a conflict naming them unless the caller passed --force (Removal::Forced, force: true on the route).

Before either survey or delete it refuses, with a conflict in both modes, a slug that nests with another declared root — a hand-edited or git-synced manifest bypasses add_root's refusal — naming the other and telling the operator to undeclare one in the manifest. --force discards the operator's own unsaved work, never another root's tree.

Past every guard it deletes both of the root's directories — roots/<slug> and code/<slug> — and then removes the manifest entry. Both, because nothing of a root may survive either tree. Each is deleted only if it is there, since a declared-but-unrealized root has neither. remove_undeclares_and_deletes pins both halves gone.

Undeclaring first would let the watcher's adopt, run on the manifest save, re-declare the still-present bare and the engine re-clone it; adopt cannot resurrect a bare that is gone.

A partial remove_dir_all failure propagates before the undeclare, so the slug stays declared and doctor/reconcile report a broken root rather than adopt bringing it back.

worktrees::remove refuses an undeclared name for the same reason, then inverts the order: git first, then undeclare. Removing the manifest entry first would let the next reconcile re-adopt the still-registered worktree. When the directory is already gone out of band, grove prunes the stale git registration so the removal is git-visible before the undeclare. The git remove is never forced, and git counts shares as untracked files, so env::unlay first takes back what grove laid there (§ Removal); a user's untracked file still refuses it, and the shares are laid again.

Removing a root through the API pokes the watcher afterwards: a removed root's engine is torn down by the reconcile pass that follows, never by an explicit stop call. Removing a worktree sends no nudge — a worktree has no engine.

Sync

roots::sync(home, slug) requires a ready root and does four things, as one lane call: fetch the trunk branch (bounded, single refspec), fast-forward the trunk checkout onto the tracking ref, prune warm-pool slots stranded at a pre-sync tip, and report.

The branch is the manifest's trunk, not the bare's HEAD, so a sync between a trunk edit and its reconcile fetches the new one (sync_fetches_and_fast_forwards_the_declared_trunk).

It never forces. A trunk follows its remote unless it carries local commits; uncommitted edits ride across the fast-forward, and only one an incoming commit would overwrite stops it. Either is a reported outcome, not a reset: SyncReport::trunk is updated, already_current, diverged, or dirty, and the daemon turns the latter two into the snapshot's sync_note. Syncing a root with nothing on disk is not_ready — a transient code, so the engine retries on the next event rather than degrading.

Slot pruning compares each slot to the trunk's tip after the op, so it recycles exactly the slots a fresh pool.fill would no longer produce, whichever way the trunk outcome went. The engine's fill loop restores the target at the new tip.

The warm pool

Warm slots are pre-checked-out worktrees under roots/<slug>/pool/ that realizing a declared worktree claims near-instantly, skipping a cold checkout. The declared target is [roots."<slug>".pool] size (default 0 — opt-in); the observed count is worktrees::pool_count, which counts registered worktrees whose path sits strictly under pool::pool_dir — strictly, because a worktree registered at the pool directory itself would otherwise count as a slot and, being the lowest path, be the one promote picked up and moved.

Who claims a slot: the realizer, not a caller. worktrees::create (the offline grove tree add) and worktrees::reconcile (what the engine runs after a declare-and-nudge, and over a hand-edited manifest) both try pool::promote first and cold-create on Cold, so every entry point redeems the pool.

pool::fill adds one detached slot at the trunk tip — resolved through roots::trunk, so a root that has declared a new trunk seeds onto that branch and not the one it is leaving — and nothing else. N calls converge to N slots. pool::reclaim is its mirror — it removes the highest-indexed slot, non-forced — so a target that drops converges too. The engine's fill task picks whichever direction the observed count needs. It prunes git-level ghosts first: a slot directory removed out of band leaves a prunable registration, fill picks the now-empty path, and the detached add then fails with "missing but already registered" — wedging every future fill. It errors when the bare is missing, a real fault since the engine only fills a ready root.

Slots get no shares (§ Depth). worktrees::actual's path-based exclusion keeps slots out of the declared set entirely, regardless of branch or detachment: a slot path does not strip under the code dir, so no basename of it is ever read as a checkout.

pool::promote(home, slug, name, branch, base):

  1. attaches the branch in the slot (DWIM, like worktree_add), from base when the caller named one and the trunk branch otherwise — named explicitly, so a promote is not silently forked from whatever commit fill seeded the slot at;
  2. claims it into the code dir with git worktree move — not a bare rename, which would strip git's gitdir pointers; worktree pointers are absolute, so crossing from roots/<slug>/pool/ to code/<slug>/ costs nothing extra;
  3. declares it in the manifest;
  4. materializes the root's shares, now that it is at canonical depth.

Attach before move is what makes promote convergent under interruption. Any worktree that ever reaches <code>/<name> already carries a branch, so a moved-but-undeclared one is adopted by worktrees::reconcile — there is no window in which a detached orphan is stranded at the user path, which reconcile could neither adopt nor recreate. An attach failure (the branch is checked out elsewhere) leaves the slot cleanly detached and reusable.

A promote never clobbers an existing <code>/<name>: that is Promotion::Cold(Conflict). An empty pool is Promotion::Cold(Empty). Neither is an error — both tell the realizer to cold-create.

Serialization

Every per-root git writer runs on that root's lane in the daemon — reconcile (promote included), sync, fill, remove, worktree ops, and doctor's converge. grove-ops does not enforce this: its flock serializes the manifest, deliberately not git, and two concurrent git worktree adds on one root race an index lock. The lane is the caller's to supply. See architecture.html § Lanes.

Where this is exercised

crates/grove-ops/src/roots.rs, worktrees.rs and pool.rs carry the unit suites, one named test per behaviour on this page; the end-to-end path — declare, realize, promote, sync, remove — is crates/grove-daemon/tests/scenario.rs.

The worktree environment

A root's worktrees are separate checkouts of one repository, so each starts without the untracked files a developer's trunk accumulated — .env, a local config, a credentials file. Shares close that gap: a root declares files it wants present in every worktree, and grove materializes them.

grove_ops::env is the sole owner of share filesystem mutation. Nothing else in the tree creates, repoints, or removes a share.

Declaring

[roots."owner/name".env]
_.symlink = [".env", "config/app.json"]   # live: a link to the trunk's copy
_.copy    = ["config/local.json"]         # seeded once: an independent real file

Two modes:

_.symlink_.copy
what lands in the worktreea relative symlink to ../…/<trunk>/<p>a real file, seeded from <trunk>/<p>
editsshared — one file, every worktree sees itindependent per worktree
re-run behaviourself-heals: a stale grove link is repointedseed-once: never overwritten
--fixbacks a conflict up, then linksno bearing — a copy has no wrong state to heal
on undeclareGC'd (it holds no data)left in place (it is a real file the worktree owns)

A symlink is identifiable as grove's own — its target climbs one .. per component of its path, then into the trunk, exactly as grove writes it — so it can be healed and collected; an in-tree link that merely starts with the trunk's name is the worktree's. A seeded copy is indistinguishable from a file the user wrote, so it is never overwritten and never collected.

A path declared in both lists is materialized as a symlink: manifest::list_shares gives _.symlink precedence.

The source is the trunk

Every share's source is <trunk>/<p> — the trunk checkout, resolved once per pass through roots::trunk and named by its branch like every other checkout in the code dir (see § The trunk). That is what makes a symlink share live: the worktree link and the operator's own trunk copy are the same file.

A source pass runs first, per declared share, and creates <trunk>/<p> empty when it is missing. A real file or a pre-made directory already there is the source and is left alone.

D5 — a user symlink at the source is read through, never replaced. A symlink where the source belongs is the user's own choice of source (<trunk>/.env → ~/secrets/env), and grove respects it: a _.symlink share reads through it (worktree → <trunk>/<p> → the user's target), and a _.copy share's NOFOLLOW source open refuses it downstream, so the copy is reported per worktree rather than silently following a redirect. Only a non-file, non-dir, non-symlink oddity (a fifo, a socket) is replaced, and only because it sits inside the trunk, which is grove's domain. During a trunk change, grove's own share link in the new trunk's source slot (laid through the old trunk while it was a worktree) is no user source: it is seeded over from the old trunk.

Detect → fix

Per declared share <p>, per present worktree. diagnose renders the root's plan and mutates nothing; materialize applies that same plan — a byte-for-byte filesystem snapshot is identical before and after, as --dry-run promises and diagnose_mutates_nothing/copy_diagnose_mutates_nothing prove.

state at <wt>/<p>verdictmaterialize (Safe)materialize (Force)
absentlinkedcreate the relative linksame
symlink → exactly ../…/<trunk>/<p>oknothingnothing
symlink pointing under the trunk, wrong pathrepointedrepoint (temp + same-dir rename(2))same
symlink pointing elsewhere (foreign)conflictnever touchedback up, then link → created
real file / directory / otherconflictnever touchedback up, then link → created

_.copy

state at <wt>/<p>verdictaction
absentcopiedseed from <trunk>/<p>
symlink pointing under the trunk (a prior _.symlink for this path)copiedreplace — the link is data-free; this is the symlink → copy migration
foreign symlink / real file / directoryokleave it: the worktree owns it

--fix has no bearing on a copy. A copy that would be seeded from a source that is no regular file is an error row in the plan, so diagnose reports it as materialize does.

GC on undeclare

A worktree top-level entry that is a symlink to ../<trunk>/<name> for a <name> no longer declared is an orphan and is removed (gc). unlinkat removes the link, never its target. A real file — including a _.copy's seeded file — or a symlink pointing anywhere else is left alone. GC is top-level only; nested-share GC is not implemented.

Removal

worktrees::remove never forces git worktree remove, which refuses over untracked files — and a share the repo does not ignore is one. env::unlay first takes back, at each declared share path, a grove-shaped link or a real file byte-identical to its trunk source: both are data-free. A path git tracks in that worktree (one git ls-files for all share paths) is git's, never taken — in a clean worktree it always equals the trunk's, and unlinking it would read as a deletion that blocks the remove. An edited copy is the worktree's own and still blocks, as does any other untracked file; on that refusal the shares are materialized again. The trunk is never unlaid — its share paths are the sources.

Statuses

ShareStatus is ok | created | linked | copied | repointed | conflict | gc | error, pinned in contracts/wire-vocab.json as share_status. The would/did distinction is not carried in the status — diagnose reuses linked/repointed/created/gc as "would-link", "would-repoint", and so on — because the renderer and the exit code branch only on conflict and error.

The whole pass is best-effort: one bad share or one unopenable worktree pushes an error row and never aborts the batch.

Never clobber

Only a symlink that is grove's own is ever touched. "Grove's own" is a purely lexical test on the link target — after any leading .. components, the first segment names the trunk — with no I/O and no canonicalization, so it cannot be steered by what is on disk.

The test accepts one further name: .trunk, the fixed directory a root still on the v1 layout carries its trunk in. A link through it is grove's own, so the next materialize repoints it onto the branch-named trunk rather than reading it as a stranger's and leaving it (materialize_repoints_a_legacy_trunk_link). That is the share half of what grove doctor --fix migrates, and the only reason the name appears in this module.

And one more, in one pass only: the old trunk, in the share pass converge_trunk runs before it moves HEAD, so links through the old trunk are repointed while they are still recognizably grove's, and each source missing from the new trunk is seeded from the old trunk's rather than created empty — a repointed link reads the same bytes, and a symlink source is carried as the same link — unless its relative target stays inside the trunk, where it would dangle, an error row asking for it to be re-created in the new trunk (a_trunk_change_carries_share_links_and_sources_onto_the_new_trunk). The pass is planned whole before its first write, so any failure the plan can see (an old source that cannot be read, or a link or copy the plan already knows will fail in some worktree) is an error row with nothing seeded and no link moved, and HEAD stays put for the next event to retry (an_unreadable_old_source_holds_the_trunk_change, a_failing_worktree_row_holds_the_trunk_change_before_any_write). A write that fails only while it is applied (permissions, or a leaf changed underneath it) is not foreseen: a failed source write still lays no link, but a failed worktree write leaves the rows applied before it in place, with HEAD held all the same. Every other pass knows only the declared trunk, so while a trunk change is refused a link through the old trunk is a conflict, never repointed into whatever occupies the new trunk's directory (a_refused_trunk_change_leaves_links_through_the_old_trunk_alone); and while the change is pending — HEAD off the declared trunk — a source missing from the new trunk is an error row, its missing parents uncreated, never created empty for the next carry to take as real.

A real file, a directory, or a foreign symlink is reported as conflict and left exactly as it was. grove doctor exits 5 on any unresolved conflict, which makes it a usable CI gate even under --dry-run.

--fix is the operator's explicit override, and it still does not destroy anything: the real file is renameat'd to the first free <leaf>.grove-bak, <leaf>.grove-bak-1, … (never over a prior backup), and only then is the link created.

The backup rename runs unlocked; the root's lane serializes it.

Security posture

Two independent gates, string and filesystem.

The string gate is manifest::validate_share_path, applied at list_shares, so only canonical, traversal-free paths reach the materializer: relative, Normal components only, no segment beginning with -, no ./empty/trailing-/ segments, and no dotted first segment once the path nests — the dot rule (§ Validation), which keeps a share from reaching down into a dotted directory while leaving .env a share like any other. Canonicality matters beyond traversal: the link pass and the GC pass derive paths differently, so a non-canonical stored string would let them disagree about the same share.

The filesystem gate is a dirfd-pinned O_NOFOLLOW descent. Every component of a share path within the worktree is opened with openat(NOFOLLOW) from a pinned dirfd, so a symlinked parent (config → /etc) trips ELOOP and can never redirect a write outside the worktree. open_dir_nofollow is the only place a parent component is opened — the one place NOFOLLOW could be forgotten. Classify and act share one pinned dirfd, which closes the lstat → create TOCTOU, and the leaf write is a relative-target temp plus a same-dir rename(2) on that fd. The base worktree and trunk directories themselves sit under the grove-controlled $GROVE_HOME and are opened NOFOLLOW on their final component.

No unsafe, no libc — the syscalls come from rustix, and the workspace forbids unsafe_code.

materialize_refuses_a_destination_under_a_symlinked_parent, copy_refuses_a_destination_under_a_symlinked_parent and ensure_source_refuses_a_symlink_redirect_in_the_trunk are the regression guards.

Depth

Shares materialize only at canonical depth — a worktree that is a direct sibling of the trunk. The link target is built as one .. per path component plus <trunk>/<p>, which is correct exactly one level under the code dir.

Warm-pool slots get no shares: under roots/<slug>/pool/slot-N the target resolves inside the pool. pool::promote materializes after the move into the code dir (fill_materializes_no_shares_in_slots).

Where materialization is wired

call sitewhenmode
worktrees::createa cold worktree checkout, right after git worktree addFix::Safe, best-effort
roots::reconcile_oneafter a root's worktrees convergeFix::Safe, best-effort
pool::promoteafter the slot is moved to canonical depth and declaredFix::Safe
doctor::runthe operator's explicit passdiagnose under --dry-run; Fix::Force under --fix, else Fix::Safe

A share hiccup never fails a checkout or a root's reconcile; doctor and the next reconcile retry it.

Only present worktrees are visited (worktrees::list, filtered on present), and the trunk — the share source — is never treated as one of them. A root whose trunk is missing contributes a single error row — "trunk missing — clone/realize the root first" — rather than a per-share pile.

The report

ShareOutcome { slug, worktree?, path, status, reason? } is one row per share per location; worktree is absent for a source-level row. It is the report array of POST /api/doctor and of the offline grove doctor, and reason carries the prose for a conflict or an error.

grove doctor's exit verdict comes from this report alone (api.html § Doctor).