From 2e21c4ba94ceed6f624bf0555a069c8f4dc42512 Mon Sep 17 00:00:00 2001 From: Savas Neto Date: Tue, 3 Nov 2026 16:55:38 -0300 Subject: [PATCH 1/2] fix(storage): stop writing into ~/.claude; sessions in ~/.verboo/projects Co-Authored-By: Claude Opus 5.5 --- UPSTREAM_SYNC.md | 10 +++ scripts/postinstall.mjs | 104 +++++++++++++--------------- scripts/postinstall.test.mjs | 45 ++++++++++++ src/utils/completionCache.test.ts | 22 ++++++ src/utils/completionCache.ts | 18 ++--- src/utils/envUtils.ts | 39 ++++++++--- src/utils/projectsDirs.test.ts | 89 ++++++++++++++++++++++++ src/utils/sessionRestore.ts | 8 ++- src/utils/sessionStorage.ts | 62 +++++++++++++++-- src/utils/sessionStoragePortable.ts | 31 +++++---- 10 files changed, 333 insertions(+), 95 deletions(-) create mode 100644 scripts/postinstall.test.mjs create mode 100644 src/utils/completionCache.test.ts create mode 100644 src/utils/projectsDirs.test.ts diff --git a/UPSTREAM_SYNC.md b/UPSTREAM_SYNC.md index 205fc028c7..903a479b83 100644 --- a/UPSTREAM_SYNC.md +++ b/UPSTREAM_SYNC.md @@ -53,6 +53,16 @@ em volta. Use `git grep "VERBOO-BRAND"` para localizar todos os pontos editados. - `src/commands/provider/` — arquivos **NÃO foram deletados** (upstream continua mexendo neles; deletar gera conflitos "deleted file modified upstream"). +#### Nada gravado nas pastas de outros apps +- `src/utils/envUtils.ts` — `getProjectsDir()` = `~/.verboo/projects` (ou + `VERBOO_CONFIG_DIR/projects`); `~/.claude/projects` e `~/.openclaude/projects` + entram em `getAdditionalProjectsDirs()` só para leitura. +- `src/utils/sessionStorage.ts` — `mirrorTranscriptToAdditionalDirs` virou + no-op; retomar sessão de diretório somente leitura copia o arquivo + (`adoptReadOnlyTranscriptForResume`, usado em `sessionRestore.ts`). +- `src/utils/completionCache.ts` — cache em `~/.verboo/completion.`. +- `scripts/postinstall.mjs` — não copia nada de `~/.claude`. + #### Mensagens reescritas - `src/utils/providerValidation.ts` (3 ocorrências) - `src/services/api/withRetry.ts` diff --git a/scripts/postinstall.mjs b/scripts/postinstall.mjs index bbf64cc726..2330e24644 100644 --- a/scripts/postinstall.mjs +++ b/scripts/postinstall.mjs @@ -6,87 +6,77 @@ * /usr/local ou ~/.npm-global). Shells bash/zsh geralmente já têm esse bin no * PATH via .bashrc/.zshrc, mas o fish não herda essas configs — é preciso * chamar `fish_add_path` explicitamente. + * + * A instalação não lê nem copia arquivos de outros apps (como ~/.claude): a + * CLI já lê skills e plugins do Claude Code em modo somente leitura. */ import { execFileSync, spawnSync } from 'node:child_process' -import { existsSync, mkdirSync, readdirSync, statSync, copyFileSync } from 'node:fs' +import { existsSync } from 'node:fs' import { join } from 'node:path' -import { homedir } from 'os' +import { pathToFileURL } from 'node:url' -function isFishShell() { - const shell = process.env.SHELL ?? '' - const parent = process.env.FISH_VERSION // set by fish itself +export function isFishShell(env = process.env) { + const shell = env.SHELL ?? '' + const parent = env.FISH_VERSION // set by fish itself return shell.endsWith('/fish') || parent !== undefined } -function getNpmGlobalBin() { +/** + * Only a global install by a regular user touches the shell: never as root + * (it would write root-owned fish config) and never in CI. + */ +export function shouldConfigureShell({ + env = process.env, + uid = process.getuid?.(), +} = {}) { + if (uid === 0) return false + if (env.CI) return false + if (env.npm_config_global !== 'true') return false + return isFishShell(env) +} + +export function getNpmGlobalBin(exec = execFileSync) { try { - const prefix = execFileSync('npm', ['prefix', '-g'], { encoding: 'utf8' }).trim() + const prefix = exec('npm', ['prefix', '-g'], { encoding: 'utf8' }).trim() return join(prefix, 'bin') } catch { return null } } -function fishAddPath(dir) { - const result = spawnSync('fish', ['-c', `fish_add_path ${dir}`], { +/** + * The directory is passed to fish as an argument, never interpolated into + * the command string, so a prefix with spaces or shell characters stays a + * single path. + */ +export function fishAddPath(dir, spawn = spawnSync) { + const result = spawn('fish', ['-c', 'fish_add_path -- $argv[1]', '--', dir], { stdio: 'inherit', timeout: 5000, }) return result.status === 0 } -function copyDirRecursive(src, dest) { - let copied = false - if (!existsSync(dest)) mkdirSync(dest, { recursive: true }) - for (const entry of readdirSync(src)) { - const srcPath = join(src, entry) - const destPath = join(dest, entry) - if (existsSync(destPath)) continue - const stat = statSync(srcPath) - if (stat.isDirectory()) { - if (copyDirRecursive(srcPath, destPath)) copied = true - } else { - copyFileSync(srcPath, destPath) - copied = true - } - } - return copied -} - -function importFromClaudeCode() { - const claude = join(homedir(), '.claude') - const verboo = join(homedir(), '.verboo') - for (const asset of ['skills', 'plugins']) { - const src = join(claude, asset) - const dest = join(verboo, asset) - if (!existsSync(src)) continue - try { - if (copyDirRecursive(src, dest)) { - process.stdout.write(`[verboo] ${asset} imported from Claude Code.\n`) +export function main({ env = process.env, write = text => process.stdout.write(text) } = {}) { + if (shouldConfigureShell({ env })) { + const binDir = getNpmGlobalBin() + if (binDir && existsSync(binDir)) { + if (fishAddPath(binDir)) { + write(`[verboo] fish_add_path ${binDir} — feito.\n`) + } else { + write( + `[verboo] Não foi possível adicionar ${binDir} ao fish automaticamente.\n` + + ` Execute manualmente: fish_add_path ${binDir}\n`, + ) } - } catch (err) { - process.stdout.write(`[verboo] Import of ${asset} from Claude Code failed: ${err.message}. Proceeding without import.\n`) } } -} -if (isFishShell()) { - const binDir = getNpmGlobalBin() - if (binDir && existsSync(binDir)) { - const ok = fishAddPath(binDir) - if (ok) { - process.stdout.write(`[verboo] fish_add_path ${binDir} — feito.\n`) - } else { - process.stdout.write( - `[verboo] Não foi possível adicionar ${binDir} ao fish automaticamente.\n` + - ` Execute manualmente: fish_add_path ${binDir}\n`, - ) - } - } + write('Verboo Code instalado com sucesso!\n') + write('Para começar, digite verboo no seu terminal.\n') } -importFromClaudeCode() - -process.stdout.write('Verboo Code instalado com sucesso!\n') -process.stdout.write('Para começar, digite verboo no seu terminal.\n') +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { + main() +} diff --git a/scripts/postinstall.test.mjs b/scripts/postinstall.test.mjs new file mode 100644 index 0000000000..d6f83a5597 --- /dev/null +++ b/scripts/postinstall.test.mjs @@ -0,0 +1,45 @@ +import assert from 'node:assert/strict' +import { mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' + +import { fishAddPath, main, shouldConfigureShell } from './postinstall.mjs' + +test('never copies anything from ~/.claude', () => { + const home = mkdtempSync(join(tmpdir(), 'verboo-postinstall-')) + try { + mkdirSync(join(home, '.claude', 'skills', 'my-skill'), { recursive: true }) + mkdirSync(join(home, '.claude', 'plugins'), { recursive: true }) + const output = [] + main({ env: { HOME: home, SHELL: '/bin/bash' }, write: text => output.push(text) }) + assert.deepEqual(readdirSync(home), ['.claude']) + assert.ok(output.join('').includes('Verboo Code instalado com sucesso!')) + } finally { + rmSync(home, { recursive: true, force: true }) + } +}) + +test('passes the npm prefix to fish as one argument', () => { + const calls = [] + const spawn = (file, args) => { + calls.push([file, ...args]) + return { status: 0 } + } + assert.equal(fishAddPath('/opt/my prefix; rm -rf ~/bin', spawn), true) + assert.deepEqual(calls, [ + ['fish', '-c', 'fish_add_path -- $argv[1]', '--', '/opt/my prefix; rm -rf ~/bin'], + ]) +}) + +test('only configures fish for a global install by a regular user outside CI', () => { + const fish = { SHELL: '/usr/bin/fish', npm_config_global: 'true' } + assert.equal(shouldConfigureShell({ env: fish, uid: 1000 }), true) + assert.equal(shouldConfigureShell({ env: fish, uid: 0 }), false) + assert.equal(shouldConfigureShell({ env: { ...fish, CI: '1' }, uid: 1000 }), false) + assert.equal(shouldConfigureShell({ env: { SHELL: '/usr/bin/fish' }, uid: 1000 }), false) + assert.equal( + shouldConfigureShell({ env: { SHELL: '/bin/zsh', npm_config_global: 'true' }, uid: 1000 }), + false, + ) +}) diff --git a/src/utils/completionCache.test.ts b/src/utils/completionCache.test.ts new file mode 100644 index 0000000000..050bffb53c --- /dev/null +++ b/src/utils/completionCache.test.ts @@ -0,0 +1,22 @@ +/** + * VERBOO-BRAND: the shell completion cache must not live in ~/.claude, where + * it overwrote Claude Code's own completion files on every `verboo update`. + * detectShell is private and setupShellCompletion edits the real rc file, so + * the wiring is asserted structurally. + */ +import { expect, test } from 'bun:test' +import { resolve } from 'path' + +const source = () => Bun.file(resolve(import.meta.dir, 'completionCache.ts')).text() + +test('completion cache lives in the Verboo config dir', async () => { + const content = await source() + expect(content).toContain('const claudeDir = getClaudeConfigHomeDir()') + expect(content).not.toMatch(/join\(home, '\.claude'\)/) +}) + +test('a Claude Code completion line in the rc file does not count as ours', async () => { + const content = await source() + expect(content).not.toContain("existing.includes('claude completion')") + expect(content).toContain('# Verboo Code shell completions') +}) diff --git a/src/utils/completionCache.ts b/src/utils/completionCache.ts index 3f0c9d2f7d..641ef60656 100644 --- a/src/utils/completionCache.ts +++ b/src/utils/completionCache.ts @@ -6,6 +6,7 @@ import { pathToFileURL } from 'url' import { color } from '../components/design-system/color.js' import { supportsHyperlinks } from '../ink/supports-hyperlinks.js' import { logForDebugging } from './debug.js' +import { getClaudeConfigHomeDir } from './envUtils.js' import { isENOENT } from './errors.js' import { execFileNoThrow } from './execFileNoThrow.js' import { logError } from './log.js' @@ -24,7 +25,9 @@ type ShellInfo = { function detectShell(): ShellInfo | null { const shell = process.env.SHELL || '' const home = homedir() - const claudeDir = join(home, '.claude') + // VERBOO-BRAND: o cache fica no diretório da Verboo. ~/.claude/completion.* + // é do Claude Code e era sobrescrito a cada `verboo update`. + const claudeDir = getClaudeConfigHomeDir() if (shell.endsWith('/zsh') || shell.endsWith('/zsh.exe')) { const cacheFile = join(claudeDir, 'completion.zsh') @@ -89,7 +92,7 @@ export async function setupShellCompletion(theme: ThemeName): Promise { // Generate the completion script by writing directly to the cache file. // Using --output avoids piping through stdout where process.exit() can // truncate output before the pipe buffer drains. - const claudeBin = process.argv[1] || 'claude' + const claudeBin = process.argv[1] || 'verboo' const result = await execFileNoThrow(claudeBin, [ 'completion', shell.shellFlag, @@ -104,10 +107,9 @@ export async function setupShellCompletion(theme: ThemeName): Promise { let existing = '' try { existing = await readFile(shell.rcFile, { encoding: 'utf-8' }) - if ( - existing.includes('claude completion') || - existing.includes(shell.cacheFile) - ) { + // VERBOO-BRAND: só o nosso cache conta; uma linha do Claude Code no rc não + // significa que as completions da Verboo estão instaladas. + if (existing.includes(shell.cacheFile)) { return `${EOL}${color('success', theme)(`Shell completions updated for ${shell.name}`)}${EOL}${chalk.dim(`See ${formatPathLink(shell.rcFile)}`)}${EOL}` } } catch (e: unknown) { @@ -123,7 +125,7 @@ export async function setupShellCompletion(theme: ThemeName): Promise { await mkdir(configDir, { recursive: true }) const separator = existing && !existing.endsWith('\n') ? '\n' : '' - const content = `${existing}${separator}\n# Claude Code shell completions\n${shell.completionLine}\n` + const content = `${existing}${separator}\n# Verboo Code shell completions\n${shell.completionLine}\n` await writeFile(shell.rcFile, content, { encoding: 'utf-8' }) return `${EOL}${color('success', theme)(`Installed ${shell.name} shell completions`)}${EOL}${chalk.dim(`Added to ${formatPathLink(shell.rcFile)}`)}${EOL}${chalk.dim(`Run: source ${shell.rcFile}`)}${EOL}` @@ -145,7 +147,7 @@ export async function regenerateCompletionCache(): Promise { logForDebugging(`update: Regenerating ${shell.name} completion cache`) - const claudeBin = process.argv[1] || 'claude' + const claudeBin = process.argv[1] || 'verboo' const result = await execFileNoThrow(claudeBin, [ 'completion', shell.shellFlag, diff --git a/src/utils/envUtils.ts b/src/utils/envUtils.ts index 1dd7e75a44..d065b60d34 100644 --- a/src/utils/envUtils.ts +++ b/src/utils/envUtils.ts @@ -5,8 +5,8 @@ import { join } from 'path' // VERBOO-BRAND: paths SEMPRE isolados em ~/.verboo. Não há fallback para // configs de outros CLIs — são instalações distintas que podem coexistir -// sem conflito na mesma máquina. Sessões (getProjectsDir) ficam intencionalmente -// no diretório compartilhado de projetos para interop com /resume. +// sem conflito na mesma máquina. Sessões também ficam em ~/.verboo/projects; +// as antigas em ~/.claude/projects são lidas só para o /resume. // // Precedência de override: // VERBOO_CONFIG_DIR (canônico) @@ -50,22 +50,43 @@ export function getTeamsDir(): string { return join(getClaudeConfigHomeDir(), 'teams') } -// Diretório de sessions/projects: mantido em ~/.claude/projects por default -// para interop com Claude Code (/resume cross-CLI). Override via -// VERBOO_PROJECTS_DIR quando quiser isolamento. +// VERBOO-BRAND: sessões novas ficam em ~/.verboo/projects (ou +// VERBOO_CONFIG_DIR/projects). Antes ficavam em ~/.claude/projects, misturadas +// com as do Claude Code — e a limpeza de sessões antigas apagava as dele. +// Override via VERBOO_PROJECTS_DIR. export function getProjectsDir(): string { if (process.env.VERBOO_PROJECTS_DIR) { return process.env.VERBOO_PROJECTS_DIR } - return join(homedir(), '.claude', 'projects') + return join(getClaudeConfigHomeDir(), 'projects') +} + +// Diretórios adicionais de projetos, SOMENTE LEITURA (o /resume enxerga as +// sessões antigas). Nada é gravado aqui: retomar uma sessão antiga copia o +// arquivo para getProjectsDir() antes de continuar. +// - ~/.claude/projects: sessões da Verboo anteriores à mudança de diretório +// (omitido quando VERBOO_CONFIG_DIR/VERBOO_PROJECTS_DIR isolam a instalação) +// - ~/.openclaude/projects: OpenClaude, se existir +let homeDirOverrideForTesting: string | undefined + +export function setHomeDirForTesting(dir: string | undefined): void { + homeDirOverrideForTesting = dir } -// Diretórios adicionais de projetos para leitura multi-source. -// Atualmente detecta OpenClaude (~/.openclaude/projects) se existir. export function getAdditionalProjectsDirs(): string[] { const dirs: string[] = [] + const home = homeDirOverrideForTesting ?? homedir() + + const legacyDir = join(home, '.claude', 'projects') + if ( + !process.env.VERBOO_CONFIG_DIR && + !process.env.VERBOO_PROJECTS_DIR && + existsSync(legacyDir) + ) { + dirs.push(legacyDir) + } - const openClaudeDir = join(homedir(), '.openclaude', 'projects') + const openClaudeDir = join(home, '.openclaude', 'projects') if (existsSync(openClaudeDir)) { dirs.push(openClaudeDir) } diff --git a/src/utils/projectsDirs.test.ts b/src/utils/projectsDirs.test.ts new file mode 100644 index 0000000000..30c0f33b48 --- /dev/null +++ b/src/utils/projectsDirs.test.ts @@ -0,0 +1,89 @@ +/** + * VERBOO-BRAND: new sessions live under the Verboo config dir. Old sessions in + * ~/.claude/projects are only read (for /resume) and copied before resuming. + */ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' + +import { + getAdditionalProjectsDirs, + getProjectsDir, + getProjectsDirs, + setClaudeConfigHomeDirForTesting, + setHomeDirForTesting, +} from './envUtils.js' +import { adoptReadOnlyTranscriptForResume } from './sessionStorage.js' + +const savedEnv = { + VERBOO_CONFIG_DIR: process.env.VERBOO_CONFIG_DIR, + VERBOO_PROJECTS_DIR: process.env.VERBOO_PROJECTS_DIR, +} +let home: string + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), 'verboo-projects-')) + // os.homedir() ignores HOME changes at runtime under Bun. + setHomeDirForTesting(home) + setClaudeConfigHomeDirForTesting(join(home, '.verboo')) + delete process.env.VERBOO_CONFIG_DIR + delete process.env.VERBOO_PROJECTS_DIR +}) + +afterEach(() => { + setHomeDirForTesting(undefined) + setClaudeConfigHomeDirForTesting(undefined) + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } + rmSync(home, { recursive: true, force: true }) +}) + +test('new sessions go to the Verboo config dir, not ~/.claude', () => { + expect(getProjectsDir()).toBe(join(home, '.verboo', 'projects')) + expect(getProjectsDir()).not.toContain('.claude') + process.env.VERBOO_PROJECTS_DIR = join(home, 'explicit') + expect(getProjectsDir()).toBe(join(home, 'explicit')) +}) + +test('old ~/.claude/projects is a read-only source only when the install is not isolated', () => { + const legacy = join(home, '.claude', 'projects') + expect(getAdditionalProjectsDirs()).not.toContain(legacy) + mkdirSync(legacy, { recursive: true }) + expect(getAdditionalProjectsDirs()).toContain(legacy) + expect(getProjectsDirs()[0]).toBe(join(home, '.verboo', 'projects')) + process.env.VERBOO_CONFIG_DIR = join(home, 'isolated') + expect(getAdditionalProjectsDirs()).not.toContain(legacy) +}) + +test('resuming an old session copies it into the Verboo dir and leaves the original untouched', async () => { + const legacyProject = join(home, '.claude', 'projects', '-work-app') + mkdirSync(join(legacyProject, 'session-1', 'tool-results'), { recursive: true }) + const original = join(legacyProject, 'session-1.jsonl') + writeFileSync(original, '{"type":"user"}\n') + writeFileSync(join(legacyProject, 'session-1', 'tool-results', 'r.txt'), 'result') + + const resumeDir = await adoptReadOnlyTranscriptForResume(original) + + const copiedProject = join(home, '.verboo', 'projects', '-work-app') + expect(resumeDir).toBe(copiedProject) + expect(readFileSync(join(copiedProject, 'session-1.jsonl'), 'utf8')).toBe('{"type":"user"}\n') + expect(readFileSync(join(copiedProject, 'session-1', 'tool-results', 'r.txt'), 'utf8')).toBe('result') + expect(readFileSync(original, 'utf8')).toBe('{"type":"user"}\n') + + // A second resume keeps the copy (and anything appended to it). + writeFileSync(join(copiedProject, 'session-1.jsonl'), '{"type":"user"}\n{"type":"assistant"}\n') + expect(await adoptReadOnlyTranscriptForResume(original)).toBe(copiedProject) + expect(readFileSync(join(copiedProject, 'session-1.jsonl'), 'utf8')).toContain('assistant') +}) + +test('a transcript already in the Verboo dir resumes in place', async () => { + const project = join(home, '.verboo', 'projects', '-work-app') + mkdirSync(project, { recursive: true }) + const transcript = join(project, 'session-2.jsonl') + writeFileSync(transcript, '{}\n') + expect(await adoptReadOnlyTranscriptForResume(transcript)).toBe(project) + expect(existsSync(join(home, '.claude'))).toBe(false) +}) diff --git a/src/utils/sessionRestore.ts b/src/utils/sessionRestore.ts index 2b941cbcb5..b5e18b70be 100644 --- a/src/utils/sessionRestore.ts +++ b/src/utils/sessionRestore.ts @@ -1,6 +1,5 @@ import { feature } from 'bun:bundle' import type { UUID } from 'crypto' -import { dirname } from 'path' import { getMainLoopModelOverride, getSessionId, @@ -45,6 +44,7 @@ import { parseUserSpecifiedModel } from './model/model.js' import { getPlansDirectory } from './plans.js' import { setCwd } from './Shell.js' import { + adoptReadOnlyTranscriptForResume, adoptResumedSessionFile, recordContentReplacement, resetSessionFilePointer, @@ -439,9 +439,13 @@ export async function processResumedConversation( // When resuming from a different project directory (git worktrees, // cross-project), transcriptPath points to the actual file; its dirname // is the project dir. Otherwise the session lives in the current project. + // VERBOO-BRAND: a session found in a read-only dir (~/.claude/projects) + // is copied into ~/.verboo/projects first and resumed from the copy. switchSession( asSessionId(sid), - opts.transcriptPath ? dirname(opts.transcriptPath) : null, + opts.transcriptPath + ? await adoptReadOnlyTranscriptForResume(opts.transcriptPath) + : null, ) // Rename asciicast recording to match the resumed session ID so // getSessionRecordingPaths() can discover it during /share diff --git a/src/utils/sessionStorage.ts b/src/utils/sessionStorage.ts index 9425ab2fcc..d8cbef45ff 100644 --- a/src/utils/sessionStorage.ts +++ b/src/utils/sessionStorage.ts @@ -9,6 +9,7 @@ import { closeSync, fstatSync, openSync, readSync } from 'fs' import { appendFile as fsAppendFile, copyFile, + cp, open as fsOpen, mkdir, readdir, @@ -230,13 +231,14 @@ export function getTranscriptPathForSession(sessionId: string): string { return join(projectDir, `${sessionId}.jsonl`) } -// Após escrever um transcript file, espelha para diretórios adicionais -// (ex: ~/.openclaude/projects/) para que outros CLIs vejam as alterações. +// VERBOO-BRAND: não espelha mais transcripts para diretórios de outros +// produtos (~/.claude, ~/.openclaude): eles são somente leitura para a Verboo. +// Mantida como no-op para não divergir das chamadas do upstream. export async function mirrorTranscriptToAdditionalDirs( writtenFile: string, sessionId: string, ): Promise { - const additionalDirs = getAdditionalProjectsDirs() + const additionalDirs: string[] = [] if (additionalDirs.length === 0) return const projectDirName = sanitizePath(getSessionProjectDir() ?? getOriginalCwd()) @@ -1381,16 +1383,25 @@ class Project { } // Fallback: search additional dirs + // VERBOO-BRAND: diretórios adicionais são somente leitura. Ao encontrar a + // sessão em um deles, copia para o diretório da Verboo e grava lá; o + // arquivo original nunca é alterado. const projectDirName = sanitizePath(getOriginalCwd()) for (const additionalDir of getAdditionalProjectsDirs()) { const candidate = join(additionalDir, projectDirName, `${sessionId}.jsonl`) try { await stat(candidate) - this.existingSessionFiles.set(sessionId, candidate) - return candidate } catch { continue } + try { + await mkdir(dirname(targetFile), { recursive: true, mode: 0o700 }) + await copyFile(candidate, targetFile) + this.existingSessionFiles.set(sessionId, targetFile) + return targetFile + } catch { + return null + } } return null @@ -1624,6 +1635,47 @@ export async function resetSessionFilePointer() { * CLI title with the stale disk value. After this write, disk == cache and * later calls (compaction, exit cleanup) absorb SDK writes normally. */ +/** + * VERBOO-BRAND: transcripts in read-only project dirs (old Verboo sessions in + * ~/.claude/projects, OpenClaude) are never written to. Before resuming one, + * copy it — and its session subdirectory, if any — into the matching project + * dir under getProjectsDir() and resume from the copy. Returns the project dir + * to resume in (the copy's), or the transcript's own dir when it is already + * writable. The original files are left untouched. + */ +export async function adoptReadOnlyTranscriptForResume( + transcriptPath: string, +): Promise { + const sourceDir = dirname(transcriptPath) + const projectsRoot = dirname(sourceDir) + const isReadOnly = getAdditionalProjectsDirs().some( + dir => join(dir) === join(projectsRoot), + ) + if (!isReadOnly) return sourceDir + + const targetDir = join(getProjectsDir(), basename(sourceDir)) + const targetPath = join(targetDir, basename(transcriptPath)) + await mkdir(targetDir, { recursive: true, mode: 0o700 }) + try { + await stat(targetPath) + } catch { + await copyFile(transcriptPath, targetPath) + const sessionSubdir = transcriptPath.replace(/\.jsonl$/, '') + try { + if ((await stat(sessionSubdir)).isDirectory()) { + await cp(sessionSubdir, targetPath.replace(/\.jsonl$/, ''), { + recursive: true, + errorOnExist: false, + force: false, + }) + } + } catch { + // No session subdirectory (tool results, subagents) to bring along. + } + } + return targetDir +} + export function adoptResumedSessionFile(): void { const project = getProject() project.sessionFile = getTranscriptPath() diff --git a/src/utils/sessionStoragePortable.ts b/src/utils/sessionStoragePortable.ts index 3422cec99d..023c01fb8a 100644 --- a/src/utils/sessionStoragePortable.ts +++ b/src/utils/sessionStoragePortable.ts @@ -9,7 +9,7 @@ import type { UUID } from 'crypto' import { open as fsOpen, readdir, realpath, stat } from 'fs/promises' import { join } from 'path' -import { getProjectsDir } from './envUtils.js' +import { getProjectsDir, getProjectsDirs } from './envUtils.js' import { getWorktreePathsPortable } from './getWorktreePathsPortable.js' import { djb2Hash } from './hash.js' @@ -441,21 +441,24 @@ export async function resolveSessionFilePath( } // No dir — scan all project directories - const projectsDir = getProjectsDir() - let dirents: string[] - try { - dirents = await readdir(projectsDir) - } catch { - return undefined - } - for (const name of dirents) { - const filePath = join(projectsDir, name, fileName) + // VERBOO-BRAND: inclui os diretórios somente leitura (sessões antigas em + // ~/.claude/projects); o diretório da Verboo vem primeiro. + for (const projectsDir of getProjectsDirs()) { + let dirents: string[] try { - const s = await stat(filePath) - if (s.size > 0) - return { filePath, projectPath: undefined, fileSize: s.size } + dirents = await readdir(projectsDir) } catch { - // ENOENT/ENOTDIR — not in this project, keep scanning + continue + } + for (const name of dirents) { + const filePath = join(projectsDir, name, fileName) + try { + const s = await stat(filePath) + if (s.size > 0) + return { filePath, projectPath: undefined, fileSize: s.size } + } catch { + // ENOENT/ENOTDIR — not in this project, keep scanning + } } } return undefined From 4084a4df0c144d8274f10f8bdebf7ff49a5daeca Mon Sep 17 00:00:00 2001 From: Savas Neto Date: Wed, 4 Nov 2026 09:48:47 -0300 Subject: [PATCH 2/2] fix(storage): resume old sessions from a copy on every path The copy step only ran on one of the resume paths. Found by end-to-end validation: - /resume, the `verboo --resume` picker and headless -p --continue/--resume kept writing into ~/.claude/projects. - `--resume ` builds the path in the Verboo dir, so nothing was copied and the old history was hidden by a new, empty file. - `--continue` no longer found sessions saved before the upgrade. - Renaming an old session from the picker wrote to the original file; metadata writers now go to the copy. Co-Authored-By: Claude Opus 5.5 --- src/cli/print.ts | 12 +++- src/screens/REPL.tsx | 5 +- src/screens/ResumeConversation.tsx | 6 +- src/utils/projectsDirs.test.ts | 54 +++++++++++++++++- src/utils/sessionStorage.ts | 88 ++++++++++++++++++++++++++---- 5 files changed, 146 insertions(+), 19 deletions(-) diff --git a/src/cli/print.ts b/src/cli/print.ts index 6b8d014e79..5f7cb7e19b 100644 --- a/src/cli/print.ts +++ b/src/cli/print.ts @@ -2,7 +2,6 @@ import { parseAgentUsageMetadata } from '../utils/agentUsageSchema.js' // biome-ignore-all assist/source/organizeImports: internal-only import markers must not be reordered import { feature } from 'bun:bundle' import { readFile, stat } from 'fs/promises' -import { dirname } from 'path' import { downloadUserSettings, redownloadUserSettings, @@ -211,6 +210,7 @@ import { parseSessionIdentifier } from 'src/utils/sessionUrl.js' import { hydrateRemoteSession, hydrateFromCCRv2InternalEvents, + adoptReadOnlyTranscriptForResume, resetSessionFilePointer, doesMessageExistInSession, findUnresolvedToolUse, @@ -4960,7 +4960,10 @@ async function loadInitialMessages( if (result.sessionId) { switchSession( asSessionId(result.sessionId), - result.fullPath ? dirname(result.fullPath) : null, + // VERBOO-BRAND: an old session in a read-only dir is resumed from a copy. + result.fullPath + ? await adoptReadOnlyTranscriptForResume(result.fullPath) + : null, ) if (persistSession) { await resetSessionFilePointer() @@ -5161,7 +5164,10 @@ async function loadInitialMessages( if (!options.forkSession && result.sessionId) { switchSession( asSessionId(result.sessionId), - result.fullPath ? dirname(result.fullPath) : null, + // VERBOO-BRAND: an old session in a read-only dir is resumed from a copy. + result.fullPath + ? await adoptReadOnlyTranscriptForResume(result.fullPath) + : null, ) if (persistSession) { await resetSessionFilePointer() diff --git a/src/screens/REPL.tsx b/src/screens/REPL.tsx index cd4066562f..aa54f56bbe 100644 --- a/src/screens/REPL.tsx +++ b/src/screens/REPL.tsx @@ -172,7 +172,7 @@ import type { ContentBlockParam, ImageBlockParam } from '@anthropic-ai/sdk/resou import type { ProcessUserInputContext } from '../utils/processUserInput/processUserInput.js'; import type { PastedContent } from '../utils/config.js'; import { copyPlanForFork, copyPlanForResume, getPlanSlug, setPlanSlug } from '../utils/plans.js'; -import { clearSessionMetadata, resetSessionFilePointer, adoptResumedSessionFile, removeTranscriptMessage, restoreSessionMetadata, getCurrentSessionTitle, isEphemeralToolProgress, isLoggableMessage, saveWorktreeState, getAgentTranscript, recordAiGeneratedTitle } from '../utils/sessionStorage.js'; +import { adoptReadOnlyTranscriptForResume, clearSessionMetadata, resetSessionFilePointer, adoptResumedSessionFile, removeTranscriptMessage, restoreSessionMetadata, getCurrentSessionTitle, isEphemeralToolProgress, isLoggableMessage, saveWorktreeState, getAgentTranscript, recordAiGeneratedTitle } from '../utils/sessionStorage.js'; import { deserializeMessages } from '../utils/conversationRecovery.js'; import { extractReadFilesFromMessages, extractBashToolsFromMessages } from '../utils/queryHelpers.js'; import { resetMicrocompactState } from '../services/compact/microCompact.js'; @@ -1929,7 +1929,8 @@ export function REPL({ // Switch session (id + project dir atomically). fullPath may point to // a different project (cross-worktree, /branch); null derives from // current originalCwd. - switchSession(asSessionId(sessionId), log.fullPath ? dirname(log.fullPath) : null); + // VERBOO-BRAND: an old session in a read-only dir is resumed from a copy. + switchSession(asSessionId(sessionId), log.fullPath ? await adoptReadOnlyTranscriptForResume(log.fullPath) : null); // Rename asciicast recording to match the resumed session ID const { renameRecordingForSession diff --git a/src/screens/ResumeConversation.tsx b/src/screens/ResumeConversation.tsx index bed3072faf..a6768ac2d9 100644 --- a/src/screens/ResumeConversation.tsx +++ b/src/screens/ResumeConversation.tsx @@ -1,6 +1,5 @@ import { c as _c } from "react-compiler-runtime"; import { feature } from 'bun:bundle'; -import { dirname } from 'path'; import React from 'react'; import { useTerminalSize } from 'src/hooks/useTerminalSize.js'; import { getOriginalCwd, switchSession } from '../bootstrap/state.js'; @@ -31,7 +30,7 @@ import { logError } from '../utils/log.js'; import { handoffToResume } from '../utils/resumeHandoff.js'; import { createSystemMessage } from '../utils/messages.js'; import { computeStandaloneAgentContext, restoreAgentFromSession, restoreWorktreeForResume } from '../utils/sessionRestore.js'; -import { adoptResumedSessionFile, enrichLogs, getSessionIdFromLog, isCustomTitleEnabled, loadAllProjectsMessageLogsProgressive, loadSameRepoMessageLogsProgressive, recordContentReplacement, resetSessionFilePointer, restoreSessionMetadata, type SessionLogResult } from '../utils/sessionStorage.js'; +import { adoptReadOnlyTranscriptForResume, adoptResumedSessionFile, enrichLogs, getSessionIdFromLog, isCustomTitleEnabled, loadAllProjectsMessageLogsProgressive, loadSameRepoMessageLogsProgressive, recordContentReplacement, resetSessionFilePointer, restoreSessionMetadata, type SessionLogResult } from '../utils/sessionStorage.js'; import type { ThinkingConfig } from '../utils/thinking.js'; import type { ContentReplacementRecord } from '../utils/toolResultStorage.js'; import { REPL } from './REPL.js'; @@ -232,7 +231,8 @@ export function ResumeConversation({ // Prefer the resolved fullPath: for imported sessions (Codex) it // points to the converted native file, not the foreign source. const sessionDirPath = result_3.fullPath ?? log_0.fullPath; - switchSession(asSessionId(result_3.sessionId), sessionDirPath ? dirname(sessionDirPath) : null); + // VERBOO-BRAND: an old session in a read-only dir is resumed from a copy. + switchSession(asSessionId(result_3.sessionId), sessionDirPath ? await adoptReadOnlyTranscriptForResume(sessionDirPath) : null); await renameRecordingForSession(); await resetSessionFilePointer(); restoreCostStateForSession(result_3.sessionId); diff --git a/src/utils/projectsDirs.test.ts b/src/utils/projectsDirs.test.ts index 30c0f33b48..124cc9c547 100644 --- a/src/utils/projectsDirs.test.ts +++ b/src/utils/projectsDirs.test.ts @@ -14,7 +14,9 @@ import { setClaudeConfigHomeDirForTesting, setHomeDirForTesting, } from './envUtils.js' -import { adoptReadOnlyTranscriptForResume } from './sessionStorage.js' +import { adoptReadOnlyTranscriptForResume, fetchLogs, saveCustomTitle } from './sessionStorage.js' +import { getOriginalCwd } from '../bootstrap/state.js' +import { sanitizePath } from './sessionStoragePortable.js' const savedEnv = { VERBOO_CONFIG_DIR: process.env.VERBOO_CONFIG_DIR, @@ -87,3 +89,53 @@ test('a transcript already in the Verboo dir resumes in place', async () => { expect(await adoptReadOnlyTranscriptForResume(transcript)).toBe(project) expect(existsSync(join(home, '.claude'))).toBe(false) }) + +test('--resume builds the path in the Verboo dir: the old session is still found and copied', async () => { + const legacyProject = join(home, '.claude', 'projects', '-work-app') + mkdirSync(legacyProject, { recursive: true }) + const original = join(legacyProject, 'session-3.jsonl') + writeFileSync(original, '{"type":"user"}\n') + + const computed = join(home, '.verboo', 'projects', '-work-app', 'session-3.jsonl') + expect(await adoptReadOnlyTranscriptForResume(computed)).toBe(join(home, '.verboo', 'projects', '-work-app')) + expect(readFileSync(computed, 'utf8')).toBe('{"type":"user"}\n') + expect(readFileSync(original, 'utf8')).toBe('{"type":"user"}\n') +}) + +test('a brand new session id stays in the Verboo dir without copying anything', async () => { + const computed = join(home, '.verboo', 'projects', '-work-app', 'session-new.jsonl') + expect(await adoptReadOnlyTranscriptForResume(computed)).toBe(join(home, '.verboo', 'projects', '-work-app')) + expect(existsSync(computed)).toBe(false) +}) + +test('renaming an old session from the picker writes to its copy, never to the original', async () => { + const legacyProject = join(home, '.claude', 'projects', '-work-app') + mkdirSync(legacyProject, { recursive: true }) + const sessionId = '7f4e8a4e-5c0b-4a4e-9d0a-1a2b3c4d5e6f' + const original = join(legacyProject, `${sessionId}.jsonl`) + writeFileSync(original, '{"type":"user"}\n') + + await saveCustomTitle(sessionId as never, 'novo nome', original) + + expect(readFileSync(original, 'utf8')).toBe('{"type":"user"}\n') + const copy = readFileSync(join(home, '.verboo', 'projects', '-work-app', `${sessionId}.jsonl`), 'utf8') + expect(copy).toContain('novo nome') +}) + +test('--continue also considers sessions saved before the move, once each', async () => { + const project = sanitizePath(getOriginalCwd()) + const sessionId = '0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d' + const entry = `${JSON.stringify({ type: 'user', sessionId, uuid: sessionId, message: { role: 'user', content: 'old prompt' } })}\n` + for (const root of ['.claude', '.verboo']) { + mkdirSync(join(home, root, 'projects', project), { recursive: true }) + } + writeFileSync(join(home, '.claude', 'projects', project, `${sessionId}.jsonl`), entry) + let logs = await fetchLogs() + expect(logs.filter(log => log.sessionId === sessionId)).toHaveLength(1) + + writeFileSync(join(home, '.verboo', 'projects', project, `${sessionId}.jsonl`), entry) + logs = await fetchLogs() + const found = logs.filter(log => log.sessionId === sessionId) + expect(found).toHaveLength(1) + expect(found[0]?.fullPath).toContain(join('.verboo', 'projects')) +}) diff --git a/src/utils/sessionStorage.ts b/src/utils/sessionStorage.ts index d8cbef45ff..7ec211e063 100644 --- a/src/utils/sessionStorage.ts +++ b/src/utils/sessionStorage.ts @@ -1643,15 +1643,48 @@ export async function resetSessionFilePointer() { * to resume in (the copy's), or the transcript's own dir when it is already * writable. The original files are left untouched. */ +function isInReadOnlyProjectsDir(transcriptPath: string): boolean { + const projectsRoot = join(dirname(dirname(transcriptPath))) + return getAdditionalProjectsDirs().some(dir => join(dir) === projectsRoot) +} + +async function findInReadOnlyProjectsDirs( + transcriptPath: string, +): Promise { + try { + await stat(transcriptPath) + return undefined + } catch { + // Not in the writable dir: look for it where old sessions live. + } + for (const dir of getAdditionalProjectsDirs()) { + const candidate = join( + dir, + basename(dirname(transcriptPath)), + basename(transcriptPath), + ) + try { + await stat(candidate) + return candidate + } catch { + // Not in this one. + } + } + return undefined +} + export async function adoptReadOnlyTranscriptForResume( transcriptPath: string, ): Promise { const sourceDir = dirname(transcriptPath) - const projectsRoot = dirname(sourceDir) - const isReadOnly = getAdditionalProjectsDirs().some( - dir => join(dir) === join(projectsRoot), - ) - if (!isReadOnly) return sourceDir + let sourcePath = transcriptPath + if (!isInReadOnlyProjectsDir(sourcePath)) { + // Lookups by session id build the path in the writable dir even when the + // session only exists in a read-only one. + const original = await findInReadOnlyProjectsDirs(transcriptPath) + if (!original) return sourceDir + sourcePath = original + } const targetDir = join(getProjectsDir(), basename(sourceDir)) const targetPath = join(targetDir, basename(transcriptPath)) @@ -1659,8 +1692,8 @@ export async function adoptReadOnlyTranscriptForResume( try { await stat(targetPath) } catch { - await copyFile(transcriptPath, targetPath) - const sessionSubdir = transcriptPath.replace(/\.jsonl$/, '') + await copyFile(sourcePath, targetPath) + const sessionSubdir = sourcePath.replace(/\.jsonl$/, '') try { if ((await stat(sessionSubdir)).isDirectory()) { await cp(sessionSubdir, targetPath.replace(/\.jsonl$/, ''), { @@ -2959,6 +2992,21 @@ async function trackSessionBranchingAnalytics( export async function fetchLogs(limit?: number): Promise { const projectDir = getProjectDir(getOriginalCwd()) const logs = await getSessionFilesLite(projectDir, limit, getOriginalCwd()) + // VERBOO-BRAND: sessions saved before the move to ~/.verboo/projects are still + // candidates for --continue. + const seen = new Set(logs.map(log => log.sessionId)) + for (const dir of getAdditionalProjectsDirs()) { + const older = await getSessionFilesLite( + join(dir, basename(projectDir)), + limit, + getOriginalCwd(), + ) + for (const log of older) { + if (seen.has(log.sessionId)) continue + seen.add(log.sessionId) + logs.push(log) + } + } // Sessões do Codex CLI (ainda não convertidas) para --continue cross-CLI logs.push(...(await getCodexLogOptions(new Set([getOriginalCwd()])))) @@ -2976,13 +3024,33 @@ function appendEntryToFile( entry: Record, ): void { const fs = getFsImplementation() + const path = writablePathForSessionFile(fullPath) const line = jsonStringify(entry) + '\n' try { - fs.appendFileSync(fullPath, line, { mode: 0o600 }) + fs.appendFileSync(path, line, { mode: 0o600 }) } catch { - fs.mkdirSync(dirname(fullPath), { mode: 0o700 }) - fs.appendFileSync(fullPath, line, { mode: 0o600 }) + fs.mkdirSync(dirname(path), { mode: 0o700 }) + fs.appendFileSync(path, line, { mode: 0o600 }) + } +} + +/** + * VERBOO-BRAND: metadata writers (rename, tag) get a path from the picker, which + * may be an old session in a read-only dir. The entry goes to its copy instead. + */ +function writablePathForSessionFile(fullPath: string): string { + if (!isInReadOnlyProjectsDir(fullPath)) return fullPath + const fs = getFsImplementation() + const target = join( + getProjectsDir(), + basename(dirname(fullPath)), + basename(fullPath), + ) + if (!fs.existsSync(target)) { + fs.mkdirSync(dirname(target), { mode: 0o700 }) + fs.copyFileSync(fullPath, target) } + return target } /**