# Parallel Worktree Disk Preflight Bug - 2026-04-30

## Source Evidence

Bug report file:

- `/Users/lu/codebase/bug.md `, note the trailing space in the filename.

Observed command:

```text
/parallel --agents 4 继续 进一步开发 火力全开
```

Observed failure:

```text
Parallel development did not auto-launch 4 worker(s): some worker launches failed
scope-worker: Failed to create worktree
code-worker: Failed to create worktree
test-worker: Failed to create worktree
integration-worker: Failed to create worktree
error: unable to create file ... No space left on device
fatal: cannot create directory ... No space left on device
Updating files: ... /247763
```

Local disk state during analysis:

```text
/dev/disk3s1 460Gi used 425Gi available 6.6Gi capacity 99%
```

## Classification

This is both an environment/resource failure and a Clavue product bug.

The environment trigger is real: the disk was nearly full, and `git worktree add` failed while checking out a very large repository. The log shows about `247,763` paths being checked out and multiple OpenSSL tree files failing with `No space left on device`.

The Clavue bug is that `/parallel` did not preflight resource cost before launching four worktree-isolated agents. It let expensive worktree creation start, failed late during checkout, produced a huge low-signal git error dump, and did not automatically degrade to a safer mode.

## User Impact

Severity: P0 for `/parallel` reliability.

Why:

- The user asked for "火力全开"; Clavue interpreted this as parallel development and attempted 4 isolated worktrees.
- On a large repo and nearly full disk, this predictably fails.
- The product made the user wait through partial checkouts and then returned a noisy failure.
- The failure leaves the user unsure whether the bug is Clavue, git, disk, or their repo.
- A world-class CLI must fail before doing expensive work when disk and repo size make success unlikely.

## Current Code Path

Relevant files:

- `src/commands/parallel/parallel.tsx`
- `src/utils/parallelDevelopment.js`
- `src/utils/worktree.ts`
- `src/utils/agentIsolationCapability.js`
- `src/tools/AgentTool/AgentTool.tsx`
- `tests/parallel-development.test.mjs`

Current behavior:

- `parseParallelDevelopmentArgs()` defaults to `agentCount = 4`, `worktreeMode = true`, and `worktreeFallbackAllowed = true`.
- `/parallel` calls `resolveAgentIsolationPlan({ requestedIsolation: 'worktree', allowSharedWorkspaceFallback: true })`.
- The readiness resolver only checks whether git worktree isolation is logically available:
  - is there a `WorktreeCreate` hook, or
  - is this a git repo with a valid `HEAD`.
- It does not check disk space, tracked file count, sparse checkout settings, or estimated checkout cost.
- `/parallel` then sends `AgentTool.call(... isolation: 'worktree')` for every worker.
- `AgentTool` resolves isolation again with `allowSharedWorkspaceFallback: false`.
- `createAgentWorktree()` calls `getOrCreateWorktree()`, which runs `git worktree add`.
- The failure happens late inside `git worktree add` during file checkout.

## Root Cause

Primary root cause:

- Worktree readiness is currently boolean and capability-based. It answers "can this repo create worktrees?" but not "should this specific `/parallel --agents N` request create N full worktrees now?"

Secondary root causes:

- `/parallel` defaults to worktree isolation even for very large repos.
- No disk-space threshold exists for parallel worktree launch.
- No tracked-file-count threshold exists for parallel worktree launch.
- No sparse-checkout recommendation is enforced before worktree launch in large repos.
- Parallel launch failures include raw git checkout output instead of a concise diagnostic.
- Failed partial worktree creation is not clearly cleaned up or surfaced as cleanup-required.

## Expected Behavior

For `/parallel --agents 4` in a huge repo or low-disk environment:

1. Clavue should preflight before launching workers.
2. If worktree launch is unsafe but fallback is allowed, Clavue should launch shared-workspace background agents or ask the user to rerun with `--no-worktree`.
3. If worktree launch is explicitly required via `--worktree`, Clavue should fail fast with a concise actionable message.
4. The error should include:
   - available disk space,
   - estimated worktree count,
   - repo tracked file count or large-repo indicator,
   - suggested remedies.
