From 0bd15ddc847b55308176e8918a59fbdd4742364c Mon Sep 17 00:00:00 2001 From: Devvyn <22340871+opticon454@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:19:20 +0800 Subject: [PATCH 1/5] feat(cases): clone a repository into a custom folder Clone Repo could only clone under ~/codeman-cases. POST /api/cases/clone now takes an optional path (parent folder plus case name) and the Clone tab gets a Clone into a custom folder option with a Browse button, mirroring Create in a custom folder. The path is judged by prepareNewCasePath, the clone is registered as a linked case, the option is admin-only in multi-user mode, and an existing target folder is refused. --- CLAUDE.md | 2 +- docs/architecture-invariants.md | 2 +- docs/wiki/Core-Concepts.md | 2 +- src/web/public/index.html | 14 +- src/web/public/session-ui.js | 72 +++++++- src/web/routes/case-routes.ts | 95 ++++++++++- src/web/schemas.ts | 6 + test/routes/case-clone-custom-folder.test.ts | 169 +++++++++++++++++++ 8 files changed, 350 insertions(+), 12 deletions(-) create mode 100644 test/routes/case-clone-custom-folder.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index 3926a6b0..56ba4e2d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -244,7 +244,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin **Ultracode / workflow-run visualization** (opt-in, default OFF): the Workflow tool writes a completion artifact only at run *end*, so live in-flight runs exist solely as transcript dirs. `workflow-run-watcher.ts` therefore synthesizes ACTIVE runs from transcripts until the completion artifact appears and supersedes them. It is **STANDALONE** and deliberately never imports or touches `subagent-watcher.ts`, despite reading the same tree. Two independent toggles: `showUltracodeAgents` (docked panel) and `ultracodeFloatingWindows` (floating windows); the watcher starts if **either** is on. → [architecture-invariants#ultracode-and-workflow-run-visualization](docs/architecture-invariants.md#ultracode-and-workflow-run-visualization) -**Clone a repository as a case** (issue #236, Add Case → **Clone Repo**): `POST /api/cases/clone` clones synchronously into the caller's case space (bounded by `GIT_CLONE_TIMEOUT_MS`, no job store); `POST /api/cases/clone-preflight` checks anonymous cloneability and lists refs. Core in `src/git-clone.ts`. ⚠️ **The URL is a code-execution surface**: refuse every `::` form and a leading `-`, spawn only argv arrays with `--` before operands. ⚠️ Stay non-interactive (`gitNonInteractiveEnv()`) or the open request hangs; never collect credentials, refuse `user:password@` URLs. ⚠️ Timeout kills the process GROUP, remove the destination only if this attempt created it, and repo contents win over scaffolding (existing `CLAUDE.md` kept, hooks merged, repo `.claude/settings*` warned about). → [architecture-invariants#clone-a-repository-as-a-case](docs/architecture-invariants.md#clone-a-repository-as-a-case) +**Clone a repository as a case** (issue #236, Add Case → **Clone Repo**): `POST /api/cases/clone` clones synchronously into the caller's case space (bounded by `GIT_CLONE_TIMEOUT_MS`, no job store); `POST /api/cases/clone-preflight` checks anonymous cloneability and lists refs. Core in `src/git-clone.ts`. ⚠️ **The URL is a code-execution surface**: refuse every `::` form and a leading `-`, spawn only argv arrays with `--` before operands. ⚠️ Stay non-interactive (`gitNonInteractiveEnv()`) or the open request hangs; never collect credentials, refuse `user:password@` URLs. ⚠️ Timeout kills the process GROUP, remove the destination only if this attempt created it, and repo contents win over scaffolding (existing `CLAUDE.md` kept, hooks merged, repo `.claude/settings*` warned about). ⚠️ A `path` clones into a custom folder and registers a linked case: admin-only in multi-user mode, judged by `prepareNewCasePath()`, and an existing target (even empty) is refused. → [architecture-invariants#clone-a-repository-as-a-case](docs/architecture-invariants.md#clone-a-repository-as-a-case) **Git worktrees of a case** (case picker → **Git worktrees…**; `src/git-worktrees.ts`, `routes/worktree-routes.ts`): a local repository case keeps worktrees at `/.claude/worktrees/` on `worktree-`, Claude Code's own `--worktree` layout. ⚠️ Only that managed path is ever created or removed, every component `lstat`ed and realpath-checked (a symlinked `.claude` is refused). ⚠️ git never runs for a Docker or remote case, nor at or inside a Docker workspace (`worktree add` runs hooks and filters on the host). ⚠️ Remove is `git worktree remove` WITHOUT `--force`, refused while a live session is inside; branch delete is `-d`, never `-D`. ⚠️ Sessions start through the existing create paths (quick-start `worktree`, or `POST /api/sessions` `workingDir`), never a new spawn path. → [architecture-invariants#git-worktrees-of-a-case](docs/architecture-invariants.md#git-worktrees-of-a-case) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index ebba7973..63f047b0 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -468,7 +468,7 @@ Tests: `test/file-preview-markdown.test.ts` (jsdom-in-vm, pins every rule above) ### Clone a repository as a case -**Clone Repo tab** (issue #236, proposed by @DodgyBadger): `POST /api/cases/clone` clones a public repository into the caller's case space and registers it as a normal local case; `POST /api/cases/clone-preflight` answers "can this be cloned anonymously, and what refs does it have?" while the user is still typing. Core in `src/git-clone.ts`, split into a PURE half (URL parse, argv/env, `ls-remote` parse, stderr classification) and a thin IO half (`probeGitRemote`, `cloneRepository`). +**Clone Repo tab** (issue #236, proposed by @DodgyBadger): `POST /api/cases/clone` clones a public repository into the caller's case space and registers it as a normal local case; `POST /api/cases/clone-preflight` answers "can this be cloned anonymously, and what refs does it have?" while the user is still typing. Core in `src/git-clone.ts`, split into a PURE half (URL parse, argv/env, `ls-remote` parse, stderr classification) and a thin IO half (`probeGitRemote`, `cloneRepository`). An optional `path` (the **Clone into a custom folder** checkbox, parent folder plus case name) clones into that exact folder instead and registers it as a LINKED case, the same way `POST /api/cases` with a `path` does: it is judged by `prepareNewCasePath()` (`web/case-path.ts`: blocked trees, symlinks, parent must exist), is admin-only in multi-user mode (it writes an absolute path into the shared linked-cases registry), and refuses a folder that already exists, empty or not, because `cloneRepository` needs a fresh destination. Deleting such a case unlinks it and never removes the files. If the registry write fails after git finished, the folder is kept and the error says where it is. - ⚠️ **The URL is a code-execution surface, which is why it is parsed rather than forwarded.** `ext::sh -c ` makes git run an arbitrary command as its transport, and ANY `::` dispatches to a `git-remote-` helper, so every `::` form is refused outright. A repository starting with `-` is read by git as a flag; that is rejected AND every spawn puts `--` before the operands, because either defence alone is one edit away from being a hole. Spawns are argv arrays, never a shell (unlike `remote-hosts.ts`, which does build a shell line and must `shellescape`). The Zod schema deliberately only length-bounds `repository` — a weaker regex duplicate of `parseGitRepositoryUrl` would be the copy that drifts. - ⚠️ **Non-interactive or it hangs the request.** The clone is synchronous by design (no job store, no polling, no cancellation surface), so an invisible credential prompt would pin an open HTTP request until the timeout. `gitNonInteractiveEnv()` closes all four prompt paths at once: `GIT_TERMINAL_PROMPT=0`, empty `GIT_ASKPASS`/`SSH_ASKPASS` + `SSH_ASKPASS_REQUIRE=never` + empty `DISPLAY`, `GCM_INTERACTIVE=never`, and `ssh -oBatchMode=yes`. `HOME`/`PATH` are inherited on purpose — a user whose own agent or credential helper already works keeps working (so a private repo may well clone; Codeman just never collects or stores credentials, and refuses a `user:password@` URL). ⚠️ In multi-user mode a NON-ADMIN's clone and preflight run with `git -c credential.helper=` (`cloneWithoutCredentialHelpers`), because the helpers belong to the one server account every user shares; admins and single-user mode keep them. The Docker server image relies on exactly this: when built with the opt-in `CODEMAN_INSTALL_GH`/`CODEMAN_INSTALL_AZ` args it configures `gh` (github.com) and an `az`-backed helper (`docker/git-credential-azure-cli`, Azure DevOps) in its SYSTEM gitconfig, both silent until the user signs the CLI in, so a private clone there still fails fast rather than prompting. diff --git a/docs/wiki/Core-Concepts.md b/docs/wiki/Core-Concepts.md index c5762d60..85fb0416 100644 --- a/docs/wiki/Core-Concepts.md +++ b/docs/wiki/Core-Concepts.md @@ -25,7 +25,7 @@ Three ways to get one, all under **New or link a case…** at the bottom of the | How | Result | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Create New** | A fresh `~/codeman-cases/` with a scaffolded `CLAUDE.md`, or with **Create in a custom folder**, a new folder inside a parent you choose, scaffolded the same way and registered in place like a linked case. | -| **Clone Repo** | A repo cloned into `~/codeman-cases/` and registered as a case. Private repos need this machine's own git credentials (see below). | +| **Clone Repo** | A repo cloned into `~/codeman-cases/` (or into a folder you choose) and registered as a case. Private repos need this machine's own git credentials (see below). | | **Link Existing** | An existing folder anywhere on disk, registered in place. Nothing is copied or moved. | Linked cases keep living where they are. Deleting a case in Codeman removes the diff --git a/src/web/public/index.html b/src/web/public/index.html index 6611e6c3..195e5900 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -3654,7 +3654,19 @@
- Filled in from the URL. Cloned into ~/codeman-cases/<name>, so deleting the case deletes this working tree. + Filled in from the URL. Cloned into ~/codeman-cases/<name>, so deleting the case deletes this working tree. +
+
+ + By default the clone goes under ~/codeman-cases. Choose another folder and it is cloned there instead; it is listed like any other case, and deleting the case only unlinks it (your files stay). +
+
diff --git a/src/web/public/session-ui.js b/src/web/public/session-ui.js index 1e5961d4..ea462d4b 100644 --- a/src/web/public/session-ui.js +++ b/src/web/public/session-ui.js @@ -4097,6 +4097,15 @@ Object.assign(CodemanApp.prototype, { set('cloneRepoUrl', ''); set('cloneCaseName', ''); set('cloneRepoRef', ''); + set('cloneCasePath', ''); + // Custom folder starts off each time, and is not offered to a non-admin in multi-user mode: the + // server refuses it (it writes outside the cases directory and into the shared registry). + const customToggle = document.getElementById('cloneCustomPathToggle'); + if (customToggle) customToggle.checked = false; + const customRow = document.getElementById('cloneCustomPathToggleRow'); + const me = window.__codemanUser || {}; + if (customRow) customRow.style.display = me.multiUser && me.role !== 'admin' ? 'none' : ''; + this.toggleCloneCustomPath(); const shallow = document.getElementById('cloneShallow'); if (shallow) shallow.checked = false; const start = document.getElementById('cloneStartSession'); @@ -4124,6 +4133,52 @@ Object.assign(CodemanApp.prototype, { } }, + /** Custom-folder row for Clone Repo: shows or hides the parent-folder field and rewords the name hint. */ + toggleCloneCustomPath() { + const custom = document.getElementById('cloneCustomPathToggle'); + const row = document.getElementById('cloneCustomPathRow'); + if (!custom || !row) return; + row.style.display = custom.checked ? '' : 'none'; + const hint = document.getElementById('cloneCaseNameHint'); + if (hint) { + hint.textContent = custom.checked + ? 'Filled in from the URL. Cloned into a folder of this name inside the parent folder below.' + : 'Filled in from the URL. Cloned into ~/codeman-cases/, so deleting the case deletes this working tree.'; + } + this.updateCloneCasePathPreview(); + }, + + /** The folder the clone would be created in: the parent field plus the case name. */ + _cloneTargetPath() { + const rawParent = (document.getElementById('cloneCasePath')?.value || '').trim(); + const name = (document.getElementById('cloneCaseName')?.value || '').trim(); + if (!rawParent || !name) return ''; + // Trailing slashes off, but `/` stays the root rather than becoming an empty path. + return `${rawParent.replace(/\/+$/, '')}/${name}`; + }, + + updateCloneCasePathPreview() { + const hint = document.getElementById('cloneCasePathPreview'); + if (!hint) return; + const target = this._cloneTargetPath(); + hint.textContent = target ? `Will clone into: ${target}` : 'Pick the folder the clone should be created inside.'; + }, + + openCloneCasePathPicker() { + const input = document.getElementById('cloneCasePath'); + PathPicker.open({ + title: 'Choose the folder to clone into', + initialPath: input.value.trim(), + directoriesOnly: true, + onSelect: (path) => { + input.value = path; + this.updateCloneCasePathPreview(); + input.focus(); + input.setSelectionRange(path.length, path.length); + }, + }); + }, + _setCloneStatus(message, kind) { const el = document.getElementById('cloneRepoStatus'); if (!el) return; @@ -4159,12 +4214,14 @@ Object.assign(CodemanApp.prototype, { onCloneNameEdited() { // Once the user types a name, autofill stops fighting them. this._cloneNameEdited = !!document.getElementById('cloneCaseName')?.value.trim(); + this.updateCloneCasePathPreview(); }, onCloneUrlInput() { const url = document.getElementById('cloneRepoUrl')?.value.trim() || ''; const nameInput = document.getElementById('cloneCaseName'); if (nameInput && !this._cloneNameEdited) nameInput.value = this._repoNameFromUrl(url); + this.updateCloneCasePathPreview(); clearTimeout(this._clonePreflightTimer); this._clonePreflightAbort?.abort(); this._clonePreflightAbort = null; @@ -4220,6 +4277,7 @@ Object.assign(CodemanApp.prototype, { // the case name is validated against), but never over a name the user typed. const nameInput = document.getElementById('cloneCaseName'); if (nameInput && !this._cloneNameEdited && parse.suggestedName) nameInput.value = parse.suggestedName; + this.updateCloneCasePathPreview(); const where = parse.owner ? `${parse.provider} ${parse.owner}/${parse.repo}` : `${parse.provider} ${parse.repo}`; if (data.gitAvailable === false) { @@ -4272,6 +4330,12 @@ Object.assign(CodemanApp.prototype, { return; } + const customFolder = !!document.getElementById('cloneCustomPathToggle')?.checked; + if (customFolder && !(document.getElementById('cloneCasePath')?.value || '').trim()) { + this.showToast('Choose the folder to clone into', 'error'); + return; + } + this._setCloneStatus(`Cloning ${url}… this can take a while for a large repository.`, ''); try { const res = await fetch('/api/cases/clone', { @@ -4279,7 +4343,13 @@ Object.assign(CodemanApp.prototype, { headers: { 'Content-Type': 'application/json' }, // Zod `.optional()` rejects an explicit null, and JSON.stringify keeps one // on the wire — omit the empty fields instead of sending null. - body: JSON.stringify({ name, repository: url, ...(ref ? { ref } : {}), ...(shallow ? { shallow: true } : {}) }), + body: JSON.stringify({ + name, + repository: url, + ...(ref ? { ref } : {}), + ...(shallow ? { shallow: true } : {}), + ...(customFolder ? { path: this._cloneTargetPath() } : {}), + }), }); const data = await res.json(); if (!data.success) { diff --git a/src/web/routes/case-routes.ts b/src/web/routes/case-routes.ts index b0849767..51c09a39 100644 --- a/src/web/routes/case-routes.ts +++ b/src/web/routes/case-routes.ts @@ -686,7 +686,7 @@ export function registerCaseRoutes( warnings: string[]; }> > => { - const { name, repository, ref, shallow, description } = parseBody(CloneCaseSchema, req.body); + const { name, repository, ref, shallow, description, path: customPath } = parseBody(CloneCaseSchema, req.body); const user = getAuthUser(req); const parsed = parseGitRepositoryUrl(repository); @@ -705,8 +705,63 @@ export function registerCaseRoutes( ); } + // A custom folder writes outside the cases directory and registers the path in the shared, + // ownerless linked-cases registry, so it carries the same bar as POST /api/cases/link. + if (customPath !== undefined) { + const denied = adminOnly(req, reply); + if (denied) return denied; + } + const casesDir = resolveCasesDir(user); - const casePath = validatePathWithinBase(name, casesDir); + let casePath: string | null; + if (customPath !== undefined) { + const prepared = await prepareNewCasePath(customPath, { + home: homedir(), + dataDir: getDataDir(), + casesDirs: [...new Set([casesDir, resolveCasesDir()])], + }); + if (!prepared.ok) { + reply.code( + prepared.code === 'UNREACHABLE' + ? 422 + : prepared.code === 'NOT_FOUND' + ? 404 + : prepared.code === 'EXISTS' + ? 409 + : 400 + ); + return createErrorResponse( + prepared.code === 'UNREACHABLE' + ? ApiErrorCode.OPERATION_FAILED + : prepared.code === 'NOT_FOUND' + ? ApiErrorCode.NOT_FOUND + : prepared.code === 'EXISTS' + ? ApiErrorCode.ALREADY_EXISTS + : ApiErrorCode.INVALID_INPUT, + prepared.reason + ); + } + // git clones into a fresh folder it creates itself; an empty existing one is refused rather than + // removed and re-made (the removal could race another writer). + if (prepared.existedEmpty) { + reply.code(409); + return createErrorResponse( + ApiErrorCode.ALREADY_EXISTS, + `${prepared.path} already exists. Pick a parent folder where the case folder does not exist yet.` + ); + } + casePath = prepared.path; + // The same folder listed as a local case in the cases dir would make deleting it remove files. + if (existsSync(join(casesDir, name))) { + reply.code(409); + return createErrorResponse( + ApiErrorCode.ALREADY_EXISTS, + 'A case with this name already exists in codeman-cases.' + ); + } + } else { + casePath = validatePathWithinBase(name, casesDir); + } if (!casePath) return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Invalid case path'); // Reject a duplicate name across EVERY case kind before invoking git, so a @@ -715,6 +770,11 @@ export function registerCaseRoutes( const linkedCases = await readLinkedCases(); const dockerCases = await readDockerCases(CODEMAN_CONFIG_DIR); const remoteCases = await readRemoteCases(CODEMAN_CONFIG_DIR); + const linkedAs = Object.entries(linkedCases).find(([, p]) => p === casePath)?.[0]; + if (linkedAs && customPath !== undefined) { + reply.code(409); + return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, `That folder is already the case "${linkedAs}"`); + } if ( existsSync(casePath) || linkedCases[name] || @@ -724,11 +784,14 @@ export function registerCaseRoutes( return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, 'Case already exists'); } - // git creates the leaf, not necessarily the case space above it. - try { - mkdirSync(casesDir, { recursive: true }); - } catch (err) { - return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err)); + // git creates the leaf, not necessarily the case space above it (a custom folder's parent + // already exists: prepareNewCasePath refused a missing one). + if (customPath === undefined) { + try { + mkdirSync(casesDir, { recursive: true }); + } catch (err) { + return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err)); + } } const clone = await cloneRepository({ @@ -794,6 +857,24 @@ export function registerCaseRoutes( warnings.push(`Case scaffolding was incomplete: ${getErrorMessage(err)}`); } + if (customPath !== undefined) { + // Re-read right before writing so a case linked while git ran is not dropped. Like + // POST /api/cases/link the write is not serialized, so this only narrows the window. + try { + const fresh = await readLinkedCases(); + if (fresh[name]) throw new Error(`Case "${name}" was linked while the clone ran`); + fresh[name] = casePath; + await fs.writeFile(LINKED_CASES_FILE, JSON.stringify(fresh, null, 2)); + } catch (err) { + // The clone itself succeeded: keep the folder (the user waited for it) and say where it is. + reply.code(500); + return createErrorResponse( + ApiErrorCode.OPERATION_FAILED, + `Cloned into ${casePath} but could not register the case (${getErrorMessage(err)}). Use Link Existing to add it.` + ); + } + } + ctx.broadcast(SseEvent.CaseCreated, { name, path: casePath }); return { success: true, diff --git a/src/web/schemas.ts b/src/web/schemas.ts index 6c1ce474..13a8b038 100644 --- a/src/web/schemas.ts +++ b/src/web/schemas.ts @@ -785,6 +785,12 @@ export const CloneCaseSchema = z.object({ /** `--depth 1`. */ shallow: z.boolean().optional(), description: z.string().max(1000).optional(), + /** + * Clone into this exact folder (parent + case name) instead of under the cases directory, and + * register it as a linked case. Absolute or starting with `~`; only length-bounded here, since + * `prepareNewCasePath()` (web/case-path.ts) judges it and produces the user-facing reason. + */ + path: z.string().min(1).max(1000).optional(), }); /** Schema for POST /api/cases/clone-preflight — ask the remote what it has, clone nothing. */ diff --git a/test/routes/case-clone-custom-folder.test.ts b/test/routes/case-clone-custom-folder.test.ts new file mode 100644 index 00000000..0c700387 --- /dev/null +++ b/test/routes/case-clone-custom-folder.test.ts @@ -0,0 +1,169 @@ +/** + * @fileoverview POST /api/cases/clone with a `path`: clone into a custom folder and register it as a + * linked case. Real filesystem under test/setup.ts's temp HOME and a REAL `git` cloning a local bare + * repo (the path policy itself is in test/case-path.test.ts). Port: N/A (app.inject()). + * + * Like case-custom-path-routes.test.ts this suite rewrites the linked-cases registry, so it refuses to + * start outside the sandboxed HOME (a raw `npx vitest` would reach the real ~/.codeman). + */ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { homedir, tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createRouteTestHarness } from './_route-test-utils.js'; +import { registerCaseRoutes } from '../../src/web/routes/case-routes.js'; +import { dataPath } from '../../src/config/instance.js'; +import { isGitAvailable } from '../../src/git-clone.js'; +import { isSandboxedHome, safeRmHomeTree } from '../mocks/index.js'; + +const LINKED = () => dataPath('linked-cases.json'); +const linked = (): Record => (existsSync(LINKED()) ? JSON.parse(readFileSync(LINKED(), 'utf8')) : {}); +const clone = (app: Awaited>['app'], payload: Record) => + app.inject({ method: 'POST', url: '/api/cases/clone', payload }); + +describe.skipIf(!isGitAvailable())('POST /api/cases/clone with a custom folder', () => { + let root: string; + let origin: string; + let workDir = ''; + + const git = (args: string[], cwd: string) => + execFileSync('git', args, { cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] }); + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'codeman-clone-custom-')); + origin = join(root, 'origin.git'); + mkdirSync(origin); + git(['init', '--bare', '--quiet'], origin); + const work = join(root, 'work'); + mkdirSync(work); + git(['init', '--quiet'], work); + git(['config', 'user.email', 'test@example.com'], work); + git(['config', 'user.name', 'Codeman Test'], work); + writeFileSync(join(work, 'README.md'), '# fixture\n'); + git(['add', '.'], work); + git(['commit', '--quiet', '-m', 'initial'], work); + git(['branch', '-M', 'main'], work); + git(['remote', 'add', 'origin', origin], work); + git(['push', '--quiet', 'origin', 'main'], work); + git(['symbolic-ref', 'HEAD', 'refs/heads/main'], origin); + }); + afterAll(() => rmSync(root, { recursive: true, force: true })); + + beforeEach(() => { + if (!isSandboxedHome()) { + throw new Error('case-clone-custom-folder.test.ts rewrites the linked-cases registry: run it via npm test'); + } + safeRmHomeTree(LINKED()); + // Resolved, because the server answers with the symlink-resolved folder. + workDir = realpathSync(mkdtempSync(join(homedir(), 'clone-custom-'))); + }); + afterEach(() => { + delete process.env.CODEMAN_MULTIUSER; + if (workDir) safeRmHomeTree(workDir); + workDir = ''; + if (isSandboxedHome()) safeRmHomeTree(LINKED()); + }); + + it('clones into the chosen folder, scaffolds it and registers it as a linked case', async () => { + const { app, ctx } = await createRouteTestHarness(registerCaseRoutes); + const target = join(workDir, 'my-clone'); + const res = await clone(app, { name: 'my-clone', repository: origin, path: target }); + expect(res.statusCode).toBe(200); + expect(res.json().data.case).toEqual({ name: 'my-clone', path: target }); + expect(existsSync(join(target, 'README.md'))).toBe(true); + expect(existsSync(join(target, '.git'))).toBe(true); + expect(existsSync(join(target, '.claude', 'settings.local.json'))).toBe(true); + expect(linked()).toEqual({ 'my-clone': target }); + expect(ctx.broadcast).toHaveBeenCalledWith('case:created', { name: 'my-clone', path: target }); + // Nothing lands under the cases directory. + expect(existsSync(join(homedir(), 'codeman-cases', 'my-clone'))).toBe(false); + }); + + it('expands ~ in the folder', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + const folder = workDir.slice(homedir().length + 1); + const res = await clone(app, { name: 'tilde', repository: origin, path: `~/${folder}/tilde` }); + expect(res.statusCode).toBe(200); + expect(existsSync(join(workDir, 'tilde', 'README.md'))).toBe(true); + }); + + it('refuses a parent folder that does not exist, and creates nothing', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + const res = await clone(app, { name: 'orphan', repository: origin, path: join(workDir, 'nope', 'orphan') }); + expect(res.statusCode).toBe(404); + expect(existsSync(join(workDir, 'nope'))).toBe(false); + expect(linked()).toEqual({}); + }); + + it('refuses a target folder that already has files, and leaves them alone', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + const target = join(workDir, 'busy'); + mkdirSync(target); + writeFileSync(join(target, 'mine.txt'), 'keep me'); + const res = await clone(app, { name: 'busy', repository: origin, path: target }); + expect(res.statusCode).toBe(409); + expect(readFileSync(join(target, 'mine.txt'), 'utf8')).toBe('keep me'); + expect(linked()).toEqual({}); + }); + + it('refuses an existing EMPTY folder rather than removing and re-making it', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + const target = join(workDir, 'empty'); + mkdirSync(target); + const res = await clone(app, { name: 'empty', repository: origin, path: target }); + expect(res.statusCode).toBe(409); + expect(res.json().error).toMatch(/already exists/); + expect(existsSync(join(target, '.git'))).toBe(false); + }); + + it('refuses a blocked tree such as ~/.ssh', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + mkdirSync(join(homedir(), '.ssh'), { recursive: true }); + const res = await clone(app, { name: 'sneaky', repository: origin, path: join(homedir(), '.ssh', 'sneaky') }); + expect(res.statusCode).toBe(400); + expect(existsSync(join(homedir(), '.ssh', 'sneaky'))).toBe(false); + }); + + it('refuses a name already linked, before running git', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + writeFileSync(LINKED(), JSON.stringify({ taken: join(workDir, 'elsewhere') })); + const res = await clone(app, { name: 'taken', repository: origin, path: join(workDir, 'taken') }); + // The harness has no preSerialization status mapping, so read the envelope's code. + expect(res.json().errorCode).toBe('ALREADY_EXISTS'); + expect(existsSync(join(workDir, 'taken'))).toBe(false); + }); + + it('leaves no folder behind when the clone fails', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + const target = join(workDir, 'ghost'); + const res = await clone(app, { name: 'ghost', repository: join(root, 'no-such-repo.git'), path: target }); + expect(res.json().errorCode).toBe('NOT_FOUND'); + expect(existsSync(target)).toBe(false); + expect(linked()).toEqual({}); + }); + + it('without a path the clone still goes under the cases directory and is not linked', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + const res = await clone(app, { name: 'custom-folder-default', repository: origin }); + try { + expect(res.statusCode).toBe(200); + expect(res.json().data.case.path).toBe(join(homedir(), 'codeman-cases', 'custom-folder-default')); + expect(linked()).toEqual({}); + } finally { + safeRmHomeTree(join(homedir(), 'codeman-cases', 'custom-folder-default')); + } + }); + + it('multi-user: a non-admin is refused (403) and nothing is cloned; an admin is allowed', async () => { + process.env.CODEMAN_MULTIUSER = '1'; + const user = await createRouteTestHarness(registerCaseRoutes, { authUser: { username: 'bob', role: 'user' } }); + const denied = await clone(user.app, { name: 'bobs', repository: origin, path: join(workDir, 'bobs') }); + expect(denied.statusCode).toBe(403); + expect(existsSync(join(workDir, 'bobs'))).toBe(false); + expect(linked()).toEqual({}); + const admin = await createRouteTestHarness(registerCaseRoutes, { authUser: { username: 'root', role: 'admin' } }); + const ok = await clone(admin.app, { name: 'roots', repository: origin, path: join(workDir, 'roots') }); + expect(ok.statusCode).toBe(200); + }); +}); From 68bd7e4d15a4d38b5036e8d3fe0d1a6d9968df36 Mon Sep 17 00:00:00 2001 From: Devvyn <22340871+opticon454@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:43:11 +0800 Subject: [PATCH 2/5] fix(cases): clone into the chosen folder itself, not a subfolder of it The custom folder was treated as a parent, so the repository landed in /. The chosen folder is now the clone destination: an empty existing folder is cloned into directly (CloneOptions.intoEmptyDir, no temporary sibling, never removed on failure), a new folder is created, and a folder with files is refused. --- CLAUDE.md | 2 +- docs/architecture-invariants.md | 2 +- docs/wiki/Core-Concepts.md | 2 +- src/git-clone.ts | 45 +++++++++++++++++--- src/web/public/index.html | 6 +-- src/web/public/session-ui.js | 15 +++---- src/web/routes/case-routes.ts | 19 ++++----- test/routes/case-clone-custom-folder.test.ts | 45 +++++++++++++++----- 8 files changed, 93 insertions(+), 43 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 56ba4e2d..343f6cd6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -244,7 +244,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin **Ultracode / workflow-run visualization** (opt-in, default OFF): the Workflow tool writes a completion artifact only at run *end*, so live in-flight runs exist solely as transcript dirs. `workflow-run-watcher.ts` therefore synthesizes ACTIVE runs from transcripts until the completion artifact appears and supersedes them. It is **STANDALONE** and deliberately never imports or touches `subagent-watcher.ts`, despite reading the same tree. Two independent toggles: `showUltracodeAgents` (docked panel) and `ultracodeFloatingWindows` (floating windows); the watcher starts if **either** is on. → [architecture-invariants#ultracode-and-workflow-run-visualization](docs/architecture-invariants.md#ultracode-and-workflow-run-visualization) -**Clone a repository as a case** (issue #236, Add Case → **Clone Repo**): `POST /api/cases/clone` clones synchronously into the caller's case space (bounded by `GIT_CLONE_TIMEOUT_MS`, no job store); `POST /api/cases/clone-preflight` checks anonymous cloneability and lists refs. Core in `src/git-clone.ts`. ⚠️ **The URL is a code-execution surface**: refuse every `::` form and a leading `-`, spawn only argv arrays with `--` before operands. ⚠️ Stay non-interactive (`gitNonInteractiveEnv()`) or the open request hangs; never collect credentials, refuse `user:password@` URLs. ⚠️ Timeout kills the process GROUP, remove the destination only if this attempt created it, and repo contents win over scaffolding (existing `CLAUDE.md` kept, hooks merged, repo `.claude/settings*` warned about). ⚠️ A `path` clones into a custom folder and registers a linked case: admin-only in multi-user mode, judged by `prepareNewCasePath()`, and an existing target (even empty) is refused. → [architecture-invariants#clone-a-repository-as-a-case](docs/architecture-invariants.md#clone-a-repository-as-a-case) +**Clone a repository as a case** (issue #236, Add Case → **Clone Repo**): `POST /api/cases/clone` clones synchronously into the caller's case space (bounded by `GIT_CLONE_TIMEOUT_MS`, no job store); `POST /api/cases/clone-preflight` checks anonymous cloneability and lists refs. Core in `src/git-clone.ts`. ⚠️ **The URL is a code-execution surface**: refuse every `::` form and a leading `-`, spawn only argv arrays with `--` before operands. ⚠️ Stay non-interactive (`gitNonInteractiveEnv()`) or the open request hangs; never collect credentials, refuse `user:password@` URLs. ⚠️ Timeout kills the process GROUP, remove the destination only if this attempt created it, and repo contents win over scaffolding (existing `CLAUDE.md` kept, hooks merged, repo `.claude/settings*` warned about). ⚠️ A `path` is the folder cloned INTO (no case-name subfolder) and registers a linked case: admin-only in multi-user mode, judged by `prepareNewCasePath()`, empty or new only (`intoEmptyDir` clones straight into an empty one and never removes it). → [architecture-invariants#clone-a-repository-as-a-case](docs/architecture-invariants.md#clone-a-repository-as-a-case) **Git worktrees of a case** (case picker → **Git worktrees…**; `src/git-worktrees.ts`, `routes/worktree-routes.ts`): a local repository case keeps worktrees at `/.claude/worktrees/` on `worktree-`, Claude Code's own `--worktree` layout. ⚠️ Only that managed path is ever created or removed, every component `lstat`ed and realpath-checked (a symlinked `.claude` is refused). ⚠️ git never runs for a Docker or remote case, nor at or inside a Docker workspace (`worktree add` runs hooks and filters on the host). ⚠️ Remove is `git worktree remove` WITHOUT `--force`, refused while a live session is inside; branch delete is `-d`, never `-D`. ⚠️ Sessions start through the existing create paths (quick-start `worktree`, or `POST /api/sessions` `workingDir`), never a new spawn path. → [architecture-invariants#git-worktrees-of-a-case](docs/architecture-invariants.md#git-worktrees-of-a-case) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 63f047b0..4b7a7ec5 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -468,7 +468,7 @@ Tests: `test/file-preview-markdown.test.ts` (jsdom-in-vm, pins every rule above) ### Clone a repository as a case -**Clone Repo tab** (issue #236, proposed by @DodgyBadger): `POST /api/cases/clone` clones a public repository into the caller's case space and registers it as a normal local case; `POST /api/cases/clone-preflight` answers "can this be cloned anonymously, and what refs does it have?" while the user is still typing. Core in `src/git-clone.ts`, split into a PURE half (URL parse, argv/env, `ls-remote` parse, stderr classification) and a thin IO half (`probeGitRemote`, `cloneRepository`). An optional `path` (the **Clone into a custom folder** checkbox, parent folder plus case name) clones into that exact folder instead and registers it as a LINKED case, the same way `POST /api/cases` with a `path` does: it is judged by `prepareNewCasePath()` (`web/case-path.ts`: blocked trees, symlinks, parent must exist), is admin-only in multi-user mode (it writes an absolute path into the shared linked-cases registry), and refuses a folder that already exists, empty or not, because `cloneRepository` needs a fresh destination. Deleting such a case unlinks it and never removes the files. If the registry write fails after git finished, the folder is kept and the error says where it is. +**Clone Repo tab** (issue #236, proposed by @DodgyBadger): `POST /api/cases/clone` clones a public repository into the caller's case space and registers it as a normal local case; `POST /api/cases/clone-preflight` answers "can this be cloned anonymously, and what refs does it have?" while the user is still typing. Core in `src/git-clone.ts`, split into a PURE half (URL parse, argv/env, `ls-remote` parse, stderr classification) and a thin IO half (`probeGitRemote`, `cloneRepository`). An optional `path` (the **Clone into a custom folder** checkbox) is the folder the repository is cloned INTO, exactly as given (the case name adds no subfolder), and it registers a LINKED case, the same way `POST /api/cases` with a `path` does: it is judged by `prepareNewCasePath()` (`web/case-path.ts`: blocked trees, symlinks, parent must exist), is admin-only in multi-user mode (it writes an absolute path into the shared linked-cases registry), and must be empty or not exist yet. An existing empty folder is cloned into directly (`CloneOptions.intoEmptyDir`: no temporary sibling and no rename, so a mount point works; a failed attempt empties it again but never removes it); a folder with anything in it is refused. Deleting such a case unlinks it and never removes the files. If the registry write fails after git finished, the folder is kept and the error says where it is. - ⚠️ **The URL is a code-execution surface, which is why it is parsed rather than forwarded.** `ext::sh -c ` makes git run an arbitrary command as its transport, and ANY `::` dispatches to a `git-remote-` helper, so every `::` form is refused outright. A repository starting with `-` is read by git as a flag; that is rejected AND every spawn puts `--` before the operands, because either defence alone is one edit away from being a hole. Spawns are argv arrays, never a shell (unlike `remote-hosts.ts`, which does build a shell line and must `shellescape`). The Zod schema deliberately only length-bounds `repository` — a weaker regex duplicate of `parseGitRepositoryUrl` would be the copy that drifts. - ⚠️ **Non-interactive or it hangs the request.** The clone is synchronous by design (no job store, no polling, no cancellation surface), so an invisible credential prompt would pin an open HTTP request until the timeout. `gitNonInteractiveEnv()` closes all four prompt paths at once: `GIT_TERMINAL_PROMPT=0`, empty `GIT_ASKPASS`/`SSH_ASKPASS` + `SSH_ASKPASS_REQUIRE=never` + empty `DISPLAY`, `GCM_INTERACTIVE=never`, and `ssh -oBatchMode=yes`. `HOME`/`PATH` are inherited on purpose — a user whose own agent or credential helper already works keeps working (so a private repo may well clone; Codeman just never collects or stores credentials, and refuses a `user:password@` URL). ⚠️ In multi-user mode a NON-ADMIN's clone and preflight run with `git -c credential.helper=` (`cloneWithoutCredentialHelpers`), because the helpers belong to the one server account every user shares; admins and single-user mode keep them. The Docker server image relies on exactly this: when built with the opt-in `CODEMAN_INSTALL_GH`/`CODEMAN_INSTALL_AZ` args it configures `gh` (github.com) and an `az`-backed helper (`docker/git-credential-azure-cli`, Azure DevOps) in its SYSTEM gitconfig, both silent until the user signs the CLI in, so a private clone there still fails fast rather than prompting. diff --git a/docs/wiki/Core-Concepts.md b/docs/wiki/Core-Concepts.md index 85fb0416..fa849ba4 100644 --- a/docs/wiki/Core-Concepts.md +++ b/docs/wiki/Core-Concepts.md @@ -25,7 +25,7 @@ Three ways to get one, all under **New or link a case…** at the bottom of the | How | Result | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Create New** | A fresh `~/codeman-cases/` with a scaffolded `CLAUDE.md`, or with **Create in a custom folder**, a new folder inside a parent you choose, scaffolded the same way and registered in place like a linked case. | -| **Clone Repo** | A repo cloned into `~/codeman-cases/` (or into a folder you choose) and registered as a case. Private repos need this machine's own git credentials (see below). | +| **Clone Repo** | A repo cloned into `~/codeman-cases/` (or straight into an empty folder you choose) and registered as a case. Private repos need this machine's own git credentials (see below). | | **Link Existing** | An existing folder anywhere on disk, registered in place. Nothing is copied or moved. | Linked cases keep living where they are. Deleting a case in Codeman removes the diff --git a/src/git-clone.ts b/src/git-clone.ts index ef3380e8..249e4234 100644 --- a/src/git-clone.ts +++ b/src/git-clone.ts @@ -50,7 +50,7 @@ import { spawn, execFileSync } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import { existsSync } from 'node:fs'; -import { rename, rm } from 'node:fs/promises'; +import { lstat, readdir, rename, rm } from 'node:fs/promises'; import { basename, dirname, join } from 'node:path'; import { EXEC_TIMEOUT_MS } from './config/exec-timeout.js'; @@ -188,8 +188,13 @@ export interface GitFailure { export interface CloneOptions { /** Pre-validated operand from `parseGitRepositoryUrl`. */ repository: string; - /** Absolute destination directory. Must NOT exist; created by git. */ + /** Absolute destination directory. Must NOT exist (created by git), unless `intoEmptyDir` is set. */ destination: string; + /** + * Clone straight into `destination` when it already exists as an EMPTY directory (the folder a user + * picked), instead of refusing it. A folder with anything in it, or a symlink, is still refused. + */ + intoEmptyDir?: boolean; /** Optional branch or tag (`--branch --single-branch`). */ ref?: string; /** `--depth 1`: history-less but much faster on large repos. */ @@ -847,6 +852,25 @@ export async function probeGitRemote( }; } +/** True for a real (not symlinked) directory with nothing in it. Any read error counts as not empty. */ +async function isEmptyDirectory(path: string): Promise { + try { + const st = await lstat(path); + return st.isDirectory() && (await readdir(path)).length === 0; + } catch { + return false; + } +} + +/** Remove everything inside `path`, keeping `path` itself. Best effort. */ +async function emptyDirectory(path: string): Promise { + try { + for (const entry of await readdir(path)) await rm(join(path, entry), { recursive: true, force: true }); + } catch { + /* nothing to clean, or it vanished */ + } +} + /** * Clone `repository` into `destination`. * @@ -872,10 +896,19 @@ export async function cloneRepository(opts: CloneOptions): Promise }; } if (existsSync(opts.destination)) { - return { - ok: false, - failure: { code: 'DESTINATION_EXISTS', message: 'The destination directory already exists.', stderr: '' }, - }; + if (!opts.intoEmptyDir || !(await isEmptyDirectory(opts.destination))) { + return { + ok: false, + failure: { code: 'DESTINATION_EXISTS', message: 'The destination directory already exists.', stderr: '' }, + }; + } + // The folder is the user's own, so there is no temporary sibling to rename into place: git fills it. + const direct = await runGit(buildCloneArgs(opts), opts.timeoutMs ?? GIT_CLONE_TIMEOUT_MS, MAX_STDERR_BYTES); + if (direct.code === 0 && !direct.spawnError) return { ok: true, stderr: sanitizeGitOutput(direct.stderr) }; + // It was empty when the clone began, so whatever is in it now is this attempt's partial tree. The + // folder itself stays. + await emptyDirectory(opts.destination); + return { ok: false, failure: classifyGitFailure(direct.stderr, direct.timedOut, direct.spawnError) }; } // Sibling of the destination (same filesystem), so the rename is atomic. diff --git a/src/web/public/index.html b/src/web/public/index.html index 195e5900..d88d2ec7 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -3658,15 +3658,15 @@
- By default the clone goes under ~/codeman-cases. Choose another folder and it is cloned there instead; it is listed like any other case, and deleting the case only unlinks it (your files stay). + By default the clone goes under ~/codeman-cases. Choose a folder and the repository is cloned into that folder itself (it must be empty); it is listed like any other case, and deleting the case only unlinks it (your files stay).
diff --git a/src/web/public/session-ui.js b/src/web/public/session-ui.js index ea462d4b..c1455d00 100644 --- a/src/web/public/session-ui.js +++ b/src/web/public/session-ui.js @@ -4142,26 +4142,24 @@ Object.assign(CodemanApp.prototype, { const hint = document.getElementById('cloneCaseNameHint'); if (hint) { hint.textContent = custom.checked - ? 'Filled in from the URL. Cloned into a folder of this name inside the parent folder below.' + ? 'Filled in from the URL. Names the case only: the repository is cloned into the folder chosen below.' : 'Filled in from the URL. Cloned into ~/codeman-cases/, so deleting the case deletes this working tree.'; } this.updateCloneCasePathPreview(); }, - /** The folder the clone would be created in: the parent field plus the case name. */ + /** The folder the repository is cloned into: exactly what the field holds (no case name is added). */ _cloneTargetPath() { - const rawParent = (document.getElementById('cloneCasePath')?.value || '').trim(); - const name = (document.getElementById('cloneCaseName')?.value || '').trim(); - if (!rawParent || !name) return ''; + const raw = (document.getElementById('cloneCasePath')?.value || '').trim(); // Trailing slashes off, but `/` stays the root rather than becoming an empty path. - return `${rawParent.replace(/\/+$/, '')}/${name}`; + return raw.length > 1 ? raw.replace(/\/+$/, '') || '/' : raw; }, updateCloneCasePathPreview() { const hint = document.getElementById('cloneCasePathPreview'); if (!hint) return; const target = this._cloneTargetPath(); - hint.textContent = target ? `Will clone into: ${target}` : 'Pick the folder the clone should be created inside.'; + hint.textContent = target ? `Will clone into: ${target}` : 'Pick the empty folder to clone into.'; }, openCloneCasePathPicker() { @@ -4214,14 +4212,12 @@ Object.assign(CodemanApp.prototype, { onCloneNameEdited() { // Once the user types a name, autofill stops fighting them. this._cloneNameEdited = !!document.getElementById('cloneCaseName')?.value.trim(); - this.updateCloneCasePathPreview(); }, onCloneUrlInput() { const url = document.getElementById('cloneRepoUrl')?.value.trim() || ''; const nameInput = document.getElementById('cloneCaseName'); if (nameInput && !this._cloneNameEdited) nameInput.value = this._repoNameFromUrl(url); - this.updateCloneCasePathPreview(); clearTimeout(this._clonePreflightTimer); this._clonePreflightAbort?.abort(); this._clonePreflightAbort = null; @@ -4277,7 +4273,6 @@ Object.assign(CodemanApp.prototype, { // the case name is validated against), but never over a name the user typed. const nameInput = document.getElementById('cloneCaseName'); if (nameInput && !this._cloneNameEdited && parse.suggestedName) nameInput.value = parse.suggestedName; - this.updateCloneCasePathPreview(); const where = parse.owner ? `${parse.provider} ${parse.owner}/${parse.repo}` : `${parse.provider} ${parse.repo}`; if (data.gitAvailable === false) { diff --git a/src/web/routes/case-routes.ts b/src/web/routes/case-routes.ts index 51c09a39..cb7f9389 100644 --- a/src/web/routes/case-routes.ts +++ b/src/web/routes/case-routes.ts @@ -714,6 +714,7 @@ export function registerCaseRoutes( const casesDir = resolveCasesDir(user); let casePath: string | null; + let intoEmptyDir = false; if (customPath !== undefined) { const prepared = await prepareNewCasePath(customPath, { home: homedir(), @@ -738,18 +739,12 @@ export function registerCaseRoutes( : prepared.code === 'EXISTS' ? ApiErrorCode.ALREADY_EXISTS : ApiErrorCode.INVALID_INPUT, - prepared.reason - ); - } - // git clones into a fresh folder it creates itself; an empty existing one is refused rather than - // removed and re-made (the removal could race another writer). - if (prepared.existedEmpty) { - reply.code(409); - return createErrorResponse( - ApiErrorCode.ALREADY_EXISTS, - `${prepared.path} already exists. Pick a parent folder where the case folder does not exist yet.` + prepared.code === 'EXISTS' + ? `${customPath} already has files in it. Pick an empty folder, or a folder that does not exist yet.` + : prepared.reason ); } + intoEmptyDir = prepared.existedEmpty; casePath = prepared.path; // The same folder listed as a local case in the cases dir would make deleting it remove files. if (existsSync(join(casesDir, name))) { @@ -776,7 +771,8 @@ export function registerCaseRoutes( return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, `That folder is already the case "${linkedAs}"`); } if ( - existsSync(casePath) || + // A custom folder was judged by prepareNewCasePath (an existing empty one is fine). + (customPath === undefined && existsSync(casePath)) || linkedCases[name] || dockerCases.some((item) => item.name === name) || remoteCases.some((item) => item.name === name) @@ -797,6 +793,7 @@ export function registerCaseRoutes( const clone = await cloneRepository({ repository: parsed.repository, destination: casePath, + ...(intoEmptyDir ? { intoEmptyDir: true } : {}), withoutCredentialHelpers: cloneWithoutCredentialHelpers(req), ...(ref ? { ref } : {}), ...(shallow ? { shallow: true } : {}), diff --git a/test/routes/case-clone-custom-folder.test.ts b/test/routes/case-clone-custom-folder.test.ts index 0c700387..a5c1ac49 100644 --- a/test/routes/case-clone-custom-folder.test.ts +++ b/test/routes/case-clone-custom-folder.test.ts @@ -1,14 +1,24 @@ /** - * @fileoverview POST /api/cases/clone with a `path`: clone into a custom folder and register it as a - * linked case. Real filesystem under test/setup.ts's temp HOME and a REAL `git` cloning a local bare - * repo (the path policy itself is in test/case-path.test.ts). Port: N/A (app.inject()). + * @fileoverview POST /api/cases/clone with a `path`: clone INTO that folder (an empty or not yet existing one, + * with no subfolder added) and register it as a linked case. Real filesystem under test/setup.ts's temp + * HOME and a REAL `git` cloning a local bare repo (the path policy itself is in test/case-path.test.ts). + * Port: N/A (app.inject()). * * Like case-custom-path-routes.test.ts this suite rewrites the linked-cases registry, so it refuses to * start outside the sandboxed HOME (a raw `npx vitest` would reach the real ~/.codeman). */ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; import { execFileSync } from 'node:child_process'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; import { homedir, tmpdir } from 'node:os'; import { join } from 'node:path'; import { createRouteTestHarness } from './_route-test-utils.js'; @@ -103,18 +113,33 @@ describe.skipIf(!isGitAvailable())('POST /api/cases/clone with a custom folder', writeFileSync(join(target, 'mine.txt'), 'keep me'); const res = await clone(app, { name: 'busy', repository: origin, path: target }); expect(res.statusCode).toBe(409); + expect(res.json().error).toMatch(/already has files/); expect(readFileSync(join(target, 'mine.txt'), 'utf8')).toBe('keep me'); expect(linked()).toEqual({}); }); - it('refuses an existing EMPTY folder rather than removing and re-making it', async () => { + it('clones straight INTO the chosen empty folder, with no subfolder named after the case', async () => { const { app } = await createRouteTestHarness(registerCaseRoutes); - const target = join(workDir, 'empty'); + const target = join(workDir, 'picked'); mkdirSync(target); - const res = await clone(app, { name: 'empty', repository: origin, path: target }); - expect(res.statusCode).toBe(409); - expect(res.json().error).toMatch(/already exists/); - expect(existsSync(join(target, '.git'))).toBe(false); + const res = await clone(app, { name: 'a-different-name', repository: origin, path: target }); + expect(res.statusCode).toBe(200); + expect(res.json().data.case).toEqual({ name: 'a-different-name', path: target }); + expect(existsSync(join(target, 'README.md'))).toBe(true); + expect(existsSync(join(target, '.git'))).toBe(true); + expect(existsSync(join(target, 'a-different-name'))).toBe(false); + expect(linked()).toEqual({ 'a-different-name': target }); + }); + + it('leaves the empty folder in place, and empty, when the clone fails', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + const target = join(workDir, 'stays'); + mkdirSync(target); + const res = await clone(app, { name: 'stays', repository: join(root, 'no-such-repo.git'), path: target }); + expect(res.json().success).toBe(false); + expect(existsSync(target)).toBe(true); + expect(readdirSync(target)).toEqual([]); + expect(linked()).toEqual({}); }); it('refuses a blocked tree such as ~/.ssh', async () => { From 086249a386822d9e8f88ade1cde23da86e6cbe14 Mon Sep 17 00:00:00 2001 From: Devvyn <22340871+opticon454@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:57:51 +0800 Subject: [PATCH 3/5] fix(cases): never delete another clone's files after a failed direct clone A direct clone into an empty folder emptied the folder after any failure, which deleted a concurrent attempt's finished clone when git had written nothing. Clones into one folder are now mutually exclusive in-process, the cleanup is skipped when git refused the folder, never ran, or the mount is unresponsive, and a name linked while the clone ran is a 409 that keeps the folder. Documents path for POST /api/cases/clone. --- CLAUDE.md | 2 +- docs/api-reference.md | 2 + docs/wiki/Core-Concepts.md | 10 ++--- src/git-clone.ts | 45 ++++++++++++++------ src/web/routes/case-routes.ts | 8 ++-- src/web/schemas.ts | 2 +- test/routes/case-clone-custom-folder.test.ts | 32 +++++++++++++- 7 files changed, 78 insertions(+), 23 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 343f6cd6..fff3794d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -244,7 +244,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin **Ultracode / workflow-run visualization** (opt-in, default OFF): the Workflow tool writes a completion artifact only at run *end*, so live in-flight runs exist solely as transcript dirs. `workflow-run-watcher.ts` therefore synthesizes ACTIVE runs from transcripts until the completion artifact appears and supersedes them. It is **STANDALONE** and deliberately never imports or touches `subagent-watcher.ts`, despite reading the same tree. Two independent toggles: `showUltracodeAgents` (docked panel) and `ultracodeFloatingWindows` (floating windows); the watcher starts if **either** is on. → [architecture-invariants#ultracode-and-workflow-run-visualization](docs/architecture-invariants.md#ultracode-and-workflow-run-visualization) -**Clone a repository as a case** (issue #236, Add Case → **Clone Repo**): `POST /api/cases/clone` clones synchronously into the caller's case space (bounded by `GIT_CLONE_TIMEOUT_MS`, no job store); `POST /api/cases/clone-preflight` checks anonymous cloneability and lists refs. Core in `src/git-clone.ts`. ⚠️ **The URL is a code-execution surface**: refuse every `::` form and a leading `-`, spawn only argv arrays with `--` before operands. ⚠️ Stay non-interactive (`gitNonInteractiveEnv()`) or the open request hangs; never collect credentials, refuse `user:password@` URLs. ⚠️ Timeout kills the process GROUP, remove the destination only if this attempt created it, and repo contents win over scaffolding (existing `CLAUDE.md` kept, hooks merged, repo `.claude/settings*` warned about). ⚠️ A `path` is the folder cloned INTO (no case-name subfolder) and registers a linked case: admin-only in multi-user mode, judged by `prepareNewCasePath()`, empty or new only (`intoEmptyDir` clones straight into an empty one and never removes it). → [architecture-invariants#clone-a-repository-as-a-case](docs/architecture-invariants.md#clone-a-repository-as-a-case) +**Clone a repository as a case** (issue #236, Add Case → **Clone Repo**): `POST /api/cases/clone` clones synchronously into the caller's case space (bounded by `GIT_CLONE_TIMEOUT_MS`, no job store); `POST /api/cases/clone-preflight` checks anonymous cloneability and lists refs. Core in `src/git-clone.ts`. ⚠️ **The URL is a code-execution surface**: refuse every `::` form and a leading `-`, spawn only argv arrays with `--` before operands. ⚠️ Stay non-interactive (`gitNonInteractiveEnv()`) or the open request hangs; never collect credentials, refuse `user:password@` URLs. ⚠️ Timeout kills the process GROUP, remove the destination only if this attempt created it, and repo contents win over scaffolding (existing `CLAUDE.md` kept, hooks merged, repo `.claude/settings*` warned about). ⚠️ A `path` is the folder cloned INTO (no case-name subfolder) and registers a linked case: admin-only in multi-user mode, judged by `prepareNewCasePath()`, empty or new only (`intoEmptyDir` clones straight into an empty one and never removes it; one direct clone per folder at a time, and its cleanup is skipped when git wrote nothing or the mount is unresponsive). → [architecture-invariants#clone-a-repository-as-a-case](docs/architecture-invariants.md#clone-a-repository-as-a-case) **Git worktrees of a case** (case picker → **Git worktrees…**; `src/git-worktrees.ts`, `routes/worktree-routes.ts`): a local repository case keeps worktrees at `/.claude/worktrees/` on `worktree-`, Claude Code's own `--worktree` layout. ⚠️ Only that managed path is ever created or removed, every component `lstat`ed and realpath-checked (a symlinked `.claude` is refused). ⚠️ git never runs for a Docker or remote case, nor at or inside a Docker workspace (`worktree add` runs hooks and filters on the host). ⚠️ Remove is `git worktree remove` WITHOUT `--force`, refused while a live session is inside; branch delete is `-d`, never `-D`. ⚠️ Sessions start through the existing create paths (quick-start `worktree`, or `POST /api/sessions` `workingDir`), never a new spawn path. → [architecture-invariants#git-worktrees-of-a-case](docs/architecture-invariants.md#git-worktrees-of-a-case) diff --git a/docs/api-reference.md b/docs/api-reference.md index 4a0cb6b7..70f9d3a7 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -1315,6 +1315,8 @@ The target is judged before anything is written: Admin only in multi-user mode (`403`), like `POST /api/cases/link`: it writes outside the cases directory and into the shared, ownerless registry. If anything fails after the first write, what this call created is removed (the whole folder if it created it, otherwise only the scaffold inside the empty folder you picked) and the response is `500`. +`POST /api/cases/clone` takes the same optional `path`, with `{ name, repository, ref?, shallow?, description?, path? }`. Without `path` the repository is cloned to `/` as always. With `path` the repository is cloned **into that exact folder** (no `` subfolder is added) and registered as a linked case, judged by the same rules as above: `400` for an invalid or blocked path (or a symlink or file at the target), `404` for a missing parent, `422` for an unreachable parent, and `409 ALREADY_EXISTS` for a folder that has files, a name already in use or a folder that is already a case. Admin only in multi-user mode (`403`). An existing empty folder is cloned into directly and is kept, emptied again, if the clone fails; a second clone into the same folder while one is running is refused with `409`. If the clone succeeds but the registry write fails (or the name was linked while git ran, which is `409`), the cloned folder is kept and the error names it: `500 OPERATION_FAILED`, then use Link Existing. + ## Git status `GET /api/sessions/:id/git-status` is what the bottom-bar Git indicator and its panel read (Settings → Header & Panels → Bottom bar, per-device, default off). It reports what the session's workspace has not committed or pushed. **Read-only and offline:** it never fetches, pulls, commits or writes (it runs `git status` with `--no-optional-locks`, so it does not even refresh the index), which is why `behind` is as of the last `git fetch` (the panel's Fetch button is a separate route, below). The session is resolved like every session route (ownership via `findSessionOrFail`; another user's session is `404`). A repository whose root is, or is inside, a Docker case workspace is dropped (from the walk-up, the scan below a folder, and the diff route): a container can write there, and a repository's own clean filter or signature program would run on the host. When a branch's upstream does not exist on the remote (deleted and pruned, or never pushed, as after cloning an empty repository and committing), `upstreamGone` is `true` and the unpushed list falls back to commits on no remote-tracking ref at all. diff --git a/docs/wiki/Core-Concepts.md b/docs/wiki/Core-Concepts.md index fa849ba4..1b2428a0 100644 --- a/docs/wiki/Core-Concepts.md +++ b/docs/wiki/Core-Concepts.md @@ -22,11 +22,11 @@ Codeman-side configuration: Three ways to get one, all under **New or link a case…** at the bottom of the case picker (the case dropdown in the bottom toolbar; on a phone, the case sheet's **Create New Case**): -| How | Result | -| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Create New** | A fresh `~/codeman-cases/` with a scaffolded `CLAUDE.md`, or with **Create in a custom folder**, a new folder inside a parent you choose, scaffolded the same way and registered in place like a linked case. | -| **Clone Repo** | A repo cloned into `~/codeman-cases/` (or straight into an empty folder you choose) and registered as a case. Private repos need this machine's own git credentials (see below). | -| **Link Existing** | An existing folder anywhere on disk, registered in place. Nothing is copied or moved. | +| How | Result | +| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Create New** | A fresh `~/codeman-cases/` with a scaffolded `CLAUDE.md`, or with **Create in a custom folder**, a new folder inside a parent you choose, scaffolded the same way and registered in place like a linked case. | +| **Clone Repo** | A repo cloned into `~/codeman-cases/` (or straight into a folder you choose, which must be empty or not exist yet) and registered as a case. Private repos need this machine's own git credentials (see below). | +| **Link Existing** | An existing folder anywhere on disk, registered in place. Nothing is copied or moved. | Linked cases keep living where they are. Deleting a case in Codeman removes the registration, and for a linked case that is all it removes. diff --git a/src/git-clone.ts b/src/git-clone.ts index 249e4234..14d206a8 100644 --- a/src/git-clone.ts +++ b/src/git-clone.ts @@ -53,6 +53,7 @@ import { existsSync } from 'node:fs'; import { lstat, readdir, rename, rm } from 'node:fs/promises'; import { basename, dirname, join } from 'node:path'; import { EXEC_TIMEOUT_MS } from './config/exec-timeout.js'; +import { probePathKind } from './utils/bounded-path-probe.js'; // ─── Tunables ──────────────────────────────────────────────────────────────── @@ -852,6 +853,16 @@ export async function probeGitRemote( }; } +/** Destinations with a direct (`intoEmptyDir`) clone in flight. */ +const directClones = new Set(); + +function destinationExists(): CloneResult { + return { + ok: false, + failure: { code: 'DESTINATION_EXISTS', message: 'The destination directory already exists.', stderr: '' }, + }; +} + /** True for a real (not symlinked) directory with nothing in it. Any read error counts as not empty. */ async function isEmptyDirectory(path: string): Promise { try { @@ -896,19 +907,29 @@ export async function cloneRepository(opts: CloneOptions): Promise }; } if (existsSync(opts.destination)) { - if (!opts.intoEmptyDir || !(await isEmptyDirectory(opts.destination))) { - return { - ok: false, - failure: { code: 'DESTINATION_EXISTS', message: 'The destination directory already exists.', stderr: '' }, - }; + // One direct clone per folder at a time: once two gits have written into the same folder their + // files cannot be told apart, so the second caller is refused before it spawns anything. Taken + // before the emptiness check (which can precede a long wait for a git slot). + if (!opts.intoEmptyDir || directClones.has(opts.destination)) return destinationExists(); + directClones.add(opts.destination); + try { + if (!(await isEmptyDirectory(opts.destination))) return destinationExists(); + // The folder is the user's own, so there is no temporary sibling to rename into place: git fills it. + const direct = await runGit(buildCloneArgs(opts), opts.timeoutMs ?? GIT_CLONE_TIMEOUT_MS, MAX_STDERR_BYTES); + if (direct.code === 0 && !direct.spawnError) return { ok: true, stderr: sanitizeGitOutput(direct.stderr) }; + const failure = classifyGitFailure(direct.stderr, direct.timedOut, direct.spawnError); + // The folder was empty and is ours alone, so what is in it is this attempt's partial tree, but only + // if git wrote anything: not when it refused the folder or never ran (slot timeout, full queue). + // A mount that stopped answering is left alone too, so a libuv worker is not held on it. + if (failure.code !== 'DESTINATION_EXISTS' && !direct.spawnError) { + if ((await probePathKind(opts.destination, { pastCap: true })) === 'directory') { + await emptyDirectory(opts.destination); + } + } + return { ok: false, failure }; + } finally { + directClones.delete(opts.destination); } - // The folder is the user's own, so there is no temporary sibling to rename into place: git fills it. - const direct = await runGit(buildCloneArgs(opts), opts.timeoutMs ?? GIT_CLONE_TIMEOUT_MS, MAX_STDERR_BYTES); - if (direct.code === 0 && !direct.spawnError) return { ok: true, stderr: sanitizeGitOutput(direct.stderr) }; - // It was empty when the clone began, so whatever is in it now is this attempt's partial tree. The - // folder itself stays. - await emptyDirectory(opts.destination); - return { ok: false, failure: classifyGitFailure(direct.stderr, direct.timedOut, direct.spawnError) }; } // Sibling of the destination (same filesystem), so the rename is atomic. diff --git a/src/web/routes/case-routes.ts b/src/web/routes/case-routes.ts index cb7f9389..e676a6db 100644 --- a/src/web/routes/case-routes.ts +++ b/src/web/routes/case-routes.ts @@ -859,14 +859,16 @@ export function registerCaseRoutes( // POST /api/cases/link the write is not serialized, so this only narrows the window. try { const fresh = await readLinkedCases(); - if (fresh[name]) throw new Error(`Case "${name}" was linked while the clone ran`); + if (fresh[name]) + throw Object.assign(new Error(`Case "${name}" was linked while the clone ran`), { conflict: true }); fresh[name] = casePath; await fs.writeFile(LINKED_CASES_FILE, JSON.stringify(fresh, null, 2)); } catch (err) { // The clone itself succeeded: keep the folder (the user waited for it) and say where it is. - reply.code(500); + const conflict = (err as { conflict?: boolean }).conflict; + reply.code(conflict ? 409 : 500); return createErrorResponse( - ApiErrorCode.OPERATION_FAILED, + conflict ? ApiErrorCode.ALREADY_EXISTS : ApiErrorCode.OPERATION_FAILED, `Cloned into ${casePath} but could not register the case (${getErrorMessage(err)}). Use Link Existing to add it.` ); } diff --git a/src/web/schemas.ts b/src/web/schemas.ts index 13a8b038..60aaab4e 100644 --- a/src/web/schemas.ts +++ b/src/web/schemas.ts @@ -786,7 +786,7 @@ export const CloneCaseSchema = z.object({ shallow: z.boolean().optional(), description: z.string().max(1000).optional(), /** - * Clone into this exact folder (parent + case name) instead of under the cases directory, and + * Clone into this exact folder (the folder itself, no case-name subfolder is added) instead of under the cases directory, and * register it as a linked case. Absolute or starting with `~`; only length-bounded here, since * `prepareNewCasePath()` (web/case-path.ts) judges it and produces the user-facing reason. */ diff --git a/test/routes/case-clone-custom-folder.test.ts b/test/routes/case-clone-custom-folder.test.ts index a5c1ac49..f5a2aa0f 100644 --- a/test/routes/case-clone-custom-folder.test.ts +++ b/test/routes/case-clone-custom-folder.test.ts @@ -24,7 +24,7 @@ import { join } from 'node:path'; import { createRouteTestHarness } from './_route-test-utils.js'; import { registerCaseRoutes } from '../../src/web/routes/case-routes.js'; import { dataPath } from '../../src/config/instance.js'; -import { isGitAvailable } from '../../src/git-clone.js'; +import { cloneRepository, isGitAvailable } from '../../src/git-clone.js'; import { isSandboxedHome, safeRmHomeTree } from '../mocks/index.js'; const LINKED = () => dataPath('linked-cases.json'); @@ -142,6 +142,36 @@ describe.skipIf(!isGitAvailable())('POST /api/cases/clone with a custom folder', expect(linked()).toEqual({}); }); + it('two clones into one empty folder at once: exactly one wins and its files survive', async () => { + const target = join(workDir, 'raced'); + mkdirSync(target); + const results = await Promise.all([ + cloneRepository({ repository: origin, destination: target, intoEmptyDir: true }), + cloneRepository({ repository: origin, destination: target, intoEmptyDir: true }), + ]); + expect(results.filter((r) => r.ok)).toHaveLength(1); + const loser = results.find((r) => !r.ok); + expect(loser && !loser.ok && loser.failure.code).toBe('DESTINATION_EXISTS'); + expect(existsSync(join(target, 'README.md'))).toBe(true); + expect(existsSync(join(target, '.git'))).toBe(true); + }); + + it('a name linked while the clone ran is a 409 that keeps the folder and names it', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + const [a, b] = await Promise.all([ + clone(app, { name: 'twin', repository: origin, path: join(workDir, 'twin-a') }), + clone(app, { name: 'twin', repository: origin, path: join(workDir, 'twin-b') }), + ]); + const loserDir = a.json().success ? join(workDir, 'twin-b') : join(workDir, 'twin-a'); + const loser = a.json().success ? b : a; + expect([a.json().success, b.json().success].filter(Boolean)).toHaveLength(1); + expect(loser.statusCode).toBe(409); + expect(loser.json().errorCode).toBe('ALREADY_EXISTS'); + expect(loser.json().error).toContain(loserDir); + expect(existsSync(join(loserDir, 'README.md'))).toBe(true); + expect(Object.keys(linked())).toEqual(['twin']); + }); + it('refuses a blocked tree such as ~/.ssh', async () => { const { app } = await createRouteTestHarness(registerCaseRoutes); mkdirSync(join(homedir(), '.ssh'), { recursive: true }); From b549a66aa3c60e2bd5f81df6515550b84a6fb763 Mon Sep 17 00:00:00 2001 From: Devvyn <22340871+opticon454@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:13:56 +0800 Subject: [PATCH 4/5] fix(cases): skip the cleanup when git never ran, and refuse Docker workspaces A direct clone whose git-slot wait timed out came back with no spawnError, so the cleanup emptied a folder git never touched. GitRun now says whether git started and the cleanup requires it. Cloning into a folder at or inside a Docker case workspace is refused, as git status, fetch and worktrees do, since git would run the new repository's hooks and filters on the host. --- CLAUDE.md | 2 +- docs/api-reference.md | 2 +- src/git-clone.ts | 28 +++++-- src/web/routes/case-routes.ts | 26 +++++++ test/routes/case-clone-custom-folder.test.ts | 81 +++++++++++++++++++- 5 files changed, 127 insertions(+), 12 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index fff3794d..c555e2bc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -244,7 +244,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin **Ultracode / workflow-run visualization** (opt-in, default OFF): the Workflow tool writes a completion artifact only at run *end*, so live in-flight runs exist solely as transcript dirs. `workflow-run-watcher.ts` therefore synthesizes ACTIVE runs from transcripts until the completion artifact appears and supersedes them. It is **STANDALONE** and deliberately never imports or touches `subagent-watcher.ts`, despite reading the same tree. Two independent toggles: `showUltracodeAgents` (docked panel) and `ultracodeFloatingWindows` (floating windows); the watcher starts if **either** is on. → [architecture-invariants#ultracode-and-workflow-run-visualization](docs/architecture-invariants.md#ultracode-and-workflow-run-visualization) -**Clone a repository as a case** (issue #236, Add Case → **Clone Repo**): `POST /api/cases/clone` clones synchronously into the caller's case space (bounded by `GIT_CLONE_TIMEOUT_MS`, no job store); `POST /api/cases/clone-preflight` checks anonymous cloneability and lists refs. Core in `src/git-clone.ts`. ⚠️ **The URL is a code-execution surface**: refuse every `::` form and a leading `-`, spawn only argv arrays with `--` before operands. ⚠️ Stay non-interactive (`gitNonInteractiveEnv()`) or the open request hangs; never collect credentials, refuse `user:password@` URLs. ⚠️ Timeout kills the process GROUP, remove the destination only if this attempt created it, and repo contents win over scaffolding (existing `CLAUDE.md` kept, hooks merged, repo `.claude/settings*` warned about). ⚠️ A `path` is the folder cloned INTO (no case-name subfolder) and registers a linked case: admin-only in multi-user mode, judged by `prepareNewCasePath()`, empty or new only (`intoEmptyDir` clones straight into an empty one and never removes it; one direct clone per folder at a time, and its cleanup is skipped when git wrote nothing or the mount is unresponsive). → [architecture-invariants#clone-a-repository-as-a-case](docs/architecture-invariants.md#clone-a-repository-as-a-case) +**Clone a repository as a case** (issue #236, Add Case → **Clone Repo**): `POST /api/cases/clone` clones synchronously into the caller's case space (bounded by `GIT_CLONE_TIMEOUT_MS`, no job store); `POST /api/cases/clone-preflight` checks anonymous cloneability and lists refs. Core in `src/git-clone.ts`. ⚠️ **The URL is a code-execution surface**: refuse every `::` form and a leading `-`, spawn only argv arrays with `--` before operands. ⚠️ Stay non-interactive (`gitNonInteractiveEnv()`) or the open request hangs; never collect credentials, refuse `user:password@` URLs. ⚠️ Timeout kills the process GROUP, remove the destination only if this attempt created it, and repo contents win over scaffolding (existing `CLAUDE.md` kept, hooks merged, repo `.claude/settings*` warned about). ⚠️ A `path` is the folder cloned INTO (no case-name subfolder) and registers a linked case: admin-only in multi-user mode, judged by `prepareNewCasePath()`, empty or new only (`intoEmptyDir` clones straight into an empty one and never removes it; one direct clone per folder at a time, and its cleanup is skipped unless git actually ran (`GitRun.started`: a refused folder, a full queue or a slot wait that timed out wrote nothing) and when the mount is unresponsive; a folder at or inside a Docker case workspace is refused `400`, since git would run the new repository's hooks and filters on the host). → [architecture-invariants#clone-a-repository-as-a-case](docs/architecture-invariants.md#clone-a-repository-as-a-case) **Git worktrees of a case** (case picker → **Git worktrees…**; `src/git-worktrees.ts`, `routes/worktree-routes.ts`): a local repository case keeps worktrees at `/.claude/worktrees/` on `worktree-`, Claude Code's own `--worktree` layout. ⚠️ Only that managed path is ever created or removed, every component `lstat`ed and realpath-checked (a symlinked `.claude` is refused). ⚠️ git never runs for a Docker or remote case, nor at or inside a Docker workspace (`worktree add` runs hooks and filters on the host). ⚠️ Remove is `git worktree remove` WITHOUT `--force`, refused while a live session is inside; branch delete is `-d`, never `-D`. ⚠️ Sessions start through the existing create paths (quick-start `worktree`, or `POST /api/sessions` `workingDir`), never a new spawn path. → [architecture-invariants#git-worktrees-of-a-case](docs/architecture-invariants.md#git-worktrees-of-a-case) diff --git a/docs/api-reference.md b/docs/api-reference.md index 70f9d3a7..5713f160 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -1315,7 +1315,7 @@ The target is judged before anything is written: Admin only in multi-user mode (`403`), like `POST /api/cases/link`: it writes outside the cases directory and into the shared, ownerless registry. If anything fails after the first write, what this call created is removed (the whole folder if it created it, otherwise only the scaffold inside the empty folder you picked) and the response is `500`. -`POST /api/cases/clone` takes the same optional `path`, with `{ name, repository, ref?, shallow?, description?, path? }`. Without `path` the repository is cloned to `/` as always. With `path` the repository is cloned **into that exact folder** (no `` subfolder is added) and registered as a linked case, judged by the same rules as above: `400` for an invalid or blocked path (or a symlink or file at the target), `404` for a missing parent, `422` for an unreachable parent, and `409 ALREADY_EXISTS` for a folder that has files, a name already in use or a folder that is already a case. Admin only in multi-user mode (`403`). An existing empty folder is cloned into directly and is kept, emptied again, if the clone fails; a second clone into the same folder while one is running is refused with `409`. If the clone succeeds but the registry write fails (or the name was linked while git ran, which is `409`), the cloned folder is kept and the error names it: `500 OPERATION_FAILED`, then use Link Existing. +`POST /api/cases/clone` takes the same optional `path`, with `{ name, repository, ref?, shallow?, description?, path? }`. Without `path` the repository is cloned to `/` as always. With `path` the repository is cloned **into that exact folder** (no `` subfolder is added) and registered as a linked case, judged by the same rules as above: `400` for an invalid or blocked path (or a symlink or file at the target), `404` for a missing parent, `422` for an unreachable parent, and `409 ALREADY_EXISTS` for a folder that has files, a name already in use or a folder that is already a case. Admin only in multi-user mode (`403`). An existing empty folder is cloned into directly and is kept, emptied again, if the clone fails; a second clone into the same folder while one is running is refused with `409`. A destination at or inside a Docker case workspace is refused `400 INVALID_INPUT` (git would run the new repository's hooks and filters on the host, and a container can write there), and `503` when the Docker case list cannot be read. If the clone succeeds but the registry write fails (or the name was linked while git ran, which is `409`), the cloned folder is kept and the error names it: `500 OPERATION_FAILED`, then use Link Existing. ## Git status diff --git a/src/git-clone.ts b/src/git-clone.ts index 14d206a8..a50227ee 100644 --- a/src/git-clone.ts +++ b/src/git-clone.ts @@ -707,6 +707,8 @@ interface GitRun { stderr: string; code: number | null; timedOut: boolean; + /** False when git never ran (queue full, slot wait timed out, spawn failed): nothing was written. */ + started: boolean; spawnError?: string; } @@ -726,10 +728,17 @@ async function runGit(args: string[], timeoutMs: number, maxStdoutBytes: number) const queuedAt = Date.now(); const slot = await acquireGitSlot(timeoutMs); if (slot === 'queue-full') { - return { stdout: '', stderr: '', code: null, timedOut: false, spawnError: 'EBUSY: git operation queue is full' }; + return { + stdout: '', + stderr: '', + code: null, + timedOut: false, + spawnError: 'EBUSY: git operation queue is full', + started: false, + }; } if (slot === 'timed-out') { - return { stdout: '', stderr: '', code: null, timedOut: true }; + return { stdout: '', stderr: '', code: null, timedOut: true, started: false }; } const remainingMs = Math.max(1, timeoutMs - (Date.now() - queuedAt)); try { @@ -742,7 +751,7 @@ async function runGit(args: string[], timeoutMs: number, maxStdoutBytes: number) detached: true, }); } catch (err) { - resolve({ stdout: '', stderr: '', code: null, timedOut: false, spawnError: String(err) }); + resolve({ stdout: '', stderr: '', code: null, timedOut: false, started: false, spawnError: String(err) }); return; } @@ -789,8 +798,10 @@ async function runGit(args: string[], timeoutMs: number, maxStdoutBytes: number) resolve(result); }; - child.on('error', (err) => finish({ stdout, stderr, code: null, timedOut, spawnError: String(err) })); - child.on('close', (code) => finish({ stdout, stderr, code, timedOut })); + child.on('error', (err) => + finish({ stdout, stderr, code: null, timedOut, started: false, spawnError: String(err) }) + ); + child.on('close', (code) => finish({ stdout, stderr, code, timedOut, started: true })); }); } finally { releaseGitSlot(); @@ -918,10 +929,11 @@ export async function cloneRepository(opts: CloneOptions): Promise const direct = await runGit(buildCloneArgs(opts), opts.timeoutMs ?? GIT_CLONE_TIMEOUT_MS, MAX_STDERR_BYTES); if (direct.code === 0 && !direct.spawnError) return { ok: true, stderr: sanitizeGitOutput(direct.stderr) }; const failure = classifyGitFailure(direct.stderr, direct.timedOut, direct.spawnError); - // The folder was empty and is ours alone, so what is in it is this attempt's partial tree, but only - // if git wrote anything: not when it refused the folder or never ran (slot timeout, full queue). + // The folder was empty when this attempt took it, so what is in it is this attempt's partial tree, but + // only if git actually ran: a refused folder, a full queue or a slot wait that timed out wrote nothing, + // and anything in the folder by then (files the user copied in, another case created there) is not ours. // A mount that stopped answering is left alone too, so a libuv worker is not held on it. - if (failure.code !== 'DESTINATION_EXISTS' && !direct.spawnError) { + if (direct.started && failure.code !== 'DESTINATION_EXISTS') { if ((await probePathKind(opts.destination, { pastCap: true })) === 'directory') { await emptyDirectory(opts.destination); } diff --git a/src/web/routes/case-routes.ts b/src/web/routes/case-routes.ts index e676a6db..8e2be286 100644 --- a/src/web/routes/case-routes.ts +++ b/src/web/routes/case-routes.ts @@ -51,6 +51,8 @@ import { probeGitRemote, } from '../../git-clone.js'; import type { GitRemoteProbe, GitUrlParse } from '../../git-clone.js'; +import { isPathWithin } from '../../git-worktrees.js'; +import { defaultDockerWorkspaces } from './git-status-routes.js'; import { generateClaudeMd } from '../../templates/claude-md.js'; import { prepareNewCasePath } from '../case-path.js'; import { @@ -147,6 +149,9 @@ const APP_VERSION = (() => { * would copy another user's workspace into the caller's own (the same escape * `/api/cases/link` is admin-only for). */ +const DOCKER_CLONE_REFUSAL = + 'Cloning is not available into a folder inside a Docker case workspace: a container can write there, and git would run the new repository’s hooks and filters on this machine. Clone outside the workspace and link it, or clone from inside the container.'; + const LOCAL_CLONE_ADMIN_ONLY = 'Cloning from a local path is admin-only in multi-user mode. Use a repository URL instead.'; @@ -790,6 +795,27 @@ export function registerCaseRoutes( } } + // git runs the new repository's hooks and filters on THIS machine once the clone finishes, and a container + // with the workspace bind-mounted can write both while it fetches. Like git status, fetch and worktrees, + // never clone at or inside a Docker case workspace. Fails closed when the Docker case list cannot be read. + try { + const roots = await Promise.all( + (await defaultDockerWorkspaces()).map((root) => fs.realpath(root).catch(() => resolve(root))) + ); + // A custom folder is already symlink-resolved; the default one is judged through its real cases dir. + const dest = + customPath !== undefined ? casePath : join(await fs.realpath(casesDir).catch(() => casesDir), name); + if (roots.some((root) => isPathWithin(dest, root))) { + return createErrorResponse(ApiErrorCode.INVALID_INPUT, DOCKER_CLONE_REFUSAL); + } + } catch { + reply.code(503); + return createErrorResponse( + ApiErrorCode.OPERATION_FAILED, + 'Could not read the Docker case list, so Codeman cannot tell whether that folder is a Docker case workspace. Try again.' + ); + } + const clone = await cloneRepository({ repository: parsed.repository, destination: casePath, diff --git a/test/routes/case-clone-custom-folder.test.ts b/test/routes/case-clone-custom-folder.test.ts index f5a2aa0f..392a50c5 100644 --- a/test/routes/case-clone-custom-folder.test.ts +++ b/test/routes/case-clone-custom-folder.test.ts @@ -7,7 +7,7 @@ * Like case-custom-path-routes.test.ts this suite rewrites the linked-cases registry, so it refuses to * start outside the sandboxed HOME (a raw `npx vitest` would reach the real ~/.codeman). */ -import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { execFileSync } from 'node:child_process'; import { existsSync, @@ -24,7 +24,12 @@ import { join } from 'node:path'; import { createRouteTestHarness } from './_route-test-utils.js'; import { registerCaseRoutes } from '../../src/web/routes/case-routes.js'; import { dataPath } from '../../src/config/instance.js'; -import { cloneRepository, isGitAvailable } from '../../src/git-clone.js'; +import { + cloneRepository, + getActiveGitOperationCount, + getQueuedGitOperationCount, + isGitAvailable, +} from '../../src/git-clone.js'; import { isSandboxedHome, safeRmHomeTree } from '../mocks/index.js'; const LINKED = () => dataPath('linked-cases.json'); @@ -172,6 +177,78 @@ describe.skipIf(!isGitAvailable())('POST /api/cases/clone with a custom folder', expect(Object.keys(linked())).toEqual(['twin']); }); + it('a direct clone whose git-slot wait times out leaves what was written into the folder meanwhile', async () => { + const target = join(workDir, 'queued'); + mkdirSync(target); + // Two slow ssh clones hold both git slots (no network needed: the ssh command just sleeps). + const prior = process.env.GIT_SSH_COMMAND; + process.env.GIT_SSH_COMMAND = 'sleep 4; true'; + try { + const holders = [0, 1].map((i) => + cloneRepository({ + repository: 'ssh://localhost/x.git', + destination: join(workDir, `hold-${i}`), + timeoutMs: 10_000, + }) + ); + await vi.waitFor(() => expect(getActiveGitOperationCount()).toBe(2)); + const queued = cloneRepository({ + repository: origin, + destination: target, + intoEmptyDir: true, + timeoutMs: 1_000, + }); + await vi.waitFor(() => expect(getQueuedGitOperationCount()).toBe(1)); + // Written during the wait, so not this attempt's: a user copying files in, or another case created there. + writeFileSync(join(target, 'mine.txt'), 'keep me'); + mkdirSync(join(target, 'src')); + const result = await queued; + expect(!result.ok && result.failure.code).toBe('TIMEOUT'); + expect(readFileSync(join(target, 'mine.txt'), 'utf8')).toBe('keep me'); + expect(existsSync(join(target, 'src'))).toBe(true); + await Promise.all(holders); + } finally { + if (prior === undefined) delete process.env.GIT_SSH_COMMAND; + else process.env.GIT_SSH_COMMAND = prior; + } + }, 30_000); + + it('refuses a folder at or inside a Docker case workspace, and creates nothing', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + const workspace = join(workDir, 'dockerws'); + mkdirSync(workspace); + writeFileSync( + join(dataPath('docker-cases.json')), + JSON.stringify([{ name: 'box', type: 'docker', hostId: 'h', hostWorkspacePath: workspace, container: 'c' }]) + ); + try { + for (const path of [workspace, join(workspace, 'repo')]) { + const res = await clone(app, { name: 'inside', repository: origin, path }); + expect(res.json().errorCode, path).toBe('INVALID_INPUT'); + expect(res.json().error, path).toMatch(/Docker case workspace/); + } + expect(readdirSync(workspace)).toEqual([]); + expect(linked()).toEqual({}); + // A sibling of the workspace is fine. + const ok = await clone(app, { name: 'beside', repository: origin, path: join(workDir, 'beside') }); + expect(ok.statusCode).toBe(200); + } finally { + safeRmHomeTree(dataPath('docker-cases.json')); + } + }); + + it('fails closed when the Docker case list cannot be read', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + writeFileSync(dataPath('docker-cases.json'), '{not json'); + try { + const res = await clone(app, { name: 'blind', repository: origin, path: join(workDir, 'blind') }); + expect(res.statusCode).toBe(503); + expect(existsSync(join(workDir, 'blind'))).toBe(false); + } finally { + safeRmHomeTree(dataPath('docker-cases.json')); + } + }); + it('refuses a blocked tree such as ~/.ssh', async () => { const { app } = await createRouteTestHarness(registerCaseRoutes); mkdirSync(join(homedir(), '.ssh'), { recursive: true }); From 41186f5ac37e72c201f6638c544d85be28f0cbf8 Mon Sep 17 00:00:00 2001 From: Devvyn <22340871+opticon454@users.noreply.github.com> Date: Sat, 31 Oct 2026 20:29:26 +0800 Subject: [PATCH 5/5] fix(cases): never let a path decide whether a refused clone empties the folder git's refusal quotes the destination, so a folder named openssl or rustls classified as HOST_UNREACHABLE and the cleanup emptied it. The cleanup now tests git's own text, DESTINATION_EXISTS is matched first, and ssl/tls are matched as words. Also: a test for the Docker refusal on the default branch, the route JSDoc and constant comment, and the folder copy (empty, or new). --- CLAUDE.md | 2 +- src/git-clone.ts | 19 ++++-- src/web/public/index.html | 4 +- src/web/public/session-ui.js | 2 +- src/web/routes/case-routes.ts | 10 +-- test/routes/case-clone-custom-folder.test.ts | 69 ++++++++++++++++++++ 6 files changed, 93 insertions(+), 13 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index c555e2bc..5d37fc8c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -244,7 +244,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin **Ultracode / workflow-run visualization** (opt-in, default OFF): the Workflow tool writes a completion artifact only at run *end*, so live in-flight runs exist solely as transcript dirs. `workflow-run-watcher.ts` therefore synthesizes ACTIVE runs from transcripts until the completion artifact appears and supersedes them. It is **STANDALONE** and deliberately never imports or touches `subagent-watcher.ts`, despite reading the same tree. Two independent toggles: `showUltracodeAgents` (docked panel) and `ultracodeFloatingWindows` (floating windows); the watcher starts if **either** is on. → [architecture-invariants#ultracode-and-workflow-run-visualization](docs/architecture-invariants.md#ultracode-and-workflow-run-visualization) -**Clone a repository as a case** (issue #236, Add Case → **Clone Repo**): `POST /api/cases/clone` clones synchronously into the caller's case space (bounded by `GIT_CLONE_TIMEOUT_MS`, no job store); `POST /api/cases/clone-preflight` checks anonymous cloneability and lists refs. Core in `src/git-clone.ts`. ⚠️ **The URL is a code-execution surface**: refuse every `::` form and a leading `-`, spawn only argv arrays with `--` before operands. ⚠️ Stay non-interactive (`gitNonInteractiveEnv()`) or the open request hangs; never collect credentials, refuse `user:password@` URLs. ⚠️ Timeout kills the process GROUP, remove the destination only if this attempt created it, and repo contents win over scaffolding (existing `CLAUDE.md` kept, hooks merged, repo `.claude/settings*` warned about). ⚠️ A `path` is the folder cloned INTO (no case-name subfolder) and registers a linked case: admin-only in multi-user mode, judged by `prepareNewCasePath()`, empty or new only (`intoEmptyDir` clones straight into an empty one and never removes it; one direct clone per folder at a time, and its cleanup is skipped unless git actually ran (`GitRun.started`: a refused folder, a full queue or a slot wait that timed out wrote nothing) and when the mount is unresponsive; a folder at or inside a Docker case workspace is refused `400`, since git would run the new repository's hooks and filters on the host). → [architecture-invariants#clone-a-repository-as-a-case](docs/architecture-invariants.md#clone-a-repository-as-a-case) +**Clone a repository as a case** (issue #236, Add Case → **Clone Repo**): `POST /api/cases/clone` clones synchronously into the caller's case space (bounded by `GIT_CLONE_TIMEOUT_MS`, no job store); `POST /api/cases/clone-preflight` checks anonymous cloneability and lists refs. Core in `src/git-clone.ts`. ⚠️ **The URL is a code-execution surface**: refuse every `::` form and a leading `-`, spawn only argv arrays with `--` before operands. ⚠️ Stay non-interactive (`gitNonInteractiveEnv()`) or the open request hangs; never collect credentials, refuse `user:password@` URLs. ⚠️ Timeout kills the process GROUP, remove the destination only if this attempt created it, and repo contents win over scaffolding (existing `CLAUDE.md` kept, hooks merged, repo `.claude/settings*` warned about). ⚠️ A `path` is the folder cloned INTO (no case-name subfolder) and registers a linked case: admin-only in multi-user mode, judged by `prepareNewCasePath()`, empty or new only (`intoEmptyDir` clones straight into an empty one and never removes it; one direct clone per folder at a time, and its cleanup is skipped unless git actually ran (`GitRun.started`: a full queue or a slot wait that timed out wrote nothing) and did not refuse the folder (git's own `already exists and is not an empty directory` text, tested directly and never through the classifier's code, since the refusal quotes the path and a folder named `openssl` once classified as unreachable) and when the mount is unresponsive; a folder at or inside a Docker case workspace is refused `400`, since git would run the new repository's hooks and filters on the host). → [architecture-invariants#clone-a-repository-as-a-case](docs/architecture-invariants.md#clone-a-repository-as-a-case) **Git worktrees of a case** (case picker → **Git worktrees…**; `src/git-worktrees.ts`, `routes/worktree-routes.ts`): a local repository case keeps worktrees at `/.claude/worktrees/` on `worktree-`, Claude Code's own `--worktree` layout. ⚠️ Only that managed path is ever created or removed, every component `lstat`ed and realpath-checked (a symlinked `.claude` is refused). ⚠️ git never runs for a Docker or remote case, nor at or inside a Docker workspace (`worktree add` runs hooks and filters on the host). ⚠️ Remove is `git worktree remove` WITHOUT `--force`, refused while a live session is inside; branch delete is `-d`, never `-D`. ⚠️ Sessions start through the existing create paths (quick-start `worktree`, or `POST /api/sessions` `workingDir`), never a new spawn path. → [architecture-invariants#git-worktrees-of-a-case](docs/architecture-invariants.md#git-worktrees-of-a-case) diff --git a/src/git-clone.ts b/src/git-clone.ts index a50227ee..51484d7a 100644 --- a/src/git-clone.ts +++ b/src/git-clone.ts @@ -596,6 +596,11 @@ export function classifyGitFailure(stderr: string, timedOut: boolean, spawnError stderr: clean, }; } + // First: git's refusal quotes the destination path, so a folder named openssl, rustls or "not found" would + // otherwise match the host and repository patterns below, and a wrong code here decides a deletion. + if (/already exists and is not an empty directory|destination path .* already exists/.test(lower)) { + return { code: 'DESTINATION_EXISTS', message: 'The destination directory already exists.', stderr: clean }; + } if (timedOut) { return { code: 'TIMEOUT', @@ -631,12 +636,13 @@ export function classifyGitFailure(stderr: string, timedOut: boolean, spawnError stderr: clean, }; } - if (/could not resolve host|connection refused|connection timed out|network is unreachable|ssl|tls/.test(lower)) { + if ( + /could not resolve host|connection refused|connection timed out|network is unreachable|\bssl\b|\btls\b|certificate|handshake/.test( + lower + ) + ) { return { code: 'HOST_UNREACHABLE', message: 'Could not reach that host from this machine.', stderr: clean }; } - if (/already exists and is not an empty directory|destination path .* already exists/.test(lower)) { - return { code: 'DESTINATION_EXISTS', message: 'The destination directory already exists.', stderr: clean }; - } return { code: 'FAILED', message: clean ? `git failed: ${firstLine(clean)}` : 'git failed.', stderr: clean }; } @@ -933,7 +939,10 @@ export async function cloneRepository(opts: CloneOptions): Promise // only if git actually ran: a refused folder, a full queue or a slot wait that timed out wrote nothing, // and anything in the folder by then (files the user copied in, another case created there) is not ours. // A mount that stopped answering is left alone too, so a libuv worker is not held on it. - if (direct.started && failure.code !== 'DESTINATION_EXISTS') { + // git's own refusal is tested on its text, not on the classifier's code, so the deletion never depends on + // which pattern matched first. + const refused = /already exists and is not an empty directory/i.test(direct.stderr); + if (direct.started && !refused && failure.code !== 'DESTINATION_EXISTS') { if ((await probePathKind(opts.destination, { pastCap: true })) === 'directory') { await emptyDirectory(opts.destination); } diff --git a/src/web/public/index.html b/src/web/public/index.html index d88d2ec7..3431915f 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -3658,7 +3658,7 @@
- By default the clone goes under ~/codeman-cases. Choose a folder and the repository is cloned into that folder itself (it must be empty); it is listed like any other case, and deleting the case only unlinks it (your files stay). + By default the clone goes under ~/codeman-cases. Choose a folder and the repository is cloned into that folder itself (an empty folder, or one that does not exist yet); it is listed like any other case, and deleting the case only unlinks it (your files stay).
- Pick the empty folder to clone into. + Pick an empty folder, or one that does not exist yet, to clone into.
diff --git a/src/web/public/session-ui.js b/src/web/public/session-ui.js index c1455d00..9407e3bd 100644 --- a/src/web/public/session-ui.js +++ b/src/web/public/session-ui.js @@ -4159,7 +4159,7 @@ Object.assign(CodemanApp.prototype, { const hint = document.getElementById('cloneCasePathPreview'); if (!hint) return; const target = this._cloneTargetPath(); - hint.textContent = target ? `Will clone into: ${target}` : 'Pick the empty folder to clone into.'; + hint.textContent = target ? `Will clone into: ${target}` : 'Pick an empty folder, or one that does not exist yet, to clone into.'; }, openCloneCasePathPicker() { diff --git a/src/web/routes/case-routes.ts b/src/web/routes/case-routes.ts index 8e2be286..ecb3a667 100644 --- a/src/web/routes/case-routes.ts +++ b/src/web/routes/case-routes.ts @@ -149,12 +149,13 @@ const APP_VERSION = (() => { * would copy another user's workspace into the caller's own (the same escape * `/api/cases/link` is admin-only for). */ -const DOCKER_CLONE_REFUSAL = - 'Cloning is not available into a folder inside a Docker case workspace: a container can write there, and git would run the new repository’s hooks and filters on this machine. Clone outside the workspace and link it, or clone from inside the container.'; - const LOCAL_CLONE_ADMIN_ONLY = 'Cloning from a local path is admin-only in multi-user mode. Use a repository URL instead.'; +/** Refusal text for a clone at or inside a Docker case workspace (git would run its hooks on the host). */ +const DOCKER_CLONE_REFUSAL = + 'Cloning is not available into a folder inside a Docker case workspace: a container can write there, and git would run the new repository’s hooks and filters on this machine. Clone outside the workspace and link it, or clone from inside the container.'; + /** * Whether a clone or preflight must run with git's credential helpers cleared: * a non-admin in multi-user mode. Every user's git runs as the one server @@ -666,7 +667,8 @@ export function registerCaseRoutes( * request died mid-clone still sees the case appear over SSE when git finishes. * * Deliberately NOT admin-gated in multi-user mode: unlike `/api/cases/link`, - * this writes only inside the caller's own `resolveCasesDir`. Two things would + * this writes only inside the caller's own `resolveCasesDir`, EXCEPT with a `path` (a custom folder, + * registered as a linked case in the shared registry), which is admin-only like Link Existing. Two things would * otherwise read through that boundary: a `local`-transport source (refused for * non-admins) and the server account's git credential helpers, which every user * shares (cleared for non-admins, see `cloneWithoutCredentialHelpers`). diff --git a/test/routes/case-clone-custom-folder.test.ts b/test/routes/case-clone-custom-folder.test.ts index 392a50c5..2c8ee229 100644 --- a/test/routes/case-clone-custom-folder.test.ts +++ b/test/routes/case-clone-custom-folder.test.ts @@ -25,6 +25,7 @@ import { createRouteTestHarness } from './_route-test-utils.js'; import { registerCaseRoutes } from '../../src/web/routes/case-routes.js'; import { dataPath } from '../../src/config/instance.js'; import { + classifyGitFailure, cloneRepository, getActiveGitOperationCount, getQueuedGitOperationCount, @@ -249,6 +250,74 @@ describe.skipIf(!isGitAvailable())('POST /api/cases/clone with a custom folder', } }); + it.each(['plain', 'openssl', 'rustls', 'does not exist'])( + 'a refused folder named %s keeps what was written meanwhile and reports DESTINATION_EXISTS', + async (folder) => { + const target = join(workDir, folder); + mkdirSync(target); + const prior = process.env.GIT_SSH_COMMAND; + process.env.GIT_SSH_COMMAND = 'sleep 2; true'; + try { + const holders = [0, 1].map((i) => + cloneRepository({ + repository: 'ssh://localhost/x.git', + destination: join(workDir, `hold-${i}`), + timeoutMs: 10_000, + }) + ); + await vi.waitFor(() => expect(getActiveGitOperationCount()).toBe(2)); + // Queues behind the holders but has time to get a slot, so git runs and refuses the folder. + const queued = cloneRepository({ + repository: origin, + destination: target, + intoEmptyDir: true, + timeoutMs: 15_000, + }); + await vi.waitFor(() => expect(getQueuedGitOperationCount()).toBe(1)); + writeFileSync(join(target, 'mine.txt'), 'keep me'); + const result = await queued; + expect(!result.ok && result.failure.code).toBe('DESTINATION_EXISTS'); + expect(readFileSync(join(target, 'mine.txt'), 'utf8')).toBe('keep me'); + await Promise.all(holders); + } finally { + if (prior === undefined) delete process.env.GIT_SSH_COMMAND; + else process.env.GIT_SSH_COMMAND = prior; + } + }, + 30_000 + ); + + it('classifies git stderr by what it says, not by words in a path it quotes', () => { + const refusal = (dir: string) => `fatal: destination path '${dir}' already exists and is not an empty directory.`; + for (const dir of ['/home/u/src/openssl', '/home/u/rustls', '/x/tls-test', '/x/repository not found']) { + expect(classifyGitFailure(refusal(dir), false).code, dir).toBe('DESTINATION_EXISTS'); + } + expect(classifyGitFailure('fatal: unable to access: SSL certificate problem: self signed', false).code).toBe( + 'HOST_UNREACHABLE' + ); + expect(classifyGitFailure('fatal: TLS handshake failure', false).code).toBe('HOST_UNREACHABLE'); + expect(classifyGitFailure('fatal: could not resolve host: example.invalid', false).code).toBe('HOST_UNREACHABLE'); + expect(classifyGitFailure("fatal: repository 'https://x/y.git/' not found", false).code).toBe('NOT_FOUND'); + }); + + it('refuses a clone without a path into the cases folder when it is a Docker case workspace', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + const casesDir = join(homedir(), 'codeman-cases'); + mkdirSync(casesDir, { recursive: true }); + writeFileSync( + dataPath('docker-cases.json'), + JSON.stringify([{ name: 'box', type: 'docker', hostId: 'h', hostWorkspacePath: casesDir, container: 'c' }]) + ); + try { + const res = await clone(app, { name: 'default-inside', repository: origin }); + expect(res.json().errorCode).toBe('INVALID_INPUT'); + expect(res.json().error).toMatch(/Docker case workspace/); + expect(existsSync(join(casesDir, 'default-inside'))).toBe(false); + } finally { + safeRmHomeTree(dataPath('docker-cases.json')); + } + }); + it('refuses a blocked tree such as ~/.ssh', async () => { const { app } = await createRouteTestHarness(registerCaseRoutes); mkdirSync(join(homedir(), '.ssh'), { recursive: true });