@myrialabs/clopen 0.4.3 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -136,6 +136,8 @@ bun run check # Type checking
136
136
 
137
137
  When running in development mode, Clopen uses `~/.clopen-dev` instead of `~/.clopen`, keeping dev data separate from any production instance.
138
138
 
139
+ Each AI engine's config/state (credentials, sessions, logs) is isolated under `~/.clopen/engine/<engine>/user/` rather than the engine's global location (`~/.codex`, `~/.copilot`, `~/.qwen`, the OpenCode XDG dirs), so Clopen never mixes with — or disturbs — your own standalone CLI usage.
140
+
139
141
  See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines and [DECISIONS.md](DECISIONS.md) for architectural decisions.
140
142
 
141
143
  ---
@@ -0,0 +1,71 @@
1
+ import fs from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import type { DatabaseConnection } from '$shared/types/database/connection';
4
+ import { getClopenDir } from '../../utils/paths';
5
+ import { debug } from '$shared/utils/logger';
6
+
7
+ export const description = 'Relocate per-engine config dirs from {clopenDir}/{engine}/user to {clopenDir}/engine/{engine}/user';
8
+
9
+ /**
10
+ * Earlier builds isolated each engine at `{clopenDir}/{engine}/user/`; the
11
+ * layout has since moved under an `engine/` parent: `{clopenDir}/engine/{engine}/user/`
12
+ * (see `getEngineUserConfigDir`). This migration relocates any directory the
13
+ * previous build already created so existing sessions/credentials carry over.
14
+ *
15
+ * Safe by construction: it only ever touches `{clopenDir}/{engine}/user/`,
16
+ * which is a path **Clopen itself created** — never the engine's global home
17
+ * (`~/.codex`, `~/.copilot`, …). A user's standalone CLI usage is untouched.
18
+ *
19
+ * Filesystem-only + idempotent: if the new dir already exists (current build
20
+ * ran first) the old one is left in place rather than clobbering live data.
21
+ */
22
+
23
+ const ENGINES = ['claude', 'codex', 'copilot', 'qwen', 'opencode'] as const;
24
+
25
+ export const up = (db: DatabaseConnection): void => {
26
+ const clopenDir = getClopenDir();
27
+ const engineParent = join(clopenDir, 'engine');
28
+
29
+ for (const engine of ENGINES) {
30
+ const oldUserDir = join(clopenDir, engine, 'user'); // {clopenDir}/{engine}/user
31
+ const newUserDir = join(engineParent, engine, 'user'); // {clopenDir}/engine/{engine}/user
32
+
33
+ try {
34
+ if (!fs.existsSync(oldUserDir)) continue;
35
+
36
+ if (fs.existsSync(newUserDir)) {
37
+ debug.warn('migration', `engine-dir: ${newUserDir} already exists — leaving ${oldUserDir} in place (no clobber)`);
38
+ continue;
39
+ }
40
+
41
+ fs.mkdirSync(join(engineParent, engine), { recursive: true });
42
+ fs.renameSync(oldUserDir, newUserDir);
43
+ debug.log('migration', `engine-dir: moved ${oldUserDir} → ${newUserDir}`);
44
+
45
+ // Remove the now-empty {clopenDir}/{engine} parent left behind.
46
+ try {
47
+ const oldParent = join(clopenDir, engine);
48
+ if (fs.readdirSync(oldParent).length === 0) fs.rmdirSync(oldParent);
49
+ } catch {
50
+ // Parent not empty or already gone — leave it.
51
+ }
52
+ } catch (err) {
53
+ // Non-fatal: the engine just starts fresh at the new dir on next use.
54
+ debug.warn('migration', `engine-dir: failed to move ${oldUserDir} → ${newUserDir}: ${err instanceof Error ? err.message : String(err)}`);
55
+ }
56
+ }
57
+
58
+ // Drop any persisted OpenCode server pointer: a cached URL/datadir from the
59
+ // pre-move location would otherwise be reuse-checked against the new dir.
60
+ // Clearing it forces a clean re-spawn into the relocated data dir.
61
+ try {
62
+ db.exec(`DELETE FROM settings WHERE key IN ('opencode.server.url', 'opencode.server.datadir')`);
63
+ } catch (err) {
64
+ debug.warn('migration', `engine-dir: failed to clear opencode server settings: ${err instanceof Error ? err.message : String(err)}`);
65
+ }
66
+ };
67
+
68
+ export const down = (): void => {
69
+ // No-op. Directory relocation is forward-only and data-preserving; reversing
70
+ // it would re-fragment state across the old/new layouts for no benefit.
71
+ };
@@ -41,6 +41,7 @@ import * as migration039 from './039_create_file_audit_log';
41
41
  import * as migration040 from './040_create_mcp_servers_table';
42
42
  import * as migration041 from './041_add_mcp_config_schema';
43
43
  import * as migration042 from './042_add_mcp_oauth';
44
+ import * as migration043 from './043_relocate_engine_config_dirs';
44
45
 
