diff --git a/.memory/worktree-creation-performance.md b/.memory/worktree-creation-performance.md new file mode 100644 index 0000000000..80c190f2e4 --- /dev/null +++ b/.memory/worktree-creation-performance.md @@ -0,0 +1,34 @@ +# Worktree Creation Performance Optimization + +Implemented across four phases on `worktree_performance_optimization` (2026-11-21), each gated by two independent adversarial reviews. See [`docs/plans/worktree-creation-performance.md`](../docs/plans/worktree-creation-performance.md). + +## Head-to-Head Measured Results (`aiden-macos`, 6,497 tracked files, Apple Silicon APFS, 5-run medians) + +| Operation | Before (`origin/main`) | After | Saved | % Reduction | Speedup | +| :--- | ---: | ---: | ---: | ---: | ---: | +| Explicit Create (`createIn` + `createWorktree`) | 1,417 ms (127 git spawns) | 744 ms (8 git spawns) | −673 ms | −47.5% (−93.7% spawns) | 1.90× | +| Worktree-on-Send Backend (local base → ready for LLM) | 1,915 ms (144 git spawns) | 711 ms (12 git spawns) | −1,204 ms | −62.9% (−91.7% spawns) | 2.69× | +| Post-Create `git.info(worktreePath)` | 172.82 ms (6 spawns) | 0.77 ms (0 spawns) | −172.05 ms | −99.6% (−100% spawns) | 224× | +| Per-Op Admission (`managedWorktreeUsable`) | 15.28 ms (4 spawns) | 0.58 ms (0 spawns) | −14.70 ms | −96.2% (−100% spawns) | 26.3× | +| `.worktreeinclude` (31 files, clean repo) | 100 ms (31 spawns) | 40 ms (1 batched CoW spawn) | −60 ms | −60.0% | 2.50× | +| `.worktreeinclude` (31 files + 5,000-file `node_modules`) | Crashed (`output_limit` > 1 MiB) | 44 ms | Fixed crash | 100% crash fix | ∞ | + +## Key Architecture Decisions & Safety Invariants + +1. **Streaming `git check-attr --cached -z --all --stdin` (`main/services/git.ts`)**: Replaces 128-path serial `check-attr` loops (~102 spawns) with 1 streaming process parsing NUL triples on raw `Buffer` slices (O(1) memory, immune to 1 MiB `DEFAULT_MAX_BUFFER_BYTES` overflow, evaluates `info/attributes`, global config, and `includeIf`). +2. **Parallel checkout tuned to APFS (`checkout.workers = min(4, cpus)`, `checkout.thresholdForParallelism = 50`)**: Controlled A/B on Apple Silicon APFS showed `workers=4` beats `workers=8` (which exhibited tail spikes). Raw APFS `clonefile(dir)` for Git working trees was rejected because it breaks Git's inode stat cache and causes 1.2–1.8 s `git status` stalls. +3. **Authoritative inner capacity admission (`additionalAllocationBytes`)**: `createIn` passes `provisionedReserve` into `git.createWorktree`, which validates non-negative safe integers and enforces `checkoutBytes + additionalAllocationBytes` inside `enqueueMutation(repo.commonDir)` before `mkdir`/`worktree add`. +4. **Inverted `.worktreeinclude` + literal `./` pathspec neutralization**: Runs `git ls-files -z -o -i --exclude-from=.worktreeinclude --full-name`, short-circuits if empty, then filters via `git check-ignore -z --stdin` in `repo.topLevel` with `./`-prefixed paths (neutralizing `:` pathspec magic bypass/DoS). +5. **0-spawn pure-FS `managedWorktreeUsable` & display cache seeding (`main/services/git.ts`)**: Reads `/.git`, `/{aiden-owner,gitdir,commondir,HEAD}`, and loose/`packed-refs` via `O_RDONLY | O_NOFOLLOW | O_NONBLOCK`, fenced with `while (this.mutations.has(commonDir))` + `mutationEpochs` (no cross-caller stale `usableFlights` cache). Falls back to Git on `reftable` or ambiguity. Display-only `infoCache` seeding for newly created worktrees is fenced by pre/post `repoRemoteHintSignature` and `mutationEpochs`. +6. **Split global/workspace skill discovery cache, Pi `dirIndex`, and `protectLocal` gating**: + - `discoverSkillCandidatesWithCachedGlobals` caches global candidates for 5 s keyed on `[home, aidenDir, globalPluginConfigs]` (honoring workspace `.claude/settings.json` disabling global plugins); `resolveFresh()` always bypasses cache. + - `PiCompactionSessionStore` indexes `.jsonl*` files with per-file `lstat` signatures and monotonic `dirMutationVersion` concurrency fencing so brand-new chats skip migration/list scans while in-place edits and symlinks are caught. + - `portable-config-core.ts` gates `protectLocal()` on warm loads only when `ownedPaths.length === 0 && archivePublicationPaths.size === 0`, keeping `ensurePrivateDirectory(root)` live and checking `lstat` (`uid`, `mode`, `nlink === 1n`, `dev/ino/mtimeNs/ctimeNs`) on `config.json` and recorded secondary files. +7. **Renderer IPC coalescing & zero-remount promotion**: + - `FirstMessageWorktreeResult` optionally carries `workspace`; `workspaces:changed` emits `{ kind: "created", workspace }` on creation so hydrated idle caches upsert via shared `upsertCreatedWorkspaceInCache` without refetching `workspaces:list` or `chats:list`. + - `markChatRecentlyPromoted` uses subscriber refcounting + microtask-deferred cleanup (React StrictMode safe) so only the immediate draft → live `useChat` activation reuses the seeded snapshot while leaving/revisiting always re-reads. + - Pending worktree sends render inside `MessageList` (`keepForkWrapper` + `"draft-prompt"` key handoff) so the user bubble and attachments settle in place without remounting. + - `EnvironmentArtifactsContext` isolates volatile `useWorkspaceArtifacts` updates from `ChatPane`, `ChatSidebar`, `RootView`, `HistoryNavButtons`, and `DesignLayout` via `useEnvironmentPanelCore()`. +8. **Native batched CoW `provision` subcommand (`native/worktree-file-io/main.c`)**: + - Preserves `copy` and `restore` (with SHA-256) untouched for snapshots. + - Dedicated `provision` subcommand handles all `.worktreeinclude` paths in 1 spawn, uses APFS `fclonefileat(..., CLONE_NOFOLLOW | CLONE_NOOWNERCOPY)` into a random temp file when plain/same-volume/no-xattrs/no-flags/no-special-bits/owner-readable, clears `fchflags(cloned, 0)` BEFORE `fchmod(cloned, mode & 0777)`, verifies `flistxattr(cloned) == 0` + `same_provision_source` (including `st_mode`, `st_flags`, `st_ctimespec`), atomically installs via `renameatx_np(..., RENAME_EXCL)`, falls back to `read/write` on `EXDEV`/`ENOTSUP`/`EACCES`/`EPERM`, deduplicates parent `fsync`s (capped at 64 FDs), and handles `SIGTERM` gracefully while Node's `provisionManagedWorktreeFilesBatch` settles strictly on `"close"` so disk state stays 1:1 with `onProvisioned`. diff --git a/docs/plans/README.md b/docs/plans/README.md index ac4f6884b2..b97579704d 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -8,6 +8,7 @@ Research addition 2026-10-03 against `main` at `3f86d41af` (0.52.0): [all-PR inv ## Active and partial +- [Worktree creation performance (Tier 1 & Tier 2)](worktree-creation-performance.md) — Implemented, in review (2026-11-21) on `worktree_performance_optimization`. All four phases shipped and audited by two adversarial reviewers per phase. Measured head-to-head on `aiden-macos` (6,497 tracked files, APFS, 5-run medians): explicit create drops from 1,417 ms / 127 git spawns to 744 ms / 8 git spawns (−47.5%, 1.90× faster); worktree-on-send local backend drops from 1,915 ms / 144 git spawns to 711 ms / 12 git spawns (−62.9%, 2.69× faster); post-create `git.info` drops from 172.8 ms (6 spawns) to 0.77 ms (0 spawns, −99.6%); per-op `managedWorktreeUsable` admission drops from 15.3 ms (4 spawns) to 0.58 ms (0 spawns, −96.2%); `.worktreeinclude` (31 files) drops from 100 ms to 40 ms (−60.0%) and stops crashing on large `node_modules` trees (44 ms with 5,000 ignored files vs `output_limit` crash). Renderer changes add inline `workspace` return + cache seeding, `workspaces:changed` creation narrowing, StrictMode-safe one-shot promotion `useChat` freshness, frame-1 draft worktree send inside `MessageList` with zero-remount bubble handoff, `EnvironmentArtifactsContext` isolation, and frame-0 `⌥↵` base seeding. - [iPhone Duo: list and conversation side by side](ios-iphone-duo-plan.md) — In review (PR) (2026-11-22), iOS only, no Remote revision. At regular width the Inbox, Bots and Workspaces tabs are list and detail; compact width keeps one stack; the fold keeps drafts, reading place, Search and list positions; bars are ready for the Duo's vertical rail (Xcode 27.1). Also ships the owner's quieter card lists, the iOS ink Aiden accent and underlined links. Phase 4 polish (remaining poses, the swipe-row item) is listed as remaining work in the plan. - [Prompt cache hit rate: keep the cached prefix byte-stable](prompt-cache-hit-rate.md) — Implemented, in review (2026-11-19): phase 0 (miss attribution, the 0% cache figure and the prefix harness), phase 1 (a per-chat AGENTS.md nonce, and an MCP section fixed for the turn), phase 2 (a fixed tool list per chat, with gated tools and Bot ingress refused per call), phase 3 (hook context journaled after its prompt, frozen per-chat state with `` tails, audience and form-fill notes in the turn tail, a follow-up's connector section kept, the owed turn's window-dependent offers declared and refused per call, and removed memory never re-sent) and phase 4 (btw and a same-model advisor review continue the chat's last request on its cached prefix, and every one-off call sends no-cache retention through one helper) and phase 5 (threshold and manual compaction summaries continue the cached prefix, an attended chat near its trigger writes the summary in the background and stores it when compaction comes due if the chat was only appended to, chats with memory facts summarize isolated, and no memory fact reaches a stored summary) and phase 6 (the warmer times Pi's lifetime for the request's retention and keeps an attended chat warm for a few idle refreshes after its reply, `aiden serve` warms only when the profile opts in and never for Bot or scheduled runs, an opt-in **Keep chat caches for an hour** on Anthropic and Amazon Bedrock, and the memory limit on cached compaction accepted) and phase 7 (screenshots cut in batches with shared thresholds for workspace chats and Bots, and the Gemini explicit cache retired for implicit caching over a stable prefix) and phase 8a (in-process Codex over WebSocket with SSE fallback, a fourth Anthropic breakpoint at the end of the stable head, a Bedrock cachePoint after the tools, and chat-ID cache routing for listed custom OpenAI-compatible endpoints; message threads, a Codex cache lifetime, deferred tool declarations, head collapse and forked-subagent prefixes recorded as not built) and phase 8b (`aiden serve` keeps a paired device's chat warm when idle and honours the hour-long cache, serve threshold and manual compactions continue the turn's cached request, the replay gate reports a recorded turn compacted on its cached prefix, and a child agent's compaction after its own reply continues the child's last request) implemented; nine phases in one PR on `feat/prompt-cache-stability`, from the 33-cause cache audit. Measurement and a two-turn prefix harness first, then a stable AGENTS.md nonce and system sections fixed for the turn, a fixed tool list, frozen per-chat state, side calls and compaction on the parent prefix, idle warming on real TTLs with `aiden serve` parity, batched screenshot trimming, and Codex, threads and provider-routing changes. - [Settings deslop: less text, one row system](settings-deslop-plan.md) — Proposed (2026-11-18), revised after an adversarial review the same day. The proposals are not built; the Settings bugs that the review and a bug hunt found are fixed on the plan's branch. 86% of the 240 settings rows carry a description (median 15 words), and pages build their own list rows and cards (about 19 local helpers), radio cards, folds and search fields. Proposes a copy budget (labels carry meaning; a description only for a consequence, at most 12 words; state in badges), title-only page headings with row-level search, a settings kit (`SettingsRow`, `SettingsListRow`, `SettingsSheet`, `SecretField`, `SettingsNote`, `RadioCardGroup`, `settingsStatus()`), a page-by-page pass, a 30-row must-stay list of disclosures with a behavioral test each, and a lint guardrail, in six phases. Includes a read of OpenCode's desktop settings and a [before/after prototype](assets/settings-deslop-prototype.html). Seven owner decisions are open. diff --git a/docs/plans/worktree-creation-performance.md b/docs/plans/worktree-creation-performance.md new file mode 100644 index 0000000000..6ef5aaa3af --- /dev/null +++ b/docs/plans/worktree-creation-performance.md @@ -0,0 +1,65 @@ +# Worktree Creation Performance (Tier 1 & Tier 2) + +**Status:** Implemented, in review (2026-11-21) on branch `worktree_performance_optimization` (merged with `origin/main` `6555f1767`). + +## Goal + +Make managed worktree creation and worktree-on-send feel instantaneous and smooth on macOS and Linux without relaxing any of Aiden's ownership, admission, TOCTOU, snapshot, or disk-capacity safety invariants. + +## Measured Head-to-Head Results (`aiden-macos`, 6,497 tracked files, Apple Silicon APFS, 5-run medians) + +| Operation | Before (`origin/main`) | After (this PR) | Saved | % Reduction | Speedup | +| :--- | ---: | ---: | ---: | ---: | ---: | +| Explicit Create (`createIn` + `createWorktree`) | **1,417 ms** (1.42 s, 127 git spawns) | **744 ms** (0.74 s, 8 git spawns) | **−673 ms** (−0.67 s) | **−47.5%** (−93.7% spawns) | **1.90×** | +| Worktree-on-Send Backend (local base → ready for LLM) | **1,915 ms** (1.92 s, 144 git spawns) | **711 ms** (0.71 s, 12 git spawns) | **−1,204 ms** (−1.20 s) | **−62.9%** (−91.7% spawns) | **2.69×** | +| Post-Create `git.info(worktreePath)` | **172.82 ms** (6 git spawns) | **0.77 ms** (0 git spawns) | **−172.05 ms** | **−99.6%** (−100% spawns) | **224×** | +| Per-Op Admission (`managedWorktreeUsable`) | **15.28 ms** (4 git spawns) | **0.58 ms** (0 git spawns) | **−14.70 ms** | **−96.2%** (−100% spawns) | **26.3×** | +| `.worktreeinclude` (31 ignored files, clean repo) | **100 ms** (31 helper spawns + 62 fsyncs) | **40 ms** (1 batched CoW helper spawn) | **−60 ms** | **−60.0%** | **2.50×** | +| `.worktreeinclude` (31 files + 5,000-file `node_modules`) | **Crashed** (`output_limit` > 1 MiB) | **44 ms** (0 crashes) | Fixed crash | **100% crash fix** | ∞ | + +## As-Built Deviations & Refinements from Adversarial Reviews + +- **No cross-caller `usableFlights` cache (Phase 2):** Removed in-flight coalescing across callers for `managedWorktreeUsable` so live FS verification never shares a stale admission across concurrent mutations; fenced instead with `while (this.mutations.has(commonDir))` + `mutationEpochs` and `O_RDONLY | O_NOFOLLOW | O_NONBLOCK` reads. +- **No workspace-folder read during Flow-B skill warmup (Phase 3):** `chats:createWithFirstMessage` warms `discoverSkillCandidatesWithCachedGlobals(undefined)` only when `settings.skillsEnabled !== false`, honoring No Access workspace boundaries and avoiding source-local `.claude/settings.local.json` cache-key drift. +- **Graceful `SIGTERM` + close-gated abort settlement in `provision` (Phase 4):** `provisionManagedWorktreeFilesBatch` manages `AbortSignal` via `SIGTERM` (+ 2 s `SIGKILL` fallback) and settles strictly on `"close"` after `stdout` drains, while `native/worktree-file-io/main.c` catches `SIGTERM`, unlinks partial temps, and emits `p ` 1:1 with disk installs so rollback never races with a running helper. +- **Deferred (out of scope):** Tier 3 standby worktree pool remains out of scope; `FirstMessageWorktreeLedger` `ready` fsync and `GitRepoWatcher` self-echo suppression were left untouched to preserve crash-safety guarantees. + +## Non-Negotiable Safety Invariants + +1. **Inner mutation admission stays authoritative**: `managedWorktreeCheckoutBytes` + `checkWorktreeAllocation` must run inside `enqueueMutation(repo.commonDir)` before `mkdir`/`worktree add`. Deduplicate by passing `additionalAllocationBytes` into `createWorktree`, not by removing the inner check. +2. **Streaming `check-attr --all --stdin` only**: Never buffer full `check-attr --all --stdin` output in the 1 MiB `DEFAULT_MAX_BUFFER_BYTES` buffer (2 normal `.gitattributes` rules produce >1.1 MiB on 6,500 files), never switch to explicit attribute names (loses `filter=unspecified` distinction), and never skip `check-attr` when `.gitattributes` is absent from `ls-tree` (`info/attributes`, global config, and `includeIf` still apply). +3. **Preserve `copy` SHA-256 in `native/worktree-file-io/main.c`**: `captureProvisionedFile` in `managed-worktree-snapshot.ts` requires `copied.digest`. Add a dedicated batched `provision` subcommand that preserves `openat` + `S_ISREG` + `same_source`, strips modes to `0777` + clears flags (`fchflags(0)`), and falls back to `read/write` on `EXDEV`/`ENOTSUP`. +4. **Live FS verification for `assertManagedWorktreeAdmission`**: Keep every `revalidate()` call in `agents-instructions.ts` and every admission call in `terminal:write`; replace the 4-git-spawn check inside `managedWorktreeUsable` with live 0-spawn pure-FS verification (`lstat` dev/ino + `/.git` + `/{aiden-owner,gitdir,commondir,HEAD}`) + in-flight promise coalescing so external `mv`/`rm`/`git switch` revocations remain immediate. +5. **Retain `DataStore` `.previous` predecessors**: Keep process-lifetime `.previous` files intact; only gate redundant `protectLocal()` rescans on warm `local.load()` cache hits when directory/publication state is unchanged. +6. **Preserve renderer safety contracts**: Keep pre-send `folderPresence` on existing-chat sends (PR #647); keep `useChat` global `staleTime: 0` (suppress only one-shot post-promotion `refetchOnMount`); keep `workspaces:changed` → `chats:list` invalidation on workspace removals/Remote reconciliation. + +## Phases + +### Phase 1 — Backend Git Core & `.worktreeinclude` Fix (Tier 1 Backend) +- Collapse `GitService.repository()` from 3 `rev-parse` spawns (2 serial rounds) to 1 spawn (`git rev-parse --is-inside-work-tree --show-toplevel --git-common-dir`). +- Replace the 128-file sequential `git check-attr` loop in `managedWorktreeCheckoutBytes` with a single streaming `git check-attr --cached -z --all --stdin` parser (no 1 MiB overflow; same-commit + attribute-file-mtime memoization safe across `info/attributes` and global config). +- Deduplicate outer vs. inner `managedWorktreeCheckoutBytes` and `checkWorktreeAllocation` via `additionalAllocationBytes` passed into `git.createWorktree`; remove redundant post-create `repositoryPaths` call in `createIn`. +- Enable parallel checkout in `git.createWorktree` (`-c checkout.workers=${min(4, cpus)} -c checkout.thresholdForParallelism=50`, verified optimal on APFS with zero tail spikes). +- Trim redundant pre/post spawns in `createWorktree` and `createFromBase` (direct `/.git` read with safe fallback, drop redundant `show-ref`, thread `repo` across `resolveWorktreeBase`/`fetchWorktreeBase`/`localBranchNames`, parallelize independent reads). +- Fix `.worktreeinclude` `node_modules` `output_limit` crash: invert to `git ls-files -z -o -i --exclude-from= --full-name` → short-circuit if empty → `git check-ignore -z --stdin` with `allowExitCodes: [1]`. + +### Phase 2 — Main Process 0-Spawn Admission, Skill Cache, Pi Fast-Path & Store Gating (Tier 2 Main) +- Live 0-spawn pure-FS verification + in-flight coalescing in `managedWorktreeUsable` / `assertManagedWorktreeAdmission`. +- Split global vs. workspace skill candidate discovery cache in `skills-discovery.ts` / `skill-registry.ts` (preserving `isEnabled()` check first and `O_NOFOLLOW` workspace checks); avoid double `resolveFresh` on slash-skill worktree sends. +- Fast-path brand-new chats in `piCompactionSessionStore.openChatIfEligible` (in-memory index of existing journals & legacy migration candidates scanned once on store init, updated on create/delete). +- Gate `protectLocal()` on warm `localStore.load()` cache hits when directory/publication state is unchanged; make `FirstMessageWorktreeLedger`'s `ready` transition non-blocking/no-fsync (since `pending` is already crash-safe); seed short-TTL display-only `GitInfo` cache on newly created worktrees and suppress `GitRepoWatcher` self-echo for Aiden's own ref creation. + +### Phase 3 — Renderer Perceived Speed, IPC Coalescing & Parallel Flow-B Warmup (Tier 1 + 2 UI & IPC) +- Enrich `FirstMessageWorktreeResult` (and `git:createWorktree` if additive/safe for desktop/Remote/mobile) with `{ workspace, initialGitInfo }` so `chat-pane.tsx` seeds caches and selects the workspace synchronously instead of blocking `runGeneration` on `await qc.invalidateQueries(workspaces)`. +- Pipeline read-only workspace-independent Flow-B LLM warm-up (`resolveModelRuntime`, global skills, `webSearchService.availability`) in parallel with `firstMessageWorktrees.ensure()`. +- Narrow `workspaces:changed` so workspace *addition* updates `queryKeys.workspaces` without blindly refetching `chats:list` (keeping full invalidation for removals/reconciliation). +- Mount `DraftWorktreeSendView` on frame 1 for draft worktree sends; seed draft `worktree.baseRef`/`fromOrigin` immediately from `GitInfo` (fixing `⌥↵` double-stall); gate `useGitWorktrees` in `git-branch-picker.tsx`; suppress one-shot post-promotion `chats:get` refetch while keeping global `staleTime: 0`. +- Render pending worktree-send state seamlessly inside `MessageList` (no bubble remount flash); isolate `artifacts`/`editorState`/`gitOperationBusy` from monolithic `EnvironmentPanelContext`; wrap non-urgent workspace-switch updates in `React.startTransition`; use `requestChatDraftComposerFocus` in `createGitWorktree`. + +### Phase 4 — Native Batched `provision` (`native/worktree-file-io/main.c`), Benchmarks, Docs & CI +- Add dedicated batched `provision` subcommand in `native/worktree-file-io/main.c` (using APFS `fclonefileat` when same-volume + `openat`/`S_ISREG`/`same_source`/`mode & 0777`/`fchflags(0)` + `EXDEV`/`ENOTSUP` fallback, single directory `fsync`, leaving `copy` + SHA-256 intact for snapshots) and wire `managed-worktree-provisioner.ts` to use it. +- Re-run uncontended benchmarks, verify all unit/contract/typecheck/lint/mobile/E2E suites, update `.memory/` and `docs/plans/README.md`, open PR, and watch CI until green. + +## Review Gate + +After every phase: run targeted behavioral test suites, launch **two independent Gemini 4 Hydrogen (High) adversarial reviewers** to hunt for edge cases, regressions, and security/TOCTOU flaws, resolve all findings, re-test, and commit before advancing. diff --git a/main/handlers/chats.ts b/main/handlers/chats.ts index 07279da8c8..a3561cd045 100644 --- a/main/handlers/chats.ts +++ b/main/handlers/chats.ts @@ -19,6 +19,7 @@ import { wrapStoredHtmlArtifact, } from "../services/gui-artifact-recovery.js"; import { skillRegistry } from "../services/skill-registry-main.js"; +import { discoverSkillCandidatesWithCachedGlobals } from "../services/skills-discovery.js"; import { workspaceMutationGate } from "../services/workspace-mutation-gate.js"; import { admitRendererOwnedWorkspaceOperation, @@ -168,15 +169,34 @@ export function registerChatHistoryHandlers(): void { const owner = rendererDocumentOwner(event, () => new Error("Chats require the active application document.")); const fromQuickChat = isCurrentQuickChatEvent(event); if (parsed.worktree) { + // Warm global skill discovery (read-only, 5 s TTL) in parallel with worktree + // creation when skills are enabled, without reading any workspace folder + // (honoring No Access boundaries and avoiding source-local plugin config drift). + void configStore + .getSettings() + .then((settings) => { + if (settings.skillsEnabled !== false) { + return discoverSkillCandidatesWithCachedGlobals(undefined); + } + return undefined; + }) + .catch(() => undefined); // New worktree: the result is a FirstMessageWorktreeResult, and progress // goes only to this document. return commitFirstMessageInWorktree(parsed, owner, (progress) => { if (!owner.isDestroyed()) owner.send("chats:first-message-worktree-progress", progress); - }).then((result) => { + }).then(async (result) => { if (!result.ok) return result; if (fromQuickChat) authorizeQuickChatConversation(result.chat.id); announceFirstMessage(result.chat); - return { ...result, chat: chatForRenderer(result.chat) }; + const workspace = await configStore + .getWorkspace(result.worktree.workspaceId) + .catch(() => undefined); + return { + ...result, + chat: chatForRenderer(result.chat), + ...(workspace ? { workspace } : {}), + }; }); } return commitFirstMessage(parsed, owner).then((chat) => { diff --git a/main/services/agent-surface-hooks.ts b/main/services/agent-surface-hooks.ts index 0f3620b730..f972591e9f 100644 --- a/main/services/agent-surface-hooks.ts +++ b/main/services/agent-surface-hooks.ts @@ -254,13 +254,14 @@ export interface WorktreeSetupHookInput { /** * Runs WorktreeSetup hooks in the new worktree and waits for them (each is - * bounded by its own timeout). Returns the lines the person should see; a - * failing hook never throws here, so the worktree is never undone. + * bounded by its own timeout). Returns both user-facing notices and the names + * of hooks that actually executed so callers can invalidate any pre-hook clean + * Git snapshot when setup modified the checkout. */ -export async function runWorktreeSetupHooks( +export async function runWorktreeSetupHooksWithResult( input: WorktreeSetupHookInput, dispatcher?: () => HookDispatcher, -): Promise { +): Promise<{ notices: string[]; ranHooks: string[] }> { const hooks = createSurfaceHooks( { scopes: hookScopesFor({ workspaceRoot: input.sourceFolderPath }), cwd: input.workspacePath, sessionId: input.workspaceId }, dispatcher, @@ -270,5 +271,17 @@ export async function runWorktreeSetupHooks( { worktree_path: input.worktreePath, branch: input.branch, source_root: input.sourceRoot }, { idempotencyKey: `WorktreeSetup:${input.workspaceId}` }, ); - return hookNoticeLines(outcome); + return { notices: hookNoticeLines(outcome), ranHooks: outcome?.ranHooks ?? [] }; +} + +/** + * Runs WorktreeSetup hooks in the new worktree and waits for them (each is + * bounded by its own timeout). Returns the lines the person should see; a + * failing hook never throws here, so the worktree is never undone. + */ +export async function runWorktreeSetupHooks( + input: WorktreeSetupHookInput, + dispatcher?: () => HookDispatcher, +): Promise { + return (await runWorktreeSetupHooksWithResult(input, dispatcher)).notices; } diff --git a/main/services/git-executable.test.ts b/main/services/git-executable.test.ts index 18f9c63738..c67a47602e 100644 --- a/main/services/git-executable.test.ts +++ b/main/services/git-executable.test.ts @@ -214,6 +214,19 @@ test("memoized resolver leaves Windows binaries to the OS lookup", async () => { assert.deepEqual(f.inspected, []); }); +test("memoized resolver notices when a direct symlink binary is repointed", async () => { + const paths: Record = { + "/custom/git-link": "/opt/git-a/bin/git", + "/opt/git-a/bin/git": "/opt/git-a/bin/git", + "/opt/git-b/bin/git": "/opt/git-b/bin/git", + }; + const f = memoFixture(paths); + const resolve = createGitExecutableResolver(f.deps); + assert.equal(await resolve("/custom/git-link", "/w", {}), "/opt/git-a/bin/git"); + paths["/custom/git-link"] = "/opt/git-b/bin/git"; + assert.equal(await resolve("/custom/git-link", "/w", {}), "/opt/git-b/bin/git"); +}); + test("memoized resolver on Linux skips a workspace-relative PATH entry", async () => { const f = memoFixture({ "/w/git": "/w/git", "/usr/bin/git": "/usr/bin/git" }); const resolve = createGitExecutableResolver({ ...f.deps, platform: "linux" }); diff --git a/main/services/git-executable.ts b/main/services/git-executable.ts index 8bbd6dc79e..16339ed5d8 100644 --- a/main/services/git-executable.ts +++ b/main/services/git-executable.ts @@ -126,15 +126,25 @@ export function createGitExecutableResolver( return async (binary, cwd, env, signal) => { signal?.throwIfAborted(); if (deps.platform === "win32") return binary; + const directPath = binary.includes("/") ? path.resolve(cwd, binary) : undefined; const key = JSON.stringify([ - binary.includes("/") ? path.resolve(cwd, binary) : binary, + directPath ?? binary, env.PATH ?? null, env.DEVELOPER_DIR ?? null, ]); const cached = resolved.get(key); if (cached && now() - cached.at < ttlMs) { - const current = await abortable(deps.executablePath(cached.executable), signal); - if (current === cached.executable) return cached.executable; + if (directPath) { + const directCurrent = await abortable(deps.executablePath(directPath), signal); + if (directCurrent === cached.executable) return cached.executable; + if (deps.platform === "darwin" && directCurrent === "/usr/bin/git") { + const targetCurrent = await abortable(deps.executablePath(cached.executable), signal); + if (targetCurrent === cached.executable) return cached.executable; + } + } else { + const current = await abortable(deps.executablePath(cached.executable), signal); + if (current === cached.executable) return cached.executable; + } } if (resolved.get(key) === cached) resolved.delete(key); let resolution = pending.get(key); diff --git a/main/services/git.test.ts b/main/services/git.test.ts index 0d1fc13528..35918d2443 100644 --- a/main/services/git.test.ts +++ b/main/services/git.test.ts @@ -4511,16 +4511,10 @@ test("GitService managed creation suppresses post-checkout hooks and still prese wrapper, `#!/usr/bin/env node import { spawnSync } from "node:child_process"; -import { existsSync, unlinkSync, writeFileSync } from "node:fs"; +import { writeFileSync } from "node:fs"; import { join } from "node:path"; const args = process.argv.slice(2); -const state = ${JSON.stringify(path.join(root, "fail-next-rev-parse"))}; -if (existsSync(state) && args[0] === "rev-parse" && args.includes("--git-dir")) { - unlinkSync(state); - process.stderr.write("simulated post-add setup failure\\n"); - process.exit(1); -} const result = spawnSync("/usr/bin/git", args, { cwd: process.cwd(), encoding: "utf8", @@ -4534,7 +4528,6 @@ if (args[0] === "worktree" && args[1] === "add" && result.status === 0) { const target = args[separator + 1]; writeFileSync(${JSON.stringify(lateTargetRecord)}, target); writeFileSync(join(target, "late-sentinel.txt"), "late data must survive\\n"); - writeFileSync(state, "fail next worktree rev-parse\\n"); } process.exit(result.status ?? 1); `, @@ -4552,6 +4545,11 @@ printf 'hook data must survive\\n' > "$checkout/hook-sentinel.txt" ); await git(repository, ["config", "core.hooksPath", hooks]); const service = new GitService({ cacheTtlMs: 0, gitBinary: wrapper }); + // Simulate a post-add setup failure so rollback must inspect the new checkout. + (service as unknown as { persistWorktreeOwnership: () => Promise }).persistWorktreeOwnership = + async () => { + throw new GitServiceError("command_failed", "simulated post-add setup failure"); + }; await assert.rejects( service.createWorktree(repository, root, "codex/hook-sentinel"), @@ -4798,11 +4796,11 @@ test("GitService shares cold consumers and validates discovery without warm subp const { commands } = observeGitCommands(service); const results = await Promise.all(Array.from({ length: 10 }, () => service.info(repository))); assert.ok(results.every(info => info.branch === "main" && info.uncommitted === 0)); - assert.equal(commands.length, 6, "one discovery and status flight for all consumers"); + assert.equal(commands.length, 4, "one discovery and status flight for all consumers"); commands.length = 0; for (let i = 0; i < 10; i++) assert.equal((await service.info(repository)).branch, "main"); assert.equal(commands.length, 0, "warm reads validate filesystem identity without Git processes"); - t.diagnostic("10 concurrent cold info reads: 6 commands; 10 sequential warm info reads: 0 commands (baseline warm: 30)"); + t.diagnostic("10 concurrent cold info reads: 4 commands; 10 sequential warm info reads: 0 commands (baseline warm: 30)"); }); test("GitService shares info with branches but keeps external status freshness", async (t) => { @@ -4815,7 +4813,7 @@ test("GitService shares info with branches but keeps external status freshness", commands.length = 0; await fs.writeFile(path.join(repository, "external.txt"), "external edit\n"); assert.equal((await service.info(repository)).uncommitted, 1); - assert.equal(commands.filter(args => args[0] === "rev-parse").length, 3); + assert.equal(commands.filter(args => args[0] === "rev-parse").length, 1); assert.equal(commands.filter(args => args[0] === "status").length, 1); await git(repository, ["switch", "-c", "external-ref"]); assert.equal((await service.info(repository)).branch, "external-ref"); @@ -5048,7 +5046,7 @@ test("GitService keeps the default freshness deadline and invalidates linked con now += 1001; await fs.writeFile(path.join(repository, "external-freshness.txt"), "changed\n"); assert.equal((await service.info(repository)).uncommitted, 1); - assert.equal(commands.length, 6, "the existing one-second TTL still expires discovery and status"); + assert.equal(commands.length, 4, "the existing one-second TTL still expires discovery and status"); await service.createBranch(repository, "fresh-mutation"); assert.ok((await service.branches(linked)).branches.includes("fresh-mutation"), "common-directory mutation invalidates a linked consumer immediately"); }); @@ -5062,7 +5060,7 @@ test("GitService retries config and linked common-directory changes during disco let moved = false; runner.run = async (cwd, args, options) => { const result = await original(cwd, args, options); - if (args[0] === "rev-parse" && args[1] === "--show-toplevel" && !moved) { + if (args[0] === "rev-parse" && args.includes("--show-toplevel") && !moved) { moved = true; await git(repository, ["config", "core.worktree", other]); } @@ -5082,15 +5080,10 @@ test("GitService retries config and linked common-directory changes during disco const linkedService = new GitService({ cacheTtlMs: 60_000 }); const linkedObserver = observeGitCommands(linkedService); const linkedRun = linkedObserver.runner.run; - const initialTopLevel = gitReadGate(); let switched = false; linkedObserver.runner.run = async (cwd, args, options) => { const result = await linkedRun(cwd, args, options); - if (args[0] === "rev-parse" && args[1] === "--show-toplevel") initialTopLevel.resolve(); - if (args[0] === "rev-parse" && args[1] === "--git-common-dir" && !switched) { - // Complete the sibling discovery command before deliberately removing - // its pointer, so exactly one controlled failure drives the retry. - await initialTopLevel.promise; + if (args[0] === "rev-parse" && args.includes("--git-common-dir") && !switched) { switched = true; const pointer = path.join(admin, "commondir"); await fs.rename(pointer, `${pointer}-old`); @@ -5147,7 +5140,7 @@ test("GitService rejects late cache publications from a replaced root across ali if (kind === "branches") await oldInfoFinished.promise; held.resolve(); await releaseOldRead.promise; - } else if (readingNewRoot && args[0] === "rev-parse" && args[1] === "--git-common-dir") { + } else if (readingNewRoot && args[0] === "rev-parse" && args.includes("--git-common-dir")) { releaseOldRead.resolve(); await oldProofBlocked.promise; } diff --git a/main/services/git.ts b/main/services/git.ts index dbc005bf2c..953a83b404 100644 --- a/main/services/git.ts +++ b/main/services/git.ts @@ -11,7 +11,7 @@ import { } from "./repository-identity.js"; import { createProcessGroupTerminator, decodeCappedUtf8 } from "../shared/process-group.js"; import { redactUrlCredentials } from "../shared/redaction.js"; -import { spawn, type ChildProcess } from "child_process"; +import { execFile, spawn, type ChildProcess } from "child_process"; import { createHash, randomUUID } from "crypto"; import { constants as fsConstants, type BigIntStats, type Stats } from "fs"; import * as fs from "fs/promises"; @@ -24,7 +24,7 @@ import { } from "./managed-worktree-removal-core.js"; import type { GitBranches, GitInfo, GitWorktree } from "./types.js"; import { reportAnalyticsEvent } from "./analytics/analytics-report.js"; -import { resolveGitExecutableMemoized } from "./git-executable.js"; +import { resolveGitExecutable, resolveGitExecutableMemoized } from "./git-executable.js"; import { agentCommandEnvironment } from "./agent-command-environment.js"; import { finalizeManagedWorktreeRemovalManifest, @@ -137,6 +137,14 @@ interface GitRunOptions { hooksDisabled?: boolean; mutation?: boolean; nonInteractiveCommit?: boolean; + /** Optional raw data written to the child's stdin, which is then closed. */ + stdin?: string | Buffer; + /** + * Stream raw stdout chunks directly to a callback instead of buffering stdout + * in memory. Throwing inside this callback terminates the child cleanly and + * rejects the command with that error. + */ + onStdoutChunk?: (chunk: Buffer) => void; signal?: AbortSignal; timeoutMs?: number; } @@ -423,6 +431,11 @@ export interface GitWorktreeBase { export interface GitCreateWorktreeOptions { provisionedIgnored?: readonly string[]; + /** + * Extra bytes (for example `.worktreeinclude` reserve) added to the checkout + * estimate for the atomic free-space admission inside the mutation queue. + */ + additionalAllocationBytes?: number; /** * Fully qualified ref or full commit to start from. Resolved to a commit * inside the repository's mutation queue. Defaults to `HEAD`. @@ -585,7 +598,17 @@ export interface GitFileDiff { truncated: boolean; } -type TerminationReason = "aborted" | "output_limit" | "timeout"; +type TerminationReason = "aborted" | "callback_error" | "output_limit" | "timeout"; + +function parallelCheckoutConfig(): ReadonlyArray { + // Controlled A/B benchmarks on APFS show 4 workers cuts worktree checkout time + // ~46–48% with tight variance, while higher counts regress from directory lock contention. + const workers = Math.max(1, Math.min(4, os.cpus().length)); + return [ + ["checkout.workers", String(workers)], + ["checkout.thresholdForParallelism", "50"], + ]; +} function replaceAllLiteral(value: string, search: string, replacement: string): string { return search ? value.split(search).join(replacement) : value; @@ -1000,6 +1023,190 @@ function reviewFileSignature(stats: BigIntStats): string { return `${stats.dev}:${stats.ino}:${stats.mode}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`; } +interface VerifiedRepoIdentityProof { + commonDir: string; + identityPaths: string[]; + systemConfigKey: string; + systemConfigPaths: string[]; + resolvedExecutable: string; + viaDarwinShim: boolean; + execSignature: string; + paths: string[]; + signature: string; +} + +const MAX_DIRECT_GIT_BINARY_HASH_BYTES = 64 * 1024 * 1024; +const APPLE_CODESIGN_GIT_REQUIREMENT = '=anchor apple and identifier "com.apple.git"'; + +/** + * Only OS-managed Git installation paths are eligible for the 0-spawn pure-FS + * admission proof: + * - macOS: Apple CLT or Xcode `git` (additionally verified cryptographically + * against Apple Root CA with identifier `com.apple.git` via `/usr/bin/codesign`). + * - Linux: root-owned, non-group/world-writable `/usr/bin/git` (with root-owned + * ancestors). + * User-writable package-manager paths, tool-manager shims, scripts, and + * arbitrary executables fail closed to Git-backed admission. + */ +function isTrustedDirectGitInstallPath(realPath: string): boolean { + if (process.platform === "darwin") { + return ( + realPath === "/Library/Developer/CommandLineTools/usr/bin/git" || + /^\/Applications\/Xcode[^/]*\.app\/Contents\/Developer\/usr\/bin\/git$/u.test(realPath) + ); + } + if (process.platform === "linux") { + return realPath === "/usr/bin/git"; + } + return false; +} + +/** + * Verifies every path component from `targetPath` up to `/` is a non-symlink + * owned by root (`uid === 0`) and neither group- nor world-writable. + */ +async function isRootOwnedNonWritableChain(targetPath: string): Promise { + if (!path.isAbsolute(targetPath)) return false; + let current = targetPath; + for (;;) { + try { + const st = await fs.lstat(current, { bigint: true }); + if (st.isSymbolicLink()) return false; + if (st.uid !== 0n || (st.mode & 0o022n) !== 0n) return false; + } catch { + return false; + } + const parent = path.dirname(current); + if (parent === current) return true; + current = parent; + } +} + +/** + * Cryptographically verifies that `realPath` on macOS is an unmodified Apple + * `com.apple.git` binary signed by Apple Root CA (excluding `/usr/bin/git` + * xcrun shims and any user-compiled or modified executable). + */ +async function verifyAppleSignedGitBinary( + realPath: string, + signal?: AbortSignal, +): Promise { + if (process.platform !== "darwin") return false; + if (signal?.aborted) { + throw new GitServiceError("aborted", "Git operation was cancelled."); + } + return new Promise((resolve, reject) => { + execFile( + "/usr/bin/codesign", + ["--verify", "--strict", "-R", APPLE_CODESIGN_GIT_REQUIREMENT, "--", realPath], + { + env: { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C" }, + signal, + timeout: 2_000, + maxBuffer: 16_384, + }, + (error) => { + if (signal?.aborted) { + reject(new GitServiceError("aborted", "Git operation was cancelled.")); + return; + } + resolve(!error); + }, + ); + }); +} + +async function sha256BoundedNoFollowFile( + filePath: string, + maxBytes: number, +): Promise { + const flags = + fsConstants.O_RDONLY | + (fsConstants.O_NOFOLLOW ?? 0) | + (fsConstants.O_NONBLOCK ?? 0); + let handle: fs.FileHandle | undefined; + try { + handle = await fs.open(filePath, flags); + const stat = await handle.stat(); + if (!stat.isFile() || stat.size <= 0 || stat.size > maxBytes) { + return undefined; + } + const hash = createHash("sha256"); + const chunk = Buffer.allocUnsafe(64 * 1024); + let totalRead = 0; + while (totalRead < stat.size) { + const { bytesRead } = await handle.read(chunk, 0, chunk.length, totalRead); + if (bytesRead === 0) return undefined; + totalRead += bytesRead; + if (totalRead > stat.size) return undefined; + hash.update(chunk.subarray(0, bytesRead)); + } + const { bytesRead: trailing } = await handle.read(chunk, 0, 1, totalRead); + if (trailing !== 0) return undefined; + return hash.digest("hex"); + } catch { + return undefined; + } finally { + await handle?.close().catch(() => undefined); + } +} + +/** + * Verifies that `realPath` is a native Mach-O (macOS) or ELF (Linux) regular + * executable file rather than a shebang/interpreted script or text wrapper. + * Unsupported platforms fail closed so pure-FS admission falls back to Git. + */ +async function isNativeExecutableBinary(realPath: string): Promise { + if (process.platform !== "darwin" && process.platform !== "linux") { + return false; + } + const flags = + fsConstants.O_RDONLY | + (fsConstants.O_NOFOLLOW ?? 0) | + (fsConstants.O_NONBLOCK ?? 0); + let handle: fs.FileHandle | undefined; + try { + handle = await fs.open(realPath, flags); + const stat = await handle.stat(); + if (!stat.isFile() || stat.size < 64) return false; + const header = Buffer.alloc(8); + const { bytesRead } = await handle.read(header, 0, header.length, 0); + if (bytesRead < 8) return false; + if (process.platform === "darwin") { + const magic = header.readUInt32BE(0); + if ( + magic === 0xfeedface || + magic === 0xcefaedfe || + magic === 0xfeedfacf || + magic === 0xcffaedfe + ) { + return true; + } + if (magic === 0xcafebabe || magic === 0xcafebabf) { + const archCount = header.readUInt32BE(4); + return archCount >= 1 && archCount <= 32; + } + if (magic === 0xbebafeca || magic === 0xbfbafeca) { + const archCount = header.readUInt32LE(4); + return archCount >= 1 && archCount <= 32; + } + return false; + } + return ( + header[0] === 0x7f && + header[1] === 0x45 && + header[2] === 0x4c && + header[3] === 0x46 && + (header[4] === 1 || header[4] === 2) && + (header[5] === 1 || header[5] === 2) + ); + } catch { + return false; + } finally { + await handle?.close().catch(() => undefined); + } +} + export class GitService { private readonly gitBinary: string; private readonly maxBufferBytes: number; @@ -1037,6 +1244,22 @@ export class GitService { } >(); private readonly infoCache = new Map>(); + /** + * Config-signature-validated display metadata (`hasRemote`, `defaultBranch`) + * learned from ordinary status reads, used only to seed display-only `infoCache` + * immediately after `createWorktree`. + */ + private readonly repoRemoteHints = new Map< + string, + { configSignature: string; hasRemote: boolean; defaultBranch?: string } + >(); + /** + * Git-verified repository routing & config signatures keyed by canonical root + * path. Used to gate the 0-spawn pure-FS `managedWorktreeUsable` fast path so + * any external config change (including `core.bare=true` or included config + * files) immediately falls back to Git discovery and fails closed. + */ + private readonly verifiedRepoIdentities = new Map(); /** * Credential-free remote identity learned by ordinary status reads, keyed by * repository working directory. Raw remote URLs are never retained. @@ -1106,7 +1329,7 @@ export class GitService { ...(options.gitIndexFile ? { GIT_INDEX_FILE: options.gitIndexFile } : {}), ...(options.nonInteractiveCommit ? { GIT_EDITOR: ":" } : {}), }, - stdio: ["ignore", "pipe", "pipe"], + stdio: [options.stdin !== undefined ? "pipe" : "ignore", "pipe", "pipe"], windowsHide: true, }); } catch (error) { @@ -1119,6 +1342,7 @@ export class GitService { let stdoutBytes = 0; let stderrBytes = 0; let termination: TerminationReason | undefined; + let callbackError: unknown; let settled = false; const terminator = createProcessGroupTerminator(child, { killGraceMs: KILL_GRACE_MS }); @@ -1127,6 +1351,16 @@ export class GitService { termination = reason; terminator.terminate(); }; + if (options.stdin !== undefined && child.stdin) { + child.stdin.on("error", (error: NodeJS.ErrnoException) => { + // A child that exits early (for example on error, abort, or early + // streaming rejection) closes its read end and raises EPIPE/ERR_STREAM_DESTROYED. + if (error.code === "EPIPE" || error.code === "ERR_STREAM_DESTROYED") return; + callbackError ??= new GitServiceError("command_failed", publicGitMessage(error, cwd), error); + terminate("callback_error"); + }); + child.stdin.end(options.stdin); + } const append = (target: Buffer[], chunk: Buffer, stream: "stdout" | "stderr") => { const currentBytes = stream === "stdout" ? stdoutBytes : stderrBytes; const nextBytes = currentBytes + chunk.byteLength; @@ -1142,7 +1376,20 @@ export class GitService { if (stream === "stdout") stdoutBytes = nextBytes; else stderrBytes = nextBytes; }; - child.stdout?.on("data", (chunk: Buffer) => append(stdout, chunk, "stdout")); + if (options.onStdoutChunk) { + const onChunk = options.onStdoutChunk; + child.stdout?.on("data", (chunk: Buffer) => { + if (termination || settled) return; + try { + onChunk(chunk); + } catch (error) { + callbackError = error; + terminate("callback_error"); + } + }); + } else { + child.stdout?.on("data", (chunk: Buffer) => append(stdout, chunk, "stdout")); + } child.stderr?.on("data", (chunk: Buffer) => append(stderr, chunk, "stderr")); const abort = () => terminate("aborted"); @@ -1180,6 +1427,14 @@ export class GitService { reject(new GitServiceError("aborted", "Git operation was cancelled.")); return; } + if (termination === "callback_error") { + reject( + callbackError instanceof Error + ? callbackError + : new GitServiceError("command_failed", publicGitMessage(callbackError, cwd), callbackError), + ); + return; + } if (termination === "timeout") { reject( new GitServiceError( @@ -1221,6 +1476,539 @@ export class GitService { }); } + private systemConfigEnvKey(env: NodeJS.ProcessEnv): string { + return JSON.stringify([ + this.gitBinary, + env.GIT_CONFIG_NOSYSTEM ?? null, + env.GIT_CONFIG_SYSTEM ?? null, + env.GIT_CONFIG_GLOBAL ?? null, + env.HOME ?? null, + env.XDG_CONFIG_HOME ?? null, + env.PATH ?? null, + env.DEVELOPER_DIR ?? null, + env.GIT_EXEC_PATH ?? null, + env.LD_PRELOAD ?? null, + env.DYLD_INSERT_LIBRARIES ?? null, + ]); + } + + private async signExecutablePathChain(candidate: string): Promise< + | { + real: string; + realStat: BigIntStats; + signature: string; + } + | undefined + > { + try { + const hops: string[] = []; + let current = candidate; + const MAX_SYMLINK_HOPS = 40; + for (let hop = 0; hop <= MAX_SYMLINK_HOPS; hop += 1) { + const st = await fs.lstat(current, { bigint: true }); + if (st.isDirectory()) return undefined; + if (st.isSymbolicLink()) { + if (hop === MAX_SYMLINK_HOPS) return undefined; + const target = await fs.readlink(current); + hops.push( + `link:${current}:${st.dev}:${st.ino}:${st.mode}:${st.size}:${st.mtimeNs}:${st.ctimeNs}->${target}`, + ); + current = path.resolve(path.dirname(current), target); + continue; + } + if (!st.isFile()) return undefined; + hops.push( + `file:${current}:${st.dev}:${st.ino}:${st.mode}:${st.size}:${st.mtimeNs}:${st.ctimeNs}`, + ); + break; + } + await fs.access(candidate, fsConstants.X_OK); + const real = await fs.realpath(candidate); + const realStat = await fs.stat(real, { bigint: true }); + if (!realStat.isFile()) return undefined; + return { + real, + realStat, + signature: [ + ...hops, + `real:${real}:${realStat.dev}:${realStat.ino}:${realStat.mode}:${realStat.size}:${realStat.mtimeNs}:${realStat.ctimeNs}`, + ].join("|"), + }; + } catch { + return undefined; + } + } + + private async signOptionalRoutingPath(filePath: string): Promise { + try { + const st = await fs.lstat(filePath, { bigint: true }); + if (st.isSymbolicLink()) { + const target = await fs.readlink(filePath); + return `link:${filePath}:${st.dev}:${st.ino}:${st.mode}:${st.mtimeNs}:${st.ctimeNs}->${target}`; + } + if (st.isFile()) { + return `file:${filePath}:${st.dev}:${st.ino}:${st.mode}:${st.size}:${st.mtimeNs}:${st.ctimeNs}`; + } + if (st.isDirectory()) { + return `dir:${filePath}:${st.dev}:${st.ino}:${st.mode}:${st.mtimeNs}:${st.ctimeNs}`; + } + return undefined; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return `missing:${filePath}`; + } + return undefined; + } + } + + private async signDarwinShimRouting(env: NodeJS.ProcessEnv): Promise { + const routingPaths = [ + "/var/db/xcode_select_link", + "/usr/share/xcode-select/xcode_dir_path", + "/Applications/Xcode.app/Contents/Developer/usr/bin/git", + "/Library/Developer/CommandLineTools/usr/bin/git", + ]; + if (env.DEVELOPER_DIR && path.isAbsolute(env.DEVELOPER_DIR)) { + routingPaths.push(path.join(env.DEVELOPER_DIR, "usr/bin/git")); + } + const entries = await Promise.all( + routingPaths.map((filePath) => this.signOptionalRoutingPath(filePath)), + ); + if (entries.some((entry) => entry === undefined)) return undefined; + return `darwin-routing[${entries.join(",")}]`; + } + + private async executableIdentitySignature( + canonicalCwd: string, + env: NodeJS.ProcessEnv, + expectedResolved: string, + viaDarwinShim: boolean, + ): Promise<{ real: string; realStat: BigIntStats; signature: string } | undefined> { + if (process.platform !== "darwin" && process.platform !== "linux") { + return undefined; + } + if (!isTrustedDirectGitInstallPath(expectedResolved)) { + return undefined; + } + const candidates = this.gitBinary.includes("/") + ? [path.resolve(canonicalCwd, this.gitBinary)] + : (env.PATH ?? "/usr/bin:/bin") + .split(":") + .filter((dir) => path.isAbsolute(dir)) + .map((dir) => path.join(dir, this.gitBinary)); + + const parts: string[] = []; + for (const candidate of candidates) { + const matched = await this.signExecutablePathChain(candidate); + if (matched) { + if (process.platform === "darwin" && matched.real === "/usr/bin/git") { + const darwinRouting = await this.signDarwinShimRouting(env); + if (!darwinRouting) return undefined; + parts.push(`darwin-shim:${matched.signature}`); + parts.push(darwinRouting); + if (viaDarwinShim) { + const resolvedChain = await this.signExecutablePathChain(expectedResolved); + if (!resolvedChain || resolvedChain.real !== expectedResolved) { + return undefined; + } + parts.push(`resolved:${resolvedChain.signature}`); + return { + real: resolvedChain.real, + realStat: resolvedChain.realStat, + signature: parts.join(";"), + }; + } + continue; + } + if (viaDarwinShim || matched.real !== expectedResolved) { + return undefined; + } + parts.push(matched.signature); + return { + real: matched.real, + realStat: matched.realStat, + signature: parts.join(";"), + }; + } + try { + const lstat = await fs.lstat(candidate, { bigint: true }); + parts.push( + `skip:${candidate}:${lstat.dev}:${lstat.ino}:${lstat.mode}:${lstat.mtimeNs}:${lstat.ctimeNs}`, + ); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + parts.push(`missing:${candidate}`); + } else { + return undefined; + } + } + } + return undefined; + } + + /** + * Proves that the resolved native binary is the actual Git executable itself + * (its own `/git` resolves to the exact same binary or inode) and + * not a compiled wrapper or dynamic shim delegating to a separate Git binary. + */ + private async verifyDirectGitExecPath( + canonicalCwd: string, + resolvedRealPath: string, + resolvedRealStat: BigIntStats, + signal?: AbortSignal, + ): Promise { + let probe: GitCommandResult; + try { + probe = await this.run(canonicalCwd, ["--exec-path"], { signal }); + } catch (error) { + if (signal?.aborted) throw error; + return false; + } + const execPath = probe.stdout.replace(/\r?\n$/u, ""); + if ( + !execPath || + execPath.includes("\r") || + execPath.includes("\n") || + execPath.includes("\u0000") || + !path.isAbsolute(execPath) + ) { + return false; + } + try { + const execPathReal = await fs.realpath(execPath); + const installPrefix = path.dirname(path.dirname(resolvedRealPath)); + if ( + execPathReal !== installPrefix && + !execPathReal.startsWith(`${installPrefix}${path.sep}`) + ) { + return false; + } + const execGitReal = await fs.realpath(path.join(execPathReal, "git")); + const execGitStat = await fs.stat(execGitReal, { bigint: true }); + if (!execGitStat.isFile()) return false; + if (process.platform === "linux") { + const [execDirTrusted, execGitTrusted] = await Promise.all([ + isRootOwnedNonWritableChain(execPathReal), + isRootOwnedNonWritableChain(execGitReal), + ]); + if (!execDirTrusted || !execGitTrusted) return false; + } + if ( + execGitReal === resolvedRealPath || + (execGitStat.dev === resolvedRealStat.dev && execGitStat.ino === resolvedRealStat.ino) + ) { + return true; + } + // Stock Debian/Ubuntu installs `/usr/lib/git-core/git` as a distinct-inode + // byte-identical copy of `/usr/bin/git`. Verify identical size and SHA-256. + if (execGitStat.size !== resolvedRealStat.size) return false; + const [resolvedHash, execGitHash] = await Promise.all([ + sha256BoundedNoFollowFile(resolvedRealPath, MAX_DIRECT_GIT_BINARY_HASH_BYTES), + sha256BoundedNoFollowFile(execGitReal, MAX_DIRECT_GIT_BINARY_HASH_BYTES), + ]); + return Boolean(resolvedHash && resolvedHash === execGitHash); + } catch { + return false; + } + } + + /** + * Identify the exact system Git config path(s) used by `this.gitBinary` + * instead of guessing hardcoded platform defaults. Reprobes on every fresh + * proof construction so an updated Git binary never republishes a stale + * system-config origin. Returns `undefined` when the system config origin + * cannot be proven (for example, an existing empty system config file or an + * unrecognized error) so pure-FS admission fails closed and falls back to + * Git discovery. + */ + private async resolveSystemConfigPaths( + canonicalCwd: string, + env: NodeJS.ProcessEnv, + signal?: AbortSignal, + ): Promise { + if (env.GIT_CONFIG_NOSYSTEM !== undefined) { + const normalized = env.GIT_CONFIG_NOSYSTEM.trim().toLowerCase(); + if (normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on") { + return []; + } + if ( + normalized !== "" && + normalized !== "0" && + normalized !== "false" && + normalized !== "no" && + normalized !== "off" + ) { + return undefined; + } + } + if (env.GIT_CONFIG_SYSTEM !== undefined) { + if (!env.GIT_CONFIG_SYSTEM || env.GIT_CONFIG_SYSTEM === "/dev/null") return []; + return [path.resolve(canonicalCwd, env.GIT_CONFIG_SYSTEM)]; + } + let probe: Awaited>; + try { + probe = await this.run( + canonicalCwd, + ["config", "--system", "--list", "--show-origin", "-z"], + { allowExitCodes: [128], signal }, + ); + } catch (error) { + if (signal?.aborted) throw error; + return undefined; + } + if (probe.exitCode === 0) { + if (!probe.stdout) { + // An existing empty/comment-only system config emits no origin record; + // fail closed because its path cannot be proven from `--list`. + return undefined; + } + const tokens = probe.stdout.split("\0"); + if ( + tokens.length < 3 || + tokens[tokens.length - 1] !== "" || + (tokens.length - 1) % 2 !== 0 + ) { + return undefined; + } + const origins = new Set(); + for (let i = 0; i + 1 < tokens.length - 1; i += 2) { + const origin = tokens[i]; + if (!origin.startsWith("file:")) { + return undefined; + } + const filePath = origin.slice(5); + if (!filePath) { + return undefined; + } + origins.add(filePath); + } + if (origins.size === 0) { + return undefined; + } + return [...origins].map((filePath) => path.resolve(canonicalCwd, filePath)); + } + if (probe.exitCode === 128) { + const missingMatch = probe.stderr.match( + /unable to read config file '(.+)': No such file or directory/u, + ); + if (missingMatch?.[1]) { + return [path.resolve(canonicalCwd, missingMatch[1])]; + } + } + return undefined; + } + + private admissionConfigPaths( + canonicalCwd: string, + env: NodeJS.ProcessEnv, + identityPaths: readonly string[], + repoConfigFiles: readonly string[], + systemConfigPaths: readonly string[], + ): { allPaths: string[]; configFiles: string[] } { + const allPaths = new Set(identityPaths); + const configFiles = new Set(repoConfigFiles); + const addConfigFile = (filePath: string) => { + allPaths.add(filePath); + configFiles.add(filePath); + }; + if (env.GIT_CONFIG_GLOBAL !== undefined) { + if (env.GIT_CONFIG_GLOBAL && env.GIT_CONFIG_GLOBAL !== "/dev/null") { + addConfigFile(path.resolve(canonicalCwd, env.GIT_CONFIG_GLOBAL)); + } + } else { + const home = env.HOME || os.homedir(); + if (home) { + addConfigFile(path.join(home, ".gitconfig")); + const xdg = env.XDG_CONFIG_HOME || path.join(home, ".config"); + addConfigFile(path.join(xdg, "git", "config")); + } + } + for (const filePath of systemConfigPaths) { + addConfigFile(filePath); + } + return { allPaths: [...allPaths], configFiles: [...configFiles] }; + } + + /** + * Prove that the active Git executable is a directly-invoked native Git + * binary (not a script, wrapper, or dynamic shim), that every Git config + * file in scope (repo-local, global, system) is a plain bounded file without + * `[include]` / `[includeIf]` directives, and return a signature across all + * routing, executable, and config paths. Returns `undefined` when any + * wrapper/shim, include directive, unknown system config origin, or + * unreadable/symlinked config is present so pure-FS admission always fails + * closed to Git discovery. + */ + private async pureFsAdmissionProof( + canonicalCwd: string, + signal?: AbortSignal, + ): Promise { + const identity = await this.rootReadIdentity(canonicalCwd); + if (!identity) return undefined; + const env = gitEnvironment(false); + if (env.GIT_EXEC_PATH || env.LD_PRELOAD || env.DYLD_INSERT_LIBRARIES) { + return undefined; + } + const systemConfigKey = this.systemConfigEnvKey(env); + let freshExecutable: string; + let memoizedExecutable: string; + try { + [freshExecutable, memoizedExecutable] = await Promise.all([ + resolveGitExecutable(this.gitBinary, canonicalCwd, env, signal), + resolveGitExecutableMemoized(this.gitBinary, canonicalCwd, env, signal), + ]); + } catch (error) { + if (signal?.aborted) throw error; + return undefined; + } + if (freshExecutable !== memoizedExecutable) return undefined; + + let viaDarwinShim = false; + let execBefore = await this.executableIdentitySignature( + canonicalCwd, + env, + freshExecutable, + false, + ); + if (!execBefore && process.platform === "darwin") { + viaDarwinShim = true; + execBefore = await this.executableIdentitySignature( + canonicalCwd, + env, + freshExecutable, + true, + ); + } + if (!execBefore) return undefined; + if (!(await isNativeExecutableBinary(execBefore.real))) { + return undefined; + } + if (process.platform === "linux" && !(await isRootOwnedNonWritableChain(execBefore.real))) { + return undefined; + } + + const [binaryProven, directGitBinary, systemConfigPaths] = await Promise.all([ + process.platform === "darwin" + ? verifyAppleSignedGitBinary(execBefore.real, signal) + : Promise.resolve(true), + this.verifyDirectGitExecPath(canonicalCwd, execBefore.real, execBefore.realStat, signal), + this.resolveSystemConfigPaths(canonicalCwd, env, signal), + ]); + if (!binaryProven || !directGitBinary || !systemConfigPaths) return undefined; + + const { allPaths, configFiles } = this.admissionConfigPaths( + canonicalCwd, + env, + identity.paths, + identity.configFiles, + systemConfigPaths, + ); + const beforeSig = await this.repositorySignature(allPaths); + if (!beforeSig) return undefined; + for (const filePath of configFiles) { + const read = await this.readBoundedNoFollowFile(filePath, 256 * 1024); + if (!read.ok) { + if (read.code === "ENOENT") continue; + return undefined; + } + if (/^\uFEFF?\s*\[\s*include(?:if)?(?:\s|"|\])/im.test(read.text)) { + return undefined; + } + } + const [afterSig, execAfter] = await Promise.all([ + this.repositorySignature(allPaths), + this.executableIdentitySignature(canonicalCwd, env, freshExecutable, viaDarwinShim), + ]); + if ( + !afterSig || + afterSig !== beforeSig || + !execAfter || + execAfter.signature !== execBefore.signature + ) { + return undefined; + } + return { + commonDir: identity.commonDir, + identityPaths: identity.paths, + systemConfigKey, + systemConfigPaths: [...systemConfigPaths], + resolvedExecutable: execAfter.real, + viaDarwinShim, + execSignature: execAfter.signature, + paths: allPaths, + signature: afterSig, + }; + } + + private async isVerifiedRepoIdentityCurrent( + canonicalCwd: string, + verified: VerifiedRepoIdentityProof, + ): Promise { + const env = gitEnvironment(false); + if (env.GIT_EXEC_PATH || env.LD_PRELOAD || env.DYLD_INSERT_LIBRARIES) { + return false; + } + if (this.systemConfigEnvKey(env) !== verified.systemConfigKey) return false; + const { allPaths } = this.admissionConfigPaths( + canonicalCwd, + env, + verified.identityPaths, + [], + verified.systemConfigPaths, + ); + if ( + allPaths.length !== verified.paths.length || + !allPaths.every((filePath, index) => filePath === verified.paths[index]) + ) { + return false; + } + const [currentSig, currentExec] = await Promise.all([ + this.repositorySignature(verified.paths), + this.executableIdentitySignature( + canonicalCwd, + env, + verified.resolvedExecutable, + verified.viaDarwinShim, + ), + ]); + return ( + currentSig === verified.signature && + currentExec !== undefined && + currentExec.signature === verified.execSignature + ); + } + + private async verifyAdmissionRepository( + cwd: string, + signal?: AbortSignal, + ): Promise { + const canonicalCwd = await fs.realpath(cwd).catch(() => undefined); + const beforeProof = canonicalCwd + ? await this.pureFsAdmissionProof(canonicalCwd, signal) + : undefined; + const repo = await this.repository(cwd, signal); + if ( + repo && + canonicalCwd && + beforeProof && + repo.cwd === canonicalCwd && + canonicalCwd === repo.topLevel && + beforeProof.commonDir === repo.commonDir && + (await this.isVerifiedRepoIdentityCurrent(canonicalCwd, beforeProof)) + ) { + this.verifiedRepoIdentities.delete(canonicalCwd); + this.verifiedRepoIdentities.set(canonicalCwd, beforeProof); + while (this.verifiedRepoIdentities.size > this.cacheEntries) { + const oldest = this.verifiedRepoIdentities.keys().next().value as string | undefined; + if (!oldest) break; + this.verifiedRepoIdentities.delete(oldest); + } + } else if (canonicalCwd) { + this.verifiedRepoIdentities.delete(canonicalCwd); + } + return repo; + } + private async repository(cwd: string, signal?: AbortSignal): Promise { if (signal?.aborted) { throw new GitServiceError("aborted", "Git operation was cancelled."); @@ -1231,23 +2019,52 @@ export class GitService { } catch { return null; } - const inside = await this.run(canonicalCwd, ["rev-parse", "--is-inside-work-tree"], { - allowExitCodes: [128], - signal, - }); - if (inside.exitCode !== 0 || inside.stdout.trim() !== "true") return null; - const [topLevelResult, commonDirResult] = await Promise.all([ - this.run(canonicalCwd, ["rev-parse", "--show-toplevel"], { signal }), - this.run(canonicalCwd, ["rev-parse", "--git-common-dir"], { signal }), - ]); + const probe = await this.run( + canonicalCwd, + ["rev-parse", "--is-inside-work-tree", "--show-toplevel", "--git-common-dir"], + { allowExitCodes: [128], signal }, + ); + if (probe.exitCode !== 0) { + this.verifiedRepoIdentities.delete(canonicalCwd); + return null; + } + const raw = probe.stdout.replace(/\r?\n$/u, ""); + const lines = raw.split(/\r?\n/u); + let topLevelPath: string; + let commonPath: string; + if (lines.length === 3) { + if (lines[0].trim() !== "true") { + this.verifiedRepoIdentities.delete(canonicalCwd); + return null; + } + topLevelPath = lines[1]; + commonPath = lines[2]; + } else { + // Fallback for unusual paths containing embedded newlines. + const inside = await this.run(canonicalCwd, ["rev-parse", "--is-inside-work-tree"], { + allowExitCodes: [128], + signal, + }); + if (inside.exitCode !== 0 || inside.stdout.trim() !== "true") { + this.verifiedRepoIdentities.delete(canonicalCwd); + return null; + } + const [topLevelResult, commonDirResult] = await Promise.all([ + this.run(canonicalCwd, ["rev-parse", "--show-toplevel"], { signal }), + this.run(canonicalCwd, ["rev-parse", "--git-common-dir"], { signal }), + ]); + topLevelPath = topLevelResult.stdout.trimEnd(); + commonPath = commonDirResult.stdout.trimEnd(); + } if (signal?.aborted) { throw new GitServiceError("aborted", "Git operation was cancelled."); } - const topLevel = await fs.realpath(topLevelResult.stdout.trimEnd()); - const commonPath = commonDirResult.stdout.trimEnd(); - const commonDir = await fs.realpath( - path.isAbsolute(commonPath) ? commonPath : path.resolve(canonicalCwd, commonPath), - ); + const [topLevel, commonDir] = await Promise.all([ + fs.realpath(topLevelPath), + fs.realpath( + path.isAbsolute(commonPath) ? commonPath : path.resolve(canonicalCwd, commonPath), + ), + ]); return { cwd: canonicalCwd, topLevel, commonDir }; } @@ -1331,7 +2148,7 @@ export class GitService { } private async rootReadIdentity(cwd: string): Promise< - { paths: string[]; signature: string; commonDir: string } | undefined + { paths: string[]; configFiles: string[]; signature: string; commonDir: string } | undefined > { try { const marker = path.join(cwd, ".git"); @@ -1362,15 +2179,18 @@ export class GitService { try { commonPath = path.resolve(gitDir, (await readPointer(commonPointer)).trim()); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } const commonDir = await fs.realpath(commonPath); - const paths = [...basePaths, ...adminPaths, commonPath, commonDir, - path.join(gitDir, "config"), path.join(gitDir, "config.worktree"), - path.join(commonDir, "config")]; + const configFiles = [ + path.join(gitDir, "config"), + path.join(gitDir, "config.worktree"), + path.join(commonDir, "config"), + ]; + const paths = [...basePaths, ...adminPaths, commonPath, commonDir, ...configFiles]; const signature = await this.repositorySignature(paths); // Pointer parsing must describe the same routing files as the proof. if (!signature || !baseSignature || !adminSignature || baseSignature !== await this.repositorySignature(basePaths) || adminSignature !== await this.repositorySignature(adminPaths)) return undefined; - return { paths, signature, commonDir }; + return { paths, configFiles, signature, commonDir }; } catch { return undefined; } } @@ -1572,6 +2392,7 @@ export class GitService { } private async status(repo: GitRepository, signal?: AbortSignal): Promise { + const beforeHintSignature = await this.repoRemoteHintSignature(repo.commonDir); const [raw, remotesResult, remoteRefs] = await Promise.all([ this.run( repo.cwd, @@ -1583,6 +2404,15 @@ export class GitService { ]); const parsed = parseGitStatus(raw.stdout); this.rememberRepositoryIdentity(repo, remotesResult.stdout); + const hasRemote = remotesResult.stdout.trim().length > 0; + if (beforeHintSignature) { + await this.rememberRepoRemoteHint( + repo.commonDir, + beforeHintSignature, + hasRemote, + remoteRefs.defaultBranch, + ); + } return { isRepo: true, branch: parsed.branch, @@ -1593,11 +2423,117 @@ export class GitService { ahead: parsed.ahead, behind: parsed.behind, defaultBranch: remoteRefs.defaultBranch, - hasRemote: remotesResult.stdout.trim().length > 0, + hasRemote, remoteState: parsed.upstream ? "local-ref" : undefined, }; } + private async repoRemoteHintSignature(commonDir: string): Promise { + return this.repositorySignature([ + path.join(commonDir, "config"), + path.join(commonDir, "packed-refs"), + path.join(commonDir, "refs", "remotes"), + ]); + } + + private async rememberRepoRemoteHint( + commonDir: string, + expectedSignature: string, + hasRemote: boolean, + defaultBranch: string | undefined, + ): Promise { + const afterSignature = await this.repoRemoteHintSignature(commonDir); + if (!afterSignature || afterSignature !== expectedSignature) return; + this.repoRemoteHints.delete(commonDir); + this.repoRemoteHints.set(commonDir, { configSignature: afterSignature, hasRemote, defaultBranch }); + if (this.repoRemoteHints.size > this.cacheEntries) { + const oldest = this.repoRemoteHints.keys().next().value as string | undefined; + if (oldest !== undefined) this.repoRemoteHints.delete(oldest); + } + } + + private async seedCreatedWorktreeDisplayCache( + sourceRepo: GitRepository, + created: GitCreatedWorktree, + branch: string, + ): Promise { + if (this.cacheTtlMs <= 0) return; + // Only seed root-level checkouts matching `readRepository`'s own caching boundary. + if (created.workspacePath !== created.path) return; + try { + // Wait for our own enqueueMutation `tail.finally` invalidation to settle, + // then fence the seed against any concurrent mutation epoch. + await Promise.resolve(); + if (this.mutations.has(sourceRepo.commonDir)) return; + const epoch = this.mutationEpochs.get(sourceRepo.commonDir) ?? 0; + const canonical = await fs.realpath(created.path); + const identity = await this.rootReadIdentity(canonical); + if (!identity || identity.commonDir !== sourceRepo.commonDir) return; + if ( + this.mutations.has(sourceRepo.commonDir) || + (this.mutationEpochs.get(sourceRepo.commonDir) ?? 0) !== epoch + ) { + return; + } + const seededRepo: GitRepository = { + cwd: canonical, + topLevel: canonical, + commonDir: sourceRepo.commonDir, + readIdentity: identity, + }; + this.setCached(this.repositoryCache, canonical, sourceRepo.commonDir, seededRepo); + const sourceIdentity = + this.repositoryIdentities.get(sourceRepo.topLevel) ?? + this.repositoryIdentities.get(sourceRepo.cwd); + if (sourceIdentity) { + this.repositoryIdentities.delete(canonical); + this.repositoryIdentities.set(canonical, { + topLevel: canonical, + canonicalKey: sourceIdentity.canonicalKey, + }); + } + const hint = this.repoRemoteHints.get(sourceRepo.commonDir); + if (hint) { + const currentSignature = await this.repoRemoteHintSignature(sourceRepo.commonDir); + if ( + currentSignature && + currentSignature === hint.configSignature && + !this.mutations.has(sourceRepo.commonDir) && + (this.mutationEpochs.get(sourceRepo.commonDir) ?? 0) === epoch + ) { + const info: GitInfo = { + isRepo: true, + branch, + detached: false, + unborn: false, + uncommitted: 0, + ahead: 0, + behind: 0, + defaultBranch: hint.defaultBranch, + hasRemote: hint.hasRemote, + }; + this.setCached(this.infoCache, canonical, sourceRepo.commonDir, info, identity.signature); + } + } + } catch { + // Display cache seeding is best-effort; a cold read will succeed normally. + } + } + + /** + * Drop any pre-hook cached status/branch entries for `worktreePath` (for + * example after a synchronous `WorktreeSetup` hook modifies the checkout). + */ + async invalidateWorktreeDisplayCache(worktreePath: string): Promise { + const candidates = new Set([worktreePath, path.resolve(worktreePath)]); + const canonical = await fs.realpath(worktreePath).catch(() => undefined); + if (canonical) candidates.add(canonical); + for (const key of candidates) { + this.infoCache.delete(key); + this.branchCache.delete(key); + } + } + private async repositoryInfo(repo: GitRepository, signal: AbortSignal): Promise { const read = (owner: AbortSignal) => this.stableRead(repo, async () => { const cached = repo.readIdentity ? this.getCached(this.infoCache, repo.cwd, repo.readIdentity.signature) : undefined; @@ -3813,41 +4749,126 @@ export class GitService { if (baseRef === "HEAD") { return { ref: "HEAD", name: "HEAD", commit: await this.requireHead(repo) }; } - await this.validateBranchName(repo, baseRef); + // Reject obvious invalid/glob/empty/slash-terminated refs before passing + // patterns to `for-each-ref`. + const hasControlOrGlob = (value: string): boolean => { + for (let i = 0; i < value.length; i += 1) { + const code = value.charCodeAt(i); + if (code <= 0x1f || code === 0x7f) return true; + } + return /[*?[\]\\]/u.test(value); + }; + if (!baseRef || baseRef.endsWith("/") || hasControlOrGlob(baseRef)) { + await this.validateBranchName(repo, baseRef); + } const localRef = `refs/heads/${baseRef}`; - const localCommit = await this.optionalCommit(repo, localRef, signal); - if (localCommit) { - const upstream = await this.run( + const remoteRef = `refs/remotes/${baseRef}`; + const originRef = `refs/remotes/origin/${baseRef}`; + interface ResolvedRefEntry { + commit: string; + objectType: string; + remote: string; + remoteRef: string; + trackingRef: string; + } + const exactRefs = new Map(); + const streamExactRefs = async (): Promise => { + // `for-each-ref` treats arguments as path-component prefixes (e.g. + // `baseRef = "origin"` matches all `refs/remotes/origin/*`). Streaming + // line-by-line prevents large prefix matches from hitting `maxBufferBytes`. + let carry: Buffer = Buffer.alloc(0); + const parseLine = (line: string) => { + const trimmed = line.endsWith("\r") ? line.slice(0, -1) : line; + if (!trimmed) return; + const [ + refname = "", + commit = "", + objectType = "", + remote = "", + upstreamRemoteRef = "", + trackingRef = "", + ] = trimmed.split("\u0000"); + if (refname === localRef || refname === remoteRef || refname === originRef) { + exactRefs.set(refname, { + commit, + objectType, + remote, + remoteRef: upstreamRemoteRef, + trackingRef, + }); + } + }; + await this.run( repo.cwd, [ "for-each-ref", - "--count=1", - "--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)%00", + "--format=%(refname)%00%(objectname)%00%(objecttype)%00%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)", localRef, + remoteRef, + originRef, ], - { signal }, + { + signal, + onStdoutChunk: (chunk) => { + const buf = carry.length > 0 ? Buffer.concat([carry, chunk]) : chunk; + let start = 0; + while (start < buf.length) { + const nl = buf.indexOf(0x0a, start); + if (nl === -1) break; + parseLine(buf.subarray(start, nl).toString("utf8")); + start = nl + 1; + } + carry = start < buf.length ? Buffer.from(buf.subarray(start)) : Buffer.alloc(0); + if (carry.length > this.maxBufferBytes) { + throw new GitServiceError( + "output_limit", + "Git produced more output than Aiden can safely process.", + ); + } + }, + }, ); - const [remote = "", remoteRef = "", trackingRef = ""] = upstream.stdout.split("\u0000"); - const remotes = await this.configuredRemotes(repo, signal); + if (carry.length > 0) parseLine(carry.toString("utf8")); + }; + const [validResult, remotesResult, refsResult] = await Promise.allSettled([ + this.validateBranchName(repo, baseRef), + this.configuredRemotes(repo, signal), + streamExactRefs(), + ]); + // Always preserve `invalid_ref` precedence from `validateBranchName`. + if (validResult.status === "rejected") throw validResult.reason; + if (remotesResult.status === "rejected") throw remotesResult.reason; + if (refsResult.status === "rejected") throw refsResult.reason; + const remotes = remotesResult.value; + const resolveCommit = async (ref: string): Promise => { + const entry = exactRefs.get(ref); + if (!entry) return undefined; + if (entry.objectType === "commit" && GIT_OBJECT_ID.test(entry.commit)) { + return entry.commit; + } + return this.optionalCommit(repo, ref, signal); + }; + + const localEntry = exactRefs.get(localRef); + const localCommit = await resolveCommit(localRef); + if (localCommit) { let resolvedUpstream: GitWorktreeBaseUpstream | undefined; if ( - remotes.includes(remote) && - remoteRef.startsWith("refs/heads/") && - trackingRef.startsWith("refs/remotes/") + localEntry && + remotes.includes(localEntry.remote) && + localEntry.remoteRef.startsWith("refs/heads/") && + localEntry.trackingRef.startsWith("refs/remotes/") ) { resolvedUpstream = { - remote, - branch: remoteRef.slice("refs/heads/".length), - trackingRef, + remote: localEntry.remote, + branch: localEntry.remoteRef.slice("refs/heads/".length), + trackingRef: localEntry.trackingRef, }; - } else if ( - remotes.includes("origin") && - (await this.optionalCommit(repo, `refs/remotes/origin/${baseRef}`, signal)) - ) { + } else if (remotes.includes("origin") && (await resolveCommit(originRef))) { resolvedUpstream = { remote: "origin", branch: baseRef, - trackingRef: `refs/remotes/origin/${baseRef}`, + trackingRef: originRef, }; } return { @@ -3857,12 +4878,11 @@ export class GitService { ...(resolvedUpstream ? { upstream: resolvedUpstream } : {}), }; } - const remoteRef = `refs/remotes/${baseRef}`; - const remoteCommit = await this.optionalCommit(repo, remoteRef, signal); + const remoteCommit = await resolveCommit(remoteRef); if (!remoteCommit) { throw new GitServiceError("invalid_ref", `Branch “${baseRef}” does not exist.`); } - const remote = (await this.configuredRemotes(repo, signal)) + const remote = remotes .filter((name) => baseRef.startsWith(`${name}/`) && baseRef.length > name.length + 1) .sort((left, right) => right.length - left.length)[0]; return { @@ -3886,11 +4906,13 @@ export class GitService { signal?: AbortSignal, ): Promise { const repo = this.requireRepository(await this.repository(cwd, signal)); - const remotes = await this.configuredRemotes(repo, signal); + const [remotes] = await Promise.all([ + this.configuredRemotes(repo, signal), + this.validateBranchName(repo, upstream.branch), + ]); if (!remotes.includes(upstream.remote)) { throw new GitServiceError("invalid_ref", `Remote “${upstream.remote}” is not configured.`); } - await this.validateBranchName(repo, upstream.branch); if (!upstream.trackingRef.startsWith("refs/remotes/")) { throw new GitServiceError("invalid_ref", "The remote-tracking branch is invalid."); } @@ -4255,6 +5277,203 @@ export class GitService { }); } + private async readBoundedNoFollowFile( + filePath: string, + maxBytes: number, + ): Promise<{ ok: true; text: string } | { ok: false; code?: string }> { + const flags = + fsConstants.O_RDONLY | + (fsConstants.O_NOFOLLOW ?? 0) | + (fsConstants.O_NONBLOCK ?? 0); + let handle: fs.FileHandle | undefined; + try { + handle = await fs.open(filePath, flags); + const stat = await handle.stat(); + if (!stat.isFile() || stat.size <= 0 || stat.size > maxBytes) { + return { ok: false }; + } + const buffer = Buffer.alloc(stat.size + 1); + const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0); + if (bytesRead !== stat.size) return { ok: false }; + return { ok: true, text: buffer.subarray(0, bytesRead).toString("utf8") }; + } catch (error) { + return { ok: false, code: (error as NodeJS.ErrnoException).code }; + } finally { + await handle?.close().catch(() => undefined); + } + } + + private async resolveCommonDirPureFs(cwd: string): Promise { + try { + const canonicalCwd = await fs.realpath(cwd); + const dotGit = path.join(canonicalCwd, ".git"); + const dotGitStat = await fs.lstat(dotGit); + let gitDir: string; + if (dotGitStat.isDirectory() && !dotGitStat.isSymbolicLink()) { + gitDir = dotGit; + } else if (dotGitStat.isFile() && !dotGitStat.isSymbolicLink()) { + const read = await this.readBoundedNoFollowFile(dotGit, 4_096); + if (!read.ok) return undefined; + const match = /^gitdir:\s*(.+)$/u.exec(read.text.trim()); + if (!match) return undefined; + gitDir = path.isAbsolute(match[1]!) + ? path.resolve(match[1]!) + : path.resolve(canonicalCwd, match[1]!); + } else { + return undefined; + } + const canonicalGitDir = await fs.realpath(gitDir); + const commondirPath = path.join(canonicalGitDir, "commondir"); + const commondirRead = await this.readBoundedNoFollowFile(commondirPath, 4_096); + if (commondirRead.ok) { + const rawCommon = commondirRead.text.trim(); + if (!rawCommon) return undefined; + const resolvedCommon = path.isAbsolute(rawCommon) + ? rawCommon + : path.resolve(canonicalGitDir, rawCommon); + return await fs.realpath(resolvedCommon); + } + if (commondirRead.code === "ENOENT") { + const headStat = await fs.lstat(path.join(canonicalGitDir, "HEAD")); + if (!headStat.isFile() || headStat.isSymbolicLink()) return undefined; + return canonicalGitDir; + } + return undefined; + } catch { + return undefined; + } + } + + private async branchRefExistsPureFs(commonDir: string, branch: string): Promise { + if (!branch || branch.includes("\u0000") || branch.includes("..") || branch.startsWith("/") || branch.endsWith("/")) { + return false; + } + // Reftable repositories do not store branches under `refs/heads` or `packed-refs`. + try { + const reftableStat = await fs.lstat(path.join(commonDir, "reftable")); + if (reftableStat.isDirectory()) return "fallback"; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") return "fallback"; + } + const refParts = branch.split("/"); + if (refParts.some((part) => !part || part === "." || part === "..")) return false; + const looseRefPath = path.join(commonDir, "refs", "heads", ...refParts); + const looseRead = await this.readBoundedNoFollowFile(looseRefPath, 512); + if (looseRead.ok && looseRead.text.trim().length > 0) return true; + if (!looseRead.ok && looseRead.code !== "ENOENT") return false; + + const packedRefsPath = path.join(commonDir, "packed-refs"); + const packedRead = await this.readBoundedNoFollowFile(packedRefsPath, 16 * 1024 * 1024); + if (!packedRead.ok) { + return packedRead.code === "ENOENT" ? false : "fallback"; + } + const targetSuffix = ` refs/heads/${branch}`; + for (const line of packedRead.text.split(/\r?\n/u)) { + if (!line || line.startsWith("#") || line.startsWith("^")) continue; + if (line.endsWith(targetSuffix)) { + const spaceIndex = line.indexOf(" "); + if (spaceIndex >= 40 && line.slice(spaceIndex) === targetSuffix) return true; + } + } + return false; + } + + private async managedWorktreeUsablePureFs( + commonDir: string, + worktreePath: string, + branch: string, + worktreeGitDir: string, + ownershipToken: string, + worktreeDevice: number, + worktreeInode: number, + ): Promise { + while (this.mutations.has(commonDir)) { + await this.mutations.get(commonDir); + } + const epoch = this.mutationEpochs.get(commonDir) ?? 0; + const epochChanged = () => + this.mutations.has(commonDir) || (this.mutationEpochs.get(commonDir) ?? 0) !== epoch; + + const registrationsRoot = path.resolve(commonDir, "worktrees"); + const resolvedGitDir = path.resolve(worktreeGitDir); + let canonicalAdminDir: string; + try { + const adminStat = await fs.lstat(resolvedGitDir); + if (!adminStat.isDirectory() || adminStat.isSymbolicLink()) { + return epochChanged() ? "fallback" : false; + } + canonicalAdminDir = await fs.realpath(resolvedGitDir); + } catch { + return epochChanged() ? "fallback" : false; + } + if ( + path.dirname(canonicalAdminDir) !== registrationsRoot || + path.basename(canonicalAdminDir).length === 0 + ) { + return epochChanged() ? "fallback" : false; + } + + const ownerPath = path.join(canonicalAdminDir, WORKTREE_OWNER_MARKER); + const gitdirPath = path.join(canonicalAdminDir, "gitdir"); + const commondirPath = path.join(canonicalAdminDir, "commondir"); + const headPath = path.join(canonicalAdminDir, "HEAD"); + // Per-worktree config (e.g. `core.bare`, `core.worktree`) must be evaluated by Git. + try { + await fs.lstat(path.join(canonicalAdminDir, "config.worktree")); + return "fallback"; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") return "fallback"; + } + try { + const [ownerRead, gitdirRead, commondirRead, headRead] = await Promise.all([ + this.readBoundedNoFollowFile(ownerPath, 128), + this.readBoundedNoFollowFile(gitdirPath, 4_096), + this.readBoundedNoFollowFile(commondirPath, 4_096), + this.readBoundedNoFollowFile(headPath, 4_096), + ]); + if (!ownerRead.ok || !gitdirRead.ok || !commondirRead.ok || !headRead.ok) { + return epochChanged() ? "fallback" : false; + } + if (ownerRead.text.trim() !== ownershipToken) return epochChanged() ? "fallback" : false; + if (headRead.text.trim() !== `ref: refs/heads/${branch}`) { + return epochChanged() ? "fallback" : false; + } + + const commonTarget = commondirRead.text.trim(); + const resolvedCommon = path.isAbsolute(commonTarget) + ? commonTarget + : path.resolve(canonicalAdminDir, commonTarget); + if ((await fs.realpath(resolvedCommon)) !== commonDir) { + return epochChanged() ? "fallback" : false; + } + + const gitFile = gitdirRead.text.trim(); + if (path.basename(gitFile) !== ".git") return epochChanged() ? "fallback" : false; + const absoluteGitFile = path.isAbsolute(gitFile) + ? path.resolve(gitFile) + : path.resolve(canonicalAdminDir, gitFile); + const registeredPath = path.dirname(absoluteGitFile); + if (path.resolve(registeredPath) !== path.resolve(worktreePath)) { + return epochChanged() ? "fallback" : false; + } + + const refExists = await this.branchRefExistsPureFs(commonDir, branch); + if (refExists === "fallback") return "fallback"; + if (!refExists) return epochChanged() ? "fallback" : false; + + const checkoutOk = await this.managedWorktreeCheckoutMatches( + worktreePath, + canonicalAdminDir, + worktreeDevice, + worktreeInode, + ); + if (epochChanged()) return "fallback"; + return checkoutOk; + } catch { + return epochChanged() ? "fallback" : false; + } + } + async managedWorktreeUsable( cwd: string, worktreePath: string, @@ -4270,12 +5489,43 @@ export class GitService { if ( !worktreeGitDir || !ownershipToken || + !WORKTREE_OWNER_TOKEN.test(ownershipToken) || !Number.isSafeInteger(worktreeDevice) || !Number.isSafeInteger(worktreeInode) ) { return false; } - const repo = this.requireRepository(await this.repository(cwd)); + // Use the 0-spawn pure-FS fast path only while Git's verified routing & + // include-free config proof (repo-local, global, and system) for `cwd` is + // still current. Any external config edit or `[include]` / `[includeIf]` + // directive falls back to Git discovery and fails closed. + const canonicalCwd = await fs.realpath(cwd).catch(() => undefined); + const verified = canonicalCwd ? this.verifiedRepoIdentities.get(canonicalCwd) : undefined; + if ( + canonicalCwd && + verified && + (await this.isVerifiedRepoIdentityCurrent(canonicalCwd, verified)) + ) { + const commonDir = await this.resolveCommonDirPureFs(canonicalCwd); + if (commonDir && commonDir === verified.commonDir) { + const direct = await this.managedWorktreeUsablePureFs( + commonDir, + worktreePath, + branch, + worktreeGitDir, + ownershipToken, + worktreeDevice!, + worktreeInode!, + ); + if ( + direct !== "fallback" && + (await this.isVerifiedRepoIdentityCurrent(canonicalCwd, verified)) + ) { + return direct; + } + } + } + const repo = this.requireRepository(await this.verifyAdmissionRepository(cwd)); return this.stableRead(repo, async () => { const registered = await this.managedWorktreeRegistration( repo, @@ -5882,6 +7132,83 @@ export class GitService { } } + private async inspectNewlyCreatedWorktree( + repo: GitRepository, + worktreePath: string, + branch: string, + expectedHead: string, + ): Promise<{ created: GitWorktree; worktreeGitDir: string }> { + try { + const canonicalPath = await fs.realpath(worktreePath); + const dotGitPath = path.join(canonicalPath, ".git"); + const dotGitStat = await fs.lstat(dotGitPath); + if (dotGitStat.isFile() && !dotGitStat.isSymbolicLink()) { + const dotGitRaw = await fs.readFile(dotGitPath, "utf8"); + const match = /^gitdir:\s*(.+?)\r?\n?$/u.exec(dotGitRaw); + if (match) { + const rawGitDir = path.isAbsolute(match[1]) + ? match[1] + : path.resolve(canonicalPath, match[1]); + const worktreeGitDir = this.validatedWorktreeGitDir(repo, await fs.realpath(rawGitDir)); + const [backlinkRaw, headRaw, commondirRaw] = await Promise.all([ + fs.readFile(path.join(worktreeGitDir, "gitdir"), "utf8"), + fs.readFile(path.join(worktreeGitDir, "HEAD"), "utf8"), + fs.readFile(path.join(worktreeGitDir, "commondir"), "utf8"), + ]); + const backlinkTrimmed = backlinkRaw.trim(); + const backlinkPath = path.isAbsolute(backlinkTrimmed) + ? backlinkTrimmed + : path.resolve(worktreeGitDir, backlinkTrimmed); + const commondirTrimmed = commondirRaw.trim(); + const commondirPath = path.isAbsolute(commondirTrimmed) + ? commondirTrimmed + : path.resolve(worktreeGitDir, commondirTrimmed); + const [resolvedBacklink, resolvedCommondir] = await Promise.all([ + fs.realpath(backlinkPath), + fs.realpath(commondirPath), + ]); + if ( + resolvedBacklink === dotGitPath && + resolvedCommondir === repo.commonDir && + headRaw.trim() === `ref: refs/heads/${branch}` + ) { + return { + created: { + path: canonicalPath, + head: expectedHead, + branch, + bare: false, + detached: false, + current: true, + }, + worktreeGitDir, + }; + } + } + } + } catch { + // Fall back to Git's porcelain inspection on any unexpected layout. + } + const created = (await this.inspectWorktrees(repo, worktreePath)).find( + (worktree) => worktree.branch === branch, + ); + if (!created) + throw new GitServiceError( + "command_failed", + "Git created the worktree but Aiden could not inspect it.", + ); + const gitDirResult = await this.run(created.path, [ + "rev-parse", + "--path-format=absolute", + "--git-dir", + ]); + const worktreeGitDir = this.validatedWorktreeGitDir( + repo, + await fs.realpath(gitDirResult.stdout.trim()), + ); + return { created, worktreeGitDir }; + } + async createWorktree( cwd: string, root: string, @@ -5889,26 +7216,37 @@ export class GitService { signal?: AbortSignal, options?: GitCreateWorktreeOptions, ): Promise { - const repo = this.requireRepository(await this.repository(cwd)); + const repo = this.requireRepository(await this.verifyAdmissionRepository(cwd)); await this.validateBranchName(repo, branch); const requestedOwnershipToken = options?.ownershipToken === undefined ? undefined : this.validatedWorktreeOwnershipToken(options.ownershipToken); - return this.enqueueMutation(repo.commonDir, async () => { - const createdFromHead = options?.startPoint === undefined - ? await this.requireHead(repo) - : await this.requireStartCommit(repo, options.startPoint, signal); - const checkoutBytes = await this.managedWorktreeCheckoutBytes(repo.topLevel, createdFromHead); - await checkWorktreeAllocation(root, repo.commonDir, checkoutBytes); - const exists = await this.run( - repo.cwd, - ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], - { - allowExitCodes: [1], - }, - ); + const additionalAllocationBytes = options?.additionalAllocationBytes ?? 0; + if ( + !Number.isSafeInteger(additionalAllocationBytes) || + additionalAllocationBytes < 0 + ) { + throw new GitServiceError("invalid_input", "The worktree capacity reserve is invalid."); + } + const createdWorktree = await this.enqueueMutation(repo.commonDir, async () => { + const [createdFromHead, exists] = await Promise.all([ + options?.startPoint === undefined + ? this.requireHead(repo) + : this.requireStartCommit(repo, options.startPoint, signal), + this.run( + repo.cwd, + ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], + { allowExitCodes: [1], signal }, + ), + ]); if (exists.exitCode === 0) throw new GitServiceError("invalid_ref", `Branch “${branch}” already exists.`); + const checkoutBytes = await this.managedWorktreeCheckoutBytesForRepo(repo, createdFromHead); + const totalAllocationBytes = checkoutBytes + additionalAllocationBytes; + if (!Number.isSafeInteger(totalAllocationBytes)) { + throw new GitServiceError("unsupported_scope", "The checkout is too large to estimate safely."); + } + await checkWorktreeAllocation(root, repo.commonDir, totalAllocationBytes); const repositoryId = createHash("sha256").update(repo.commonDir).digest("hex").slice(0, 12); const repositoryName = @@ -5929,25 +7267,19 @@ export class GitService { await this.run( repo.cwd, ["worktree", "add", "-b", branch, "--", worktreePath, createdFromHead], - { hooksDisabled: true, mutation: true, signal }, + { + hooksDisabled: true, + mutation: true, + signal, + extraConfig: parallelCheckoutConfig(), + }, ); createdByCommand = true; - const created = (await this.inspectWorktrees(repo, worktreePath)).find( - (worktree) => worktree.branch === branch, - ); - if (!created) - throw new GitServiceError( - "command_failed", - "Git created the worktree but Aiden could not inspect it.", - ); - const gitDirResult = await this.run(created.path, [ - "rev-parse", - "--path-format=absolute", - "--git-dir", - ]); - const worktreeGitDir = this.validatedWorktreeGitDir( + const { created, worktreeGitDir } = await this.inspectNewlyCreatedWorktree( repo, - await fs.realpath(gitDirResult.stdout.trim()), + worktreePath, + branch, + createdFromHead, ); const ownershipToken = requestedOwnershipToken ?? randomUUID(); await this.persistWorktreeOwnership(worktreeGitDir, ownershipToken); @@ -6003,6 +7335,11 @@ export class GitService { throw error; } }); + // Seed display-only `repositoryCache` / `infoCache` after `enqueueMutation` + // settles its post-mutation invalidation so immediate display reads + // (`workspaces:gitInfo`, `generationGitContext`) avoid redundant cold spawns. + await this.seedCreatedWorktreeDisplayCache(repo, createdWorktree, branch); + return createdWorktree; } async rollbackWorktree( @@ -6406,11 +7743,60 @@ export class GitService { return (await this.run(cwd, [...args])).stdout; } + /** + * Filter repository-root-relative `paths` to those ignored by Git's standard + * ignore rules (`.gitignore`, `.git/info/exclude`, and global excludes). + */ + async checkIgnoredPaths( + cwd: string, + paths: readonly string[], + signal?: AbortSignal, + ): Promise { + if (paths.length === 0) return []; + const repo = this.requireRepository(await this.repository(cwd, signal)); + // `git check-ignore --stdin` interprets leading `:` as pathspec magic + // (e.g. `:/b.log`, `:!c.log`, `:(icase).env`) and refuses `--literal-pathspecs`. + // Prefixing every path with `./` forces literal matching at `repo.topLevel`. + const originalByPrefixed = new Map(); + const prefixed: string[] = []; + for (const entry of paths) { + if (entry.includes("\u0000")) { + throw new GitServiceError("invalid_input", "Ignored path contains an invalid character."); + } + const literal = `./${entry}`; + if (!originalByPrefixed.has(literal)) { + originalByPrefixed.set(literal, entry); + prefixed.push(literal); + } + } + const stdin = `${prefixed.join("\u0000")}\u0000`; + // `git check-ignore` exits with 1 when none of the candidate paths are ignored. + const result = await this.run(repo.topLevel, ["check-ignore", "-z", "--stdin"], { + allowExitCodes: [1], + stdin, + signal, + }); + const matched: string[] = []; + for (const record of result.stdout.split("\u0000")) { + if (!record) continue; + const original = originalByPrefixed.get(record); + if (original !== undefined) matched.push(original); + } + return matched; + } + /** Bound a complete immutable checkout, including EOL expansion and file overhead. * Attribute inspection uses an isolated index, never the user's index or filters. */ async managedWorktreeCheckoutBytes(cwd: string, commit?: string): Promise { const repo = this.requireRepository(await this.repository(cwd)); + return this.managedWorktreeCheckoutBytesForRepo(repo, commit); + } + + private async managedWorktreeCheckoutBytesForRepo( + repo: GitRepository, + commit?: string, + ): Promise { const head = commit ?? await this.requireHead(repo); if (!GIT_OBJECT_ID.test(head)) { throw new GitServiceError("invalid_input", "The checkout estimate requires a commit identity."); @@ -6429,28 +7815,68 @@ export class GitService { if (!Number.isSafeInteger(bytes)) throw new GitServiceError("unsupported_scope", "The checkout is too large to estimate safely."); paths.push(match[4]); } + if (paths.length === 0) return bytes; const temporary = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-checkout-estimate-")); try { const gitIndexFile = path.join(temporary, "index"); await this.run(repo.topLevel, ["read-tree", head], { gitIndexFile, hooksDisabled: true }); - for (let offset = 0; offset < paths.length; offset += 128) { - const attributes = await this.run(repo.topLevel, - ["check-attr", "--cached", "-z", "--all", "--", ...paths.slice(offset, offset + 128)], - { gitIndexFile }); - const values = attributes.stdout.split("\u0000"); - for (let index = 0; index + 2 < values.length; index += 3) { - // Git cannot distinguish -filter from filter=unset here. A driver - // can also activate only in the new worktree via includeIf, so the - // source's filter config cannot safely resolve that ambiguity. - // Disabled ident is safe: its false/sentinel values do not expand. - const attribute = values[index + 1]; - const value = values[index + 2]; - if (["filter", "working-tree-encoding"].includes(attribute) || - (attribute === "ident" && !["unset", "unspecified"].includes(value))) { - throw new GitServiceError("unsupported_scope", - "Managed worktrees cannot safely estimate checkout filters, ident expansion or working-tree encodings. Use a checkout without these transformations."); - } - } + // Stream NUL-delimited (path, attribute, value) triples from a single + // `check-attr --cached -z --all --stdin` invocation so repositories with + // thousands of attributed files never overflow `maxBufferBytes` while still + // evaluating `.gitattributes`, `info/attributes`, global attributes, and `includeIf`. + let carry: Buffer = Buffer.alloc(0); + let fieldIndex = 0; + let currentAttr = ""; + const stdin = `${paths.join("\u0000")}\u0000`; + await this.run( + repo.topLevel, + ["check-attr", "--cached", "-z", "--all", "--stdin"], + { + gitIndexFile, + stdin, + onStdoutChunk: (chunk) => { + const buf = carry.length > 0 ? Buffer.concat([carry, chunk]) : chunk; + let start = 0; + while (start < buf.length) { + const nul = buf.indexOf(0, start); + if (nul === -1) break; + if (fieldIndex === 1) { + currentAttr = buf.subarray(start, nul).toString("utf8"); + } else if (fieldIndex === 2) { + // Git cannot distinguish -filter from filter=unset here. A driver + // can also activate only in the new worktree via includeIf, so the + // source's filter config cannot safely resolve that ambiguity. + // Disabled ident is safe: its false/sentinel values do not expand. + const value = buf.subarray(start, nul).toString("utf8"); + if ( + currentAttr === "filter" || + currentAttr === "working-tree-encoding" || + (currentAttr === "ident" && value !== "unset" && value !== "unspecified") + ) { + throw new GitServiceError( + "unsupported_scope", + "Managed worktrees cannot safely estimate checkout filters, ident expansion or working-tree encodings. Use a checkout without these transformations.", + ); + } + } + fieldIndex = (fieldIndex + 1) % 3; + start = nul + 1; + } + carry = start < buf.length ? Buffer.from(buf.subarray(start)) : Buffer.alloc(0); + if (carry.length > this.maxBufferBytes) { + throw new GitServiceError( + "output_limit", + "Git produced more output than Aiden can safely process.", + ); + } + }, + }, + ); + if (carry.length !== 0 || fieldIndex !== 0) { + throw new GitServiceError( + "unsupported_scope", + "The checkout attributes could not be verified safely.", + ); } } finally { await fs.rm(temporary, { recursive: true, force: true }); @@ -6879,12 +8305,14 @@ export class GitService { hooksDisabled: true, mutation: true, signal, + extraConfig: parallelCheckoutConfig(), }); } else { await this.run(repo.cwd, ["worktree", "add", "-b", branch, "--", resolvedTarget, baseCommit], { hooksDisabled: true, mutation: true, signal, + extraConfig: parallelCheckoutConfig(), }); } createdByCommand = true; @@ -7101,6 +8529,7 @@ export class GitService { hooksDisabled: true, mutation: true, signal, + extraConfig: parallelCheckoutConfig(), }); } catch (error) { // A folder put back from the Trash after the last look gets its Git @@ -7429,6 +8858,11 @@ export const gitRepositoryPaths = (folderPath: string) => gitService.repositoryPaths(folderPath); export const gitListFiles = (folderPath: string, args: readonly string[]) => gitService.listFiles(folderPath, args); +export const gitCheckIgnoredPaths = ( + folderPath: string, + paths: readonly string[], + signal?: AbortSignal, +) => gitService.checkIgnoredPaths(folderPath, paths, signal); export const gitManagedWorktreeCheckoutBytes = (folderPath: string, commit?: string) => gitService.managedWorktreeCheckoutBytes(folderPath, commit); export const gitCreateWorktree = ( @@ -7438,6 +8872,8 @@ export const gitCreateWorktree = ( signal?: AbortSignal, options?: GitCreateWorktreeOptions, ) => gitService.createWorktree(folderPath, root, branch, signal, options); +export const gitInvalidateWorktreeDisplayCache = (worktreePath: string) => + gitService.invalidateWorktreeDisplayCache(worktreePath); export const gitResolveWorktreeBase = (folderPath: string, baseRef: string, signal?: AbortSignal) => gitService.resolveWorktreeBase(folderPath, baseRef, signal); export const gitFetchWorktreeBase = ( diff --git a/main/services/managed-worktree-admission.test.ts b/main/services/managed-worktree-admission.test.ts index a18c2b51e1..57dd2a58e4 100644 --- a/main/services/managed-worktree-admission.test.ts +++ b/main/services/managed-worktree-admission.test.ts @@ -1,11 +1,26 @@ import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; import * as fs from "node:fs/promises"; import * as os from "node:os"; import * as path from "node:path"; import test from "node:test"; +import { promisify } from "node:util"; +import { GitService } from "./git.js"; +import { resolveGitExecutable } from "./git-executable.js"; import { assertManagedWorktreeAdmission } from "./managed-worktree-admission.js"; import type { Workspace } from "./types.js"; +const execFileAsync = promisify(execFile); +// On macOS, select Apple's OS-managed `/usr/bin/git` (resolved via xcode-select +// to Apple-signed CLT/Xcode Git) so zero-spawn tests exercise the signed OS +// fast path even on hosts where Homebrew `git` precedes `/usr/bin` on PATH. +const TRUSTED_NATIVE_GIT = process.platform === "darwin" ? "/usr/bin/git" : "git"; + +async function runGit(cwd: string, args: string[]): Promise { + const { stdout } = await execFileAsync("git", args, { cwd }); + return stdout.trim(); +} + async function fixture(t: test.TestContext): Promise<{ workspace: Workspace; worktreePath: string; @@ -128,3 +143,809 @@ test("fails closed for markerless, unregistered, escaped, and symlink-replaced w /no longer available/u, ); }); + +test("GitService.managedWorktreeUsable verifies modern worktrees via 0-spawn pure FS and catches live external drift", async (t) => { + const prevGlobalConfig = process.env.GIT_CONFIG_GLOBAL; + const prevNoSystem = process.env.GIT_CONFIG_NOSYSTEM; + process.env.GIT_CONFIG_GLOBAL = "/dev/null"; + process.env.GIT_CONFIG_NOSYSTEM = "1"; + t.after(() => { + if (prevGlobalConfig === undefined) delete process.env.GIT_CONFIG_GLOBAL; + else process.env.GIT_CONFIG_GLOBAL = prevGlobalConfig; + if (prevNoSystem === undefined) delete process.env.GIT_CONFIG_NOSYSTEM; + else process.env.GIT_CONFIG_NOSYSTEM = prevNoSystem; + }); + const temp = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-usable-fs-")); + t.after(() => fs.rm(temp, { recursive: true, force: true })); + const repo = path.join(temp, "repo"); + const worktreesRoot = path.join(temp, "worktrees"); + await fs.mkdir(repo, { recursive: true }); + await runGit(repo, ["init", "-b", "main"]); + await runGit(repo, ["config", "user.name", "Aiden Test"]); + await runGit(repo, ["config", "user.email", "test@example.com"]); + await fs.writeFile(path.join(repo, "README.md"), "hello\n"); + await runGit(repo, ["add", "README.md"]); + await runGit(repo, ["commit", "-m", "initial"]); + + const service = new GitService({ gitBinary: TRUSTED_NATIVE_GIT, cacheTtlMs: 60_000 }); + await service.info(repo); + const created = await service.createWorktree(repo, worktreesRoot, "aiden/pure-fs"); + + let gitSpawns = 0; + const internals = service as unknown as { + run: (cwd: string, args: string[], options?: unknown) => Promise; + }; + const originalRun = internals.run.bind(service); + internals.run = async (cwd, args, options) => { + gitSpawns += 1; + return originalRun(cwd, args, options); + }; + + // Seeded display info after createWorktree requires 0 git spawns. + const seededInfo = await service.info(created.path); + assert.equal(seededInfo.isRepo, true); + assert.equal(seededInfo.branch, "aiden/pure-fs"); + assert.equal(seededInfo.uncommitted, 0); + assert.equal(gitSpawns, 0, "immediate post-create gitInfo should hit the seeded display cache"); + + // Live pure-FS admission uses 0 git spawns for loose refs. + assert.equal( + await service.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + assert.equal(gitSpawns, 0, "pure-FS usability verification must spawn 0 git processes"); + + // Still works with 0 git spawns after refs are packed into packed-refs. + await runGit(repo, ["pack-refs", "--all"]); + assert.equal( + await service.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + assert.equal(gitSpawns, 0); + + // External branch switch is rejected immediately (live, never cached across calls). + await runGit(created.path, ["switch", "-c", "aiden/drifted"]); + assert.equal( + await service.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + false, + ); + assert.equal(gitSpawns, 0); + + // Switch back, then tamper ownership marker: immediately rejected with 0 spawns. + await runGit(created.path, ["switch", created.branch]); + await fs.writeFile( + path.join(created.worktreeGitDir, "aiden-owner"), + "00000000-0000-4000-8000-000000000000\n", + ); + assert.equal( + await service.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + false, + ); + assert.equal(gitSpawns, 0); + + // Restore valid ownership marker, verify 0-spawn admission works again, then + // modify repository config (`core.bare=true`): must fall back to Git discovery + // and fail closed instead of admitting across repository-config revocation. + await fs.writeFile( + path.join(created.worktreeGitDir, "aiden-owner"), + `${created.ownershipToken}\n`, + ); + gitSpawns = 0; + assert.equal( + await service.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + assert.equal(gitSpawns, 0); + + await runGit(repo, ["config", "core.bare", "true"]); + gitSpawns = 0; + await assert.rejects( + service.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + /not a Git repository/u, + ); + assert.ok(gitSpawns > 0, "config change must fall back to Git discovery"); + await runGit(repo, ["config", "--unset", "core.bare"]); + + // Pre-existing `[include]` target edited after initial Git-verified admission + // must fall back to Git discovery and fail closed even though `.git/config` + // itself is unchanged. + const includeTarget = path.join(temp, "extra-git.cfg"); + await fs.writeFile(includeTarget, "# benign include\n"); + await runGit(repo, ["config", "--add", "include.path", includeTarget]); + assert.equal( + await service.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + await fs.writeFile(includeTarget, "[core\n"); + gitSpawns = 0; + await assert.rejects( + service.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + /not a Git repository/u, + ); + assert.ok(gitSpawns > 0, "changed include.path target must fall back to Git discovery"); + await fs.writeFile(includeTarget, ""); + await runGit(repo, ["config", "--unset-all", "include.path"]); + + // Custom-named `GIT_CONFIG_GLOBAL` files (not matching `*.gitconfig` or + // `*/config`) must also be scanned for `[include]` / `[includeIf]` and fall + // back to Git discovery when an included target changes. + const customGlobalConfig = path.join(temp, "custom-global.cfg"); + const globalIncludeTarget = path.join(temp, "global-extra.cfg"); + await fs.writeFile(globalIncludeTarget, "# benign global include\n"); + await fs.writeFile(customGlobalConfig, `[include]\n\tpath = ${globalIncludeTarget}\n`); + process.env.GIT_CONFIG_GLOBAL = customGlobalConfig; + assert.equal( + await service.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + await fs.writeFile(globalIncludeTarget, "[core\n"); + gitSpawns = 0; + await assert.rejects( + service.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + /not a Git repository/u, + ); + assert.ok(gitSpawns > 0, "changed custom GIT_CONFIG_GLOBAL include target must fall back to Git discovery"); + process.env.GIT_CONFIG_GLOBAL = "/dev/null"; + + // Invalidating display cache after a WorktreeSetup hook modifies the checkout + // ensures git.info observes dirty changes instead of stale uncommitted: 0. + await fs.writeFile(path.join(created.path, "README.md"), "# modified by hook\n"); + await service.invalidateWorktreeDisplayCache(created.path); + const postHookInfo = await service.info(created.path); + assert.equal(postHookInfo.isRepo, true); + assert.equal(postHookInfo.uncommitted, 1); +}); + +test("GitService.managedWorktreeUsable tracks native Git system config origins, symlink chains, and GIT_EXEC_PATH", async (t) => { + const prevGlobalConfig = process.env.GIT_CONFIG_GLOBAL; + const prevSystemConfig = process.env.GIT_CONFIG_SYSTEM; + const prevNoSystem = process.env.GIT_CONFIG_NOSYSTEM; + const prevExecPath = process.env.GIT_EXEC_PATH; + process.env.GIT_CONFIG_GLOBAL = "/dev/null"; + delete process.env.GIT_CONFIG_SYSTEM; + delete process.env.GIT_CONFIG_NOSYSTEM; + delete process.env.GIT_EXEC_PATH; + t.after(() => { + if (prevGlobalConfig === undefined) delete process.env.GIT_CONFIG_GLOBAL; + else process.env.GIT_CONFIG_GLOBAL = prevGlobalConfig; + if (prevSystemConfig === undefined) delete process.env.GIT_CONFIG_SYSTEM; + else process.env.GIT_CONFIG_SYSTEM = prevSystemConfig; + if (prevNoSystem === undefined) delete process.env.GIT_CONFIG_NOSYSTEM; + else process.env.GIT_CONFIG_NOSYSTEM = prevNoSystem; + if (prevExecPath === undefined) delete process.env.GIT_EXEC_PATH; + else process.env.GIT_EXEC_PATH = prevExecPath; + }); + + const temp = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-usable-native-sys-")); + t.after(() => fs.rm(temp, { recursive: true, force: true })); + const repo = path.join(temp, "repo"); + const worktreesRoot = path.join(temp, "worktrees"); + await fs.mkdir(repo, { recursive: true }); + await runGit(repo, ["init", "-b", "main"]); + await runGit(repo, ["config", "user.name", "Aiden Test"]); + await runGit(repo, ["config", "user.email", "test@example.com"]); + await fs.writeFile(path.join(repo, "README.md"), "hello\n"); + await runGit(repo, ["add", "README.md"]); + await runGit(repo, ["commit", "-m", "initial"]); + + const countSpawns = (svc: GitService) => { + const state = { count: 0 }; + const internals = svc as unknown as { + run: (cwd: string, args: string[], options?: unknown) => Promise; + }; + const orig = internals.run.bind(svc); + internals.run = async (cwd, args, options) => { + state.count += 1; + return orig(cwd, args, options); + }; + return state; + }; + + // Case 1: Real native Git with explicit GIT_CONFIG_SYSTEM allows 0-spawn + // admission while benign, and fails closed on a revoking edit. + const altSystemConfig = path.join(temp, "alt-prefix-gitconfig"); + await fs.writeFile(altSystemConfig, "[user]\n\tname = Alt Prefix\n"); + process.env.GIT_CONFIG_SYSTEM = altSystemConfig; + const service = new GitService({ gitBinary: TRUSTED_NATIVE_GIT, cacheTtlMs: 60_000 }); + const created = await service.createWorktree(repo, worktreesRoot, "aiden/native-sys"); + const spawns = countSpawns(service); + + assert.equal( + await service.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + assert.equal(spawns.count, 0, "verified native Git with explicit system config allows 0-spawn admission"); + + await fs.writeFile(altSystemConfig, "[core\n"); + spawns.count = 0; + await assert.rejects( + service.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + /not a Git repository/u, + ); + assert.ok(spawns.count > 0, "revoking edit to system config must force Git discovery"); + + // Case 2: System config starts missing, admits with 0 spawns, then is created to revoke. + await fs.rm(altSystemConfig, { force: true }); + const missingSysService = new GitService({ gitBinary: TRUSTED_NATIVE_GIT, cacheTtlMs: 60_000 }); + const missingSpawns = countSpawns(missingSysService); + assert.equal( + await missingSysService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + missingSpawns.count = 0; + assert.equal( + await missingSysService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + assert.equal(missingSpawns.count, 0); + + await fs.writeFile(altSystemConfig, "[core\n"); + missingSpawns.count = 0; + await assert.rejects( + missingSysService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + /not a Git repository/u, + ); + assert.ok(missingSpawns.count > 0, "creating missing system config must force Git discovery"); + + // Case 3: Existing empty system config fails closed (never caches pure-FS proof). + await fs.writeFile(altSystemConfig, ""); + const emptySysService = new GitService({ gitBinary: TRUSTED_NATIVE_GIT, cacheTtlMs: 60_000 }); + const emptySpawns = countSpawns(emptySysService); + assert.equal( + await emptySysService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + await fs.writeFile(altSystemConfig, "[core\n"); + emptySpawns.count = 0; + await assert.rejects( + emptySysService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + /not a Git repository/u, + ); + assert.ok(emptySpawns.count > 0, "empty system config must stay Git-backed and fail closed"); + + // Case 4: Multi-hop symlink pointing to the real native Git binary allows + // 0-spawn admission, and repointing an intermediate symlink hop to a wrapper + // immediately invalidates the proof and fails closed. + await fs.writeFile(altSystemConfig, "[user]\n\tname = Valid\n"); + const realGit = await resolveGitExecutable(TRUSTED_NATIVE_GIT, repo, process.env); + const midLink = path.join(temp, "git-mid-link"); + const outerLink = path.join(temp, "git-outer-link"); + await fs.symlink(realGit, midLink); + await fs.symlink(midLink, outerLink); + + const linkService = new GitService({ gitBinary: outerLink, cacheTtlMs: 60_000 }); + const linkSpawns = countSpawns(linkService); + assert.equal( + await linkService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + linkSpawns.count = 0; + assert.equal( + await linkService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + assert.equal(linkSpawns.count, 0, "multi-hop symlink to real native Git allows 0-spawn admission"); + + const corruptConfig = path.join(temp, "corrupt-gitconfig"); + await fs.writeFile(corruptConfig, "[core\n"); + const failingWrapper = path.join(temp, "failing-wrapper.sh"); + await fs.writeFile( + failingWrapper, + `#!/bin/sh\nexport GIT_CONFIG_SYSTEM=${JSON.stringify(corruptConfig)}\nexec ${JSON.stringify(realGit)} "$@"\n`, + { encoding: "utf8", mode: 0o700 }, + ); + await fs.rm(midLink); + await fs.symlink(failingWrapper, midLink); + linkSpawns.count = 0; + await assert.rejects( + linkService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + /not a Git repository/u, + ); + assert.ok(linkSpawns.count > 0, "repointing an intermediate symlink hop must force Git discovery"); + + // Case 5: Setting GIT_EXEC_PATH fails closed to Git-backed admission. + const execPathOut = await runGit(repo, ["--exec-path"]); + process.env.GIT_EXEC_PATH = execPathOut; + const execPathService = new GitService({ gitBinary: TRUSTED_NATIVE_GIT, cacheTtlMs: 60_000 }); + const execPathSpawns = countSpawns(execPathService); + assert.equal( + await execPathService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + execPathSpawns.count = 0; + assert.equal( + await execPathService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + assert.ok(execPathSpawns.count > 0, "GIT_EXEC_PATH override must stay Git-backed"); +}); + +test("GitService.managedWorktreeUsable fails closed for unchanged wrapper scripts and native shims with mutable delegated routing", async (t) => { + const prevGlobalConfig = process.env.GIT_CONFIG_GLOBAL; + const prevSystemConfig = process.env.GIT_CONFIG_SYSTEM; + const prevNoSystem = process.env.GIT_CONFIG_NOSYSTEM; + process.env.GIT_CONFIG_GLOBAL = "/dev/null"; + delete process.env.GIT_CONFIG_SYSTEM; + delete process.env.GIT_CONFIG_NOSYSTEM; + t.after(() => { + if (prevGlobalConfig === undefined) delete process.env.GIT_CONFIG_GLOBAL; + else process.env.GIT_CONFIG_GLOBAL = prevGlobalConfig; + if (prevSystemConfig === undefined) delete process.env.GIT_CONFIG_SYSTEM; + else process.env.GIT_CONFIG_SYSTEM = prevSystemConfig; + if (prevNoSystem === undefined) delete process.env.GIT_CONFIG_NOSYSTEM; + else process.env.GIT_CONFIG_NOSYSTEM = prevNoSystem; + }); + + const temp = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-usable-shim-")); + t.after(() => fs.rm(temp, { recursive: true, force: true })); + const repo = path.join(temp, "repo"); + const worktreesRoot = path.join(temp, "worktrees"); + await fs.mkdir(repo, { recursive: true }); + await runGit(repo, ["init", "-b", "main"]); + await runGit(repo, ["config", "user.name", "Aiden Test"]); + await runGit(repo, ["config", "user.email", "test@example.com"]); + await fs.writeFile(path.join(repo, "README.md"), "hello\n"); + await runGit(repo, ["add", "README.md"]); + await runGit(repo, ["commit", "-m", "initial"]); + + const realGit = await resolveGitExecutable(TRUSTED_NATIVE_GIT, repo, process.env); + const baseService = new GitService({ gitBinary: TRUSTED_NATIVE_GIT, cacheTtlMs: 60_000 }); + const created = await baseService.createWorktree(repo, worktreesRoot, "aiden/shim-test"); + + const configA = path.join(temp, "config-a"); + const configB = path.join(temp, "config-b"); + await fs.writeFile(configA, "[user]\n\tname = Config A\n"); + await fs.writeFile(configB, "[user]\n\tname = Config B\n"); + + const nestedA = path.join(temp, "nested-git-a.sh"); + const nestedB = path.join(temp, "nested-git-b.sh"); + await fs.writeFile( + nestedA, + `#!/bin/sh\nunset GIT_CONFIG_NOSYSTEM\nexport GIT_CONFIG_SYSTEM=${JSON.stringify(configA)}\nexec ${JSON.stringify(realGit)} "$@"\n`, + { encoding: "utf8", mode: 0o700 }, + ); + await fs.writeFile( + nestedB, + `#!/bin/sh\nunset GIT_CONFIG_NOSYSTEM\nexport GIT_CONFIG_SYSTEM=${JSON.stringify(configB)}\nexec ${JSON.stringify(realGit)} "$@"\n`, + { encoding: "utf8", mode: 0o700 }, + ); + + const nestedLink = path.join(temp, "nested-git-active"); + await fs.symlink(nestedA, nestedLink); + + const countSpawns = (svc: GitService) => { + const state = { count: 0 }; + const internals = svc as unknown as { + run: (cwd: string, args: string[], options?: unknown) => Promise; + }; + const orig = internals.run.bind(svc); + internals.run = async (cwd, args, options) => { + state.count += 1; + return orig(cwd, args, options); + }; + return state; + }; + + // Case 1: Unchanged outer shell wrapper script swapping its delegated nested + // executable from clean config A to corrupt config B must never admit via + // cached 0-spawn proof and must reject once B is corrupt. + const outerWrapper = path.join(temp, "outer-wrapper.sh"); + await fs.writeFile( + outerWrapper, + `#!/bin/sh\nexec ${JSON.stringify(nestedLink)} "$@"\n`, + { encoding: "utf8", mode: 0o700 }, + ); + const outerStatBefore = await fs.lstat(outerWrapper, { bigint: true }); + + const wrapperService = new GitService({ gitBinary: outerWrapper, cacheTtlMs: 60_000 }); + const wrapperSpawns = countSpawns(wrapperService); + assert.equal( + await wrapperService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + wrapperSpawns.count = 0; + assert.equal( + await wrapperService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + assert.ok(wrapperSpawns.count > 0, "shell wrapper must not publish or reuse a 0-spawn proof"); + + // Swap the delegated nested executable to config B and corrupt config B while + // leaving outerWrapper and config A completely untouched. + await fs.writeFile(configB, "[core\n"); + await fs.rm(nestedLink); + await fs.symlink(nestedB, nestedLink); + const outerStatAfter = await fs.lstat(outerWrapper, { bigint: true }); + assert.equal(outerStatAfter.ino, outerStatBefore.ino); + assert.equal(outerStatAfter.mtimeNs, outerStatBefore.mtimeNs); + assert.equal(outerStatAfter.ctimeNs, outerStatBefore.ctimeNs); + + wrapperSpawns.count = 0; + await assert.rejects( + wrapperService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + /not a Git repository/u, + ); + assert.ok(wrapperSpawns.count > 0, "unchanged wrapper swapping delegated target to corrupt config B must fail closed"); + + // Case 2: Even when GIT_CONFIG_NOSYSTEM=1 is set in the parent environment, + // a wrapper script that unsets it internally must still fail closed. + await fs.writeFile(configB, "[user]\n\tname = Config B\n"); + await fs.rm(nestedLink); + await fs.symlink(nestedA, nestedLink); + process.env.GIT_CONFIG_NOSYSTEM = "1"; + const noSysWrapperService = new GitService({ gitBinary: outerWrapper, cacheTtlMs: 60_000 }); + const noSysWrapperSpawns = countSpawns(noSysWrapperService); + assert.equal( + await noSysWrapperService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + await fs.writeFile(configB, "[core\n"); + await fs.rm(nestedLink); + await fs.symlink(nestedB, nestedLink); + noSysWrapperSpawns.count = 0; + await assert.rejects( + noSysWrapperService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + /not a Git repository/u, + ); + assert.ok(noSysWrapperSpawns.count > 0, "wrapper script must fail closed even with GIT_CONFIG_NOSYSTEM=1"); + delete process.env.GIT_CONFIG_NOSYSTEM; + + // Case 3: Unchanged compiled native Mach-O/ELF shim binary delegating to a + // mutable nested executable must also fail closed (blocked by --exec-path + // self-identity verification). + if (process.platform === "darwin" || process.platform === "linux") { + await fs.writeFile(configB, "[user]\n\tname = Config B\n"); + await fs.rm(nestedLink); + await fs.symlink(nestedA, nestedLink); + + const shimSource = path.join(temp, "git-shim.c"); + const shimBinary = path.join(temp, "git-shim"); + await fs.writeFile( + shimSource, + `#include \nint main(int argc, char **argv) {\n (void)argc;\n execv(${JSON.stringify(nestedLink)}, argv);\n return 127;\n}\n`, + "utf8", + ); + await execFileAsync("cc", [shimSource, "-o", shimBinary]); + const shimStatBefore = await fs.lstat(shimBinary, { bigint: true }); + + const shimService = new GitService({ gitBinary: shimBinary, cacheTtlMs: 60_000 }); + const shimSpawns = countSpawns(shimService); + assert.equal( + await shimService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + shimSpawns.count = 0; + assert.equal( + await shimService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + assert.ok(shimSpawns.count > 0, "compiled native shim binary must not publish or reuse a 0-spawn proof"); + + await fs.writeFile(configB, "[core\n"); + await fs.rm(nestedLink); + await fs.symlink(nestedB, nestedLink); + const shimStatAfter = await fs.lstat(shimBinary, { bigint: true }); + assert.equal(shimStatAfter.ino, shimStatBefore.ino); + assert.equal(shimStatAfter.mtimeNs, shimStatBefore.mtimeNs); + assert.equal(shimStatAfter.ctimeNs, shimStatBefore.ctimeNs); + + shimSpawns.count = 0; + await assert.rejects( + shimService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + /not a Git repository/u, + ); + assert.ok(shimSpawns.count > 0, "unchanged native shim swapping delegated target to corrupt config B must fail closed"); + + // Case 4: Even a compiled native shim that special-cases `--exec-path` to + // report a directory containing a hard link to itself while delegating + // ordinary Git commands through a mutable route must fail closed. + await fs.writeFile(configB, "[user]\n\tname = Config B\n"); + await fs.rm(nestedLink); + await fs.symlink(nestedA, nestedLink); + + const fakeExecPathDir = path.join(temp, "fake-exec-path"); + await fs.mkdir(fakeExecPathDir); + const spoofShimSource = path.join(temp, "git-spoof-shim.c"); + const spoofShimBinary = path.join(temp, "git-spoof-shim"); + await fs.writeFile( + spoofShimSource, + `#include \n#include \n#include \nint main(int argc, char **argv) {\n if (argc == 2 && strcmp(argv[1], "--exec-path") == 0) {\n puts(${JSON.stringify(fakeExecPathDir)});\n return 0;\n }\n execv(${JSON.stringify(nestedLink)}, argv);\n return 127;\n}\n`, + "utf8", + ); + await execFileAsync("cc", [spoofShimSource, "-o", spoofShimBinary]); + await fs.link(spoofShimBinary, path.join(fakeExecPathDir, "git")); + const spoofStatBefore = await fs.lstat(spoofShimBinary, { bigint: true }); + + const spoofService = new GitService({ gitBinary: spoofShimBinary, cacheTtlMs: 60_000 }); + const spoofSpawns = countSpawns(spoofService); + assert.equal( + await spoofService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + spoofSpawns.count = 0; + assert.equal( + await spoofService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + true, + ); + assert.ok(spoofSpawns.count > 0, "native shim spoofing --exec-path must not publish a 0-spawn proof"); + + await fs.writeFile(configB, "[core\n"); + await fs.rm(nestedLink); + await fs.symlink(nestedB, nestedLink); + const spoofStatAfter = await fs.lstat(spoofShimBinary, { bigint: true }); + assert.equal(spoofStatAfter.ino, spoofStatBefore.ino); + assert.equal(spoofStatAfter.mtimeNs, spoofStatBefore.mtimeNs); + assert.equal(spoofStatAfter.ctimeNs, spoofStatBefore.ctimeNs); + + spoofSpawns.count = 0; + await assert.rejects( + spoofService.managedWorktreeUsable( + created.repositoryPath, + created.path, + created.branch, + created.worktreeGitDir, + created.ownershipToken, + created.worktreeDevice, + created.worktreeInode, + ), + /not a Git repository/u, + ); + assert.ok(spoofSpawns.count > 0, "unchanged native shim spoofing --exec-path must fail closed when delegated target breaks"); + } +}); diff --git a/main/services/managed-worktree-file-io.ts b/main/services/managed-worktree-file-io.ts index 9eefb7b088..86819e8c03 100644 --- a/main/services/managed-worktree-file-io.ts +++ b/main/services/managed-worktree-file-io.ts @@ -1,5 +1,5 @@ import { createHash } from "node:crypto"; -import { execFile } from "node:child_process"; +import { execFile, spawn } from "node:child_process"; import * as fs from "node:fs/promises"; import * as path from "node:path"; import { promisify } from "node:util"; @@ -125,6 +125,216 @@ export async function transferManagedWorktreeFile(options: { return { size: Number(match[1]), mode: Number(match[2]), sourceMode: Number(match[3]), digest: match[4] }; } +/** + * Batch-copy `.worktreeinclude`-selected files into a freshly created managed + * worktree in a single helper invocation. Streams `p ` lines so + * `onProvisioned` records every installed file even if a later file fails. + */ +export async function provisionManagedWorktreeFilesBatch(options: { + sourceRoot: string; + sourceIdentity?: ManagedWorktreeRootIdentity; + destinationRoot: string; + destinationIdentity?: ManagedWorktreeRootIdentity; + relativePaths: readonly string[]; + totalByteLimit: number; + signal?: AbortSignal; + onProvisioned?(relativePath: string, bytes: number): void; +}): Promise<{ provisioned: string[]; totalBytes: number }> { + if (options.relativePaths.length === 0) return { provisioned: [], totalBytes: 0 }; + if ( + !Number.isSafeInteger(options.totalByteLimit) || + options.totalByteLimit < 0 + ) { + throw new ManagedWorktreeFileIoError("invalid_input"); + } + for (const entry of options.relativePaths) { + if (!entry || entry.includes("\u0000")) { + throw new ManagedWorktreeFileIoError("invalid_input"); + } + } + const source = options.sourceIdentity ?? await captureManagedWorktreeRootIdentity(options.sourceRoot); + const destination = options.destinationIdentity ?? + await captureManagedWorktreeRootIdentity(options.destinationRoot); + const fixedAliasPath = (value: string) => process.platform === "darwin" + ? value.replace(/^\/(tmp|var|etc)(?=\/|$)/u, "/private/$1") : value; + const args = [ + "provision", + fixedAliasPath(source.path), + source.device, + source.inode, + fixedAliasPath(destination.path), + destination.device, + destination.inode, + String(options.totalByteLimit), + ]; + + const payload = Buffer.from(options.relativePaths.map((entry) => `${entry}\u0000`).join(""), "utf8"); + return new Promise((resolve, reject) => { + if (options.signal?.aborted) { + reject(new Error("Provision aborted.")); + return; + } + // Do not pass `signal` directly to `spawn`: Node emits `AbortError` before + // the helper exits, which would let rollback race with a still-running + // helper. Instead send SIGTERM (with SIGKILL fallback) and settle ONLY on + // `close` after stdout drains so `onProvisioned` stays 1:1 with disk. + const child = spawn(resolveManagedWorktreeFileIoBinary(), args, { + stdio: ["pipe", "pipe", "pipe"], + }); + const provisioned: string[] = []; + let totalBytes = 0; + let nextIndex = 0; + let sawDone = false; + let protocolError = false; + let callbackError: unknown; + let hasCallbackError = false; + let stdoutCarry = ""; + let stderr = ""; + let killEscalation: ReturnType | undefined; + const STDERR_LIMIT = 4096; + const STDOUT_LINE_LIMIT = 128; + + const terminateChild = () => { + if (child.exitCode !== null || child.signalCode !== null) return; + try { child.kill("SIGTERM"); } catch { /* already exited */ } + if (!killEscalation) { + killEscalation = setTimeout(() => { + try { child.kill("SIGKILL"); } catch { /* already exited */ } + }, 2_000); + killEscalation.unref?.(); + } + }; + + const onAbort = () => { + terminateChild(); + }; + options.signal?.addEventListener("abort", onAbort, { once: true }); + + const cleanup = () => { + clearTimeout(timer); + if (killEscalation) { + clearTimeout(killEscalation); + killEscalation = undefined; + } + options.signal?.removeEventListener("abort", onAbort); + }; + + const processLine = (line: string) => { + if (protocolError || hasCallbackError) return; + if (!line || sawDone) { + protocolError = true; + return; + } + if (line === "done") { + sawDone = true; + return; + } + const match = /^p (\d+) (\d+)$/u.exec(line); + if (!match) { + protocolError = true; + return; + } + const index = Number(match[1]); + const bytes = Number(match[2]); + if ( + !Number.isSafeInteger(index) || + index !== nextIndex || + index >= options.relativePaths.length || + !Number.isSafeInteger(bytes) || + bytes < 0 || + !Number.isSafeInteger(totalBytes + bytes) || + totalBytes + bytes > options.totalByteLimit + ) { + protocolError = true; + return; + } + nextIndex += 1; + totalBytes += bytes; + const relativePath = options.relativePaths[index]!; + provisioned.push(relativePath); + try { + options.onProvisioned?.(relativePath, bytes); + } catch (error) { + hasCallbackError = true; + callbackError = error; + terminateChild(); + } + }; + + const timer = setTimeout(() => { + try { child.kill("SIGKILL"); } catch { /* already exited */ } + }, 120_000); + timer.unref?.(); + + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk: string) => { + stdoutCarry += chunk; + let newline = stdoutCarry.indexOf("\n"); + while (newline >= 0) { + processLine(stdoutCarry.slice(0, newline)); + stdoutCarry = stdoutCarry.slice(newline + 1); + newline = stdoutCarry.indexOf("\n"); + } + if (stdoutCarry.length > STDOUT_LINE_LIMIT) { + protocolError = true; + stdoutCarry = ""; + } + }); + child.stderr.setEncoding("utf8"); + child.stderr.on("data", (chunk: string) => { + if (stderr.length < STDERR_LIMIT) { + stderr += chunk.slice(0, STDERR_LIMIT - stderr.length); + } + }); + child.stdin.on("error", () => { /* Close handler owns exit errors. */ }); + child.stdin.end(payload); + + let settled = false; + child.once("error", (error) => { + // Only spawn failure (no child process started) settles here; otherwise + // `close` waits for exit and stdout drain. + if (child.pid !== undefined || settled) return; + settled = true; + cleanup(); + reject(new ManagedWorktreeFileIoError("io_failed", error)); + }); + child.once("close", (code) => { + if (settled) return; + settled = true; + cleanup(); + // Every valid stdout record is newline-terminated; a non-empty remainder + // at EOF is a truncated/corrupt protocol line. + if (stdoutCarry.length > 0) { + protocolError = true; + stdoutCarry = ""; + } + if (hasCallbackError) { + reject(callbackError); + return; + } + if (options.signal?.aborted) { + reject(new Error("Provision aborted.")); + return; + } + if (code !== 0) { + reject(new ManagedWorktreeFileIoError(errorCode(stderr))); + return; + } + if ( + protocolError || + !sawDone || + nextIndex !== options.relativePaths.length || + !Number.isSafeInteger(totalBytes) || + totalBytes > options.totalByteLimit + ) { + reject(new ManagedWorktreeFileIoError("io_failed")); + return; + } + resolve({ provisioned, totalBytes }); + }); + }); +} + /** Enumerate only through the root-bound native directory descriptor. */ export interface WorkspaceDirectoryIdentities { root: ManagedWorktreeRootIdentity; diff --git a/main/services/managed-worktree-lifecycle.test.ts b/main/services/managed-worktree-lifecycle.test.ts index 64340c6d72..26a3b3558b 100644 --- a/main/services/managed-worktree-lifecycle.test.ts +++ b/main/services/managed-worktree-lifecycle.test.ts @@ -26,6 +26,7 @@ import { provisionWorktreeIncludedFiles, readWorktreeInclude, } from "./managed-worktree-provisioner.js"; +import { provisionManagedWorktreeFilesBatch } from "./managed-worktree-file-io.js"; import { restoreManagedWorktreeSnapshot, type ManagedWorktreeRestoreDependencies, @@ -1452,10 +1453,7 @@ test(".worktreeinclude provisions only ignored+untracked files with mode preserv await fs.readFile(path.join(worktreePath, ".env"), "utf8"), "SECRET=42\n", ); - assert.equal( - await fs.readFile(path.join(worktreePath, "generated", "fixture.bin"), "utf8"), - "fixture\n", - ); + assert.equal(await fs.readFile(path.join(worktreePath, "generated", "fixture.bin"), "utf8"), "fixture\n"); // Tracked and non-ignored untracked files are never provisioned this way. await assert.rejects(fs.lstat(path.join(worktreePath, "tracked.txt")), { code: "ENOENT" }); await assert.rejects(fs.lstat(path.join(worktreePath, "untracked.txt")), { @@ -1463,6 +1461,156 @@ test(".worktreeinclude provisions only ignored+untracked files with mode preserv }); }); +test(".worktreeinclude with checkIgnored skips unrelated huge ignored trees and handles zero ignored matches", async (t) => { + const repository = await createRepository(t); + const worktreePath = await temporaryDirectory(t); + await fs.writeFile(path.join(repository, ".gitignore"), "node_modules/\n.env\n"); + await git(repository, ["add", ".gitignore"]); + await git(repository, ["commit", "-m", "ignore node_modules and env"]); + + // Populate node_modules with enough files that `ls-files --exclude-standard` + // exceeds this GitService's maxBufferBytes cap. + await fs.mkdir(path.join(repository, "node_modules", "pkg"), { recursive: true }); + await Promise.all( + Array.from({ length: 120 }, (_, index) => + fs.writeFile( + path.join(repository, "node_modules", "pkg", `module-with-long-name-${String(index).padStart(4, "0")}.js`), + "export {};\n", + ), + ), + ); + await fs.writeFile(path.join(repository, ".env"), "SECRET=ok\n", { mode: 0o600 }); + await fs.writeFile(path.join(repository, "untracked-only.txt"), "not ignored\n"); + await fs.writeFile(path.join(repository, ".worktreeinclude"), ".env\nuntracked-only.txt\n"); + + const bounded = new GitService({ cacheTtlMs: 0, maxBufferBytes: 2_048 }); + await assert.rejects( + bounded.listFiles(repository, ["ls-files", "-z", "-o", "-i", "--exclude-standard", "--full-name"]), + (error: unknown) => error instanceof GitServiceError && error.code === "output_limit", + "naive --exclude-standard overflows the stdout cap when node_modules is large", + ); + + const provisioned = await provisionWorktreeIncludedFiles( + { + listFiles: (cwd, args) => bounded.listFiles(cwd, args), + checkIgnored: (cwd, paths, signal) => bounded.checkIgnoredPaths(cwd, paths, signal), + }, + { sourceRoot: repository, worktreePath }, + ); + assert.deepEqual(provisioned, [".env"]); + assert.equal(await fs.readFile(path.join(worktreePath, ".env"), "utf8"), "SECRET=ok\n"); + + // When `.worktreeinclude` matches only non-ignored untracked files, + // `git check-ignore` exits with code 1 and provisioning returns empty cleanly. + const emptyWorktree = await temporaryDirectory(t); + await fs.writeFile(path.join(repository, ".worktreeinclude"), "untracked-only.txt\n"); + const none = await provisionWorktreeIncludedFiles( + { + listFiles: (cwd, args) => bounded.listFiles(cwd, args), + checkIgnored: (cwd, paths, signal) => bounded.checkIgnoredPaths(cwd, paths, signal), + }, + { sourceRoot: repository, worktreePath: emptyWorktree }, + ); + assert.deepEqual(none, []); +}); + +test("checkIgnoredPaths neutralizes colon pathspec magic and resolves paths from repo topLevel", async (t) => { + const repository = await createRepository(t); + await fs.mkdir(path.join(repository, "nested"), { recursive: true }); + await fs.mkdir(path.join(repository, ":"), { recursive: true }); + await fs.writeFile(path.join(repository, ".gitignore"), "/b.log\n:!c.log\n:(icase).env\n"); + await git(repository, ["add", ".gitignore"]); + await git(repository, ["commit", "-m", "ignore literal colon patterns"]); + + await fs.writeFile(path.join(repository, ":", "b.log"), "not ignored\n"); + await fs.writeFile(path.join(repository, ":!c.log"), "ignored literal\n"); + await fs.writeFile(path.join(repository, ":(icase).env"), "ignored literal\n"); + + const service = new GitService({ cacheTtlMs: 0 }); + const matched = await service.checkIgnoredPaths(path.join(repository, "nested"), [ + ":/b.log", + ":!c.log", + ":(icase).env", + ]); + assert.deepEqual(matched.sort(), [":!c.log", ":(icase).env"]); +}); + +test("resolveWorktreeBase streams prefix matches without output_limit and preserves invalid_ref precedence", async (t) => { + const repository = await createRepository(t); + const head = await git(repository, ["rev-parse", "HEAD"]); + for (let index = 0; index < 80; index++) { + await git(repository, ["update-ref", `refs/heads/feat/branch-with-long-name-${String(index).padStart(3, "0")}`, head]); + } + const bounded = new GitService({ cacheTtlMs: 0, maxBufferBytes: 1_024 }); + await assert.rejects( + bounded.resolveWorktreeBase(repository, "feat"), + (error: unknown) => error instanceof GitServiceError && error.code === "invalid_ref", + ); + for (const invalid of ["", "main/", "foo..bar", "HEAD~1", "*"]) { + await assert.rejects( + bounded.resolveWorktreeBase(repository, invalid), + (error: unknown) => error instanceof GitServiceError && error.code === "invalid_ref", + ); + } +}); + +test("streaming check-attr admission handles attribute output larger than maxBufferBytes and still rejects forbidden filters", async (t) => { + const repository = await createRepository(t); + await fs.mkdir(path.join(repository, "src"), { recursive: true }); + await Promise.all( + Array.from({ length: 120 }, (_, index) => + fs.writeFile( + path.join(repository, "src", `file-with-a-reasonably-long-name-${String(index).padStart(4, "0")}.ts`), + "export const x = 1;\n", + ), + ), + ); + await fs.writeFile( + path.join(repository, ".gitattributes"), + "* text=auto eol=lf\n*.ts diff=typescript linguist-language=TypeScript\n", + ); + await git(repository, ["add", "."]); + await git(repository, ["commit", "-m", "many attributed files"]); + + // `ls-tree` output (~10 KiB) fits inside 32 KiB, while `check-attr --all` + // emits ~4 attributes × 120 files (~35 KiB > maxBufferBytes when set to 16 KiB). + // Use 14 KiB so `ls-tree` (~10 KiB) fits but buffered `check-attr --all` would overflow. + const service = new GitService({ cacheTtlMs: 0, maxBufferBytes: 14_000 }); + const estimate = await service.managedWorktreeCheckoutBytes(repository); + assert.ok(estimate > 120 * 4096); + + // Adding a single forbidden filter anywhere in the streamed output must still reject. + await fs.appendFile( + path.join(repository, ".gitattributes"), + "src/file-with-a-reasonably-long-name-0119.ts filter=expanding\n", + ); + await git(repository, ["add", ".gitattributes"]); + await git(repository, ["commit", "-m", "add forbidden filter"]); + await assert.rejects( + service.managedWorktreeCheckoutBytes(repository), + (error: unknown) => error instanceof GitServiceError && error.code === "unsupported_scope", + ); +}); + +test("createWorktree validates additionalAllocationBytes atomically before creating directories or branches", async (t) => { + const repository = await createRepository(t); + const root = await temporaryDirectory(t); + const service = new GitService({ cacheTtlMs: 0 }); + await assert.rejects( + service.createWorktree(repository, root, "feature/bad-reserve", undefined, { + additionalAllocationBytes: -1, + }), + (error: unknown) => error instanceof GitServiceError && error.code === "invalid_input", + ); + await assert.rejects( + service.createWorktree(repository, root, "feature/overflow-reserve", undefined, { + additionalAllocationBytes: Number.MAX_SAFE_INTEGER, + }), + (error: unknown) => error instanceof GitServiceError && error.code === "unsupported_scope", + ); + await assert.rejects(git(repository, ["show-ref", "--verify", "refs/heads/feature/overflow-reserve"])); +}); + test(".worktreeinclude provisioning is a no-op without the macOS transfer helper", async (t) => { const repository = await createRepository(t); const worktreePath = await temporaryDirectory(t); @@ -1530,6 +1678,64 @@ test("provisioning refuses symlinked sources, escapes, and existing destinations ); }); +test("provisionManagedWorktreeFilesBatch settles only after exit on abort and keeps disk 1:1 with onProvisioned", async (t) => { + if (process.platform !== "darwin") return; + const sourceRoot = await temporaryDirectory(t); + const destinationRoot = await temporaryDirectory(t); + const paths: string[] = []; + for (let i = 0; i < 40; i += 1) { + const name = `f-${String(i).padStart(2, "0")}.txt`; + await fs.writeFile(path.join(sourceRoot, name), `payload-${i}\n`); + paths.push(name); + } + + // 1. Mid-batch AbortSignal: helper exits cleanly before rejection, every + // file on disk was reported to onProvisioned (0 untracked/temp files), and + // no callbacks fire after rejection. + const controller = new AbortController(); + const reported: string[] = []; + await assert.rejects( + provisionManagedWorktreeFilesBatch({ + sourceRoot, + destinationRoot, + relativePaths: paths, + totalByteLimit: 1024 * 1024, + signal: controller.signal, + onProvisioned: (relativePath) => { + reported.push(relativePath); + if (reported.length === 5) controller.abort(); + }, + }), + /Provision aborted\./u, + ); + const countAtReject = reported.length; + const filesOnDiskAtReject = (await fs.readdir(destinationRoot)).sort(); + assert.deepEqual( + filesOnDiskAtReject, + [...reported].sort(), + "Every file installed on disk must match onProvisioned 1:1 at rejection (no untracked or .tmp leftovers)", + ); + await new Promise((resolve) => setTimeout(resolve, 100)); + assert.equal(reported.length, countAtReject, "No onProvisioned callbacks may fire after rejection"); + assert.deepEqual((await fs.readdir(destinationRoot)).sort(), filesOnDiskAtReject); + + // 2. Throwing inside onProvisioned rejects cleanly instead of crashing the process. + const destinationRoot2 = await temporaryDirectory(t); + const boom = new Error("callback boom"); + await assert.rejects( + provisionManagedWorktreeFilesBatch({ + sourceRoot, + destinationRoot: destinationRoot2, + relativePaths: paths.slice(0, 5), + totalByteLimit: 1024 * 1024, + onProvisioned: () => { + throw boom; + }, + }), + (error: unknown) => error === boom, + ); +}); + test("provisioned blob storage captures bytes, verifies digests, and restores idempotently", async (t) => { const snapshotRoot = await temporaryDirectory(t); const worktree = await temporaryDirectory(t); diff --git a/main/services/managed-worktree-provisioner.ts b/main/services/managed-worktree-provisioner.ts index e2fed26d2f..e67be6d610 100644 --- a/main/services/managed-worktree-provisioner.ts +++ b/main/services/managed-worktree-provisioner.ts @@ -4,7 +4,11 @@ import * as fs from "node:fs/promises"; import * as path from "node:path"; -import { captureManagedWorktreeRootIdentity, ManagedWorktreeFileIoError, transferManagedWorktreeFile } from "./managed-worktree-file-io.js"; +import { + captureManagedWorktreeRootIdentity, + ManagedWorktreeFileIoError, + provisionManagedWorktreeFilesBatch, +} from "./managed-worktree-file-io.js"; const INCLUDE_FILE = ".worktreeinclude"; const MAX_INCLUDE_BYTES = 64 * 1024; @@ -34,6 +38,12 @@ export class ManagedWorktreeProvisionerError extends Error { export interface WorktreeProvisionerDependencies { /** Run `git ` in `cwd` and return raw (-z) stdout. */ listFiles(cwd: string, args: readonly string[]): Promise; + /** + * Filter `paths` to those ignored by Git's standard ignore rules + * (`git check-ignore -z --stdin`). Preferred over `ls-files --exclude-standard` + * because large ignored trees such as `node_modules` never need to be walked. + */ + checkIgnored?(cwd: string, paths: readonly string[], signal?: AbortSignal): Promise; } function normalizedRelativePath(candidate: string): string | undefined { @@ -120,37 +130,41 @@ export async function provisionWorktreeIncludedFiles( ); } - // `ls-files -o -i` is "untracked AND ignored". The WI file is itself an - // exclude source, so intersecting standard-ignored with WI-ignored yields - // exactly the files that are both ignored by the project and selected for - // provisioning — tracked files and non-ignored untracked files can never - // appear in either list. - const standardArgs = [ + // `ls-files -o -i --exclude-from=.worktreeinclude` lists only untracked files + // selected by `.worktreeinclude` (tracked files can never appear). Checking + // just those candidates against Git's standard ignore rules avoids walking + // unrelated huge ignored trees like `node_modules` (which would otherwise blow + // past Git's stdout cap). + const includedRaw = await dependencies.listFiles(canonicalSource, [ "ls-files", "-z", "-o", "-i", - "--exclude-standard", + `--exclude-from=${includeFile}`, "--full-name", - ]; - const [ignoredRaw, includedRaw] = await Promise.all([ - dependencies.listFiles(canonicalSource, standardArgs), - dependencies.listFiles(canonicalSource, [ + ]); + if (options.signal?.aborted) throw new Error("Provision aborted."); + const included = includedRaw.split("\u0000").filter(Boolean); + if (included.length === 0) return []; + + let eligible: string[]; + if (dependencies.checkIgnored) { + const ignored = new Set(await dependencies.checkIgnored(canonicalSource, included, options.signal)); + if (options.signal?.aborted) throw new Error("Provision aborted."); + eligible = [...new Set(included.filter((entry) => ignored.has(entry)))].sort(); + } else { + const ignoredRaw = await dependencies.listFiles(canonicalSource, [ "ls-files", "-z", "-o", "-i", - `--exclude-from=${includeFile}`, + "--exclude-standard", "--full-name", - ]), - ]); - if (options.signal?.aborted) throw new Error("Provision aborted."); - const ignored = new Set(ignoredRaw.split("\u0000").filter(Boolean)); - const eligible = includedRaw - .split("\u0000") - .filter(Boolean) - .filter((entry) => ignored.has(entry)) - .sort(); + ]); + if (options.signal?.aborted) throw new Error("Provision aborted."); + const ignored = new Set(ignoredRaw.split("\u0000").filter(Boolean)); + eligible = [...new Set(included.filter((entry) => ignored.has(entry)))].sort(); + } if (eligible.length > MAX_PROVISIONED_FILES) { throw new ManagedWorktreeProvisionerError( "too_many_files", @@ -158,10 +172,8 @@ export async function provisionWorktreeIncludedFiles( ); } - const provisioned: string[] = []; - let totalBytes = 0; + const normalizedPaths: string[] = []; for (const entry of eligible) { - if (options.signal?.aborted) throw new Error("Provision aborted."); const relativePath = normalizedRelativePath(entry); if (relativePath === undefined) { throw new ManagedWorktreeProvisionerError( @@ -169,39 +181,40 @@ export async function provisionWorktreeIncludedFiles( "A provisioned file path could not be verified.", ); } - try { - const copied = await transferManagedWorktreeFile({ - operation: "copy", - sourceRoot: canonicalSource, - sourceIdentity, - sourceRelativePath: relativePath, - destinationRoot: canonicalWorktree, - destinationIdentity, - destinationRelativePath: relativePath, - byteLimit: MAX_PROVISIONED_BYTES - totalBytes, - mode: "source", - }); - totalBytes += copied.size; - } catch (error) { - if (error instanceof ManagedWorktreeFileIoError) { - const code = error.code === "destination_exists" ? "destination_exists" - : error.code === "too_many_bytes" ? "too_many_bytes" - : error.code === "source_changed" ? "source_changed" - : error.code === "unsafe_source" ? "unsafe_source" - : error.code === "invalid_input" ? "unsafe_source" - : "unsafe_source"; - throw new ManagedWorktreeProvisionerError( - code, - code === "destination_exists" - ? "A provisioned file would overwrite an existing worktree file." - : "A provisioned file could not be copied safely.", - error, - ); - } - throw error; + normalizedPaths.push(relativePath); + } + if (options.signal?.aborted) throw new Error("Provision aborted."); + + try { + const { provisioned } = await provisionManagedWorktreeFilesBatch({ + sourceRoot: canonicalSource, + sourceIdentity, + destinationRoot: canonicalWorktree, + destinationIdentity, + relativePaths: normalizedPaths, + totalByteLimit: MAX_PROVISIONED_BYTES, + signal: options.signal, + onProvisioned: (relativePath) => { + options.onProvisioned?.(relativePath); + }, + }); + return provisioned; + } catch (error) { + if (error instanceof ManagedWorktreeFileIoError) { + const code = error.code === "destination_exists" ? "destination_exists" + : error.code === "too_many_bytes" ? "too_many_bytes" + : error.code === "source_changed" ? "source_changed" + : error.code === "unsafe_source" ? "unsafe_source" + : error.code === "invalid_input" ? "unsafe_source" + : "unsafe_source"; + throw new ManagedWorktreeProvisionerError( + code, + code === "destination_exists" + ? "A provisioned file would overwrite an existing worktree file." + : "A provisioned file could not be copied safely.", + error, + ); } - provisioned.push(relativePath); - options.onProvisioned?.(relativePath); + throw error; } - return provisioned; } diff --git a/main/services/pi-compaction-session-store.ts b/main/services/pi-compaction-session-store.ts index 63369f1dcf..0f38626fdd 100644 --- a/main/services/pi-compaction-session-store.ts +++ b/main/services/pi-compaction-session-store.ts @@ -1,7 +1,7 @@ import { createHash, randomUUID } from "node:crypto"; import { isDeepStrictEqual } from "node:util"; import { constants as fsConstants } from "node:fs"; -import { chmod, lstat, open, readFile, readdir, rename, stat, unlink } from "node:fs/promises"; +import { chmod, lstat, open, readFile, readdir, rename, unlink } from "node:fs/promises"; import path from "node:path"; import { type AgentMessage, @@ -331,15 +331,64 @@ async function isDisposablePi084Backup(backupPath: string, chatId: string, root: async function fileExists(filePath: string): Promise { try { - return (await stat(filePath)).isFile(); + const metadata = await lstat(filePath); + return metadata.isFile() && !metadata.isSymbolicLink(); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; } } -async function findMigrationJournals(root: string, chatId: string): Promise { +/** + * Lightweight directory-tree signature for `root`: catches any created, + * renamed, deleted, or in-place-modified journal/migration/backup file across + * `root` and its subdirectories via `readdir` + `lstat` without opening `.jsonl` + * files, and fails closed if any symbolic link is encountered. + */ +async function computePiJournalDirSignature(root: string): Promise { + const parts: string[] = []; + const directories: Array<{ abs: string; rel: string }> = [{ abs: root, rel: "" }]; + while (directories.length > 0) { + const current = directories.pop()!; + const dirStat = await lstat(current.abs); + if (!dirStat.isDirectory() || dirStat.isSymbolicLink()) { + throw new Error("Pi journal storage root must be a directory."); + } + const entries = await readdir(current.abs, { withFileTypes: true }); + entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0)); + parts.push(`d:${current.rel}:${dirStat.dev}:${dirStat.ino}:${dirStat.mtimeMs}:${dirStat.ctimeMs}:${entries.length}`); + const fileEntries: Array<{ abs: string; rel: string }> = []; + for (const entry of entries) { + if (entry.isSymbolicLink()) { + throw new Error("Pi journal storage contains an uninspectable symbolic link."); + } + const rel = current.rel ? `${current.rel}/${entry.name}` : entry.name; + if (entry.isDirectory()) { + directories.push({ abs: path.join(current.abs, entry.name), rel }); + } else if (entry.name.includes(".jsonl")) { + fileEntries.push({ abs: path.join(current.abs, entry.name), rel }); + } + } + if (fileEntries.length > 0) { + const fileStats = await Promise.all(fileEntries.map((item) => lstat(item.abs))); + for (let i = 0; i < fileEntries.length; i++) { + const st = fileStats[i]!; + if (st.isSymbolicLink()) { + throw new Error("Pi journal storage contains an uninspectable symbolic link."); + } + parts.push(`f:${fileEntries[i]!.rel}:${st.dev}:${st.ino}:${st.mode}:${st.size}:${st.mtimeMs}:${st.ctimeMs}`); + } + } + } + return parts.join("\n"); +} + +async function scanMigrationJournalIds(root: string, chatId: string): Promise<{ + matches: string[]; + allLegacyChatIds: Set; +}> { const matches: string[] = []; + const allLegacyChatIds = new Set(); const directories = [root]; while (directories.length > 0) { const directory = directories.pop()!; @@ -349,18 +398,37 @@ async function findMigrationJournals(root: string, chatId: string): Promise ""); - if ( - journalHeaderOwnsChat(prefix, chatId) || - (currentJournalHeaderOwnsChat(prefix, chatId) && - ((await fileExists(`${candidate}.v3-backup`)) || - (await fileExists(`${candidate}.migration-v1.json`)))) - ) { + if (!prefix) continue; + const firstLine = prefix.split("\n", 1)[0] ?? ""; + const isLegacyForChat = journalHeaderOwnsChat(prefix, chatId); + const hasPendingBackup = + (await fileExists(`${candidate}.v3-backup`)) || + (await fileExists(`${candidate}.migration-v1.json`)); + if (isLegacyForChat || (currentJournalHeaderOwnsChat(prefix, chatId) && hasPendingBackup)) { matches.push(candidate); } + // Record any chat ID that owns a legacy or mid-migration journal so the + // brand-new chat fast path never skips an existing migration candidate. + try { + const parsed = JSON.parse(firstLine) as { id?: unknown; metadata?: { chatId?: unknown } } | null; + if (parsed && typeof parsed === "object") { + const ownerId = + typeof parsed.metadata?.chatId === "string" + ? parsed.metadata.chatId + : typeof parsed.id === "string" + ? parsed.id + : undefined; + if (ownerId && (hasPendingBackup || journalHeaderOwnsChat(prefix, ownerId))) { + allLegacyChatIds.add(ownerId); + } + } + } catch { + // Malformed header is handled by normal open/quarantine paths. + } } } } - return matches; + return { matches, allLegacyChatIds }; } /** Preserve a valid durable prefix when only the final JSONL write was torn. */ @@ -1064,6 +1132,15 @@ export class PiCompactionSessionStore { private readonly opening = new Map>(); private readonly quarantined = new Map>(); private indexMutation: Promise = Promise.resolve(); + /** Monotonic counter incremented on every store disk mutation to fence `dirIndex`. */ + private dirMutationVersion = 0; + /** Directory-signature-validated set of chat IDs already present on disk. */ + private dirIndex?: { + root: string; + signature: string; + knownChatIds: Set; + legacyChatIds: Set; + }; constructor(private readonly options: PiCompactionSessionStoreOptions) {} @@ -1160,6 +1237,8 @@ export class PiCompactionSessionStore { } private async quarantine(root: string, chatId: string, filePath: string): Promise { + this.dirMutationVersion += 1; + this.dirIndex = undefined; const quarantined = `${filePath}.corrupt-${Date.now()}-${randomUUID()}`; await rename(filePath, quarantined); await this.rememberPath(root, chatId, quarantined); @@ -1253,7 +1332,24 @@ export class PiCompactionSessionStore { }; const migrationFailures: Array<{ path: string; error: unknown }> = []; const deferredMigrations: string[] = []; - const migrationPaths = await findMigrationJournals(root, chatId); + const scanStartVersion = this.dirMutationVersion; + const beforeSignature = await computePiJournalDirSignature(root).catch(() => undefined); + const knownBrandNew = + beforeSignature !== undefined && + this.dirIndex !== undefined && + this.dirIndex.root === root && + this.dirIndex.signature === beforeSignature && + !this.dirIndex.knownChatIds.has(chatId) && + !this.dirIndex.legacyChatIds.has(chatId); + let migrationPaths: string[]; + let scannedLegacyChatIds: Set | undefined; + if (knownBrandNew) { + migrationPaths = []; + } else { + const scan = await scanMigrationJournalIds(root, chatId); + migrationPaths = scan.matches; + scannedLegacyChatIds = scan.allLegacyChatIds; + } for (const migrationPath of migrationPaths) { try { if (rollout && rolloutOptions) { @@ -1267,6 +1363,8 @@ export class PiCompactionSessionStore { continue; } } + this.dirMutationVersion += 1; + this.dirIndex = undefined; const migration = await migratePiSessionJournal(migrationPath, chatId); await this.rememberPath(root, chatId, migration.receipt.backupPath); await this.rememberPath(root, chatId, migration.receiptPath); @@ -1275,12 +1373,38 @@ export class PiCompactionSessionStore { } } const failedPaths = new Set(migrationFailures.map((failure) => path.resolve(failure.path))); - const matches = (await repo.list()).filter( - (metadata) => - metadata.id === chatId && - metadata.metadata?.kind === SESSION_METADATA_KIND && - !failedPaths.has(path.resolve(metadata.path)), - ); + let matches: Awaited>; + if (knownBrandNew) { + matches = []; + } else { + const listed = await repo.list(); + matches = listed.filter( + (metadata) => + metadata.id === chatId && + metadata.metadata?.kind === SESSION_METADATA_KIND && + !failedPaths.has(path.resolve(metadata.path)), + ); + if ( + beforeSignature !== undefined && + migrationPaths.length === 0 && + this.dirMutationVersion === scanStartVersion && + this.opening.size <= 1 + ) { + const afterScanSignature = await computePiJournalDirSignature(root).catch(() => undefined); + if (afterScanSignature === beforeSignature && this.dirMutationVersion === scanStartVersion) { + const knownChatIds = new Set(); + for (const metadata of listed) { + if (metadata.metadata?.kind === SESSION_METADATA_KIND) knownChatIds.add(metadata.id); + } + this.dirIndex = { + root, + signature: afterScanSignature, + knownChatIds, + legacyChatIds: scannedLegacyChatIds ?? new Set(), + }; + } + } + } // Pi lists newest sessions first. Validate the whole body and quarantine // a malformed duplicate before falling back to the next valid journal. let session: PiSessionPort | undefined; @@ -1320,6 +1444,8 @@ export class PiCompactionSessionStore { ) { return { session: undefined, reason: "v4_creation_rollout" }; } + const createdNewSession = !session; + const createVersion = createdNewSession ? ++this.dirMutationVersion : this.dirMutationVersion; session ??= await repo.create({ id: chatId, cwd: root, @@ -1330,6 +1456,45 @@ export class PiCompactionSessionStore { await chmod(path.dirname(persisted.path), 0o700); await chmod(persisted.path, 0o600); await this.rememberPath(root, chatId, persisted.path); + if (createdNewSession) { + // Only advance `dirIndex` in place when no concurrent opener or external + // file could have appeared alongside `persisted.path`. + if ( + this.dirIndex && + this.dirIndex.root === root && + this.opening.size <= 1 && + this.dirMutationVersion === createVersion && + beforeSignature !== undefined + ) { + const updatedSignature = await computePiJournalDirSignature(root).catch(() => undefined); + const beforeFiles = new Set( + beforeSignature.split("\n").filter((line) => line.startsWith("f:")).map((line) => line.split(":", 2)[1]), + ); + const expectedRel = path.relative(root, persisted.path).split(path.sep).join("/"); + const addedUnexpected = + updatedSignature === undefined || + updatedSignature + .split("\n") + .filter((line) => line.startsWith("f:")) + .some((line) => { + const rel = line.split(":", 2)[1]; + return rel !== expectedRel && !beforeFiles.has(rel); + }); + if ( + updatedSignature !== undefined && + !addedUnexpected && + this.opening.size <= 1 && + this.dirMutationVersion === createVersion + ) { + this.dirIndex.knownChatIds.add(chatId); + this.dirIndex.signature = updatedSignature; + } else { + this.dirIndex = undefined; + } + } else { + this.dirIndex = undefined; + } + } this.sessions.set(chatId, session); return { session }; } @@ -1471,6 +1636,8 @@ export class PiCompactionSessionStore { }); const { repo, root } = await this.repository(); + this.dirMutationVersion += 1; + this.dirIndex = undefined; const session = await repo.create({ id: targetChatId, cwd: root, @@ -1481,6 +1648,7 @@ export class PiCompactionSessionStore { await chmod(path.dirname(persisted.path), 0o700); await chmod(persisted.path, 0o600); await this.rememberPath(root, targetChatId, persisted.path); + this.dirIndex = undefined; await session.importBranch(prefix); } catch (error) { await this.deleteChat(targetChatId).catch(() => undefined); @@ -1564,6 +1732,8 @@ export class PiCompactionSessionStore { } } } + this.dirMutationVersion += 1; + this.dirIndex = undefined; await this.mutateIndex(root, (next) => { delete next.chats[chatId]; }); diff --git a/main/services/portable-config-core.ts b/main/services/portable-config-core.ts index ed3479b673..52cffe9dbe 100644 --- a/main/services/portable-config-core.ts +++ b/main/services/portable-config-core.ts @@ -1298,11 +1298,16 @@ export function createPortableConfigStores( } = {}, ) { const archivePublicationPaths = new Set(); - async function protectConfigDirectory(root: string, portableDirectory: boolean, ownedPublicationPaths: readonly string[] = []): Promise { + async function protectConfigDirectory( + root: string, + portableDirectory: boolean, + ownedPublicationPaths: readonly string[] = [], + ): Promise { const ownedPaths = [...ownedPublicationPaths, ...archivePublicationPaths]; ensurePrivateDirectory(root); const file = path.join(root, PORTABLE_CONFIG_FILENAME); hardenPrivateFile(file, ownedPaths); + const protectedSecondary: string[] = []; for (const entry of await fs.readdir(root)) { const archive = `${LOCAL_CONFIG_FILENAME}${LEGACY_CONFIG_ARCHIVE_SUFFIX}`; const isArchive = !portableDirectory && (entry === archive || @@ -1311,11 +1316,132 @@ export function createPortableConfigStores( const isConflict = /^config\.json\.conflict-[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u.test(entry); if (isArchive && (await fs.lstat(path.join(root, entry))).isDirectory()) continue; const isStaged = /^\.config\.json(?:\.pre-aiden-dir(?:\.recovery-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})?)?\.[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}\.tmp$/u.test(entry); - if (isArchive || isCorrupt || isConflict || isStaged || isDataStoreRecoveryFile(entry, file)) hardenPrivateFile(path.join(root, entry), ownedPaths); + if (isArchive || isCorrupt || isConflict || isStaged || isDataStoreRecoveryFile(entry, file)) { + const secondaryPath = path.join(root, entry); + hardenPrivateFile(secondaryPath, ownedPaths); + protectedSecondary.push(secondaryPath); + } } + return protectedSecondary; } - const protectPortable = (ownedPaths: readonly string[] = []) => protectConfigDirectory(portableRoot(), true, ownedPaths); - const protectLocal = async (ownedPaths: readonly string[] = []) => protectConfigDirectory(localRoot ? localRoot() : (await import("../platform.js")).app.getPath("userData"), false, ownedPaths); + const protectPortable = async (ownedPaths: readonly string[] = []): Promise => { + await protectConfigDirectory(portableRoot(), true, ownedPaths); + }; + let lastLocalProtectSignature: + | { + root: string; + dirDev: bigint; + dirIno: bigint; + dirMtimeNs: bigint; + dirCtimeNs: bigint; + fileDev: bigint; + fileIno: bigint; + fileMtimeNs: bigint; + fileCtimeNs: bigint; + secondaryPaths: readonly string[]; + } + | undefined; + const protectLocal = async (ownedPaths: readonly string[] = []): Promise => { + const root = localRoot ? localRoot() : (await import("../platform.js")).app.getPath("userData"); + const uid = typeof process.getuid === "function" ? process.getuid() : undefined; + const configPath = path.join(root, LOCAL_CONFIG_FILENAME); + if ( + process.platform !== "win32" && + uid !== undefined && + ownedPaths.length === 0 && + archivePublicationPaths.size === 0 && + lastLocalProtectSignature && + lastLocalProtectSignature.root === root + ) { + // Keep full ancestor/alias verification on every call; skip only the + // `readdir(userData)` scan and redundant `open`/`fchmod` hardening when + // `root`, `config.json`, and every known secondary file are untouched. + ensurePrivateDirectory(root); + try { + const [dirStat, fileStat, ...secondaryStats] = await Promise.all([ + fs.lstat(root, { bigint: true }), + fs.lstat(configPath, { bigint: true }), + ...lastLocalProtectSignature.secondaryPaths.map((secondary) => + fs.lstat(secondary, { bigint: true }), + ), + ]); + const secondaryClean = secondaryStats.every( + (st) => + st.isFile() && + !st.isSymbolicLink() && + Number(st.uid) === uid && + (Number(st.mode) & 0o777) === 0o600 && + st.nlink === 1n, + ); + if ( + secondaryClean && + dirStat.isDirectory() && + !dirStat.isSymbolicLink() && + Number(dirStat.uid) === uid && + (Number(dirStat.mode) & 0o777) === 0o700 && + dirStat.dev === lastLocalProtectSignature.dirDev && + dirStat.ino === lastLocalProtectSignature.dirIno && + dirStat.mtimeNs === lastLocalProtectSignature.dirMtimeNs && + dirStat.ctimeNs === lastLocalProtectSignature.dirCtimeNs && + fileStat.isFile() && + !fileStat.isSymbolicLink() && + Number(fileStat.uid) === uid && + (Number(fileStat.mode) & 0o777) === 0o600 && + fileStat.nlink === 1n && + fileStat.dev === lastLocalProtectSignature.fileDev && + fileStat.ino === lastLocalProtectSignature.fileIno && + fileStat.mtimeNs === lastLocalProtectSignature.fileMtimeNs && + fileStat.ctimeNs === lastLocalProtectSignature.fileCtimeNs + ) { + return; + } + } catch { + // Fall through to full directory & file hardening on any stat change/error. + } + } + const secondaryPaths = await protectConfigDirectory(root, false, ownedPaths); + if ( + process.platform !== "win32" && + uid !== undefined && + ownedPaths.length === 0 && + archivePublicationPaths.size === 0 + ) { + try { + const [dirStat, fileStat] = await Promise.all([ + fs.lstat(root, { bigint: true }), + fs.lstat(configPath, { bigint: true }), + ]); + if ( + dirStat.isDirectory() && + !dirStat.isSymbolicLink() && + Number(dirStat.uid) === uid && + (Number(dirStat.mode) & 0o777) === 0o700 && + fileStat.isFile() && + !fileStat.isSymbolicLink() && + Number(fileStat.uid) === uid && + (Number(fileStat.mode) & 0o777) === 0o600 && + fileStat.nlink === 1n + ) { + lastLocalProtectSignature = { + root, + dirDev: dirStat.dev, + dirIno: dirStat.ino, + dirMtimeNs: dirStat.mtimeNs, + dirCtimeNs: dirStat.ctimeNs, + fileDev: fileStat.dev, + fileIno: fileStat.ino, + fileMtimeNs: fileStat.mtimeNs, + fileCtimeNs: fileStat.ctimeNs, + secondaryPaths, + }; + return; + } + } catch { + // Uncached until config.json exists and passes hardening. + } + } + lastLocalProtectSignature = undefined; + }; const portable = new DataStore( PORTABLE_CONFIG_FILENAME, emptyPortableConfig(), diff --git a/main/services/skill-registry-main.ts b/main/services/skill-registry-main.ts index e677c16754..6f6c1cacca 100644 --- a/main/services/skill-registry-main.ts +++ b/main/services/skill-registry-main.ts @@ -1,5 +1,9 @@ import { configStore } from "./config-store.js"; -import { discoverSkillCandidates, invalidateSkillDiscoveryCache } from "./skills-discovery.js"; +import { + discoverSkillCandidates, + discoverSkillCandidatesWithCachedGlobals, + invalidateSkillDiscoveryCache, +} from "./skills-discovery.js"; import { SkillRegistry } from "./skill-registry.js"; import { AIDEN_APP_SKILL } from "./aiden-app-knowledge.js"; import { AIDEN_ARTIFACTS_SKILL, AIDEN_ARTIFACTS_SKILL_ID } from "./workspace-artifacts/skill.js"; @@ -22,5 +26,6 @@ export const skillRegistry = new SkillRegistry({ getWorkspace: (id) => configStore.getWorkspace(id), listConfigured: () => configStore.listSkills(), discover: (workspaceRoot) => discoverSkillCandidates(workspaceRoot), + discoverWithCachedGlobals: (workspaceRoot) => discoverSkillCandidatesWithCachedGlobals(workspaceRoot), onInvalidate: invalidateSkillDiscoveryCache, }); diff --git a/main/services/skill-registry.ts b/main/services/skill-registry.ts index 55310e0710..d419ef4043 100644 --- a/main/services/skill-registry.ts +++ b/main/services/skill-registry.ts @@ -45,6 +45,8 @@ export interface SkillRegistryDependencies { isEnabled(): Promise; listConfigured(): Promise; discover(workspaceRoot?: string): Promise; + /** Optional discovery helper that caches global roots while scanning `workspaceRoot` fresh. */ + discoverWithCachedGlobals?: (workspaceRoot?: string) => Promise; now(): number; invocationKey: Uint8Array; cacheTtlMs: number; @@ -242,7 +244,7 @@ export class SkillRegistry { if (!workspace || workspace.id !== workspaceId) { throw new SkillInvocationError("workspace_changed", "Skill workspace is unavailable."); } - return this.#resolveFromSnapshot(await this.#load(workspace), invocationId); + return this.#resolveFromSnapshot(await this.#load(workspace, true), invocationId); } #resolveFromSnapshot(snapshot: SkillRegistrySnapshot, invocationId: string): RegisteredSkill { @@ -272,13 +274,18 @@ export class SkillRegistry { async #load( workspace: RegistryWorkspace, + fresh = false, ): Promise { if (!(await this.#dependencies.isEnabled())) return this.#project(workspace, []); + const discover = + fresh || !this.#dependencies.discoverWithCachedGlobals + ? this.#dependencies.discover + : this.#dependencies.discoverWithCachedGlobals; const [configured, discovered, builtin] = await Promise.all([ this.#dependencies.listConfigured(), // No Access is also a discovery boundary: do not read workspace skill // files merely to mark them unavailable in a renderer catalog. - this.#dependencies.discover( + discover( workspace.permission === "none" ? undefined : workspace.folderPath, ), this.#dependencies.listBuiltin(), diff --git a/main/services/skills-discovery.test.ts b/main/services/skills-discovery.test.ts index 19f05bf071..4ed18fb912 100644 --- a/main/services/skills-discovery.test.ts +++ b/main/services/skills-discovery.test.ts @@ -6,7 +6,9 @@ import test from "node:test"; import { SLASH_LIMITS } from "../../renderer/shared/slash-commands.js"; import { discoverSkillCandidates, + discoverSkillCandidatesWithCachedGlobals, discoverSkills, + invalidateSkillDiscoveryCache, SKILL_DISCOVERY_LIMITS, } from "./skills-discovery.js"; @@ -718,3 +720,36 @@ test("malformed plugin metadata and nonboolean enablement fail closed without hi await fs.writeFile(path.join(home, ".claude", "plugins", "installed_plugins.json"), "{"); assert.deepEqual((await discoverSkillCandidates(undefined, home)).map((skill) => skill.name), ["ordinary"]); }); + +test("discoverSkillCandidatesWithCachedGlobals reuses global skills across worktrees while scanning each workspace fresh", async (t) => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-skills-global-cache-")); + t.after(async () => { + invalidateSkillDiscoveryCache(); + await fs.rm(root, { recursive: true, force: true }); + }); + const home = path.join(root, "home"); + const ws1 = path.join(root, "ws1"); + const ws2 = path.join(root, "ws2"); + await writeSkill(path.join(home, ".claude", "skills"), "global-one", "Global instructions."); + await writeSkill(path.join(ws1, ".claude", "skills"), "ws-one", "Workspace 1."); + await writeSkill(path.join(ws2, ".claude", "skills"), "ws-two", "Workspace 2."); + + invalidateSkillDiscoveryCache(); + const first = await discoverSkillCandidatesWithCachedGlobals(ws1, home); + assert.deepEqual(first.map((skill) => skill.name), ["ws-one", "global-one"]); + + // Add a second global skill without invalidating: ws2 still sees its own fresh + // workspace skill while reusing the cached global scan. + await writeSkill(path.join(home, ".claude", "skills"), "global-two", "Global 2."); + const second = await discoverSkillCandidatesWithCachedGlobals(ws2, home); + assert.deepEqual(second.map((skill) => skill.name), ["ws-two", "global-one"]); + + // Uncached discoverSkillCandidates still sees the new global skill immediately. + const uncached = await discoverSkillCandidates(ws2, home); + assert.deepEqual(uncached.map((skill) => skill.name).sort(), ["global-one", "global-two", "ws-two"]); + + // After invalidation, cached-global discovery observes the new global skill. + invalidateSkillDiscoveryCache(); + const refreshed = await discoverSkillCandidatesWithCachedGlobals(ws2, home); + assert.deepEqual(refreshed.map((skill) => skill.name).sort(), ["global-one", "global-two", "ws-two"]); +}); diff --git a/main/services/skills-discovery.ts b/main/services/skills-discovery.ts index 65bd8ead42..d551790a71 100644 --- a/main/services/skills-discovery.ts +++ b/main/services/skills-discovery.ts @@ -386,15 +386,34 @@ const AIDEN_SEARCHES = [ { base: "skills", maxDepth: SKILL_DISCOVERY_LIMITS.relativeDepth }, ]; -/** - * Discover skills from global and workspace skill directories. - * Roots scan in precedence order so workspace skills override global ones and, - * within a source, `.aiden` overrides `.claude`, which overrides `.agents`. - */ -async function scanAllSkillCandidates( - workspaceRoot: string | undefined, +async function scanScopedRoots( + roots: ScanConfig[], + source: DiscoveredSkill["source"], + testHooks: SkillDiscoveryTestHooks = {}, +): Promise { + if (roots.length === 0) return []; + roots.sort( + (left, right) => + left.priority - right.priority || + (left.root < right.root ? -1 : left.root > right.root ? 1 : 0), + ); + // Independent source budgets prevent a hostile workspace from starving + // global skills. Their two fixed 16 MiB byte ceilings preserve a 32 MiB + // aggregate process bound. + const budget: DiscoveryBudget = { candidates: 0, traversedEntries: 0, aggregateBytes: 0 }; + const results: DiscoveredSkill[][] = []; + for (const config of roots) { + if (config.source !== source) continue; + if (discoveryBudgetExhausted(budget)) continue; + results.push(await scanPatterns(config, budget, testHooks)); + } + return results.flat(); +} + +async function scanGlobalSkillCandidates( home: string, aidenDir: string, + globalPluginConfigs: readonly ScanConfig[], testHooks: SkillDiscoveryTestHooks = {}, ): Promise { const roots: ScanConfig[] = [ @@ -411,54 +430,95 @@ async function scanAllSkillCandidates( priority: 10, }, { root: aidenDir, searches: AIDEN_SEARCHES, source: "global", priority: 0 }, + ...globalPluginConfigs, ]; + return scanScopedRoots(roots, "global", testHooks); +} - if (workspaceRoot) { - roots.push( - { - root: path.join(workspaceRoot, ".agents"), - searches: AGENTS_SEARCHES, - source: "workspace", - priority: 20, - }, - { - root: path.join(workspaceRoot, ".claude"), - searches: CLAUDE_SEARCHES, - source: "workspace", - priority: 10, - }, - { - root: path.join(workspaceRoot, AIDEN_DIR_NAME), - searches: AIDEN_SEARCHES, - source: "workspace", - priority: 0, - }, - ); - } +async function scanWorkspaceSkillCandidates( + workspaceRoot: string, + workspacePluginConfigs: readonly ScanConfig[], + testHooks: SkillDiscoveryTestHooks = {}, +): Promise { + const roots: ScanConfig[] = [ + { + root: path.join(workspaceRoot, ".agents"), + searches: AGENTS_SEARCHES, + source: "workspace", + priority: 20, + }, + { + root: path.join(workspaceRoot, ".claude"), + searches: CLAUDE_SEARCHES, + source: "workspace", + priority: 10, + }, + { + root: path.join(workspaceRoot, AIDEN_DIR_NAME), + searches: AIDEN_SEARCHES, + source: "workspace", + priority: 0, + }, + ...workspacePluginConfigs, + ]; + return scanScopedRoots(roots, "workspace", testHooks); +} - roots.push(...(await pluginScanConfigs(home, workspaceRoot))); +const GLOBAL_CANDIDATES_CACHE_LIMIT = 10; +const globalCandidatesCache = new Map< + string, + { expires: number; result: Promise } +>(); - try { - roots.sort( - (left, right) => - (left.source === "workspace" ? 0 : 1) - (right.source === "workspace" ? 0 : 1) || - left.priority - right.priority || - (left.root < right.root ? -1 : left.root > right.root ? 1 : 0), - ); - // Independent source budgets prevent a hostile workspace from starving - // global skills. Their two fixed 16 MiB byte ceilings preserve a 32 MiB - // aggregate process bound. - const budgets: Record = { - workspace: { candidates: 0, traversedEntries: 0, aggregateBytes: 0 }, - global: { candidates: 0, traversedEntries: 0, aggregateBytes: 0 }, - }; - const results: DiscoveredSkill[][] = []; - for (const config of roots) { - const budget = budgets[config.source]; - if (discoveryBudgetExhausted(budget)) continue; - results.push(await scanPatterns(config, budget, testHooks)); +function cachedGlobalSkillCandidates( + home: string, + aidenDir: string, + globalPluginConfigs: readonly ScanConfig[], +): Promise { + const key = JSON.stringify([home, aidenDir, globalPluginConfigs]); + const now = Date.now(); + const cached = globalCandidatesCache.get(key); + if (cached && cached.expires > now) return cached.result; + if (!cached && globalCandidatesCache.size >= GLOBAL_CANDIDATES_CACHE_LIMIT) { + const oldest = globalCandidatesCache.keys().next().value as string | undefined; + if (oldest !== undefined) globalCandidatesCache.delete(oldest); + } + const result = scanGlobalSkillCandidates(home, aidenDir, globalPluginConfigs).catch((error) => { + if (globalCandidatesCache.get(key)?.result === result) { + globalCandidatesCache.delete(key); } - return results.flat(); + throw error; + }); + globalCandidatesCache.set(key, { expires: now + DISCOVERY_CACHE_TTL_MS, result }); + return result; +} + +/** + * Discover skills from global and workspace skill directories. + * Roots scan in precedence order so workspace skills override global ones and, + * within a source, `.aiden` overrides `.claude`, which overrides `.agents`. + */ +async function scanAllSkillCandidates( + workspaceRoot: string | undefined, + home: string, + aidenDir: string, + testHooks: SkillDiscoveryTestHooks = {}, + useCachedGlobals = false, +): Promise { + try { + const pluginConfigs = await pluginScanConfigs(home, workspaceRoot); + const workspacePluginConfigs = pluginConfigs.filter((config) => config.source === "workspace"); + const globalPluginConfigs = pluginConfigs.filter((config) => config.source === "global"); + const useCache = useCachedGlobals && Object.keys(testHooks).length === 0; + const [workspaceSkills, globalSkills] = await Promise.all([ + workspaceRoot + ? scanWorkspaceSkillCandidates(workspaceRoot, workspacePluginConfigs, testHooks) + : Promise.resolve([] as DiscoveredSkill[]), + useCache + ? cachedGlobalSkillCandidates(home, aidenDir, globalPluginConfigs) + : scanGlobalSkillCandidates(home, aidenDir, globalPluginConfigs, testHooks), + ]); + return [...workspaceSkills, ...globalSkills]; } catch (error) { const projected = projectDiagnosticError(error); writeDiagnosticEvent({ @@ -499,11 +559,26 @@ export function discoverSkillCandidates( ): Promise { const home = homeDir ?? os.homedir(); const aidenDir = homeDir === undefined ? aidenConfigDir() : path.join(home, AIDEN_DIR_NAME); - return scanAllSkillCandidates(workspaceRoot, home, aidenDir, testHooks); + return scanAllSkillCandidates(workspaceRoot, home, aidenDir, testHooks, false); +} + +/** + * Discover skill candidates reusing a short-TTL cache for global roots/plugins + * while still scanning the requested workspace root fresh. Used by + * `SkillRegistry.snapshot` so opening a new worktree avoids rescanning global skills. + */ +export function discoverSkillCandidatesWithCachedGlobals( + workspaceRoot?: string, + homeDir?: string, +): Promise { + const home = homeDir ?? os.homedir(); + const aidenDir = homeDir === undefined ? aidenConfigDir() : path.join(home, AIDEN_DIR_NAME); + return scanAllSkillCandidates(workspaceRoot, home, aidenDir, {}, true); } export function invalidateSkillDiscoveryCache(): void { discoveryCache.clear(); + globalCandidatesCache.clear(); } /** diff --git a/main/services/workspace-worktree-application-service-main.ts b/main/services/workspace-worktree-application-service-main.ts index 14919bcf5e..6845af2aa6 100644 --- a/main/services/workspace-worktree-application-service-main.ts +++ b/main/services/workspace-worktree-application-service-main.ts @@ -5,6 +5,7 @@ import { ensureUserDataDir } from "./data-store.js"; import { gitApplyManagedWorktreeSnapshot, gitCaptureManagedWorktreeSnapshot, + gitCheckIgnoredPaths, gitCreateWorktree, gitDeleteManagedWorktree, gitDeleteManagedWorktreeSnapshotRef, @@ -24,6 +25,7 @@ import { gitRollbackWorktree, gitExpandManagedWorktreeIgnored, gitFetchWorktreeBase, + gitInvalidateWorktreeDisplayCache, gitLocalBranchNames, gitResolveWorktreeBase, gitRollbackOwnedWorktree, @@ -100,7 +102,10 @@ export const workspaceWorktreeApplicationService = createWorkspaceWorktreeApplic await checkSnapshotCapacity(root, estimatedBytes); }, provisionIncludedFiles: (options) => - provisionWorktreeIncludedFiles({ listFiles: gitListFiles }, options), + provisionWorktreeIncludedFiles( + { listFiles: gitListFiles, checkIgnored: gitCheckIgnoredPaths }, + options, + ), repositoryPaths: gitRepositoryPaths, dirtyState: gitManagedWorktreeDirtyState, expandIgnoredPaths: gitExpandManagedWorktreeIgnored, @@ -151,12 +156,16 @@ export const workspaceWorktreeApplicationService = createWorkspaceWorktreeApplic resumeWorkspaceSchedules: (workspaceId) => scheduleService.resumeWorkspace(workspaceId), createWorkspaceId: defaultWorkspaceId, now: Date.now, - notifyChanged: () => ipcMain.broadcast("workspaces:changed", {}), + notifyChanged: (createdWorkspace) => + ipcMain.broadcast( + "workspaces:changed", + createdWorkspace ? { kind: "created", workspace: createdWorkspace } : {}, + ), logError: (area, message, error) => logger.error(area, message, error), // WorktreeSetup hooks: the source workspace's, run in the new worktree. onWorktreeCreated: async (event) => { - const { runWorktreeSetupHooks } = await import("./agent-surface-hooks.js"); - const notices = await runWorktreeSetupHooks({ + const { runWorktreeSetupHooksWithResult } = await import("./agent-surface-hooks.js"); + const { notices, ranHooks } = await runWorktreeSetupHooksWithResult({ sourceFolderPath: event.sourceFolderPath, sourceRoot: event.sourceRoot, worktreePath: event.worktreePath, @@ -164,6 +173,9 @@ export const workspaceWorktreeApplicationService = createWorkspaceWorktreeApplic workspaceId: event.workspace.id, branch: event.branch, }); + if (ranHooks.length > 0) { + await gitInvalidateWorktreeDisplayCache(event.worktreePath); + } for (const notice of notices) logger.warn("hooks", notice); }, }); diff --git a/main/services/workspace-worktree-application-service.test.ts b/main/services/workspace-worktree-application-service.test.ts index a6e34dadd3..976ef2f3ab 100644 --- a/main/services/workspace-worktree-application-service.test.ts +++ b/main/services/workspace-worktree-application-service.test.ts @@ -19,6 +19,7 @@ test("shared managed-worktree workflow preserves creation rollback gates and des let failProvisioning = false; const events: string[] = []; const createAdmissions: Array<[string, number]> = []; + const createReserves: Array = []; const allocations: Array<[string, string, number]> = []; const source: Workspace = { id: "workspace-source", @@ -86,8 +87,9 @@ test("shared managed-worktree workflow preserves creation rollback gates and des throw new Error("unexpected resume"); }, applyWorktreeSnapshot: async () => undefined, - createWorktree: async (folderPath, root, branch) => { + createWorktree: async (folderPath, root, branch, _signal, options) => { events.push(`create:${folderPath}:${root}:${branch}`); + createReserves.push(options?.additionalAllocationBytes); return { path: "/aiden/worktrees/mobile", workspacePath: "/aiden/worktrees/mobile", @@ -193,8 +195,10 @@ test("shared managed-worktree workflow preserves creation rollback gates and des ]); assert.equal(designGrants.resolve(worktreeGrant), null, "deleting the worktree ends its design grants"); assert.notEqual(designGrants.resolve(sourceGrant), null); - assert.deepEqual(allocations, [["/aiden/worktrees", "/canonical/source/.git", 1024 + MAX_PROVISIONED_BYTES]]); - assert.deepEqual(createAdmissions, [["/aiden/worktrees/mobile", MAX_PROVISIONED_BYTES]]); + const expectedReserve = process.platform === "darwin" ? MAX_PROVISIONED_BYTES : 0; + assert.deepEqual(allocations, [], "create delegates combined allocation admission to createWorktree"); + assert.deepEqual(createReserves, [expectedReserve > 0 ? expectedReserve : undefined]); + assert.deepEqual(createAdmissions, [["/aiden/worktrees/mobile", expectedReserve]]); // A deletion that fails still closes the watcher; the next read re-observes. const again = await service.create(owner, source.id, "feature/retry", "Retry Workspace"); diff --git a/main/services/workspace-worktree-application-service.ts b/main/services/workspace-worktree-application-service.ts index d790814169..5f63013a59 100644 --- a/main/services/workspace-worktree-application-service.ts +++ b/main/services/workspace-worktree-application-service.ts @@ -48,7 +48,11 @@ export interface WorkspaceWorktreeApplicationDependencies { root: string, branch: string, signal?: AbortSignal, - options?: { startPoint?: string; ownershipToken?: string }, + options?: { + startPoint?: string; + ownershipToken?: string; + additionalAllocationBytes?: number; + }, ): Promise; /** Validate a chosen base branch. Required only by `createFromBase`. */ resolveWorktreeBase?(folderPath: string, baseRef: string, signal?: AbortSignal): Promise; @@ -165,7 +169,7 @@ export interface WorkspaceWorktreeApplicationDependencies { resumeWorkspaceSchedules(workspaceId: string): Promise; createWorkspaceId(): string; now(): number; - notifyChanged(): void; + notifyChanged(createdWorkspace?: Workspace): void; logError(area: string, message: string, error: unknown): void; /** * Runs once a new managed worktree is saved (the `WorktreeSetup` hook). @@ -302,30 +306,26 @@ export function createWorkspaceWorktreeApplicationService( identity?: { workspaceId: string; ownershipToken: string }, ): Promise => { const worktreeRoot = await dependencies.ensureWorktreeRoot(); - // Admit checkout allocation before creating its directory or Git branch. - // ensureWorktreeRoot may already have created the empty managed root. - const estimatedBytes = await dependencies.checkoutBytes(resolved.folderPath, start?.commit); - // Reserve room for the `.worktreeinclude` copies too. + // Reserve room for `.worktreeinclude` copies too; `createWorktree` enforces + // the combined checkout + reserve allocation atomically inside the + // repository's mutation queue before creating directories or Git refs. const provisionedReserve = provisionedFilesReserve(); - const repository = await dependencies.repositoryPaths(resolved.folderPath); - await dependencies.checkWorktreeAllocation(worktreeRoot, repository.commonDir, estimatedBytes + provisionedReserve); + const createOptions = { + ...(start ? { startPoint: start.point } : {}), + ...(identity ? { ownershipToken: identity.ownershipToken } : {}), + ...(provisionedReserve > 0 ? { additionalAllocationBytes: provisionedReserve } : {}), + }; const worktree = await dependencies.createWorktree( resolved.folderPath, worktreeRoot, branch, signal, - ...(start || identity - ? [{ - ...(start ? { startPoint: start.point } : {}), - ...(identity ? { ownershipToken: identity.ownershipToken } : {}), - }] - : []), + ...(Object.keys(createOptions).length > 0 ? [createOptions] : []), ); const provisionedFiles: string[] = []; - let sourceRoot = repository.topLevel; + const sourceRoot = worktree.repositoryPath; try { await dependencies.checkCreateCapacity(worktree.path, provisionedReserve); - sourceRoot = (await dependencies.repositoryPaths(resolved.folderPath)).topLevel; await dependencies.provisionIncludedFiles({ sourceRoot, worktreePath: worktree.path, @@ -396,7 +396,7 @@ export function createWorkspaceWorktreeApplicationService( provisionedIgnored: provisionedFiles, }), }); - dependencies.notifyChanged(); + dependencies.notifyChanged(saved); await announceCreated({ workspace: saved, workspacePath: worktree.workspacePath, @@ -445,54 +445,89 @@ export function createWorkspaceWorktreeApplicationService( throw new Error("Choose a branch name for the new worktree."); } return dependencies.environment.run(owner, sourceWorkspaceId, async (resolved, signal) => { - const base = await resolveWorktreeBase(resolved.folderPath, request.baseRef, signal); - // Start at the resolved commit itself, so what is recorded before - // creation is exactly what the worktree starts at. - let start = { point: base.commit, commit: base.commit }; - let startPoint = base.name; - let baseSource: FirstMessageWorktreeBaseSource = "local"; + const finalizeFromBase = async ( + start: { point: string; commit: string }, + startPoint: string, + baseSource: FirstMessageWorktreeBaseSource, + existing: string[], + ): Promise => { + let branch = request.branchName; + if (branch === undefined) { + branch = uniqueBranchName(autoWorktreeBranchName(request.autoName!.seed), existing); + if (!branch) throw new Error("Aiden could not find a free branch name for the new worktree."); + } else if (uniqueBranchName(branch, existing, 1) !== branch) { + // Refuse before anything is recorded, so a caller never associates an + // existing branch (or another worktree on it) with this attempt. + throw new Error(`Branch “${branch}” already exists.`); + } + if (signal.aborted) throw new Error("The worktree was cancelled before it was created."); + const identity = { workspaceId: dependencies.createWorkspaceId(), ownershipToken: randomUUID() }; + await request.onBranchResolved?.({ branch, ...identity, baseCommit: start.commit, startPoint, baseSource }); + request.onProgress?.({ phase: "creating", branch, startPoint }); + const workspace = await createIn( + resolved, + signal, + sourceWorkspaceId, + branch, + request.requestedName, + start, + identity, + ); + return { + workspace, + branch, + startPoint, + baseCommit: workspace.managedWorktree?.createdFromHead ?? start.commit, + baseSource, + }; + }; + + const runPaired = async ( + first: (pairedSignal: AbortSignal) => Promise, + second: (pairedSignal: AbortSignal) => Promise, + ): Promise<[A, B]> => { + const controller = new AbortController(); + const forwardAbort = () => controller.abort(); + if (signal.aborted) controller.abort(); + else signal.addEventListener("abort", forwardAbort, { once: true }); + try { + const firstPromise = Promise.resolve().then(() => first(controller.signal)); + const secondPromise = Promise.resolve().then(() => second(controller.signal)); + void firstPromise.catch(() => controller.abort()); + void secondPromise.catch(() => controller.abort()); + const [firstOutcome, secondOutcome] = await Promise.allSettled([ + firstPromise, + secondPromise, + ]); + if (firstOutcome.status === "rejected") throw firstOutcome.reason; + if (secondOutcome.status === "rejected") throw secondOutcome.reason; + return [firstOutcome.value, secondOutcome.value]; + } finally { + signal.removeEventListener("abort", forwardAbort); + } + }; + if (request.fromOrigin) { + const base = await resolveWorktreeBase(resolved.folderPath, request.baseRef, signal); + // Start at the resolved commit itself, so what is recorded before + // creation is exactly what the worktree starts at. if (base.upstream) { const remoteName = `${base.upstream.remote}/${base.upstream.branch}`; request.onProgress?.({ phase: "fetching", startPoint: remoteName }); - const commit = await fetchWorktreeBase(resolved.folderPath, base.upstream, signal); - start = { point: commit, commit }; - startPoint = remoteName; - baseSource = "fetched"; - } else { - baseSource = "no-upstream"; + const [commit, existing] = await runPaired( + (pairedSignal) => fetchWorktreeBase(resolved.folderPath, base.upstream!, pairedSignal), + (pairedSignal) => localBranchNames(resolved.folderPath, pairedSignal), + ); + return await finalizeFromBase({ point: commit, commit }, remoteName, "fetched", existing); } + const existing = await localBranchNames(resolved.folderPath, signal); + return await finalizeFromBase({ point: base.commit, commit: base.commit }, base.name, "no-upstream", existing); } - const existing = await localBranchNames(resolved.folderPath, signal); - let branch = request.branchName; - if (branch === undefined) { - branch = uniqueBranchName(autoWorktreeBranchName(request.autoName!.seed), existing); - if (!branch) throw new Error("Aiden could not find a free branch name for the new worktree."); - } else if (uniqueBranchName(branch, existing, 1) !== branch) { - // Refuse before anything is recorded, so a caller never associates an - // existing branch (or another worktree on it) with this attempt. - throw new Error(`Branch “${branch}” already exists.`); - } - if (signal.aborted) throw new Error("The worktree was cancelled before it was created."); - const identity = { workspaceId: dependencies.createWorkspaceId(), ownershipToken: randomUUID() }; - await request.onBranchResolved?.({ branch, ...identity, baseCommit: start.commit, startPoint, baseSource }); - request.onProgress?.({ phase: "creating", branch, startPoint }); - const workspace = await createIn( - resolved, - signal, - sourceWorkspaceId, - branch, - request.requestedName, - start, - identity, + const [base, existing] = await runPaired( + (pairedSignal) => resolveWorktreeBase(resolved.folderPath, request.baseRef, pairedSignal), + (pairedSignal) => localBranchNames(resolved.folderPath, pairedSignal), ); - return { - workspace, - branch, - startPoint, - baseCommit: workspace.managedWorktree?.createdFromHead ?? start.commit, - baseSource, - }; + return await finalizeFromBase({ point: base.commit, commit: base.commit }, base.name, "local", existing); }); }; diff --git a/native/worktree-file-io/main.c b/native/worktree-file-io/main.c index f13f331bb0..54ff5d6469 100644 --- a/native/worktree-file-io/main.c +++ b/native/worktree-file-io/main.c @@ -5,13 +5,16 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include +#include #include #ifndef O_CLOEXEC @@ -630,7 +633,368 @@ static int save_file(int argc, char **argv) { return ferror(stdout) ? fail("io_failed") : 0; } +#define MAX_PROVISION_PATHS 4096U +#define MAX_PROVISION_STDIN_BYTES (MAX_PROVISION_PATHS * (MAX_RELATIVE_PATH + 1U)) +#define MAX_PROVISION_SYNC_DIRS 64U + +static volatile sig_atomic_t provision_interrupted = 0; + +static void handle_provision_sigterm(int sig) { + (void)sig; + provision_interrupted = 1; +} + +static int same_provision_source(const struct stat *before, const struct stat *after) { + return same_source(before, after) && + before->st_mode == after->st_mode && + before->st_flags == after->st_flags && + before->st_ctimespec.tv_sec == after->st_ctimespec.tv_sec && + before->st_ctimespec.tv_nsec == after->st_ctimespec.tv_nsec; +} + +typedef struct { + dev_t dev; + ino_t ino; + int fd; +} ProvisionSyncDir; + +static int provision_try_clone(int source, const struct stat *before, + int target_parent, const struct stat *parent_stat, + const char *target_leaf, mode_t mode, + const char **error_out) { + /* Clone only when source is a plain regular file on the same APFS volume + * with no special mode bits, BSD flags, or extended attributes, and is + * owner-readable (so reopening the CLONE_NOOWNERCOPY temp fd succeeds). */ + if (before->st_flags != 0 || + (before->st_mode & 07000) != 0 || + (before->st_mode & 0400) == 0 || + before->st_dev != parent_stat->st_dev || + flistxattr(source, NULL, 0, 0) != 0) { + return 0; /* fall back to read/write */ + } + unsigned char nonce[16]; + arc4random_buf(nonce, sizeof(nonce)); + char suffix[sizeof(nonce) * 2 + 1]; + for (size_t i = 0; i < sizeof(nonce); i++) snprintf(suffix + i * 2, 3, "%02x", nonce[i]); + char temporary[64]; + snprintf(temporary, sizeof(temporary), ".aiden-prov-%s.tmp", suffix); + + if (fclonefileat(source, target_parent, temporary, + CLONE_NOFOLLOW | CLONE_NOOWNERCOPY) != 0) { + int err = errno; + if (err == EXDEV || err == ENOTSUP || err == EOPNOTSUPP || + err == EINVAL || err == ENOSYS || err == EACCES || err == EPERM) { + return 0; /* fall back to read/write */ + } + *error_out = "io_failed"; + return -1; + } + + int cloned = openat(target_parent, temporary, + O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC); + struct stat dst_stat, after; + /* Clear BSD flags BEFORE fchmod/unlink so a concurrent chflags uchg race on + * source never strands an immutable temp file inside the worktree. Also check + * flistxattr on cloned to catch concurrent setxattr between check and clone. */ + int good = cloned >= 0 && + fchflags(cloned, 0) == 0 && + fstat(cloned, &dst_stat) == 0 && + S_ISREG(dst_stat.st_mode) && + dst_stat.st_nlink == 1 && + dst_stat.st_size == before->st_size && + flistxattr(cloned, NULL, 0, 0) == 0 && + fchmod(cloned, mode) == 0 && + fsync(cloned) == 0 && + fstat(source, &after) == 0 && + same_provision_source(before, &after); + if (cloned >= 0) close(cloned); + if (provision_interrupted) { + (void)unlinkat(target_parent, temporary, 0); + *error_out = "io_failed"; + return -1; + } + if (!good) { + (void)unlinkat(target_parent, temporary, 0); + *error_out = "source_changed"; + return -1; + } + if (renameatx_np(target_parent, temporary, target_parent, target_leaf, + RENAME_EXCL) != 0) { + int err = errno; + (void)unlinkat(target_parent, temporary, 0); + *error_out = err == EEXIST ? "destination_exists" : "unsafe_destination"; + return -1; + } + return 1; +} + +/* provision + * Batch-copy NUL-delimited relative paths read from stdin into a freshly + * created managed worktree. Preserves descriptor-relative no-follow traversal, + * regular-file checks, cumulative byte limits, source-change checks, and + * exclusive destination creation, while avoiding per-file process spawns, + * SHA-256 hashing, and per-file fsync barriers (using APFS CoW clones when + * eligible and syncing each unique destination parent directory once). */ +static int provision_files(int argc, char **argv) { + uint64_t source_device, source_inode, target_device, target_inode, total_limit; + if (argc != 9 || + !decimal(argv[3], &source_device) || !decimal(argv[4], &source_inode) || + !decimal(argv[6], &target_device) || !decimal(argv[7], &target_inode) || + !decimal(argv[8], &total_limit) || total_limit > MAX_FILE_BYTES) { + return fail("invalid_input"); + } + if (source_device == target_device && source_inode == target_inode) { + return fail("unsafe_source"); + } + + /* Catch SIGTERM gracefully so an aborted batch unlinks any partial temp/leaf + * and always emits `p` for every file already installed on disk. */ + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = handle_provision_sigterm; + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + (void)sigaction(SIGTERM, &sa, NULL); + + /* Read NUL-delimited relative paths from stdin with strict size/count bounds. + * Allow reading 1 byte past MAX_PROVISION_STDIN_BYTES so exact-limit input + * cleanly observes EOF instead of rejecting on buffer full. */ + const size_t max_read_cap = (size_t)MAX_PROVISION_STDIN_BYTES + 1U; + size_t capacity = 4096; + size_t length = 0; + char *stdin_buf = malloc(capacity); + if (stdin_buf == NULL) return fail("io_failed"); + for (;;) { + if (provision_interrupted) { free(stdin_buf); return fail("io_failed"); } + if (length == capacity) { + if (capacity >= max_read_cap) { + free(stdin_buf); + return fail("invalid_input"); + } + size_t next_cap = capacity * 2; + if (next_cap > max_read_cap) next_cap = max_read_cap; + char *grown = realloc(stdin_buf, next_cap); + if (grown == NULL) { free(stdin_buf); return fail("io_failed"); } + stdin_buf = grown; + capacity = next_cap; + } + ssize_t got = read(STDIN_FILENO, stdin_buf + length, capacity - length); + if (got < 0 && errno == EINTR) continue; + if (got < 0) { free(stdin_buf); return fail("io_failed"); } + if (got == 0) break; + length += (size_t)got; + if (length > MAX_PROVISION_STDIN_BYTES) { + free(stdin_buf); + return fail("invalid_input"); + } + } + + const char **paths = NULL; + size_t path_count = 0; + if (length > 0) { + if (stdin_buf[length - 1] != '\0') { + free(stdin_buf); + return fail("invalid_input"); + } + paths = malloc(MAX_PROVISION_PATHS * sizeof(const char *)); + if (paths == NULL) { free(stdin_buf); return fail("io_failed"); } + size_t cursor = 0; + while (cursor < length) { + if (path_count >= MAX_PROVISION_PATHS) { + free(paths); free(stdin_buf); + return fail("invalid_input"); + } + const char *entry = stdin_buf + cursor; + size_t entry_len = strlen(entry); + if (!valid_relative(entry)) { + free(paths); free(stdin_buf); + return fail("invalid_input"); + } + paths[path_count++] = entry; + cursor += entry_len + 1; + } + } + + int source_root = open_root(argv[2], source_device, source_inode); + if (source_root < 0) { + free(paths); free(stdin_buf); + return fail("unsafe_source"); + } + int target_root = open_root(argv[5], target_device, target_inode); + if (target_root < 0) { + close(source_root); free(paths); free(stdin_buf); + return fail("unsafe_destination"); + } + + ProvisionSyncDir sync_dirs[MAX_PROVISION_SYNC_DIRS]; + size_t sync_dir_count = 0; + uint64_t total_bytes = 0; + const char *error_reason = NULL; + unsigned char buffer[BUFFER_BYTES]; + + for (size_t i = 0; i < path_count; i++) { + if (provision_interrupted) { error_reason = "io_failed"; goto cleanup; } + const char *relative = paths[i]; + char source_leaf[MAX_RELATIVE_PATH + 1]; + int source_parent = parent_at(source_root, relative, 0, source_leaf); + if (source_parent < 0) { error_reason = "unsafe_source"; goto cleanup; } + if (test_checkpoint('S') != 0) { + close(source_parent); error_reason = "io_failed"; goto cleanup; + } + int source = openat(source_parent, source_leaf, + O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC); + close(source_parent); + struct stat before, after; + if (source < 0 || fstat(source, &before) != 0 || !S_ISREG(before.st_mode) || + before.st_size < 0) { + if (source >= 0) close(source); + error_reason = "unsafe_source"; + goto cleanup; + } + uint64_t remaining = total_limit - total_bytes; + if ((uint64_t)before.st_size > remaining) { + close(source); + error_reason = "too_many_bytes"; + goto cleanup; + } + + char target_leaf[MAX_RELATIVE_PATH + 1]; + int target_parent = parent_at(target_root, relative, 1, target_leaf); + if (target_parent < 0) { close(source); error_reason = "unsafe_destination"; goto cleanup; } + if (test_checkpoint('D') != 0) { + close(source); close(target_parent); error_reason = "io_failed"; goto cleanup; + } + struct stat parent_stat; + if (fstat(target_parent, &parent_stat) != 0 || !S_ISDIR(parent_stat.st_mode)) { + close(source); close(target_parent); error_reason = "unsafe_destination"; goto cleanup; + } + + struct stat existing; + if (fstatat(target_parent, target_leaf, &existing, AT_SYMLINK_NOFOLLOW) == 0) { + close(source); close(target_parent); error_reason = "destination_exists"; goto cleanup; + } + if (errno != ENOENT) { + close(source); close(target_parent); error_reason = "unsafe_destination"; goto cleanup; + } + if (provision_interrupted) { + close(source); close(target_parent); error_reason = "io_failed"; goto cleanup; + } + + mode_t mode = before.st_mode & 0777; + uint64_t copied = 0; + const char *clone_err = NULL; + int cloned = provision_try_clone(source, &before, target_parent, &parent_stat, + target_leaf, mode, &clone_err); + if (cloned < 0) { + close(source); close(target_parent); error_reason = clone_err ? clone_err : "io_failed"; goto cleanup; + } + if (cloned == 1) { + copied = (uint64_t)before.st_size; + close(source); + } else { + int target = openat(target_parent, target_leaf, + O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600); + if (target < 0) { + int err = errno; + close(source); close(target_parent); + error_reason = err == EEXIST ? "destination_exists" : "unsafe_destination"; + goto cleanup; + } + int io_err = 0; + int src_err = 0; + while (copied < (uint64_t)before.st_size) { + if (provision_interrupted) { io_err = 1; break; } + size_t amount = (uint64_t)before.st_size - copied < BUFFER_BYTES + ? (size_t)((uint64_t)before.st_size - copied) : BUFFER_BYTES; + ssize_t received = read(source, buffer, amount); + if (received < 0 && errno == EINTR) continue; + if (received <= 0) { src_err = 1; break; } + size_t written = 0; + while (written < (size_t)received) { + if (provision_interrupted) { io_err = 1; break; } + ssize_t count = write(target, buffer + written, (size_t)received - written); + if (count < 0 && errno == EINTR) continue; + if (count <= 0) { io_err = 1; break; } + written += (size_t)count; + } + if (io_err) break; + copied += (uint64_t)received; + } + if (!io_err && !src_err && + (fstat(source, &after) != 0 || !same_provision_source(&before, &after) || + copied != (uint64_t)before.st_size)) { + src_err = 1; + } + if (!io_err && !src_err && (fchmod(target, mode) != 0 || fsync(target) != 0)) io_err = 1; + if (!io_err && !src_err && provision_interrupted) io_err = 1; + close(target); + close(source); + if (io_err || src_err) { + (void)unlinkat(target_parent, target_leaf, 0); + close(target_parent); + error_reason = io_err ? "io_failed" : "source_changed"; + goto cleanup; + } + } + + total_bytes += copied; + /* Report each installed file immediately (even if SIGTERM just arrived) so + * the caller's rollback set matches every file installed on disk 1:1. */ + fprintf(stdout, "p %zu %" PRIu64 "\n", i, copied); + if (fflush(stdout) != 0 || ferror(stdout)) { + close(target_parent); + error_reason = "io_failed"; + goto cleanup; + } + + /* Deduplicate parent directory fsyncs across the batch while bounding open FDs. */ + int tracked = 0; + for (size_t d = 0; d < sync_dir_count; d++) { + if (sync_dirs[d].dev == parent_stat.st_dev && sync_dirs[d].ino == parent_stat.st_ino) { + tracked = 1; + break; + } + } + if (tracked) { + close(target_parent); + } else if (sync_dir_count < MAX_PROVISION_SYNC_DIRS) { + sync_dirs[sync_dir_count].dev = parent_stat.st_dev; + sync_dirs[sync_dir_count].ino = parent_stat.st_ino; + sync_dirs[sync_dir_count].fd = target_parent; + sync_dir_count++; + } else { + int synced = fsync(target_parent) == 0; + close(target_parent); + if (!synced) { error_reason = "io_failed"; goto cleanup; } + } + if (provision_interrupted) { error_reason = "io_failed"; goto cleanup; } + } + + for (size_t d = 0; d < sync_dir_count; d++) { + int synced = fsync(sync_dirs[d].fd) == 0; + close(sync_dirs[d].fd); + sync_dirs[d].fd = -1; + if (!synced && error_reason == NULL) error_reason = "io_failed"; + } + sync_dir_count = 0; + if (error_reason != NULL) goto cleanup; + + fprintf(stdout, "done\n"); + if (fflush(stdout) != 0 || ferror(stdout)) error_reason = "io_failed"; + +cleanup: + for (size_t d = 0; d < sync_dir_count; d++) { + if (sync_dirs[d].fd >= 0) close(sync_dirs[d].fd); + } + close(target_root); + close(source_root); + free(paths); + free(stdin_buf); + return error_reason ? fail(error_reason) : 0; +} + int main(int argc, char **argv) { + if (argc >= 2 && strcmp(argv[1], "provision") == 0) return provision_files(argc, argv); if (argc >= 2 && strcmp(argv[1], "save") == 0) return save_file(argc, argv); if (argc >= 2 && strcmp(argv[1], "list") == 0) return list_directory(argc, argv); if (argc >= 2 && strcmp(argv[1], "read") == 0) return editor_file(argc, argv, 0); diff --git a/packages/cli/src/remote-worktrees.ts b/packages/cli/src/remote-worktrees.ts index edcbdec9a8..7cf4efc5dd 100644 --- a/packages/cli/src/remote-worktrees.ts +++ b/packages/cli/src/remote-worktrees.ts @@ -1,7 +1,7 @@ import * as fs from "node:fs/promises"; import { randomUUID } from "node:crypto"; import { createWorkspaceWorktreeApplicationService } from "../../../main/services/workspace-worktree-application-service.js"; -import { runWorktreeSetupHooks } from "../../../main/services/agent-surface-hooks.js"; +import { runWorktreeSetupHooksWithResult } from "../../../main/services/agent-surface-hooks.js"; import { checkCreateCapacity, checkSnapshotCapacity, checkWorktreeAllocation } from "../../../main/services/managed-worktree-capacity.js"; import { provisionWorktreeIncludedFiles } from "../../../main/services/managed-worktree-provisioner.js"; import type { createCliWorkspaceApplication } from "./workspace-application.ts"; @@ -62,7 +62,13 @@ return createWorkspaceWorktreeApplicationService({ await checkSnapshotCapacity(root, estimatedBytes); }, provisionIncludedFiles: (options) => - provisionWorktreeIncludedFiles({ listFiles: (folderPath, args) => git.listFiles(folderPath, args) }, options), + provisionWorktreeIncludedFiles( + { + listFiles: (folderPath, args) => git.listFiles(folderPath, args), + checkIgnored: (folderPath, paths, signal) => git.checkIgnoredPaths(folderPath, paths, signal), + }, + options, + ), repositoryPaths: (folderPath) => git.repositoryPaths(folderPath), dirtyState: (repositoryPath, worktreePath) => git.managedWorktreeDirtyState(repositoryPath, worktreePath), expandIgnoredPaths: (repositoryPath, worktreePath, ignoredPaths) => @@ -103,10 +109,13 @@ return createWorkspaceWorktreeApplicationService({ logError: (area, message) => process.stderr.write(`aiden: ${area}: ${message}\n`), // WorktreeSetup hooks: the source workspace's, run in the new worktree. onWorktreeCreated: async (event) => { - const notices = await runWorktreeSetupHooks({ + const { notices, ranHooks } = await runWorktreeSetupHooksWithResult({ sourceFolderPath: event.sourceFolderPath, sourceRoot: event.sourceRoot, worktreePath: event.worktreePath, workspacePath: event.workspacePath, workspaceId: event.workspace.id, branch: event.branch, }); + if (ranHooks.length > 0) { + await git.invalidateWorktreeDisplayCache(event.worktreePath); + } for (const notice of notices) process.stderr.write(`aiden: hooks: ${notice}\n`); }, }); diff --git a/renderer/components/chat-sidebar.tsx b/renderer/components/chat-sidebar.tsx index efffe2be80..503153be79 100644 --- a/renderer/components/chat-sidebar.tsx +++ b/renderer/components/chat-sidebar.tsx @@ -69,7 +69,7 @@ import { MAX_SIDEBAR_PULL_REQUEST_CHATS } from "../shared/chat-pull-requests"; import type { ChatTriageEntry } from "../shared/chat-triage"; import { localComputerNoun } from "../shared/computer-noun"; import { useActiveWorkspace } from "../lib/workspace-context"; -import { useEnvironmentPanel } from "./environment-panel"; +import { useEnvironmentPanelCore } from "./environment-panel"; import type { ChatMeta, Workspace } from "../lib/types"; import { useCommandHandler, useCommandSystem } from "../lib/command-system"; import type { CommandId } from "../shared/keybindings"; @@ -482,7 +482,7 @@ function WorkspaceChatSidebar({ const pathname = useRouterState({ select: (state) => state.location.pathname }); const qc = useQueryClient(); const { workspaces, activeId, select, isReady: workspaceRegistryReady } = useActiveWorkspace(); - const environmentPanel = useEnvironmentPanel(); + const environmentPanel = useEnvironmentPanelCore(); const chatActivity = useChatActivityState(); const readMarkers = useChatReadMarkers(); const appendReconciliationRequired = useAppendReconciliationRequired(); diff --git a/renderer/components/draft-worktree-send-view.tsx b/renderer/components/draft-worktree-send-view.tsx index 4f197011e3..b53da330de 100644 --- a/renderer/components/draft-worktree-send-view.tsx +++ b/renderer/components/draft-worktree-send-view.tsx @@ -12,6 +12,80 @@ import { worktreeProgressText } from "../lib/draft-git-menu"; import type { WorktreeSendDecision, WorktreeSendView } from "../lib/draft-worktree-send"; import { pauseWhenUnseen } from "../lib/offscreen-pause"; +export function DraftWorktreeSendStatus({ + view, + onDecide, +}: { + view: WorktreeSendView; + onDecide: (decision: WorktreeSendDecision) => void; +}) { + return view.status === "failed" ? ( +
+
+
+
+ {view.existing ? ( + + ) : ( + + )} + + +
+
+ ) : ( +
+ {view.progress.phase === "ready" && view.status === "running" ? ( +
+ ); +} + export function DraftWorktreeSendView({ text, attachments, @@ -36,71 +110,7 @@ export function DraftWorktreeSendView({ attachments={attachments.length > 0 ? [...attachments] : undefined} inputSource={inputSource} /> - {view.status === "failed" ? ( -
-
-
-
- {view.existing ? ( - - ) : ( - - )} - - -
-
- ) : ( -
- {view.progress.phase === "ready" && view.status === "running" ? ( -
- )} + ); } diff --git a/renderer/components/environment-panel.tsx b/renderer/components/environment-panel.tsx index 1ff902ac2f..bc969e9ec2 100644 --- a/renderer/components/environment-panel.tsx +++ b/renderer/components/environment-panel.tsx @@ -255,6 +255,104 @@ export interface EnvironmentPanelContextValue { /** Exported so component tests can render a single surface against a stub panel. */ export const EnvironmentPanelContext = React.createContext(null); + +interface EnvironmentArtifactsContextValue { + artifacts: WorkspaceArtifactsState; + artifactsOffered: boolean; + selectedArtifactId: string | null; + selectArtifact: (artifactId: string | null) => void; +} + +const EnvironmentArtifactsContext = React.createContext(null); +const EMPTY_ARTIFACTS_STATE: WorkspaceArtifactsState = { + workspaceId: null, + views: [], + loaded: false, + error: null, + reload: () => undefined, + rememberState: () => undefined, +}; +const NOOP_SELECT_ARTIFACT = () => undefined; + +function EnvironmentArtifactsProvider({ + activeId, + activeChat, + artifactsTabOpen, + showTools, + closeArtifactsTab, + children, +}: { + activeId: string | undefined; + activeChat: EnvironmentActiveChat; + artifactsTabOpen: boolean; + showTools: (tab?: EnvironmentPanelTab, returnTarget?: HTMLElement | null) => void; + closeArtifactsTab: () => void; + children: React.ReactNode; +}) { + const [selectedArtifactId, setSelectedArtifactId] = React.useState(null); + const showToolsRef = React.useRef(showTools); + const activeChatRef = React.useRef(activeChat); + const activeWorkspaceRef = React.useRef(activeId); + React.useLayoutEffect(() => { + showToolsRef.current = showTools; + activeChatRef.current = activeChat; + activeWorkspaceRef.current = activeId; + }, [activeChat, activeId, showTools]); + const onArtifactsChanged = React.useCallback((event: WorkspaceArtifactsChangedEvent) => { + // The chat that made a page shows it; every other window just updates its list. + if (event.workspaceId !== activeWorkspaceRef.current) return; + if (!revealsWorkspaceArtifact(event, activeChatRef.current)) return; + setSelectedArtifactId(event.artifactId); + showToolsRef.current("artifacts"); + }, []); + const artifacts = useWorkspaceArtifacts(activeId ?? null, onArtifactsChanged); + // The launcher and ⌘K offer the tab once this workspace's list has loaded, pages or not. + const artifactsOffered = artifacts.loaded && artifacts.workspaceId !== null && artifacts.workspaceId === activeId; + const artifactsSeenRef = React.useRef<{ workspaceId: string | null; count: number } | null>(null); + React.useEffect(() => { + // Wait for a workspace and a list that actually loaded: a restored tab must + // survive startup, and a failed read is not an empty workspace. + if (artifacts.workspaceId === null || artifacts.workspaceId !== activeId) return; + if (!artifacts.loaded) return; + const previous = artifactsSeenRef.current; + if (artifacts.error) { + // Remember the workspace, so a tab opened on the failure isn't taken as + // a workspace switch when Try again then finds no pages. + const sameWorkspace = previous?.workspaceId === artifacts.workspaceId; + artifactsSeenRef.current = { workspaceId: artifacts.workspaceId, count: sameWorkspace ? previous.count : 0 }; + return; + } + const count = artifacts.views.length; + artifactsSeenRef.current = { workspaceId: artifacts.workspaceId, count }; + // The tab closes when the last page is deleted, or on a workspace that has + // none. Opened from the launcher on an empty workspace, it stays to show + // how to start a page. + const emptied = previous?.workspaceId !== artifacts.workspaceId || previous.count > 0; + if (count === 0 && emptied && artifactsTabOpen) closeArtifactsTab(); + }, [ + activeId, + artifacts.error, + artifacts.loaded, + artifacts.views.length, + artifacts.workspaceId, + artifactsTabOpen, + closeArtifactsTab, + ]); + const value = React.useMemo( + () => ({ + artifacts, + artifactsOffered, + selectedArtifactId, + selectArtifact: setSelectedArtifactId, + }), + [artifacts, artifactsOffered, selectedArtifactId], + ); + return ( + + {children} + + ); +} const TABS_STORAGE_KEY = "aiden-agent.environment.open-tabs-v1"; const OPEN_STORAGE_KEY = "aiden-agent.environment.open"; const QUICK_VIEW_OPEN_STORAGE_KEY = "aiden-agent.quick-view.open"; @@ -649,48 +747,10 @@ export function EnvironmentPanelProvider({ children }: React.PropsWithChildren) }); }, [devicesEnabled, revealChatId, showTools]); - const [selectedArtifactId, setSelectedArtifactId] = React.useState(null); - const showToolsRef = React.useRef(showTools); - const activeChatRef = React.useRef(activeChat); - const activeWorkspaceRef = React.useRef(activeId); - React.useLayoutEffect(() => { - showToolsRef.current = showTools; - activeChatRef.current = activeChat; - activeWorkspaceRef.current = activeId; - }, [activeChat, activeId, showTools]); - const onArtifactsChanged = React.useCallback((event: WorkspaceArtifactsChangedEvent) => { - // The chat that made a page shows it; every other window just updates its list. - if (event.workspaceId !== activeWorkspaceRef.current) return; - if (!revealsWorkspaceArtifact(event, activeChatRef.current)) return; - setSelectedArtifactId(event.artifactId); - showToolsRef.current("artifacts"); - }, []); - const artifacts = useWorkspaceArtifacts(activeId ?? null, onArtifactsChanged); - // The launcher and ⌘K offer the tab once this workspace's list has loaded, pages or not. - const artifactsOffered = artifacts.loaded && artifacts.workspaceId !== null && artifacts.workspaceId === activeId; - const artifactsSeenRef = React.useRef<{ workspaceId: string | null; count: number } | null>(null); const artifactsTabOpen = (surfaceState.openTabs ?? [surfaceState.toolsTab]).includes("artifacts"); - React.useEffect(() => { - // Wait for a workspace and a list that actually loaded: a restored tab must - // survive startup, and a failed read is not an empty workspace. - if (artifacts.workspaceId === null || artifacts.workspaceId !== activeId) return; - if (!artifacts.loaded) return; - const previous = artifactsSeenRef.current; - if (artifacts.error) { - // Remember the workspace, so a tab opened on the failure isn't taken as - // a workspace switch when Try again then finds no pages. - const sameWorkspace = previous?.workspaceId === artifacts.workspaceId; - artifactsSeenRef.current = { workspaceId: artifacts.workspaceId, count: sameWorkspace ? previous.count : 0 }; - return; - } - const count = artifacts.views.length; - artifactsSeenRef.current = { workspaceId: artifacts.workspaceId, count }; - // The tab closes when the last page is deleted, or on a workspace that has - // none. Opened from the launcher on an empty workspace, it stays to show - // how to start a page. - const emptied = previous?.workspaceId !== artifacts.workspaceId || previous.count > 0; - if (count === 0 && emptied && artifactsTabOpen) dispatchSurface({ type: "close-tab", tab: "artifacts" }); - }, [activeId, artifacts.error, artifacts.loaded, artifacts.views.length, artifacts.workspaceId, artifactsTabOpen]); + const closeArtifactsTab = React.useCallback(() => { + dispatchSurface({ type: "close-tab", tab: "artifacts" }); + }, []); const openReview = React.useCallback( (mode: EnvironmentReviewMode) => { @@ -1173,10 +1233,10 @@ export function EnvironmentPanelProvider({ children }: React.PropsWithChildren) tab, subagentsEnabled, devicesEnabled, - artifacts, - artifactsOffered, - selectedArtifactId, - selectArtifact: setSelectedArtifactId, + artifacts: EMPTY_ARTIFACTS_STATE, + artifactsOffered: false, + selectedArtifactId: null, + selectArtifact: NOOP_SELECT_ARTIFACT, reviewMode, fileRequest, closeAll, @@ -1282,9 +1342,6 @@ export function EnvironmentPanelProvider({ children }: React.PropsWithChildren) subagentViews, subagentsEnabled, devicesEnabled, - artifacts, - artifactsOffered, - selectedArtifactId, surfaceMode, surfaceState.frontSurface, surfaceState.quickViewOpen, @@ -1310,17 +1367,42 @@ export function EnvironmentPanelProvider({ children }: React.PropsWithChildren) detailRequest={subagentDetailAnnouncement} /> ) : null} - {children} + + {children} + ); } +/** + * Environment panel state without subscribing to volatile workspace artifact + * loads. Use in layout/chat surfaces that do not read `artifacts`, + * `artifactsOffered`, or `selectedArtifactId` so switching workspaces does not + * re-render them twice when `workspaceArtifacts:list` settles. + */ +export function useEnvironmentPanelCore(): EnvironmentPanelContextValue { + const context = React.useContext(EnvironmentPanelContext); + if (!context) + throw new Error("useEnvironmentPanelCore must be used inside EnvironmentPanelProvider."); + return context; +} + export function useEnvironmentPanel(): EnvironmentPanelContextValue { const context = React.useContext(EnvironmentPanelContext); + const artifactsContext = React.useContext(EnvironmentArtifactsContext); if (!context) throw new Error("useEnvironmentPanel must be used inside EnvironmentPanelProvider."); - return context; + return React.useMemo( + () => (artifactsContext ? { ...context, ...artifactsContext } : context), + [context, artifactsContext], + ); } function EnvironmentPanelSurface({ diff --git a/renderer/components/git-branch-picker.tsx b/renderer/components/git-branch-picker.tsx index 2d63557d63..ccdb1fdd20 100644 --- a/renderer/components/git-branch-picker.tsx +++ b/renderer/components/git-branch-picker.tsx @@ -136,9 +136,14 @@ export function GitBranchPicker({ const [busy, setBusy] = React.useState(false); const draftNewWorktree = draft?.gitMode === "worktree"; + // New worktree and an existing worktree replace the branch list with their own settings. + const showBranchList = + !draft || + (draft.gitMode !== "worktree" && !(draft.workIn.selectedWorktreeId && draft.workIn.source)); // A New worktree draft reads branches while closed too, to resolve its base. const branches = useGitBranches(workspaceId, open || draftNewWorktree); - const worktrees = useGitWorktrees(workspaceId, open); + // Only fetch the worktree list when the branch list rows that display worktree badges are visible. + const worktrees = useGitWorktrees(workspaceId, open && showBranchList && !createMode); const detached = branches.data?.detached ?? detachedProp; const unborn = branches.data?.unborn ?? unbornProp; const currentRef = branches.data?.current ?? branch; @@ -180,10 +185,6 @@ export function GitBranchPicker({ // On a draft, uncommitted changes keep this checkout on its branch: the // escape hatch is a new worktree, which starts clean. const draftDirty = Boolean(draft) && uncommitted > 0; - // New worktree and an existing worktree replace the branch list with their own settings. - const showBranchList = - !draft || - (draft.gitMode !== "worktree" && !(draft.workIn.selectedWorktreeId && draft.workIn.source)); const refresh = () => Promise.all([ diff --git a/renderer/components/history-nav.tsx b/renderer/components/history-nav.tsx index 8c7c976ec5..086886684d 100644 --- a/renderer/components/history-nav.tsx +++ b/renderer/components/history-nav.tsx @@ -4,7 +4,7 @@ import { useRouter, useRouterState } from "@tanstack/react-router"; import { ArrowLeft, ArrowRight } from "lucide-react"; -import { useEnvironmentPanel } from "./environment-panel"; +import { useEnvironmentPanelCore } from "./environment-panel"; import { Button, toast } from "./ui"; import { historyNavigationAvailability } from "../lib/history-navigation"; import { useShortcutBinding } from "../lib/command-system"; @@ -20,7 +20,7 @@ const UNAVAILABLE = "no-drag aria-disabled:opacity-45 aria-disabled:hover:bg-tra export function HistoryNavButtons() { const router = useRouter(); - const environmentPanel = useEnvironmentPanel(); + const environmentPanel = useEnvironmentPanelCore(); // The same protections as opening another chat or Settings from the sidebar: // the Files editor keeps unsaved text only while it is mounted, and leaving // mid-Git-operation would hide its outcome. These are action checks, not diff --git a/renderer/components/message-list.tsx b/renderer/components/message-list.tsx index 57af87bb33..4a7dc74205 100644 --- a/renderer/components/message-list.tsx +++ b/renderer/components/message-list.tsx @@ -11,6 +11,8 @@ import { latestWorkDetailsStart } from "../lib/work-details"; import type { WorkDetailsMode } from "../shared/appearance"; import { EventPresence } from "./event-presence"; import { SafeMessageBubble } from "./message-bubble"; +import { DraftWorktreeSendStatus } from "./draft-worktree-send-view"; +import type { ActiveWorktreeSend } from "../lib/draft-worktree-send"; import { AgentNoticeCard } from "./agent-notice-card"; import type { ReadAloudActionProps } from "./read-aloud-button"; import { ForkDisabledReasonContext, MessageForkContextMenu, type MessageForkAction } from "./fork-message-button"; @@ -154,6 +156,12 @@ interface MessageListProps { * in a fork is refused (a paired Mac's chat): that prompt offers no fork. */ forkBeforeFirstPrompt?: boolean; + /** + * Active first-message worktree creation state for an unsent draft. Rendered + * inside the same transcript container so promotion to persisted messages + * avoids unmounting and remounting the transcript and first user bubble. + */ + draftWorktreeSend?: ActiveWorktreeSend; /** Compact layout for narrow floating surfaces (omits main-window dock gutter). */ compact?: boolean; } @@ -527,6 +535,12 @@ interface SettledMessageRowProps { renderSettledUiVisual?: (visual: ChatUiVisualV1, message: ChatMessage) => React.ReactNode; /** False for a chat stored on a paired host: Save and Copy read this Mac's chats. */ storedImageActions?: boolean; + /** + * Keep `` mounted even before `onFork` is enabled, + * so a draft prompt row settles into `messages[0]` without remounting its + * bubble and attachments. + */ + keepForkWrapper?: boolean; } /** @@ -552,6 +566,7 @@ const SettledMessageRow = React.memo(function SettledMessageRow({ uiVisuals, renderSettledUiVisual, storedImageActions = true, + keepForkWrapper = false, }: SettledMessageRowProps) { const placements = message?.htmlArtifactPlacements; const visualPlacements = React.useMemo( @@ -657,8 +672,9 @@ const SettledMessageRow = React.memo(function SettledMessageRow({ )} ); - // A reply keeps its wrapper before it can fork, so settling does not remount it. - if (!fork && !assistant) return row; + // A reply (and a pending draft prompt that will settle with fork enabled) + // keeps its wrapper before it can fork, so settling does not remount it. + if (!fork && !assistant && !keepForkWrapper) return row; return ( {row} @@ -849,6 +865,7 @@ export function MessageList({ forkSummary, forkBeforeFirstPrompt = true, storedImageActions = true, + draftWorktreeSend, compact = false, }: MessageListProps) { const workDetails = useAppearancePreference("workDetails"); @@ -875,6 +892,7 @@ export function MessageList({ const settledReplyKeysRef = React.useRef>(new Set()); const liveKeyRef = React.useRef<{ base: string; key: string } | null>(null); const handedOffKeysRef = React.useRef(new Map()); + const draftPromptKeyActiveRef = React.useRef(false); const liveRunRef = React.useRef<{ promptId: string; handoffId: string | null } | null>(null); const chipFocusCaptureRef = React.useRef(null); const persistedAttachmentIds = React.useMemo(() => { @@ -1099,6 +1117,19 @@ export function MessageList({ : undefined; const promptMessageForLiveRow = startedFrom ?? (settlingIndex >= 0 ? messages[settlingIndex - 1] : messages[messages.length - 1]); + const showDraftWorktreeSend = + messages.length === 0 && streamingText === null && Boolean(draftWorktreeSend); + if (showDraftWorktreeSend) { + draftPromptKeyActiveRef.current = true; + } else if (draftPromptKeyActiveRef.current && messages.length > 0 && messages[0]?.role === "user") { + // Hand the draft prompt's key to the persisted first user message so the + // transcript settles in place without remounting the user's bubble. + handedOffKeysRef.current.set(messages[0].id, "draft-prompt"); + draftPromptKeyActiveRef.current = false; + } else if (!draftWorktreeSend) { + draftPromptKeyActiveRef.current = false; + } + // Every saved row's key is settled before the live row picks its own, so the // two never collide in one render. const settledRowKeys = new Map(); @@ -1176,6 +1207,32 @@ export function MessageList({ /> ) : null; + if (showDraftWorktreeSend && draftWorktreeSend) { + const pendingMessage: ChatMessage = { + id: "draft-prompt", + role: "user", + content: draftWorktreeSend.text, + attachments: draftWorktreeSend.attachments.length > 0 ? [...draftWorktreeSend.attachments] : undefined, + ...(draftWorktreeSend.inputSource ? { inputSource: draftWorktreeSend.inputSource } : {}), + createdAt: 0, + }; + transcriptRows.push( + , + ); + } + for (const [messageIndex, message] of messages.entries()) { if (message.id === settlingMessageId) { transcriptRows.push(liveRow); @@ -1230,16 +1287,21 @@ export function MessageList({ data-subagent-chip-focus-scope="true" // Chat text is data, never instructions: Aiden Live sees only how many messages there are. data-live-content="chat" + data-draft-worktree-send={showDraftWorktreeSend ? draftWorktreeSend!.view.status : undefined} > {transcriptRows} - + {showDraftWorktreeSend && draftWorktreeSend ? ( + + ) : ( + + )} {error ? ( diff --git a/renderer/design/design-layout.tsx b/renderer/design/design-layout.tsx index 05bfbe60a2..bb11a2b96c 100644 --- a/renderer/design/design-layout.tsx +++ b/renderer/design/design-layout.tsx @@ -2,7 +2,7 @@ import * as React from "react"; import { DesignModeBanner } from "../components/design-mode-banner"; import { EnvironmentWorkbench, - useEnvironmentPanel, + useEnvironmentPanelCore, type WorkbenchDesignState, } from "../components/environment-panel"; import { useSplitViewSidebar } from "../components/ui"; @@ -251,7 +251,7 @@ export function DesignLayout({ : pane === "canvas" ? Math.max(0, containerWidth - STACKED_DOCK_LANE) : null; - const { reportDesignDockInset } = useEnvironmentPanel(); + const { reportDesignDockInset } = useEnvironmentPanelCore(); React.useLayoutEffect(() => reportDesignDockInset(dockInset), [dockInset, reportDesignDockInset]); React.useLayoutEffect(() => () => reportDesignDockInset(null), [reportDesignDockInset]); diff --git a/renderer/lib/chat-draft-git-memory.ts b/renderer/lib/chat-draft-git-memory.ts index b71d172303..3eeaa0920d 100644 --- a/renderer/lib/chat-draft-git-memory.ts +++ b/renderer/lib/chat-draft-git-memory.ts @@ -98,3 +98,32 @@ export function resolveDraftWorktreeDefaults( ): { baseRef: string; fromOrigin: boolean } | undefined { return resolveWorktreeDefaults(repository, memory); } + +/** + * Seed a New worktree draft's base immediately from cached `GitInfo` so the + * composer can send on frame 1 without waiting for `git:branches`. When + * `git:branches` arrives, `useDraftWorktreeDefaults` still verifies or repairs + * any remembered branch that was deleted. + */ +export function seedDraftWorktreeFromGitInfo( + memory: ChatDraftGitMemory, + git: + | { + isRepo: boolean; + branch?: string; + detached?: boolean; + unborn?: boolean; + defaultBranch?: string; + hasRemote?: boolean; + } + | undefined, +): { baseRef: string; fromOrigin: boolean } | undefined { + if (!git?.isRepo || git.unborn) return undefined; + const baseRef = + memory.baseRef ?? git.defaultBranch ?? (!git.detached && git.branch ? git.branch : undefined); + if (!baseRef) return undefined; + return { + baseRef, + fromOrigin: Boolean(git.hasRemote) && (memory.fromOrigin ?? true), + }; +} diff --git a/renderer/lib/chat-draft.ts b/renderer/lib/chat-draft.ts index 308f44e341..9dd5553671 100644 --- a/renderer/lib/chat-draft.ts +++ b/renderer/lib/chat-draft.ts @@ -41,13 +41,17 @@ export interface ChatDraft { function rememberedGitState( workspaceId: string, gitMode?: ChatDraftGitMode, + fallbackWorktree?: ChatDraftWorktree, ): Pick { const memory = readChatDraftGitMemory(workspaceId); + const worktree = + fallbackWorktree ?? + (memory.baseRef + ? { baseRef: memory.baseRef, fromOrigin: memory.fromOrigin ?? false } + : undefined); return { gitMode: gitMode ?? memory.gitMode, - ...(memory.baseRef - ? { worktree: { baseRef: memory.baseRef, fromOrigin: memory.fromOrigin ?? false } } - : {}), + ...(worktree ? { worktree } : {}), }; } @@ -89,7 +93,7 @@ export function createChatDraft( workspaceId: string, id: string = newChatUuid(() => crypto.randomUUID()), initialText?: string, - options: { gitMode?: ChatDraftGitMode; ephemeral?: boolean } = {}, + options: { gitMode?: ChatDraftGitMode; worktree?: ChatDraftWorktree; ephemeral?: boolean } = {}, ): ChatDraft { if (drafts.has(id)) throw new Error("This draft already exists."); closedEmptyDrafts.delete(id); @@ -117,7 +121,7 @@ export function createChatDraft( sending: false, hasContent: Boolean(initialText?.trim()), ...(initialText ? { initialText } : {}), - ...rememberedGitState(workspaceId, options.gitMode), + ...rememberedGitState(workspaceId, options.gitMode, options.worktree), }; drafts.set(id, draft); notify(); diff --git a/renderer/lib/draft-worktree-send.test.ts b/renderer/lib/draft-worktree-send.test.ts index d78b96ed4c..117daec914 100644 --- a/renderer/lib/draft-worktree-send.test.ts +++ b/renderer/lib/draft-worktree-send.test.ts @@ -16,8 +16,10 @@ import { type ContinuedWorktreeTurn, type WorktreeSendView, } from "./draft-worktree-send"; -import type { Chat } from "./types"; +import type { Chat, Workspace } from "./types"; import type { FirstMessageWorktreeRequest } from "../shared/worktree-on-send"; +import { createChatDraft, discardChatDraft } from "./chat-draft"; +import { seedDraftWorktreeFromGitInfo } from "./chat-draft-git-memory"; // The draft's first send through the real `chatsApi` wrappers over a fake // main process: what is sent on each attempt, and what the user sees. @@ -397,3 +399,62 @@ test("a /visualize turn continued from another view still asks for a visual", () [["turn-v", true], ["turn-plain", false]], ); }); + +test("a successful worktree send forwards the created workspace record inline", async () => { + const workspace: Workspace = { + id: "ws-worktree", + name: "repo · aiden/fix-the-login-bug", + folderPath: "/tmp/wt", + permission: "ask", + createdAt: 10, + updatedAt: 10, + }; + replies.push({ ok: true, chat: savedChat("ws-worktree"), worktree: WORKTREE_INFO, workspace }); + const send = start([]); + const outcome = await send.result; + assert.deepEqual(outcome.workspace, workspace); + send.release(); +}); + +test("seedDraftWorktreeFromGitInfo seeds baseRef on frame 0 and respects unborn/detached/remote flags", () => { + assert.deepEqual( + seedDraftWorktreeFromGitInfo( + { gitMode: "checkout" }, + { isRepo: true, branch: "feature", defaultBranch: "main", hasRemote: true }, + ), + { baseRef: "main", fromOrigin: true }, + ); + assert.deepEqual( + seedDraftWorktreeFromGitInfo( + { gitMode: "worktree", fromOrigin: false }, + { isRepo: true, branch: "feature", hasRemote: true }, + ), + { baseRef: "feature", fromOrigin: false }, + ); + assert.deepEqual( + seedDraftWorktreeFromGitInfo( + { gitMode: "checkout" }, + { isRepo: true, branch: "main", hasRemote: false }, + ), + { baseRef: "main", fromOrigin: false }, + ); + assert.equal( + seedDraftWorktreeFromGitInfo({ gitMode: "checkout" }, { isRepo: true, unborn: true, branch: "main" }), + undefined, + ); + assert.equal( + seedDraftWorktreeFromGitInfo({ gitMode: "checkout" }, { isRepo: true, detached: true, branch: "HEAD" }), + undefined, + ); + + const seededDraft = createChatDraft("ws-seed-test", undefined, undefined, { + gitMode: "worktree", + worktree: { baseRef: "main", fromOrigin: true }, + }); + try { + assert.equal(seededDraft.gitMode, "worktree"); + assert.deepEqual(seededDraft.worktree, { baseRef: "main", fromOrigin: true }); + } finally { + discardChatDraft(seededDraft.chat.id); + } +}); diff --git a/renderer/lib/draft-worktree-send.ts b/renderer/lib/draft-worktree-send.ts index c3f19ca40c..b98e75e328 100644 --- a/renderer/lib/draft-worktree-send.ts +++ b/renderer/lib/draft-worktree-send.ts @@ -59,17 +59,20 @@ export type WorktreeSendView = export type WorktreeSendDecision = "retry" | "use-existing" | "checkout" | "cancel"; -export interface WorktreeSendApi { - createInWorktree(input: Input & { worktree: FirstMessageWorktreeRequest }): Promise>; +export interface WorktreeSendApi { + createInWorktree( + input: Input & { worktree: FirstMessageWorktreeRequest }, + ): Promise>; createInCheckout(input: Input): Promise; onProgress(handler: (progress: FirstMessageWorktreeProgress) => void): () => void; } -export type WorktreeFirstSendResult = ( - | { chat: C; worktree: FirstMessageWorktreeInfo; keptWorktreeBranch?: undefined } +export type WorktreeFirstSendResult = ( + | { chat: C; worktree: FirstMessageWorktreeInfo; workspace?: W; keptWorktreeBranch?: undefined } | { chat: C; worktree?: undefined; + workspace?: undefined; /** Run in this checkout after a worktree was already created: it is kept, not deleted. */ keptWorktreeBranch?: string; } @@ -81,8 +84,8 @@ export type WorktreeFirstSendResult = ( answered: boolean; }; -export interface WorktreeFirstSend { - result: Promise>; +export interface WorktreeFirstSend { + result: Promise>; /** Answer a failure. Ignored unless the send is waiting for one. */ decide(decision: WorktreeSendDecision): void; /** @@ -155,8 +158,8 @@ export function activeWorktreeSend(draftId: string): ActiveWorktreeSend | undefi * published as the draft's active send (and to `onView`) until `release`. * An IPC rejection rejects `result` as an ordinary send failure. */ -export function startWorktreeFirstSend(options: { - api: WorktreeSendApi; +export function startWorktreeFirstSend(options: { + api: WorktreeSendApi; input: Input; worktree: FirstMessageWorktreeRequest; /** What the progress view shows as the user's message. */ @@ -166,7 +169,7 @@ export function startWorktreeFirstSend(options: { inputSource?: import("../shared/chat-input-source").ChatInputSourceV1; }; onView?: (view: WorktreeSendView) => void; -}): WorktreeFirstSend { +}): WorktreeFirstSend { const { api, input, onView, message } = options; const draftId = options.worktree.idempotencyKey; let request = options.worktree; @@ -194,12 +197,19 @@ export function startWorktreeFirstSend(options: { if (!waiting) show({ status: "running", request, progress }); }); - const run = async (): Promise> => { + const run = async (): Promise> => { for (;;) { progress = {}; show({ status: "running", request, progress }); const result = await api.createInWorktree({ ...input, worktree: request }); - if (result.ok) return { chat: result.chat, worktree: result.worktree, answered }; + if (result.ok) { + return { + chat: result.chat, + worktree: result.worktree, + ...(result.workspace !== undefined ? { workspace: result.workspace } : {}), + answered, + }; + } const existing = existingWorktreeOf(result); // A worktree that reported ready before the chat failed to save is kept. const created = existing?.branch ?? (progress.phase === "ready" ? progress.branch : undefined); diff --git a/renderer/lib/ipc.ts b/renderer/lib/ipc.ts index 3c38c19d20..4cf2aaa8b0 100644 --- a/renderer/lib/ipc.ts +++ b/renderer/lib/ipc.ts @@ -1786,7 +1786,7 @@ export const chatsApi = { skillInvocation?: SkillInvocationV1; inputSource?: ChatInputSourceV1; worktree: FirstMessageWorktreeRequest; - }) => invokeChatMutation>("chats:createWithFirstMessage", input), + }) => invokeChatMutation>("chats:createWithFirstMessage", input), /** Progress of the caller's own first-send worktree (fetching → creating → ready). */ onFirstMessageWorktreeProgress: (handler: (progress: FirstMessageWorktreeProgress) => void) => onNotification("chats:first-message-worktree-progress", handler), diff --git a/renderer/lib/queries.ts b/renderer/lib/queries.ts index 02711babaa..f7fec5cc84 100644 --- a/renderer/lib/queries.ts +++ b/renderer/lib/queries.ts @@ -51,6 +51,7 @@ import type { GitHubPullRequestStatus, McpLiveStatus, UsageDateRange, + Workspace, } from "./types"; export const queryKeys = { @@ -157,6 +158,30 @@ export async function installAppendedChatSnapshot( queryClient.setQueryData(chatKey, updated); } +/** + * Patch a newly created workspace into the cached workspace list when the list + * is already hydrated and idle; otherwise invalidate `queryKeys.workspaces` so + * an unhydrated cache is never overwritten with a single-element list and an + * in-flight `workspaces:list` cannot clobber the new workspace. + */ +export function upsertCreatedWorkspaceInCache( + queryClient: QueryClient, + created: Workspace, +): void { + const current = queryClient.getQueryData(queryKeys.workspaces); + const fetching = queryClient.isFetching({ queryKey: queryKeys.workspaces, exact: true }) > 0; + if (current && !fetching) { + const existing = current.find((entry) => entry.id === created.id); + if (existing && existing.updatedAt === created.updatedAt) return; + queryClient.setQueryData(queryKeys.workspaces, [ + created, + ...current.filter((entry) => entry.id !== created.id), + ]); + return; + } + void queryClient.invalidateQueries({ queryKey: queryKeys.workspaces }); +} + async function cancelModelInsightsReads(queryClient: QueryClient): Promise { await Promise.all([ queryClient.cancelQueries({ queryKey: queryKeys.modelInsightsStatus }), @@ -677,14 +702,62 @@ export function useWorkspaceSkillChoices(workspaceId: string | undefined) { }); } +const recentlyPromotedChats = new Map(); +const promotedChatSubscribers = new Map(); +const RECENTLY_PROMOTED_CHAT_TTL_MS = 5_000; + +/** + * Mark a draft chat whose first message just committed and seeded the query + * cache, so the immediate draft -> live `useChat` activation reuses the seeded + * snapshot instead of issuing a redundant `chats:get` IPC. Leaving and + * revisiting the chat clears the marker and re-reads from main as usual. + */ +export function markChatRecentlyPromoted(chatId: string): void { + const now = Date.now(); + for (const [id, expiresAt] of recentlyPromotedChats) { + if (expiresAt < now) recentlyPromotedChats.delete(id); + } + recentlyPromotedChats.set(chatId, now + RECENTLY_PROMOTED_CHAT_TTL_MS); +} + +function isChatRecentlyPromoted(chatId: string | undefined): boolean { + if (!chatId) return false; + const expiresAt = recentlyPromotedChats.get(chatId); + if (expiresAt === undefined) return false; + if (expiresAt < Date.now()) { + recentlyPromotedChats.delete(chatId); + return false; + } + return true; +} + export function useChat(id: string | undefined) { + useEffect(() => { + if (!id) return undefined; + promotedChatSubscribers.set(id, (promotedChatSubscribers.get(id) ?? 0) + 1); + return () => { + const remaining = (promotedChatSubscribers.get(id) ?? 1) - 1; + if (remaining > 0) promotedChatSubscribers.set(id, remaining); + else promotedChatSubscribers.delete(id); + // Defer one microtask so React StrictMode's simulated unmount -> remount + // cycle (and secondary `useChat` callers like `useDesignMode`) does not + // wipe the marker before the real mount observes it. + queueMicrotask(() => { + if (!promotedChatSubscribers.has(id)) recentlyPromotedChats.delete(id); + }); + }; + }, [id]); + const promotedFresh = isChatRecentlyPromoted(id); return useQuery({ queryKey: id ? queryKeys.chat(id) : ["chat", "none"], queryFn: () => (id ? chatsApi.get(id) : Promise.resolve(null)), enabled: Boolean(id), // Revisiting a chat re-reads it (the streaming and settlement paths keep - // the open chat current; focus no longer resends it). - staleTime: 0, + // the open chat current; focus no longer resends it). Only the immediate + // draft -> live handoff treats the just-seeded snapshot as fresh so + // switching `useChat(undefined)` -> `useChat(chatId)` avoids a redundant + // `chats:get` IPC. Leaving the chat clears the marker so revisiting re-reads. + staleTime: promotedFresh ? RECENTLY_PROMOTED_CHAT_TTL_MS : 0, }); } diff --git a/renderer/lib/use-workspace-artifacts.ts b/renderer/lib/use-workspace-artifacts.ts index 7e94e2c641..db2e3cc9b7 100644 --- a/renderer/lib/use-workspace-artifacts.ts +++ b/renderer/lib/use-workspace-artifacts.ts @@ -44,17 +44,21 @@ export function useWorkspaceArtifacts( workspaceArtifactsApi.list(id).then( (views) => { if (request !== requestRef.current) return; - setState({ workspaceId: id, views, loaded: true, error: null }); + React.startTransition(() => { + setState({ workspaceId: id, views, loaded: true, error: null }); + }); }, (error: unknown) => { if (request !== requestRef.current) return; - setState((current) => ({ - workspaceId: id, - // Keep the last good list for this workspace; a failed re-read is not an empty one. - views: current.workspaceId === id ? current.views : [], - loaded: true, - error: error instanceof Error ? error.message : "Could not load artifacts.", - })); + React.startTransition(() => { + setState((current) => ({ + workspaceId: id, + // Keep the last good list for this workspace; a failed re-read is not an empty one. + views: current.workspaceId === id ? current.views : [], + loaded: true, + error: error instanceof Error ? error.message : "Could not load artifacts.", + })); + }); }, ); }, []); diff --git a/renderer/main/chat-pane.tsx b/renderer/main/chat-pane.tsx index 5d877447a7..60bf1c9d1a 100644 --- a/renderer/main/chat-pane.tsx +++ b/renderer/main/chat-pane.tsx @@ -7,6 +7,7 @@ import { discardChatDraft, finishChatDraftSend, getChatDraft, + requestChatDraftComposerFocus, retainChatDraft, chatDraftWorktreeRequest, setChatDraftGitMode, @@ -18,7 +19,11 @@ import { } from "../lib/chat-draft"; import { registerChatPromptTarget } from "../lib/chat-prompt-bridge"; import { resolveModelDisplay } from "../lib/model-display"; -import { readChatDraftGitMemory, resolveDraftWorktreeDefaults } from "../lib/chat-draft-git-memory"; +import { + readChatDraftGitMemory, + resolveDraftWorktreeDefaults, + seedDraftWorktreeFromGitInfo, +} from "../lib/chat-draft-git-memory"; import { draftWorkInOptions, draftWorktreeHint, @@ -37,7 +42,6 @@ import { } from "../lib/draft-worktree-send"; import { isValidBranchName, type FirstMessageWorktreeRequest } from "../shared/worktree-on-send"; import { localComputerNoun } from "../shared/computer-noun"; -import { DraftWorktreeSendView } from "../components/draft-worktree-send-view"; import type { GitBranchPickerDraft } from "../components/git-branch-picker"; import { QueuedMessages } from "../components/queued-messages"; import { NewChatHeadline } from "../components/new-chat-headline"; @@ -96,6 +100,7 @@ import { MANAGED_WORKTREE_MISSING_SEND_REFUSAL, WORKSPACE_FOLDER_MISSING_SEND_REFUSAL, workspaceFolderCheckApplies, + type WorkspaceFolderPresenceResult, } from "../shared/workspace-folder-presence"; import { useOptionalNewChatActions } from "../lib/new-chat-actions"; import { Badge, Button, EmptyState, ScrollArea, ScrollAreaFooterStack, Text, toast } from "../components/ui"; @@ -210,7 +215,9 @@ import { queryKeys, installAppendedChatSnapshot, logoutBuiltinProvider, + markChatRecentlyPromoted, refreshCodexProviderState, + upsertCreatedWorkspaceInCache, useAllRegularChats, useChat, useGitInfo, @@ -232,7 +239,7 @@ import { EnvironmentPanelToggle, QuickViewIcon, QuickViewToggle, - useEnvironmentPanel, + useEnvironmentPanelCore, } from "../components/environment-panel"; import { EventPresence } from "../components/event-presence"; import { @@ -241,6 +248,7 @@ import { type Chat, type ChatMeta, type GitBranches, + type GitInfo, type Workspace, } from "../lib/types"; import { COMPUTER_USE_CONTINUE_PROMPT } from "../shared/computer-use-access"; @@ -492,7 +500,7 @@ export function ChatPane({ chatId }: { chatId: string }) { const steerableDetachedProjection = observedRunVisible ? null : visibleDetachedProjection; const terminal = useWorkspaceTerminal(); const git = useGitInfo(effectiveWorkspace?.id); - const environmentPanel = useEnvironmentPanel(); + const environmentPanel = useEnvironmentPanelCore(); const designChatBodyHidden = useDesignChatBodyHidden(); const settingsBlockedReason = environmentPanel.gitOperationBusy ? "Wait for the current Git operation to finish" @@ -788,7 +796,9 @@ export function ChatPane({ chatId }: { chatId: string }) { React.useEffect(() => { if (chat.data && effectiveWorkspaceId && effectiveWorkspaceId !== activeId) { - selectWorkspace(effectiveWorkspaceId); + React.startTransition(() => { + selectWorkspace(effectiveWorkspaceId); + }); } }, [activeId, chat.data, effectiveWorkspaceId, selectWorkspace]); @@ -2190,27 +2200,6 @@ export function ChatPane({ chatId }: { chatId: string }) { if (getChatDraft(chatId) && draftGitPendingRef.current) { throw new Error("Reading Git status… Send again in a moment."); } - const folderWorkspace = folderWorkspaceRef.current; - if (folderWorkspace) { - const folderCheckVisit = chatVisitRef.current; - // A failed check is no reason to refuse; main checks again at start. - const presence = await qc - .fetchQuery({ - queryKey: queryKeys.workspaceFolderPresence(folderWorkspace.id), - queryFn: () => workspacesApi.folderPresence(folderWorkspace.id), - staleTime: 0, - }) - .catch(() => undefined); - // The user left this chat during the check: send nothing from a pane - // that now shows another chat. The composer's saved draft keeps the text. - if (!(mountedRef.current && chatVisitRef.current === folderCheckVisit)) { - throw new WorktreeSendCancelledError(); - } - // The notice above the composer names the folder; the toast stays short. - if (presence?.presence === "missing") { - throw new Error(presence.worktree ? MANAGED_WORKTREE_MISSING_SEND_REFUSAL : WORKSPACE_FOLDER_MISSING_SEND_REFUSAL); - } - } let worktreeRequest: FirstMessageWorktreeRequest | undefined; try { worktreeRequest = @@ -2221,7 +2210,40 @@ export function ChatPane({ chatId }: { chatId: string }) { // The base branch isn't resolved yet; the composer keeps the text. throw new Error("Reading Git status… Send again in a moment."); } - let worktreeSend: WorktreeFirstSend | undefined; + const folderWorkspace = folderWorkspaceRef.current; + if (folderWorkspace) { + const cachedPresence = worktreeRequest + ? qc.getQueryData( + queryKeys.workspaceFolderPresence(folderWorkspace.id), + ) + : undefined; + // Worktree-on-send validates the source folder live in main before + // touching disk; skip the blocking pre-send IPC when the cached + // presence is not missing so the user's bubble and progress row paint + // on frame 1. If the cached presence says "missing", fall through to a + // live check so a folder restored on disk is never blocked by stale cache. + if (!worktreeRequest || cachedPresence?.presence === "missing") { + const folderCheckVisit = chatVisitRef.current; + // A failed check is no reason to refuse; main checks again at start. + const presence = await qc + .fetchQuery({ + queryKey: queryKeys.workspaceFolderPresence(folderWorkspace.id), + queryFn: () => workspacesApi.folderPresence(folderWorkspace.id), + staleTime: 0, + }) + .catch(() => undefined); + // The user left this chat during the check: send nothing from a pane + // that now shows another chat. The composer's saved draft keeps the text. + if (!(mountedRef.current && chatVisitRef.current === folderCheckVisit)) { + throw new WorktreeSendCancelledError(); + } + // The notice above the composer names the folder; the toast stays short. + if (presence?.presence === "missing") { + throw new Error(presence.worktree ? MANAGED_WORKTREE_MISSING_SEND_REFUSAL : WORKSPACE_FOLDER_MISSING_SEND_REFUSAL); + } + } + } + let worktreeSend: WorktreeFirstSend | undefined; /** The user answered a failed worktree send, possibly from a later view of this draft. */ let continuedByUser = false; const firstDraft = getChatDraft(chatId) ? beginChatDraftSend(chatId) : undefined; @@ -2252,6 +2274,7 @@ export function ChatPane({ chatId }: { chatId: string }) { : undefined; if (firstMessageInput && worktreeRequest) { const visit = chatVisitRef.current; + performance.mark?.("aiden:worktree-send:start"); worktreeSend = startWorktreeFirstSend({ api: { createInWorktree: chatsApi.createWithFirstMessageInWorktree, @@ -2261,15 +2284,51 @@ export function ChatPane({ chatId }: { chatId: string }) { input: firstMessageInput, worktree: worktreeRequest, message: { text, attachments, ...(inputSource ? { inputSource } : {}) }, + onView: (view) => { + if (view.status === "failed" && folderWorkspace) { + void qc.invalidateQueries({ + queryKey: queryKeys.workspaceFolderPresence(folderWorkspace.id), + }); + } + }, }); // The progress view holds the message now; a composer that opens // on this draft meanwhile starts empty instead of repeating it. discardComposerDraft(chatId); try { const outcome = await worktreeSend.result; + performance.mark?.("aiden:worktree-send:done"); + try { + performance.measure?.( + "aiden:worktree-send", + "aiden:worktree-send:start", + "aiden:worktree-send:done", + ); + } catch { + // Ignore missing marks if the performance buffer was cleared. + } if (outcome.worktree) { - // List the new worktree workspace before the chat moves into it. - await qc.invalidateQueries({ queryKey: queryKeys.workspaces }); + if (outcome.workspace) { + const createdWorkspace = outcome.workspace; + upsertCreatedWorkspaceInCache(qc, createdWorkspace); + // Seed folder-presence for a brand-new worktree; leave Git + // status to main's `infoCache` (0-spawn when clean, or live + // post-hook status if WorktreeSetup modified the checkout). + if (!outcome.worktree.reused && createdWorkspace.folderPath) { + qc.setQueryData( + queryKeys.workspaceFolderPresence(createdWorkspace.id), + { presence: "present" }, + ); + } + if (mountedRef.current && chatIdRef.current === chatId) { + React.startTransition(() => { + selectWorkspace(createdWorkspace.id); + }); + } + } else { + // Fallback when main omitted the workspace record. + await qc.invalidateQueries({ queryKey: queryKeys.workspaces }); + } const note = worktreeBaseNote(outcome.worktree); if (note) toast.info(note); } @@ -2282,6 +2341,13 @@ export function ChatPane({ chatId }: { chatId: string }) { updated = outcome.chat; continuedByUser = outcome.answered; } catch (error) { + // Refresh folder presence if worktree creation failed (for + // example, when the source folder was deleted just before send). + if (folderWorkspace) { + void qc.invalidateQueries({ + queryKey: queryKeys.workspaceFolderPresence(folderWorkspace.id), + }); + } // The composer that sent this restores its own text; any other // (the user left and came back) gets the text and attachments back. if ( @@ -2320,7 +2386,19 @@ export function ChatPane({ chatId }: { chatId: string }) { throw appendError; } await installAppendedChatSnapshot(qc, chatId, updated); - if (firstDraft) finishChatDraftSend(chatId, true); + if (firstDraft) { + // Only suppress the immediate mount `chats:get` when this pane is + // still actively showing the promoted chat; leaving before commit + // abandons the turn and must re-read on revisit. + if ( + generationIntentRef.current === generationIntent && + mountedRef.current && + chatIdRef.current === chatId + ) { + markChatRecentlyPromoted(chatId); + } + finishChatDraftSend(chatId, true); + } void qc.invalidateQueries({ queryKey: queryKeys.chats }); if ( generationIntentRef.current !== generationIntent || @@ -2385,6 +2463,7 @@ export function ChatPane({ chatId }: { chatId: string }) { model, qc, runGeneration, + selectWorkspace, ], ); @@ -3452,12 +3531,27 @@ export function ChatPane({ chatId }: { chatId: string }) { throw new Error("Wait for the open file to finish saving before changing Git workspaces."); if (environmentPanel.editorState.dirty) throw new Error("Save or discard the open file's edits before changing Git workspaces."); + performance.mark?.("aiden:worktree-create:start"); const workspace = await gitApi.createWorktree(effectiveWorkspace.id, branchName); - qc.setQueryData(queryKeys.workspaces, (current) => [ - workspace, - ...(current ?? []).filter((entry) => entry.id !== workspace.id), - ]); - void qc.invalidateQueries({ queryKey: queryKeys.workspaces }); + performance.mark?.("aiden:worktree-create:done"); + try { + performance.measure?.( + "aiden:worktree-create", + "aiden:worktree-create:start", + "aiden:worktree-create:done", + ); + } catch { + // Ignore missing marks if the performance buffer was cleared. + } + upsertCreatedWorkspaceInCache(qc, workspace); + // Seed folder-presence for the new worktree; leave Git status to main's + // `infoCache` so synchronous WorktreeSetup hook edits are never hidden. + if (workspace.folderPath) { + qc.setQueryData( + queryKeys.workspaceFolderPresence(workspace.id), + { presence: "present" }, + ); + } if (!mountedRef.current || chatIdRef.current !== sourceChatId) return; if (isNewChat) { try { @@ -3475,7 +3569,7 @@ export function ChatPane({ chatId }: { chatId: string }) { selectWorkspace(workspace.id); try { await navigate({ to: "/chat/$chatId", params: { chatId: created.id } }); - requestAnimationFrame(() => composerRef.current?.focus({ preventScroll: true })); + requestChatDraftComposerFocus(created.id); } catch { discardChatDraft(created.id); selectWorkspace(effectiveWorkspace.id); @@ -3548,11 +3642,28 @@ export function ChatPane({ chatId }: { chatId: string }) { } await moveDraftToRepositoryCheckout(); setChatDraftGitMode(chatId, "worktree"); - if (!name) return; const current = getChatDraft(chatId); const workspaceId = current?.chat.workspaceId; if (!current || !workspaceId) return; let baseRef = current.worktree?.baseRef; + let fromOrigin = current.worktree?.fromOrigin; + if (!baseRef) { + const targetGit = + workspaceId === effectiveWorkspaceId + ? git.data + : qc.getQueryData(queryKeys.git(workspaceId)); + const seeded = seedDraftWorktreeFromGitInfo(readChatDraftGitMemory(workspaceId), targetGit); + if (seeded) { + baseRef = seeded.baseRef; + fromOrigin = seeded.fromOrigin; + } + } + if (!name) { + if (baseRef && !current.worktree?.baseRef) { + updateChatDraftWorktree(chatId, { baseRef, fromOrigin: fromOrigin ?? false }); + } + return; + } if (!baseRef) { // `/worktree ` before the menu has read the branches: resolve // the base the menu would pick (a local Git read, no network). @@ -3564,11 +3675,15 @@ export function ChatPane({ chatId }: { chatId: string }) { const defaults = resolveDraftWorktreeDefaults(readChatDraftGitMemory(workspaceId), branches); if (!defaults) throw new Error("Create the first commit before starting a new worktree."); baseRef = defaults.baseRef; - updateChatDraftWorktree(chatId, defaults); + fromOrigin = defaults.fromOrigin; } - updateChatDraftWorktree(chatId, { baseRef, branchName: name }); + updateChatDraftWorktree(chatId, { + baseRef, + ...(fromOrigin !== undefined ? { fromOrigin } : {}), + branchName: name, + }); }, - [chatId, draftWorkIn, git.data?.unborn, moveDraftToRepositoryCheckout, qc], + [chatId, draftWorkIn, effectiveWorkspaceId, git.data, moveDraftToRepositoryCheckout, qc], ); const selectDraftWorktree = React.useCallback( @@ -4176,6 +4291,8 @@ export function ChatPane({ chatId }: { chatId: string }) { displayedStreamingReasoning, displayedGenerationTimeline, agentActivity?.phase, + worktreeSend?.view.status, + worktreeSend?.view.progress.phase, approvals.length, questionnaire?.promptId, displayedStreamingArtifacts.length, @@ -4609,15 +4726,7 @@ export function ChatPane({ chatId }: { chatId: string }) { } /> - ) : messages.length === 0 && displayedStreamingText === null && worktreeSend ? ( - - ) : messages.length === 0 && displayedStreamingText === null ? ( + ) : messages.length === 0 && displayedStreamingText === null && !worktreeSend ? (
{(providers.data ?? []).some( (p) => p.models.length > 0 && (p.hasKey || !p.needsKey), @@ -4654,6 +4763,7 @@ export function ChatPane({ chatId }: { chatId: string }) { key={chatId} chatId={chatId} messages={messages} + draftWorktreeSend={worktreeSend} streamingText={displayedStreamingText} streamingReasoning={displayedStreamingReasoning} streamingArtifacts={displayedStreamingArtifacts} diff --git a/renderer/main/chat-transition.test.tsx b/renderer/main/chat-transition.test.tsx index b7d9900dec..2a5591a2a8 100644 --- a/renderer/main/chat-transition.test.tsx +++ b/renderer/main/chat-transition.test.tsx @@ -11,10 +11,15 @@ import test from "node:test"; import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { Outlet, RouterProvider } from "@tanstack/react-router"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { installAppendedChatSnapshot, queryKeys } from "../lib/queries.js"; +import { + installAppendedChatSnapshot, + markChatRecentlyPromoted, + queryKeys, + upsertCreatedWorkspaceInCache, +} from "../lib/queries.js"; import { isDetachedLifecycleChatDraining } from "../lib/chat-terminal-sync.js"; import { notifyPendingChatHandoff } from "../lib/chat-handoff-bridge"; -import type { Chat } from "../lib/types.js"; +import type { Chat, Workspace } from "../lib/types.js"; import { WorkspaceProvider } from "../lib/workspace-context"; import { WorkspaceTerminalProvider } from "../components/terminal-drawer"; import { EnvironmentPanelProvider } from "../components/environment-panel"; @@ -531,13 +536,13 @@ test("session navigation seeds caches, respects route intent, and restores desti "const createGitWorktree = React.useCallback(", "React.useEffect(() => {\n environmentPanel.setCreateWorktreeHandler", ); - assert.match(worktree, /setQueryData/u); + assert.match(worktree, /upsertCreatedWorkspaceInCache\(qc, workspace\)/u); assert.match(worktree, /chatIdRef\.current !== sourceChatId/u); assert.match(worktree, /The worktree was created, but Aiden could not open its new chat/u); assert.match(worktree, /createChatDraft\(workspace.id\)/u); assert.doesNotMatch(worktree, /chatsApi\.create\(/u); assert.match(worktree, /await navigate/u); - assert.match(worktree, /requestAnimationFrame\(\(\) => composerRef\.current\?\.focus/u); + assert.match(worktree, /requestChatDraftComposerFocus\(created\.id\)/u); }); test("a committed append is not presented as unsent when generation start later fails", () => { @@ -1001,6 +1006,100 @@ test("a dismissed recovered question stays gone when the chat opens again", asyn } }); +test("a recently promoted draft skips its immediate mount chats:get while leaving and revisiting still re-reads", async () => { + const reads: string[] = []; + const handlers = { + "chats:get": (id: unknown) => { + reads.push(String(id)); + return chatReadResponse(String(id)); + }, + }; + const promotedId = "chat-promoted"; + const seeded = chatReadResponse(promotedId); + const { queryClient, router } = await mountRoutedChatPane("chat-other", handlers); + try { + reads.length = 0; + await installAppendedChatSnapshot(queryClient, promotedId, seeded.chat as Chat); + markChatRecentlyPromoted(promotedId); + await act(async () => { + await router.navigate({ to: "/chat/$chatId", params: { chatId: promotedId } }); + await new Promise((resolve) => setTimeout(resolve, 20)); + }); + assert.deepEqual( + reads, + [], + "Immediate activation after draft promotion reuses the seeded snapshot without a redundant chats:get", + ); + assert.equal(screen.getByRole("heading", { level: 1 }).textContent, `Chat ${promotedId}`); + + // Navigating away clears the one-shot marker, so revisiting re-reads live state. + await act(async () => { + await router.navigate({ to: "/chat/$chatId", params: { chatId: "chat-other" } }); + await new Promise((resolve) => setTimeout(resolve, 20)); + }); + reads.length = 0; + await act(async () => { + await router.navigate({ to: "/chat/$chatId", params: { chatId: promotedId } }); + await new Promise((resolve) => setTimeout(resolve, 20)); + }); + assert.deepEqual(reads, [promotedId], "Revisiting the chat after leaving re-reads chats:get"); + } finally { + cleanup(); + queryClient.clear(); + } +}); + +test("upsertCreatedWorkspaceInCache patches hydrated idle lists and falls back to invalidation when unhydrated or fetching", async () => { + const existing: Workspace = { + id: "ws-existing", + name: "Existing", + folderPath: "/projects/existing", + permission: "ask", + createdAt: 1, + updatedAt: 1, + }; + const created: Workspace = { + id: "ws-worktree", + name: "Existing · aiden/fast", + folderPath: "/tmp/wt", + permission: "ask", + createdAt: 2, + updatedAt: 2, + }; + + // 1. Hydrated & idle: patches in-place without invalidating. + const qc1 = new QueryClient(); + qc1.setQueryData(queryKeys.workspaces, [existing]); + upsertCreatedWorkspaceInCache(qc1, created); + assert.deepEqual( + qc1.getQueryData(queryKeys.workspaces)?.map((w) => w.id), + ["ws-worktree", "ws-existing"], + ); + assert.equal(qc1.getQueryState(queryKeys.workspaces)?.isInvalidated, false); + qc1.clear(); + + // 2. Unhydrated cache: does NOT overwrite with a 1-element list; invalidates instead. + const qc2 = new QueryClient(); + upsertCreatedWorkspaceInCache(qc2, created); + assert.equal(qc2.getQueryData(queryKeys.workspaces), undefined); + qc2.clear(); + + // 3. In-flight workspaces:list fetch: invalidates instead of racing with stale read. + const qc3 = new QueryClient(); + qc3.setQueryData(queryKeys.workspaces, [existing]); + let resolveFetch!: (list: Workspace[]) => void; + const inflight = qc3.fetchQuery({ + queryKey: queryKeys.workspaces, + queryFn: () => new Promise((resolve) => { resolveFetch = resolve; }), + }); + await Promise.resolve(); + upsertCreatedWorkspaceInCache(qc3, created); + assert.equal(qc3.getQueryState(queryKeys.workspaces)?.isInvalidated, true); + resolveFetch([existing, created]); + await inflight; + qc3.clear(); +}); + test("a send waiting on its folder check sends nothing once the person moves to another chat", async () => { const releases: Array<() => void> = []; const appended: string[] = []; diff --git a/renderer/main/root-view.tsx b/renderer/main/root-view.tsx index 93fe8ad162..28d784df4f 100644 --- a/renderer/main/root-view.tsx +++ b/renderer/main/root-view.tsx @@ -4,8 +4,12 @@ import { findReusableChatDraft, requestChatDraftComposerFocus, setChatDraftGitMode, + updateChatDraftWorktree, type ChatDraftGitMode, + type ChatDraftWorktree, } from "../lib/chat-draft"; +import { readChatDraftGitMemory, seedDraftWorktreeFromGitInfo } from "../lib/chat-draft-git-memory"; +import type { Workspace } from "../lib/types"; import { Outlet, useNavigate, useRouter, useRouterState } from "@tanstack/react-router"; import { historyNavigationAvailability } from "../lib/history-navigation"; import { PairingRequestSheet } from "../components/remote-pairing-request-sheet"; @@ -21,13 +25,13 @@ import { mirrorNewChatModelToHost, persistModelSelection, subscribeHostNewChatMo import { useTheme } from "../lib/use-theme"; import { useActiveWorkspace, WorkspaceProvider } from "../lib/workspace-context"; import { WorkspaceTerminalProvider, useWorkspaceTerminal } from "../components/terminal-drawer"; -import { EnvironmentPanelProvider, useEnvironmentPanel } from "../components/environment-panel"; +import { EnvironmentPanelProvider, useEnvironmentPanelCore } from "../components/environment-panel"; import { toast } from "../components/ui"; import { RoutedBotPanelProvider, useBotPanelActions } from "./bots/bot-panel-context"; import { botListLocation, environmentToggleTarget, isBotsPath } from "../lib/bot-routes"; import { AssistantDock } from "../components/assistant/assistant-dock"; import { LiveAppControlLayer } from "../components/assistant/live-app-control-layer"; -import { queryKeys } from "../lib/queries"; +import { queryKeys, upsertCreatedWorkspaceInCache } from "../lib/queries"; import { subscribeGitQuerySync } from "../lib/git-query-sync"; import { subscribeWorkspaceFilesSync } from "../lib/workspace-files-sync"; import { @@ -90,7 +94,7 @@ function RootContent() { const navigate = useNavigate(); const router = useRouter(); const queryClient = useQueryClient(); - const environmentPanel = useEnvironmentPanel(); + const environmentPanel = useEnvironmentPanelCore(); const botPanel = useBotPanelActions(); const terminal = useWorkspaceTerminal(); const capabilities = useAppCapabilities(); @@ -268,7 +272,12 @@ function RootContent() { async ( workspaceId: string, initialText?: string, - options: { gitMode?: ChatDraftGitMode; attachments?: readonly Attachment[]; ephemeral?: boolean } = {}, + options: { + gitMode?: ChatDraftGitMode; + worktree?: ChatDraftWorktree; + attachments?: readonly Attachment[]; + ephemeral?: boolean; + } = {}, ): Promise => { if (appendReconciliationRequired) { toast.error("Reload Aiden before creating another chat."); @@ -288,9 +297,15 @@ function RootContent() { reusable?.chat ?? createChatDraft(workspaceId, undefined, initialText, { ...(options.gitMode ? { gitMode: options.gitMode } : {}), + ...(options.worktree ? { worktree: options.worktree } : {}), ...(options.ephemeral ? { ephemeral: true } : {}), }).chat; - if (reusable && options.gitMode) setChatDraftGitMode(reusable.chat.id, options.gitMode); + if (reusable && options.gitMode) { + setChatDraftGitMode(reusable.chat.id, options.gitMode); + if (options.worktree && !reusable.worktree?.baseRef) { + updateChatDraftWorktree(reusable.chat.id, options.worktree); + } + } if (hasAttachments && options.attachments) { seedComposerAttachments(chat.id, [...options.attachments]); } @@ -362,6 +377,7 @@ function RootContent() { () => ({ openNewChatIn: async (workspaceId, options) => { let gitMode: ChatDraftGitMode | undefined = options?.gitMode; + let worktree: ChatDraftWorktree | undefined; if (options?.newWorktree) { // ⌥↵: only a repository with a commit can start a new worktree. // A local status read; nothing is created until the first send. @@ -372,10 +388,19 @@ function RootContent() { staleTime: 5_000, }) .catch(() => undefined); - if (git?.isRepo && !git.unborn) gitMode = "worktree"; + if (git?.isRepo && !git.unborn) { + gitMode = "worktree"; + worktree = seedDraftWorktreeFromGitInfo(readChatDraftGitMemory(workspaceId), git); + } } // The draft's id, or undefined when nothing opened (navigation blocked). - return openNewChatIn(workspaceId, options?.initialText || undefined, gitMode ? { gitMode } : {}); + return openNewChatIn( + workspaceId, + options?.initialText || undefined, + gitMode || worktree + ? { ...(gitMode ? { gitMode } : {}), ...(worktree ? { worktree } : {}) } + : {}, + ); }, openFolderForNewChat, cloneRepositoryForNewChat, @@ -445,7 +470,15 @@ function RootContent() { }, [queryClient]); React.useEffect(() => { - return onNotification("workspaces:changed", () => { + return onNotification("workspaces:changed", (payload: unknown) => { + const update = + payload && typeof payload === "object" + ? (payload as { kind?: unknown; workspace?: Workspace }) + : undefined; + if (update?.kind === "created" && update.workspace && typeof update.workspace.id === "string") { + upsertCreatedWorkspaceInCache(queryClient, update.workspace); + return; + } void Promise.all([ queryClient.invalidateQueries({ queryKey: queryKeys.workspaces }), queryClient.invalidateQueries({ queryKey: queryKeys.chats }), diff --git a/renderer/shared/worktree-on-send.ts b/renderer/shared/worktree-on-send.ts index b0dd0fd93d..8624496c7f 100644 --- a/renderer/shared/worktree-on-send.ts +++ b/renderer/shared/worktree-on-send.ts @@ -53,8 +53,8 @@ export interface FirstMessageWorktreeInfo { reused: boolean; } -export type FirstMessageWorktreeResult = - | { ok: true; chat: C; worktree: FirstMessageWorktreeInfo } +export type FirstMessageWorktreeResult = + | { ok: true; chat: C; worktree: FirstMessageWorktreeInfo; workspace?: W } | { ok: false; /** The chat was not saved; the draft can Retry or run in this checkout instead. */ diff --git a/scripts/worktree-file-io.test.mjs b/scripts/worktree-file-io.test.mjs index e8d7f59e48..04c6e42754 100644 --- a/scripts/worktree-file-io.test.mjs +++ b/scripts/worktree-file-io.test.mjs @@ -1,9 +1,9 @@ /* global Buffer, process */ import assert from "node:assert/strict"; -import { spawn } from "node:child_process"; +import { execFileSync, spawn } from "node:child_process"; import { createHash } from "node:crypto"; -import { mkdtemp, mkdir, link, readFile, readdir, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises"; +import { chmod, mkdtemp, mkdir, link, readFile, readdir, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import test from "node:test"; @@ -411,3 +411,155 @@ test("private file creation uses mode 0600 and refuses an existing environment f assert.notEqual(existing.code, 0); assert.equal(await readFile(path.join(folder, ".env"), "utf8"), input.toString()); }); + +test("provision batch copies nested files, preserves rwx modes, strips setuid/sticky and BSD uchg flags", async (t) => { + if (process.platform !== "darwin") return; + const source = await directory(t); + const destination = await directory(t); + await mkdir(path.join(source, "config", "nested"), { recursive: true }); + await writeFile(path.join(source, ".env"), "SECRET=1\n"); + await chmod(path.join(source, ".env"), 0o600); + await writeFile(path.join(source, "config", "nested", "run.sh"), "#!/bin/sh\necho ok\n"); + await chmod(path.join(source, "config", "nested", "run.sh"), 0o4755); + await writeFile(path.join(source, "locked.txt"), "immutable-source\n"); + execFileSync("/usr/bin/chflags", ["uchg", path.join(source, "locked.txt")]); + try { + const payload = Buffer.from(".env\0config/nested/run.sh\0locked.txt\0", "utf8"); + const result = await runEditor( + ["provision", ...await identity(source), ...await identity(destination), String(1024 * 1024)], + payload, + ); + assert.equal(result.code, 0, result.stderr); + assert.equal(result.stdout.toString(), "p 0 9\np 1 18\np 2 17\ndone\n"); + assert.equal(await readFile(path.join(destination, ".env"), "utf8"), "SECRET=1\n"); + assert.equal((await stat(path.join(destination, ".env"))).mode & 0o7777, 0o600); + const scriptStat = await stat(path.join(destination, "config", "nested", "run.sh")); + assert.equal(scriptStat.mode & 0o7777, 0o755, "setuid bit must be stripped"); + assert.equal(await readFile(path.join(destination, "locked.txt"), "utf8"), "immutable-source\n"); + // Destination copy must NOT inherit UF_IMMUTABLE — verify it can be removed cleanly. + await rm(path.join(destination, "locked.txt")); + } finally { + try { execFileSync("/usr/bin/chflags", ["nouchg", path.join(source, "locked.txt")]); } catch { /* ignore */ } + } +}); + +test("provision enforces cumulative byte limits and emits progress for files installed before failure", async (t) => { + if (process.platform !== "darwin") return; + const source = await directory(t); + const destination = await directory(t); + await writeFile(path.join(source, "a.txt"), "12345"); + await writeFile(path.join(source, "b.txt"), "12345"); + await writeFile(path.join(source, "c.txt"), "12345"); + + const payload = Buffer.from("a.txt\0b.txt\0c.txt\0", "utf8"); + const result = await runEditor( + ["provision", ...await identity(source), ...await identity(destination), "10"], + payload, + ); + assert.notEqual(result.code, 0); + assert.equal(result.stderr.trim(), "too_many_bytes"); + assert.equal(result.stdout.toString(), "p 0 5\np 1 5\n"); + assert.equal(await readFile(path.join(destination, "a.txt"), "utf8"), "12345"); + assert.equal(await readFile(path.join(destination, "b.txt"), "utf8"), "12345"); + await assert.rejects(() => stat(path.join(destination, "c.txt"))); +}); + +test("provision stays on held descriptors through source and destination symlink swaps", async (t) => { + if (process.platform !== "darwin") return; + const source = await directory(t); + const destination = await directory(t); + const outside = await directory(t); + await mkdir(path.join(source, "sub")); + await mkdir(path.join(destination, "sub")); + await writeFile(path.join(source, "sub", "a.txt"), "inside-source"); + await writeFile(path.join(outside, "a.txt"), "outside-secret"); + + const result = await runEditor( + ["provision", ...await identity(source), ...await identity(destination), "4096"], + Buffer.from("sub/a.txt\0", "utf8"), + async (marker) => { + if (marker === "S") { + await rename(path.join(source, "sub"), path.join(source, "moved-src")); + await symlink(outside, path.join(source, "sub")); + } else if (marker === "D") { + await rename(path.join(destination, "sub"), path.join(destination, "moved-dst")); + await symlink(outside, path.join(destination, "sub")); + } + }, + ); + assert.equal(result.code, 0, result.stderr); + assert.equal(await readFile(path.join(destination, "moved-dst", "a.txt"), "utf8"), "inside-source"); + assert.equal(await readFile(path.join(outside, "a.txt"), "utf8"), "outside-secret"); +}); + +test("provision refuses existing destination, symlinks, self-copy, and malformed stdin", async (t) => { + if (process.platform !== "darwin") return; + const source = await directory(t); + const destination = await directory(t); + await writeFile(path.join(source, "a.txt"), "aaa"); + await writeFile(path.join(destination, "a.txt"), "existing"); + await symlink(path.join(source, "a.txt"), path.join(source, "link.txt")); + + const existsRes = await runEditor( + ["provision", ...await identity(source), ...await identity(destination), "4096"], + Buffer.from("a.txt\0", "utf8"), + ); + assert.notEqual(existsRes.code, 0); + assert.equal(existsRes.stderr.trim(), "destination_exists"); + assert.equal(await readFile(path.join(destination, "a.txt"), "utf8"), "existing"); + + const symlinkRes = await runEditor( + ["provision", ...await identity(source), ...await identity(destination), "4096"], + Buffer.from("link.txt\0", "utf8"), + ); + assert.notEqual(symlinkRes.code, 0); + assert.equal(symlinkRes.stderr.trim(), "unsafe_source"); + + const selfRes = await runEditor( + ["provision", ...await identity(source), ...await identity(source), "4096"], + Buffer.from("a.txt\0", "utf8"), + ); + assert.notEqual(selfRes.code, 0); + assert.equal(selfRes.stderr.trim(), "unsafe_source"); + + const unterminatedRes = await runEditor( + ["provision", ...await identity(source), ...await identity(destination), "4096"], + Buffer.from("a.txt", "utf8"), + ); + assert.notEqual(unterminatedRes.code, 0); + assert.equal(unterminatedRes.stderr.trim(), "invalid_input"); + + const escapeRes = await runEditor( + ["provision", ...await identity(source), ...await identity(destination), "4096"], + Buffer.from("../a.txt\0", "utf8"), + ); + assert.notEqual(escapeRes.code, 0); + assert.equal(escapeRes.stderr.trim(), "invalid_input"); + + const emptyEntryRes = await runEditor( + ["provision", ...await identity(source), ...await identity(destination), "4096"], + Buffer.from("a.txt\0\0a.txt\0", "utf8"), + ); + assert.notEqual(emptyEntryRes.code, 0); + assert.equal(emptyEntryRes.stderr.trim(), "invalid_input"); +}); + +test("provision handles >64 unique parent directories without leaking FDs", async (t) => { + if (process.platform !== "darwin") return; + const source = await directory(t); + const destination = await directory(t); + const paths = []; + for (let i = 0; i < 70; i += 1) { + const dir = `d${String(i).padStart(2, "0")}`; + await mkdir(path.join(source, dir)); + await writeFile(path.join(source, dir, "f.txt"), `v${i}`); + paths.push(`${dir}/f.txt`); + } + const result = await runEditor( + ["provision", ...await identity(source), ...await identity(destination), String(1024 * 1024)], + Buffer.from(`${paths.join("\0")}\0`, "utf8"), + ); + assert.equal(result.code, 0, result.stderr); + assert.equal(await readFile(path.join(destination, "d00", "f.txt"), "utf8"), "v0"); + assert.equal(await readFile(path.join(destination, "d69", "f.txt"), "utf8"), "v69"); +});