5. The product should not dump thousands of git checkout lines.

Suggested user-facing failure:

```text
Worktree isolation preflight failed: this repo has about 247,763 tracked files and only 6.6 GiB free. Creating 4 full worktrees is likely to exhaust disk.

No workers were launched.

Next actions:
- Run `/parallel --no-worktree --agents 4 <goal>` to use shared-workspace agents.
- Free disk space and retry.
- Configure `.clavue/settings.json` with `worktree.sparsePaths` for this repo.
- Use `--agents 1` for isolated worktree mode.
```

## Fix Plan

### 1. Add Worktree Resource Preflight

Create a preflight function near the existing isolation resolver.

Suggested location:

- `src/utils/agentIsolationCapability.js`, if kept JS-only and cheap.
- Or `src/utils/worktree.ts`, if it needs git helpers and filesystem stats.

Suggested API:

```ts
type AgentWorktreeResourcePreflight = {
  safe: boolean
  reason?: string
  trackedFileCount?: number
  freeDiskBytes?: number
  estimatedWorktreeCount?: number
  recommendations: string[]
}
```

Inputs:

- `cwd`
- `agentCount`
- `requestedIsolation`
- `allowSharedWorkspaceFallback`

Checks:

- Worktree capability readiness, existing behavior.
- Free disk space at `.clavue/worktrees` parent.
- Tracked file count via `git ls-files`.
- Whether `settings.worktree.sparsePaths` is configured.
- Optional existing worktree count under `.clavue/worktrees`.

Minimum thresholds:

- Hard fail or fallback if free disk is below a safe floor, for example `< 10 GiB`.
- Warn or fallback if `trackedFileCount > 100,000` and `agentCount > 1` without sparse paths.
- Fail fast if `agentCount * estimatedRepoCheckoutCost` is greater than available free disk.

Keep thresholds configurable:

- `CLAVUE_WORKTREE_MIN_FREE_MB`
- `CLAVUE_WORKTREE_LARGE_REPO_FILE_LIMIT`
- `CLAVUE_WORKTREE_PREFLIGHT_DISABLE=1` for emergency override.

### 2. Wire Preflight Into `/parallel`

Target:

- `src/commands/parallel/parallel.tsx`

Behavior:

- Before building worker specs, run resource preflight when `!parsed.teamMode && parsed.worktreeMode`.
- If unsafe and `parsed.worktreeFallbackAllowed === true`, set:
  - `agentIsolation = undefined`
  - `effectiveParsed.worktreeMode = false`
  - `isolationFallbackReason = <concise preflight reason>`
- If unsafe and fallback is not allowed, return no workers and a concise error.
- Do not call `AgentTool.call()` with `isolation: 'worktree'` when preflight says unsafe.

Important:

- The default command `/parallel --agents 4 <goal>` allows fallback.
- Explicit `/parallel --worktree --agents 4 <goal>` should not fallback silently.

### 3. Make `AgentTool` Defensively Safe

Target:

- `src/tools/AgentTool/AgentTool.tsx`

Reason:

- `/parallel` is not the only caller. Any direct Agent launch with `isolation: 'worktree'` can hit this.

Behavior:

- When `effectiveIsolation === 'worktree'`, run the same resource preflight with `agentCount = 1`.
- If unsafe, throw a concise error before `createAgentWorktree()`.
- Preserve explicit failure because direct Agent worktree isolation is an explicit request at that layer.

### 4. Sanitize Worktree Creation Errors

Target:

- `src/utils/worktree.ts`

Behavior:

- Detect `ENOSPC` or `No space left on device` in `createStderr`.
- Throw a concise classified error:

```text
Failed to create worktree: disk is full while checking out this repo. Free disk space or configure worktree.sparsePaths.
```

- Avoid returning the entire raw `git worktree add` stderr to `/parallel`.
- Include raw stderr only in debug logs, not user-facing message.