45
46
  // Export all migrations in order
46
47
  export const migrations = [
@@ -295,6 +296,12 @@ export const migrations = [
295
296
  description: migration042.description,
296
297
  up: migration042.up,
297
298
  down: migration042.down
299
+ },
300
+ {
301
+ id: '043',
302
+ description: migration043.description,
303
+ up: migration043.up,
304
+ down: migration043.down
298
305
  }
299
306
  ];
300
307
 
@@ -143,6 +143,20 @@ export const mcpServerQueries = {
143
143
  );
144
144
  },
145
145
 
146
+ /**
147
+ * Update a stdio server's command + args. Lets users repair incomplete
148
+ * registry metadata (e.g. a CLI that needs a `mcp` subcommand to start) that
149
+ * would otherwise leave the server permanently unreachable.
150
+ */
151
+ updateCommand(id: number, command: string, args: string[]): void {
152
+ const db = getDatabase();
153
+ db.prepare(`UPDATE mcp_servers SET command = ?, args = ? WHERE id = ?`).run(
154
+ command,
155
+ JSON.stringify(args),
156
+ id
157
+ );
158
+ },
159
+
146
160
  /** Store (or clear with null) the managed OAuth state JSON for a server. */
147
161
  setOAuth(id: number, oauth: string | null): void {
148
162
  const db = getDatabase();
@@ -105,14 +105,18 @@ Three key rules that **every** layer upholds:
105
105
  > URL** by adding a sibling `getXxxMcpConfig()` helper in
106
106
  > `backend/mcp/internal/config.ts`. Do **NOT** propose a "new MCP bridge",
107
107
  > "per-engine MCP server", or "per-stream MCP path". See §9.12.
108
- > 2. **Shared CLI dotfiles are swapped from DB, not isolated.** When a CLI
109
- > stores its credentials in a known location (e.g. `~/.codex/auth.json`),
110
- > the multi-account approach is to snapshot that file into the DB on
111
- > login and write the chosen account's snapshot back on switch. Do
112
- > **NOT** propose per-account isolated home directories
113
- > (`CODEX_HOME=/foo/account-1/`); that path complicates session-state
114
- > sharing, token refresh persistence, and user-level config inheritance.
115
- > See §9.13.
108
+ > 2. **Engine home dirs are isolated per-engine (Clopen vs. global), but
109
+ > multi-account stays DB-swap.** Two different axes — don't conflate them:
110
+ > - **Clopen vs. the user's global CLI usage:** every engine's home/config
111
+ > is redirected to `{clopenDir}/engine/{engine}/user/` via that engine's env
112
+ > var (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `COPILOT_HOME` via
113
+ > `baseDirectory`, `QWEN_RUNTIME_DIR`, `XDG_*` for OpenCode) so Clopen
114
+ > never touches `~/.codex`, `~/.copilot`, … See §9.19.
115
+ > - **Multiple accounts *within* Clopen:** still the auth-blob swap — one
116
+ > shared dotfile inside that isolated home, snapshotted to/from the DB on
117
+ > login/switch. Do **NOT** propose **per-account** home dirs
118
+ > (`CODEX_HOME=/foo/account-1/`); that splits session-state, breaks
119
+ > fork-by-copy, and loses token-refresh persistence. See §9.13.
116
120
 
117
121
  ---
118
122
 
@@ -10,17 +10,17 @@
10
10
  import { join } from 'path';
11
11
  import { engineQueries } from '../../../database/queries';
12
12
  import { debug } from '$shared/utils/logger';
13
- import { getCleanSpawnEnv, getClopenDir } from '../../../utils/index.js';
13
+ import { getCleanSpawnEnv, getEngineUserConfigDir } from '../../../utils/index.js';
14
14
 
15
15
  let _ready = false;
16
16
  let _initPromise: Promise<void> | null = null;
17
17
  let _envOverrides: Record<string, string> = {};
18
18
 
19
19
  /**
20
- * Returns the isolated Claude config directory under {clopenDir}/claude/user/
20
+ * Returns the isolated Claude config directory under {clopenDir}/engine/claude/user/
21
21
  */
22
22
  export function getClaudeUserConfigDir(): string {
23
- return join(getClopenDir(), 'claude', 'user');
23
+ return getEngineUserConfigDir('claude');
24
24
  }
25
25
 
26
26
  /**
@@ -19,11 +19,15 @@
19
19
 
20
20
  import fs from 'node:fs';
21
21
  import path from 'node:path';
22
- import os from 'node:os';
23
22
  import { engineQueries, type EngineAccount } from '../../../database/queries/engine-queries';
23
+ import { getEngineUserConfigDir } from '$backend/utils/paths';
24
24
  import { debug } from '$shared/utils/logger';
25
25
 
26
- const CODEX_HOME = path.join(os.homedir(), '.codex');
26
+ // Isolate Codex state (auth.json, sessions) to {clopenDir}/engine/codex/user/ instead
27
+ // of the shared ~/.codex so Clopen never mixes with the user's own Codex CLI
28
+ // usage. The same path is forwarded to every spawned `codex` subprocess via the
29
+ // CODEX_HOME env var (see ./stream.ts and ws/engine/codex/accounts.ts).
30
+ const CODEX_HOME = getEngineUserConfigDir('codex');
27
31
  const AUTH_JSON_PATH = path.join(CODEX_HOME, 'auth.json');
28
32
  const AUTH_JSON_TMP_PATH = path.join(CODEX_HOME, 'auth.json.tmp');
29
33
 
@@ -26,6 +26,7 @@ import { extractJson } from '../../structured-helpers';
26
26
  import { engineQueries } from '$backend/database/queries/engine-queries';
27
27
  import { resolveOsPath } from '$backend/utils/paths';
28
28
  import { resolveBinary } from '$backend/utils/cli';
29
+ import { getCleanSpawnEnv } from '$backend/utils/index.js';
29
30
  import { getCodexMcpConfig } from '../../../mcp';
30
31
  import { CODEX_MODELS } from './models';
31
32
  import { debug } from '$shared/utils/logger';
@@ -44,6 +45,7 @@ import {
44
45
  parseCodexCredential,
45
46
  applyAccountAuth,
46
47
  snapshotAuthJsonToActiveAccount,
48
+ getCodexHomeDir,
47
49
  } from './credential';
48
50
  import { forkCodexSessionState, sessionStateExists } from './session-fork';
49
51
  import path from 'node:path';
@@ -103,9 +105,13 @@ export class CodexEngine implements AIEngine {
103
105
  // `workspace-write` sandbox relies on platform primitives (Seatbelt on
104
106
  // macOS, Landlock on Linux) that are absent on Windows, where the CLI
105
107
  // degrades to read-only — using full-access keeps behaviour consistent.
108
+ // The SDK does NOT inherit process.env when `env` is provided, so we
109
+ // pass the full clean spawn env and layer CODEX_HOME on top to redirect
110
+ // the subprocess's auth.json + sessions into Clopen's isolated dir.
106
111
  this.codex = new Codex({
107
112
  apiKey: credential.kind === 'api_key' ? credential.apiKey : undefined,
108
113
  ...(codexBinary ? { codexPathOverride: codexBinary } : {}),
114
+ env: { ...getCleanSpawnEnv(), CODEX_HOME: getCodexHomeDir() },
109
115
  config: {
110
116
  show_raw_agent_reasoning: true,
111
117
  ...(Object.keys(mcpConfig).length > 0 ? { mcp_servers: mcpConfig } : {}),
@@ -18,7 +18,7 @@ import type { EngineOutput, EngineModel } from '$shared/types/unified';
18
18
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
19
19
  import { buildJsonPrompt, extractJson } from '../../structured-helpers';
20
20
  import { engineQueries } from '$backend/database/queries/engine-queries';
21
- import { resolveOsPath } from '$backend/utils/paths';
21
+ import { resolveOsPath, getEngineUserConfigDir } from '$backend/utils/paths';
22
22
  import { debug } from '$shared/utils/logger';
23
23
  import { getCopilotMcpConfig } from '../../../mcp';
24
24
  import { handleStreamError, buildSessionError } from './error-handler';
@@ -123,6 +123,10 @@ export class CopilotEngine implements AIEngine {
123
123
  this.client = new CopilotClient({
124
124
  gitHubToken: account.credential,
125
125
  useLoggedInUser: false,
126
+ // Isolate Copilot state (session-state, session-store.db, logs) to
127
+ // {clopenDir}/engine/copilot/user/ instead of the shared ~/.copilot. The SDK
128
+ // forwards this as COPILOT_HOME to the spawned runtime.
129
+ baseDirectory: getEngineUserConfigDir('copilot'),
126
130
  });
127
131
 
128
132
  await this.client.start();
@@ -17,10 +17,16 @@ import { getOpenCodeMcpConfig } from '../../../mcp';
17
17
  import { settingsQueries } from '../../../database/queries';
18
18
  import { generateOpenCodeProviderConfig } from './config';
19
19
  import { resolveBinaryWithRefresh } from '$backend/utils/cli';
20
+ import { getEngineUserConfigDir } from '$backend/utils/paths';
20
21
  import { debug } from '$shared/utils/logger';
21
22
 
22
23
  const OPENCODE_HOST = '127.0.0.1';
23
24
  const DB_KEY = 'opencode.server.url';
25
+ // The isolated data dir the persisted server was spawned with. A reused server
26
+ // inherits the env it was spawned with, so if our target dir has changed (code
27
+ // update that moves the isolation path, or a server left over from before
28
+ // isolation existed) we must NOT reuse it — respawn into the right dir instead.
29
+ const DB_KEY_DATADIR = 'opencode.server.datadir';
24
30
  const HEALTH_TIMEOUT = 1500;
25
31
  const SERVER_START_TIMEOUT = 30_000; // 30s — generous for slow devices
26
32
 
@@ -76,6 +82,7 @@ export async function ensureClient(): Promise<OpencodeClient> {
76
82
  // Do NOT clear initPromise — another caller may have started one
77
83
  debug.log('engine', 'Open Code server disconnected, recovering...');
78
84
  settingsQueries.delete(DB_KEY);
85
+ settingsQueries.delete(DB_KEY_DATADIR);
79
86
  clearClientState();
80
87
  }
81
88
 
@@ -99,12 +106,24 @@ export async function ensureClient(): Promise<OpencodeClient> {
99
106
  async function init(): Promise<void> {
100
107
  debug.log('engine', 'Initializing Open Code client...');
101
108
 
102
- // 1. Try to reuse an existing server persisted in DB
109
+ // Isolate OpenCode's state (opencode.db, snapshots, logs, config) to
110
+ // {clopenDir}/engine/opencode/user/ instead of the shared XDG dirs
111
+ // (~/.local/share/opencode, ~/.config/opencode) so Clopen never mixes with
112
+ // the user's own OpenCode CLI usage. OpenCode follows the XDG base-dir spec
113
+ // and appends `/opencode` to each base. Credentials + MCP config are injected
114
+ // via OPENCODE_CONFIG_CONTENT, so no auth file needs to carry over.
115
+ const opencodeUserDir = getEngineUserConfigDir('opencode');
116
+
117
+ // 1. Try to reuse an existing server persisted in DB — but only if it was
118
+ // spawned with the SAME isolated data dir we'd use now. A mismatch means the
119
+ // stored server points at a stale location (pre-isolation, or a moved path);
120
+ // reusing it would silently keep writing to the wrong dir.
103
121
  const stored = settingsQueries.get(DB_KEY);
122
+ const storedDataDir = settingsQueries.get(DB_KEY_DATADIR)?.value;
104
123
  if (stored?.value) {
105
124
  debug.log('engine', `Found stored Open Code server: ${stored.value}, checking...`);
106
125
 
107
- if (await isServerAlive(stored.value)) {
126
+ if (storedDataDir === opencodeUserDir && await isServerAlive(stored.value)) {
108
127
  const { createOpencodeClient } = await import('@opencode-ai/sdk');
109
128
  client = createOpencodeClient({ baseUrl: stored.value });
110
129
  serverHandle = { url: stored.value, close() {} };
@@ -114,8 +133,13 @@ async function init(): Promise<void> {
114
133
  return;
115
134
  }
116
135
 
117
- debug.log('engine', 'Stored server not responding, spawning new one...');
136
+ if (storedDataDir !== opencodeUserDir) {
137
+ debug.log('engine', `Stored Open Code server data dir mismatch (${storedDataDir ?? 'unknown'} ≠ ${opencodeUserDir}), spawning fresh...`);
138
+ } else {
139
+ debug.log('engine', 'Stored server not responding, spawning new one...');
140
+ }
118
141
  settingsQueries.delete(DB_KEY);
142
+ settingsQueries.delete(DB_KEY_DATADIR);
119
143
  }
120
144
 
121
145
  // 2. Spawn a new server via Bun.spawn with absolute binary path.
@@ -172,7 +196,7 @@ async function init(): Promise<void> {
172
196
  ? JSON.stringify(mergedConfig)
173
197
  : '{}';
174
198
 
175
- debug.log('engine', `Spawning: ${args.join(' ')}`);
199
+ debug.log('engine', `Spawning: ${args.join(' ')} (data dir: ${opencodeUserDir})`);
176
200
 
177
201
  const proc = Bun.spawn(args, {
178
202
  stdout: 'pipe',
@@ -180,6 +204,10 @@ async function init(): Promise<void> {
180
204
  env: {
181
205
  ...process.env,
182
206
  ...providerConfig.envVars,
207
+ XDG_DATA_HOME: opencodeUserDir,
208
+ XDG_CONFIG_HOME: opencodeUserDir,
209
+ XDG_STATE_HOME: opencodeUserDir,
210
+ XDG_CACHE_HOME: opencodeUserDir,
183
211
  OPENCODE_CONFIG_CONTENT: configContent,
184
212
  },
185
213
  });
@@ -243,7 +271,8 @@ async function init(): Promise<void> {
243
271
  ready = true;
244
272
 
245
273
  settingsQueries.set(DB_KEY, url);
246
- debug.log('engine', `Open Code client ready (server: ${url})`);
274
+ settingsQueries.set(DB_KEY_DATADIR, opencodeUserDir);
275
+ debug.log('engine', `Open Code client ready (server: ${url}, data dir: ${opencodeUserDir})`);
247
276
  }
248
277
 
249
278
  export function getClient(): OpencodeClient | null {
@@ -285,6 +314,7 @@ export async function disposeOpenCodeClient(forRestart = false): Promise<void> {
285
314
  }
286
315
  }
287
316
  settingsQueries.delete(DB_KEY);
317
+ settingsQueries.delete(DB_KEY_DATADIR);
288
318
  } catch (error) {
289
319
  debug.error('engine', 'Error stopping Open Code server:', error);
290
320
  }
@@ -292,6 +322,7 @@ export async function disposeOpenCodeClient(forRestart = false): Promise<void> {
292
322
  } else if (forRestart) {
293
323
  // No active handle but forRestart requested — ensure DB is clean
294
324
  settingsQueries.delete(DB_KEY);
325
+ settingsQueries.delete(DB_KEY_DATADIR);
295
326
  }
296
327
 
297
328
  clearClientState();
@@ -21,6 +21,7 @@ import type { EngineAccount } from '$backend/database/queries/engine-queries';
21
21
  import { getCleanSpawnEnv } from '$backend/utils/index.js';
22
22
  import { debug } from '$shared/utils/logger';
23
23
  import { parseQwenCredential, resolveQwenBaseUrl } from './credential';
24
+ import { getQwenRuntimeDir } from './session-fork';
24
25
 
25
26
  export interface QwenEnvResolution {
26
27
  env: Record<string, string>;
@@ -68,6 +69,12 @@ export function getEngineEnv(accountId?: number): QwenEnvResolution | null {
68
69
 
69
70
  env['OPENAI_API_KEY'] = credential.apiKey;
70
71
  env['OPENAI_BASE_URL'] = baseUrl;
72
+ // Isolate Qwen's runtime output (chats/sessions, history, logs, tmp) to
73
+ // {clopenDir}/engine/qwen/user/ instead of the shared ~/.qwen. Mirrors the path
74
+ // the fork helper reads from (see ./session-fork.ts). The CLI's global
75
+ // settings.json stays in ~/.qwen — there is no env override for it — but
76
+ // Clopen uses paste-token auth so that file is irrelevant here.
77
+ env['QWEN_RUNTIME_DIR'] = getQwenRuntimeDir();
71
78
  // Strip any inherited Qwen OAuth hints — if the host shell exports them
72
79
  // the bundled CLI prefers the OAuth path even when API-key env vars are
73
80
  // present, surfacing the "OAuth free tier discontinued" error.
@@ -34,9 +34,21 @@
34
34
  import fs from 'node:fs';
35
35
  import path from 'node:path';
36
36
  import os from 'node:os';
37
+ import { getEngineUserConfigDir } from '$backend/utils/paths';
37
38
  import { debug } from '$shared/utils/logger';
38
39
 
39
- const QWEN_PROJECTS_DIR = path.join(os.homedir(), '.qwen', 'projects');
40
+ /**
41
+ * Qwen's runtime output base, forwarded to the CLI via `QWEN_RUNTIME_DIR`
42
+ * (see ./environment.ts). The bundled CLI writes chats under
43
+ * `<runtimeBase>/projects/<sanitized-cwd>/chats/` (Storage.getProjectDir →
44
+ * getRuntimeBaseDir), so this helper must resolve to the SAME base the env
45
+ * var sets or the fork would land in a directory the CLI never reads.
46
+ */
47
+ export function getQwenRuntimeDir(): string {
48
+ return getEngineUserConfigDir('qwen');
49
+ }
50
+
51
+ const QWEN_PROJECTS_DIR = path.join(getQwenRuntimeDir(), 'projects');
40
52
 
41
53
  /**
42
54
  * Mirror of `sanitizeCwd` in @qwen-code/sdk's bundled CLI
@@ -94,16 +94,19 @@ getProvidersWithAccounts(engineType?) // join used by endpoint listing
94
94
  see `streamQuery` in `copilot/stream.ts` and §9.9 below.
95
95
 
96
96
  > **Pattern: auth-blob materialization for shared CLI dotfiles.**
97
- > Some CLIs (e.g. Codex's `~/.codex/auth.json`) read credentials from a
98
- > fixed location on disk that **cannot** be redirected per-process without
99
- > isolating the entire home dir. For those engines, `credential` stores
100
- > the **whole file content** as a JSON wrapper
97
+ > Some CLIs (e.g. Codex's `auth.json`) read credentials from a fixed
98
+ > filename inside their home dir. That home dir is isolated to
99
+ > `{clopenDir}/engine/codex/user/` (via `CODEX_HOME` — see §9.19), but it is a
100
+ > **single** dir shared by all of the engine's Clopen accounts, so the
101
+ > dotfile inside it still has to be swapped per account. For those engines,
102
+ > `credential` stores the **whole file content** as a JSON wrapper
101
103
  > (`{ kind: 'chatgpt', authJson: '...' }`), and the adapter / WS handler
102
104
  > writes that blob back to the shared dotfile on `accounts-switch`. After
103
105
  > each stream, snapshot the (possibly-refreshed-by-the-CLI) dotfile back
104
106
  > into `engine_accounts.credential` so token refreshes survive across
105
- > account switches. This keeps multi-account support working without
106
- > isolated `XYZ_HOME` directories — see §9.13 for the rationale.
107
+ > account switches. This keeps multi-account support working **without**
108
+ > per-account `XYZ_HOME` directories — see §9.13 for the rationale, and
109
+ > §9.19 for the Clopen-vs-global home-dir isolation.
107
110
 
108
111
  ### 3.4 The models.dev catalog (OpenCode-specific)
109
112
 
@@ -271,15 +271,19 @@ surface as.
271
271
  the filename, not a directory name:
272
272
 
273
273
  ```
274
- ~/.codex/sessions/<YYYY>/<MM>/<DD>/rollout-<TIMESTAMP>-<thread_id>.jsonl
274
+ <CODEX_HOME>/sessions/<YYYY>/<MM>/<DD>/rollout-<TIMESTAMP>-<thread_id>.jsonl
275
275
  ```
276
276
 
277
+ where `<CODEX_HOME>` is Clopen's isolated `{clopenDir}/engine/codex/user/` (§9.19),
278
+ **not** `~/.codex` — the helper reads it via `getCodexHomeDir()`, so it
279
+ tracks the isolated dir automatically.
280
+
277
281
  The fork helper walks the date-tree to find the source by
278
282
  `-<thread_id>.jsonl` suffix, copies it into TODAY's `YYYY/MM/DD` dir
279
283
  under a new `rollout-<now>-<forkId>.jsonl` filename, and replaces every
280
284
  occurrence of the source id (UUIDs don't collide with other content in
281
285
  the file). Earlier versions of `codex/session-fork.ts` mistakenly
282
- assumed a directory layout (`~/.codex/sessions/<thread_id>/`) — the
286
+ assumed a directory layout (`<CODEX_HOME>/sessions/<thread_id>/`) — the
283
287
  result was a permanently-broken fork because `sessionStateExists()`
284
288
  never matched. If you change the helper, watch for that regression.
285
289
 
@@ -289,9 +293,13 @@ project's cwd via the SDK's `sanitizeCwd()`
289
293
  (`cwd.replace(/[^a-zA-Z0-9]/g, '-')`, lowercased on win32):
290
294
 
291
295
  ```
292
- ~/.qwen/projects/<sanitized-cwd>/chats/<sessionId>.jsonl
296
+ <QWEN_RUNTIME_DIR>/projects/<sanitized-cwd>/chats/<sessionId>.jsonl
293
297
  ```
294
298
 
299
+ where `<QWEN_RUNTIME_DIR>` is Clopen's isolated `{clopenDir}/engine/qwen/user/`
300
+ (§9.19), **not** `~/.qwen` — both the env var and the fork helper
301
+ (`getQwenRuntimeDir()`) resolve to the same base, so they stay in sync.
302
+
295
303
  Every record line carries a `sessionId` field equal to the file's
296
304
  basename. The fork helper copies the file to
297
305
  `<chats>/<forkId>.jsonl` in the same project directory and replaces
@@ -444,28 +452,34 @@ What you must NOT do:
444
452
  - ❌ A local type alias when the SDK exports the type (Open Code,
445
453
  Copilot). Import `McpRemoteConfig` / `MCPHTTPServerConfig` directly.
446
454
 
447
- ### 9.13 Auth-blob swap into a shared CLI dotfile (vs. per-account isolated dirs)
455
+ ### 9.13 Auth-blob swap into a shared CLI dotfile (vs. **per-account** isolated dirs)
456
+
457
+ > **Scope:** this section is about multiple accounts *within* Clopen. The
458
+ > orthogonal question — keeping Clopen's whole footprint out of the user's
459
+ > global `~/.codex` / `~/.copilot` — is **§9.19**, and there the answer is
460
+ > the opposite: we DO override the home env var, but with **one dir per
461
+ > engine shared by all accounts**, not one per account.
448
462
 
449
463
  When a CLI hard-codes its credential location (Codex reads
450
- `~/.codex/auth.json`; Gemini CLI reads `~/.gemini/oauth_creds.json`;
451
- etc.), the naïve approach is to give each Clopen account its own
464
+ `<CODEX_HOME>/auth.json`; Gemini CLI reads `~/.gemini/oauth_creds.json`;
465
+ etc.), the naïve approach is to give **each Clopen account** its own
452
466
  isolated home directory and override the CLI's home env var
453
- (`CODEX_HOME`, `GEMINI_HOME`). **Don't.** That approach has bitten us:
467
+ (`CODEX_HOME=/foo/account-1/`, `/foo/account-2/`, …). **Don't.** A
468
+ *per-account* split has bitten us:
454
469
 
455
- - Session/thread state lives in the same dir tree (`~/.codex/sessions/`,
456
- `~/.codex/projects/`), so isolating the dir splits session memory,
457
- breaks fork-by-copy, and loses the user's `config.toml` overrides.
470
+ - Session/thread state lives in the same dir tree (`<CODEX_HOME>/sessions/`,
471
+ `<CODEX_HOME>/projects/`), so a per-account split fragments session
472
+ memory and breaks fork-by-copy across accounts.
458
473
  - Token refresh happens in-place in the dotfile — refreshes performed
459
- inside an isolated dir do not propagate back to the user's "real"
460
- home unless we add a watcher.
461
- - The CLI's other features (e.g. project trust, `.agents` allowlist)
462
- expect the dir to be the user's normal one.
474
+ under account A's dir don't reach account B.
463
475
 
464
- **Use the shared-location-with-DB-swap pattern instead:**
476
+ Instead, all Clopen accounts for an engine share the **single** isolated
477
+ home from §9.19, and multi-account is handled by swapping the one dotfile
478
+ inside it to/from the DB:
465
479
 
466
480
  | Step | Behavior |
467
481
  |---|---|
468
- | **Login** | Spawn the CLI's login command (`codex login`, etc.) which writes the user's normal dotfile. On success, **read the dotfile content** and persist it to `engine_accounts.credential` as a JSON wrapper, e.g. `{ kind: 'chatgpt', authJson: '<file content>' }`. |
482
+ | **Login** | Spawn the CLI's login command (`codex login`, etc.) — run with the isolated home env var set (e.g. `CODEX_HOME`) so it writes the dotfile inside `{clopenDir}/engine/{engine}/user/`, not `~`. On success, **read the dotfile content** and persist it to `engine_accounts.credential` as a JSON wrapper, e.g. `{ kind: 'chatgpt', authJson: '<file content>' }`. |
469
483
  | **Switch account** | `accounts-switch` handler reads the chosen account's `credential`, parses the wrapper, writes `authJson` **back to the shared dotfile** with an atomic replace (`write to .tmp` + `rename`). |
470
484
  | **Stream-start** | Adapter ensures the dotfile reflects the right blob (re-write if drift detected; cheap idempotent op). |
471
485
  | **Stream-end** | Read the dotfile back and snapshot it into the active account's `credential` so any token refresh the CLI performed during the turn survives across switches. |
@@ -773,3 +787,90 @@ What you must NOT do:
773
787
 
774
788
  ---
775
789
 
790
+ ### 9.19 Per-engine config-dir isolation (`{clopenDir}/engine/{engine}/user/`)
791
+
792
+ Every engine's CLI/SDK writes runtime state (credentials, session/rollout
793
+ files, logs, caches) to a home dir. Left at the default, that dir is the
794
+ user's **global** one — `~/.codex`, `~/.copilot`, `~/.config/opencode` +
795
+ `~/.local/share/opencode`, `~/.qwen` — so Clopen's activity gets mixed in
796
+ with the user's own standalone CLI usage. We isolate each engine to
797
+ `{clopenDir}/engine/{engine}/user/` (where `clopenDir` is `~/.clopen`, or
798
+ `~/.clopen-dev` in development) via that engine's home env var. The
799
+ `engine/` parent groups all AI-engine state in one place, separate from
800
+ Clopen's other data dirs (`{clopenDir}/snapshots/`, the DB, …). The helper
801
+ is `getEngineUserConfigDir(engine)` in `backend/utils/paths.ts` — one
802
+ source of truth; do not hand-join the path.
803
+
804
+ | Engine | Lever | Where set |
805
+ |---|---|---|
806
+ | Claude | `CLAUDE_CONFIG_DIR` | `claude/environment.ts` (`getClaudeUserConfigDir()` → helper) |
807
+ | Codex | `CODEX_HOME` | `codex/credential.ts` (`CODEX_HOME` const) **+** the SDK's `env` in `codex/stream.ts` **+** the `codex login` PTY env in `ws/engine/codex/accounts.ts` |
808
+ | Copilot | `baseDirectory` (SDK sets `COPILOT_HOME`) | `copilot/stream.ts` `new CopilotClient({ baseDirectory })` |
809
+ | Qwen | `QWEN_RUNTIME_DIR` | `qwen/environment.ts` **+** `getQwenRuntimeDir()` in `qwen/session-fork.ts` |
810
+ | OpenCode | `XDG_DATA_HOME` / `XDG_CONFIG_HOME` / `XDG_STATE_HOME` / `XDG_CACHE_HOME` | `opencode/server.ts` spawn env |
811
+
812
+ Sharp edges, each of which silently defeats isolation if missed:
813
+
814
+ - **Codex SDK drops `process.env` when you pass `env`.** `@openai/codex-sdk`
815
+ docs: *"When provided, the SDK will not inherit variables from
816
+ `process.env`."* So you must pass the **full** `getCleanSpawnEnv()` and
817
+ layer `CODEX_HOME` on top — passing `{ CODEX_HOME }` alone strips `PATH`,
818
+ `HOME`, etc. and the subprocess fails to launch.
819
+ - **Set `CODEX_HOME` in every spawn site, not just the SDK.** `codex login`
820
+ runs in a separate PTY (`ws/engine/codex/accounts.ts`); without
821
+ `CODEX_HOME` there, the OAuth `auth.json` lands in `~/.codex` while the
822
+ stream reads the isolated dir → "logged in but not authenticated".
823
+ - **Keep the fork helper's base in lockstep with the env var.** Codex's
824
+ `session-fork.ts` reads `getCodexHomeDir()` and Qwen's reads
825
+ `getQwenRuntimeDir()` — both resolve to the same isolated base the env
826
+ var sets. If they drift, `sessionStateExists()` returns false and
827
+ multi-branch checkpoints break (see §9.10).
828
+ - **Qwen isolation is partial — and that's accepted.** `QWEN_RUNTIME_DIR`
829
+ relocates runtime output (chats/sessions, history, logs, tmp) but the
830
+ CLI's global `settings.json` / OAuth creds still resolve to `~/.qwen`
831
+ (`Storage.getGlobalQwenDir()`, no env override). Harmless here: Clopen
832
+ uses paste-token auth, so those files are never written by our path.
833
+ - **OpenCode honors all four XDG bases and appends `/opencode` to each.**
834
+ Setting `XDG_{DATA,CONFIG,STATE,CACHE}_HOME` to the isolated dir lands its
835
+ state at `{clopenDir}/engine/opencode/user/opencode/…` (the extra
836
+ `opencode/` segment is the XDG app-name namespace — unavoidable, and there
837
+ is no single "data dir" env that skips it). Credentials + MCP config are
838
+ injected via `OPENCODE_CONFIG_CONTENT`, so the isolated data dir starts
839
+ empty and needs no auth file carried over.
840
+ - **OpenCode reuses a persisted server — guard reuse on the data dir.**
841
+ `opencode/server.ts` caches the live server's URL in the `settings` table
842
+ (`opencode.server.url`) and reuses it across reconnects/restarts. A reused
843
+ server keeps the env (and thus the data dir) it was **spawned** with, so a
844
+ server left over from before isolation — or from a different isolation path
845
+ — would silently keep writing to the old location even though the env is
846
+ now correct. The fix: persist the spawned data dir as
847
+ `opencode.server.datadir` and **refuse to reuse** when it ≠ the current
848
+ `getEngineUserConfigDir('opencode')`; respawn instead. This was the actual
849
+ bug behind "every engine isolated except OpenCode" — the binary respected
850
+ XDG fine; a stale reused server was the culprit. Symptom to watch for: data
851
+ still landing in `~/.local/share/opencode` after the env looks right.
852
+
853
+ **This is orthogonal to multi-account (§9.13).** All of an engine's Clopen
854
+ accounts share this **one** isolated dir; multiple accounts inside it are
855
+ still the auth-blob swap, **not** a dir per account.
856
+
857
+ **Two different "migration" questions — keep them apart:**
858
+
859
+ - **From the user's *global* dir (`~/.codex`, …) → no migration.** Forward-only
860
+ by design: conversations created before isolation keep their session/rollout
861
+ files in the global dir and lose engine-side resume continuity after the
862
+ switch (the message history in Clopen's own DB is unaffected and still
863
+ renders). Credentials are safe — they live in `engine_accounts.credential`
864
+ and re-materialize into the isolated dir on next use. A clean-cut switch was
865
+ chosen over copying because the shared-SQLite engines (Copilot's
866
+ `session-store.db`, OpenCode's monolithic `opencode.db`) interleave Clopen
867
+ and standalone sessions in one file, with no safe per-session extraction.
868
+ - **Between Clopen's *own* isolated layouts → yes, migrated.** An earlier build
869
+ used `{clopenDir}/{engine}/user/` (no `engine/` parent). Migration
870
+ `043_relocate_engine_config_dirs.ts` moves any such dir to the current
871
+ `{clopenDir}/engine/{engine}/user/`. This is always safe — it only ever
872
+ touches a path Clopen created, never the user's global home — and idempotent
873
+ (skips when the new dir already exists; non-fatal on error). It also clears
874
+ the persisted `opencode.server.{url,datadir}` so a server cached against the
875
+ pre-move dir is re-spawned into the relocated one.
876
+
@@ -204,7 +204,16 @@ export class GitService {
204
204
 
205
205
  async getDiffCommit(cwd: string, commitHash: string): Promise<GitFileDiff[]> {
206
206
  assertSafeGitRevish(commitHash, 'commit hash');
207
- const result = await execGit(['diff', `${commitHash}^`, commitHash], cwd);
207
+ // Root commits have no parent, so `<hash>^` can't resolve and `git diff`
208
+ // fails silently (empty stdout) — which previously surfaced as "No files
209
+ // changed". Detect the parentless case and diff against the empty tree via
210
+ // `diff-tree --root` so the initial commit's files show up as additions.
211
+ // Commits with a parent (including merges) keep the original behaviour.
212
+ const hasParent =
213
+ (await execGit(['rev-parse', '--verify', '--quiet', `${commitHash}^`], cwd)).exitCode === 0;
214
+ const result = hasParent
215
+ ? await execGit(['diff', `${commitHash}^`, commitHash], cwd)
216
+ : await execGit(['diff-tree', '-p', '--root', '--no-commit-id', commitHash], cwd);
208
217
  return parseDiff(result.stdout);
209
218
  }
210
219