### 5. Cleanup Partial Worktrees

Target:

- `src/utils/worktree.ts`

Behavior:

- If `git worktree add` fails after creating a registered or partial directory, attempt:
  - `git worktree remove --force <path>`
  - remove orphan branch if it exists
  - `git worktree prune` if safe
- If cleanup fails, include a concise cleanup instruction:

```text
Partial worktree may remain at .clavue/worktrees/<slug>. Run `git worktree prune` after freeing disk space.
```

Do not run destructive cleanup outside `.clavue/worktrees`.

### 6. Improve `/team` Readiness Copy

Target:

- `src/utils/parallelDevelopment.js`
- `src/commands/team/team.tsx`

Behavior:

- `getParallelDevelopmentReadinessLines()` should include worktree resource readiness, not only background-agent enabled state.
- For large repos, recommend:
  - `/parallel --no-worktree --agents 4 "<goal>"`
  - `worktree.sparsePaths`
  - fewer agents for worktree isolation.

## Tests To Add

### Unit Tests

Target:

- `tests/parallel-development.test.mjs`

Add cases:

- Resource preflight falls back to shared workspace when:
  - `agentCount = 4`
  - low free disk
  - large tracked file count
  - fallback allowed.
- Resource preflight fails when:
  - explicit `--worktree`
  - low free disk
  - large tracked file count
  - fallback not allowed.
- Error message contains recommendations and does not contain raw `Updating files` dump.

### Worktree Tests

Target:

- Existing worktree tests or new `tests/worktree-resource-preflight.test.mjs`.

Add cases:

- `No space left on device` is classified as disk-space failure.
- Partial worktree cleanup is attempted only under `.clavue/worktrees`.
- Large repo without sparse paths is unsafe for multi-agent worktree mode.
- Large repo with sparse paths can be safe if disk is sufficient.

### Product Truth Tests

Target:

- `tests/product-truth-surfaces.test.mjs`

Add cases:

- Runtime capability copy does not claim worktree isolation is ready unless preflight passes.
- `/team` or readiness output mentions preflight and fallback.

## Verification Commands

Focused:

```bash
node --test tests/parallel-development.test.mjs
node --test tests/product-truth-surfaces.test.mjs
```

After implementation:

```bash
npm run check
npm run build
```

Manual smoke:

```bash
CLAVUE_WORKTREE_MIN_FREE_MB=999999 node dist/cli.js
/parallel --agents 4 继续 进一步开发 火力全开
```

Expected manual smoke result:

- No worktree checkout starts.
- No `Updating files` dump appears.
- Clavue either launches shared-workspace agents or returns a concise preflight failure depending on fallback settings.

## Acceptance Criteria

This bug is fixed when:

- `/parallel --agents 4 <goal>` does not attempt full worktree checkout on low-disk or huge-repo conditions.
- `/parallel --worktree --agents 4 <goal>` fails before worker launch with a concise actionable error.
- Direct `Agent(... isolation: "worktree")` fails fast when one worktree is unsafe.
- User-facing errors do not include thousands of raw git checkout lines.
- Partial failed worktrees are cleaned up or reported with exact cleanup instructions.
- Tests cover low disk, large repo, fallback allowed, fallback disallowed, and ENOSPC error classification.

## Immediate User Workaround

Until the fix ships:

```text
/parallel --no-worktree --agents 4 继续 进一步开发 火力全开
```

or:

```text
/parallel --agents 1 --worktree 继续 进一步开发
```

Also free disk space before running worktree-isolated parallel development. Current machine state during analysis showed only `6.6 GiB` free on a `460 GiB` volume.

For large repos, configure sparse checkout:

```json
{
  "worktree": {
    "sparsePaths": ["src", "tests", "docs", "package.json", "package-lock.json"]
  }
}
```

## Decision

Treat this as a Clavue P0 robustness bug in `/parallel` and agent worktree isolation.

It is not enough to say "disk was full." A world-class Clavue must anticipate this class of failure, avoid expensive doomed work, and offer a safe fallback path.
