Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat(dev): keep worktree dev state isolated on T3 Code dev servers (#4555)
Theo Brownea17cbc3b4022
diff --git a/.agents/skills/test-t3-app/SKILL.md b/.agents/skills/test-t3-app/SKILL.mdindex b59ed9ddf..f26270cd0 100644--- a/.agents/skills/test-t3-app/SKILL.md+++ b/.agents/skills/test-t3-app/SKILL.md@@ -13,11 +13,13 @@ Use this skill for the web client. For iOS Simulator, Android Emulator, or physi2. Choose a base directory that belongs only to the current worktree or test:- Use the repository's ignored `.t3` directory for reusable worktree-local state.- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.-3. Start the full web stack with `vp run dev --home-dir <base-dir>`.+3. Start the full web stack with `vp run dev`. In a linked worktree it defaults to that worktree's gitignored `.t3`; pass `--home-dir <base-dir>` only when the test needs a different isolated directory.4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.+The worktree-local default deliberately outranks an ambient `T3CODE_HOME`; do not pass the shared home through to a worktree dev server.+The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.## Preserve the environment while iterating@@ -55,7 +57,7 @@ T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.-Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.+Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.## Inspect or seed SQLite statediff --git a/AGENTS.md b/AGENTS.mdindex ef69591a3..7b67ebb7b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -13,6 +13,10 @@- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.+## Dev Servers++- In a linked git worktree, dev state defaults to that worktree's gitignored `.t3`. This deliberately outranks an ambient `T3CODE_HOME`, which could otherwise select the installed app's live `~/.t3/userdata` database. An explicit `--home-dir` still wins.+## Package Roles- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.diff --git a/docs/reference/scripts.md b/docs/reference/scripts.mdindex 746aa66d5..b985c9c9e 100644--- a/docs/reference/scripts.md+++ b/docs/reference/scripts.md@@ -3,7 +3,8 @@- `vp run dev` — Starts contracts, server, and web in watch mode.- `vp run dev:server` — Starts just the WebSocket server. The server process runs on Bun (`@effect/platform-bun` + `BunPtyAdapter`), but task running uses `vp run`.- `vp run dev:web` — Starts just the Vite dev server for the web app.-- Dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.+- Dev commands run from a linked **git worktree** default to that worktree's gitignored `.t3`, even when `T3CODE_HOME` is set, storing state in `<worktree>/.t3/userdata`. Pass `--home-dir <path>` to choose another isolated directory explicitly. Submodules are not worktrees and keep the normal precedence.+- From the **main checkout**, dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.- Web dev commands do not auto-open a browser. Open the one-time pairing URL printed by the server so the first browser navigation is authenticated. Set `T3CODE_NO_BROWSER=0` only when interactive auto-open is intentional.- Pass dev-runner flags directly after the root task name, for example:`vp run dev --home-dir /tmp/t3code-dev`diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 7d0cc5eb8..b83ecc536 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -194,6 +194,10 @@"./httpReadiness": {"types": "./src/httpReadiness.ts","import": "./src/httpReadiness.ts"+ },+ "./devHome": {+ "types": "./src/devHome.ts",+ "import": "./src/devHome.ts"}},"scripts": {diff --git a/packages/shared/src/devHome.test.ts b/packages/shared/src/devHome.test.tsnew file mode 100644index 000000000..812c34e3c--- /dev/null+++ b/packages/shared/src/devHome.test.ts@@ -0,0 +1,106 @@+// @effect-diagnostics nodeBuiltinImport:off - builds real worktree layouts on disk.+import * as NodeServices from "@effect/platform-node/NodeServices";+import { assert, describe, it } from "@effect/vitest";+import * as NodeFS from "node:fs";+import * as NodeOS from "node:os";+import * as NodePath from "node:path";+import * as Effect from "effect/Effect";++import { resolveGitWorktreePath, resolveWorktreeT3Home } from "./devHome.ts";++const makeRepo = (+ kind:+ | "worktree"+ | "checkout"+ | "bare"+ | "submodule"+ | "unreadable-git-file"+ | "bare-repo-worktree"+ | "custom-common-dir-worktree",+) =>+ Effect.acquireRelease(+ Effect.sync(() => {+ const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-devhome-"));+ if (kind === "worktree") {+ NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /elsewhere/.git/worktrees/x\n");+ } else if (kind === "bare-repo-worktree") {+ // `git worktree add` from a bare repo: the common dir is `<name>.git`.+ NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /srv/myrepo.git/worktrees/x\n");+ } else if (kind === "custom-common-dir-worktree") {+ // $GIT_COMMON_DIR need not be named `.git` at all.+ NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /srv/store/worktrees/x\n");+ } else if (kind === "submodule") {+ NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: ../.git/modules/sub\n");+ } else if (kind === "unreadable-git-file") {+ NodeFS.writeFileSync(NodePath.join(root, ".git"), "not a gitdir pointer\n");+ } else if (kind === "checkout") {+ NodeFS.mkdirSync(NodePath.join(root, ".git"));+ }+ const nested = NodePath.join(root, "apps", "web", "src");+ NodeFS.mkdirSync(nested, { recursive: true });+ return { root, nested };+ }),+ ({ root }) => Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true })),+ );++describe("resolveGitWorktreePath", () => {+ it.effect("finds a worktree root from a nested directory", () =>+ Effect.gen(function* () {+ const { root, nested } = yield* makeRepo("worktree");+ assert.equal(yield* resolveGitWorktreePath(nested), NodePath.resolve(root));+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ it.effect("reports a main checkout as not a linked worktree", () =>+ Effect.gen(function* () {+ const { nested } = yield* makeRepo("checkout");+ assert.equal(yield* resolveGitWorktreePath(nested), undefined);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ it.effect("reports a directory outside a repository", () =>+ Effect.gen(function* () {+ const { nested } = yield* makeRepo("bare");+ assert.equal(yield* resolveGitWorktreePath(nested), undefined);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ it.effect("reports a submodule as not a linked worktree", () =>+ Effect.gen(function* () {+ const { nested } = yield* makeRepo("submodule");+ assert.equal(yield* resolveGitWorktreePath(nested), undefined);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ it.effect("reports a .git file without a usable gitdir pointer", () =>+ Effect.gen(function* () {+ const { nested } = yield* makeRepo("unreadable-git-file");+ assert.equal(yield* resolveGitWorktreePath(nested), undefined);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ it.effect("finds a worktree of a bare repository", () =>+ Effect.gen(function* () {+ const { root, nested } = yield* makeRepo("bare-repo-worktree");+ assert.equal(yield* resolveGitWorktreePath(nested), NodePath.resolve(root));+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );++ it.effect("finds a worktree whose common dir is not named .git", () =>+ Effect.gen(function* () {+ const { root, nested } = yield* makeRepo("custom-common-dir-worktree");+ assert.equal(yield* resolveGitWorktreePath(nested), NodePath.resolve(root));+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );+});++describe("resolveWorktreeT3Home", () => {+ it.effect("answers with .t3 before the dev runner creates it", () =>+ Effect.gen(function* () {+ const { root, nested } = yield* makeRepo("worktree");+ const home = yield* resolveWorktreeT3Home(nested);+ assert.equal(home, NodePath.join(NodePath.resolve(root), ".t3"));+ assert.isFalse(NodeFS.existsSync(home ?? ""));+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );+});diff --git a/packages/shared/src/devHome.ts b/packages/shared/src/devHome.tsnew file mode 100644index 000000000..1fde5409f--- /dev/null+++ b/packages/shared/src/devHome.ts@@ -0,0 +1,103 @@+/**+ * Where development state lives, and how to keep it away from the shared+ * `~/.t3` that a user's installed T3 Code runs against.+ *+ * A linked git worktree gets its own (gitignored) `.t3`: feature work in a+ * throwaway branch must not share a database with the real app, and an ambient+ * `T3CODE_HOME` counts as an explicit base dir — flipping the state directory+ * from `<base>/dev` to `<base>/userdata`, the live production database.+ */++import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Option from "effect/Option";+import * as Path from "effect/Path";++/**+ * A `.git` file points at the real git directory. A linked worktree's lives at+ * `<common-dir>/worktrees/<name>`; a submodule's at+ * `<super-git-dir>/modules/<name>`. Both are files, so the pointer — not the+ * file-vs-directory distinction alone — is what identifies a worktree.+ *+ * The common dir is not necessarily named `.git`: a worktree of a bare repo+ * points at `<repo>.git/worktrees/<name>`, and `$GIT_COMMON_DIR` can be+ * anything. So match on the `worktrees/<name>` tail, which git always uses,+ * rather than on the name of the directory containing it.+ */+const pointsAtLinkedWorktree = (gitFileContents: string, path: Path.Path): boolean => {+ const gitdir = gitFileContents+ .split(/\r?\n/)+ .map((line) => line.trim())+ .find((line) => line.startsWith("gitdir:"))+ ?.slice("gitdir:".length)+ .trim();+ if (gitdir === undefined || gitdir.length === 0) {+ return false;+ }+ // Compare as path segments so a directory merely named `…worktrees…` cannot+ // match as a substring. Trailing separators normalize away first.+ const segments = path+ .normalize(gitdir.replaceAll("\\", "/"))+ .split(/[/\\]/)+ .filter((segment) => segment.length > 0);+ // `<common-dir>/worktrees/<name>`: `worktrees` is the penultimate segment,+ // and something must precede it. This excludes `<git-dir>/modules/<name>`.+ return segments.length >= 3 && segments.at(-2) === "worktrees";+};++/**+ * The path of the linked git worktree containing `cwd`, or undefined when+ * `cwd` is not inside one. Git marks a linked worktree by making `.git` a file+ * whose `gitdir:` points into the repository's `.git/worktrees`.+ *+ * Walks up to the repository root, so running from a subdirectory resolves the+ * same worktree as running from the top.+ */+export const resolveGitWorktreePath = (+ cwd: string,+): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;++ let directory = path.resolve(cwd);+ for (;;) {+ const gitPath = path.join(directory, ".git");+ const info = yield* fileSystem.stat(gitPath).pipe(Effect.option);+ if (Option.isSome(info)) {+ // A directory means the main checkout. Stop either way: nesting one+ // repository inside another does not make the outer one this root.+ if (info.value.type !== "File") {+ return undefined;+ }+ // A submodule also has a `.git` file, but it is not a worktree of this+ // repository and gets no worktree-local home.+ const contents = yield* fileSystem+ .readFileString(gitPath)+ .pipe(Effect.orElseSucceed(() => ""));+ return pointsAtLinkedWorktree(contents, path) ? directory : undefined;+ }+ const parent = path.dirname(directory);+ if (parent === directory) {+ return undefined;+ }+ directory = parent;+ }+ });++/**+ * The worktree-local data directory for `cwd`, or undefined outside a linked+ * worktree. Deliberately does not require the directory to exist yet: falling+ * back because it is missing would send callers at the shared home.+ */+export const resolveWorktreeT3Home = (+ cwd: string,+): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>+ Effect.gen(function* () {+ const worktreePath = yield* resolveGitWorktreePath(cwd);+ if (worktreePath === undefined) {+ return undefined;+ }+ const path = yield* Path.Path;+ return path.join(worktreePath, ".t3");+ });diff --git a/packages/shared/src/hostProcess.ts b/packages/shared/src/hostProcess.tsindex baff2c5ff..4885072a0 100644--- a/packages/shared/src/hostProcess.ts+++ b/packages/shared/src/hostProcess.ts@@ -30,6 +30,13 @@ export const HostProcessEnvironment = Context.Reference<NodeJS.ProcessEnv>(},);+export const HostProcessWorkingDirectory = Context.Reference<string>(+ "@t3tools/shared/hostProcess/HostProcessWorkingDirectory",+ {+ defaultValue: () => process.cwd(),+ },+);+export const HostProcessExecutablePath = Context.Reference<string>("@t3tools/shared/hostProcess/HostProcessExecutablePath",{diff --git a/scripts/dev-runner.test.ts b/scripts/dev-runner.test.tsindex 3b79db49f..ad95a4983 100644--- a/scripts/dev-runner.test.ts+++ b/scripts/dev-runner.test.ts@@ -1,6 +1,14 @@+// @effect-diagnostics nodeBuiltinImport:off - builds real worktree layouts on disk.import * as NodeServices from "@effect/platform-node/NodeServices";+import * as NodeFS from "node:fs";+import * as NodeOS from "node:os";+import * as NodePath from "node:path";import * as NetService from "@t3tools/shared/Net";-import { HostProcessPlatform } from "@t3tools/shared/hostProcess";+import {+ HostProcessEnvironment,+ HostProcessPlatform,+ HostProcessWorkingDirectory,+} from "@t3tools/shared/hostProcess";import { assert, describe, it } from "@effect/vitest";import * as ConfigProvider from "effect/ConfigProvider";import * as Effect from "effect/Effect";@@ -629,5 +637,113 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {assert.notInclude(error.message, "secret-token-value");});});++ describe("t3 home precedence", () => {+ const makeWorktree = Effect.acquireRelease(+ Effect.sync(() => {+ const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-devrunner-"));+ NodeFS.writeFileSync(+ NodePath.join(root, ".git"),+ "gitdir: /elsewhere/.git/worktrees/x\n",+ );+ return root;+ }),+ (root) => Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true })),+ );++ const spawnedHome = (input: {+ readonly t3Home: string | undefined;+ readonly cwd: string;+ readonly ambientHome: string | undefined;+ }) =>+ Effect.gen(function* () {+ let captured: Record<string, string | undefined> | undefined;+ const spawnerLayer = Layer.succeed(+ ChildProcessSpawner.ChildProcessSpawner,+ ChildProcessSpawner.make((command) => {+ captured = (+ command as {+ readonly options?: { readonly env?: Record<string, string | undefined> };+ }+ ).options?.env;+ return Effect.succeed(mockProcess(0));+ }),+ );++ yield* runDevRunnerWithInput({ ...devServerInput, t3Home: input.t3Home }).pipe(+ Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),+ Effect.provideService(HostProcessPlatform, "linux"),+ Effect.provideService(HostProcessWorkingDirectory, input.cwd),+ Effect.provideService(+ HostProcessEnvironment,+ input.ambientHome === undefined ? {} : { T3CODE_HOME: input.ambientHome },+ ),+ );++ return captured?.T3CODE_HOME;+ });++ it.effect("prefers an explicit --home-dir over the worktree default", () =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ const root = yield* makeWorktree;+ const home = yield* spawnedHome({+ t3Home: "/tmp/explicit-home",+ cwd: root,+ ambientHome: "/home/user/.t3",+ });+ assert.equal(home, path.resolve("/tmp/explicit-home"));+ }).pipe(Effect.scoped),+ );++ it.effect("treats a blank --home-dir as unset rather than as a selection", () =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ const root = yield* makeWorktree;+ const home = yield* spawnedHome({+ t3Home: " ",+ cwd: root,+ ambientHome: "/home/user/.t3",+ });+ assert.equal(home, path.join(path.resolve(root), ".t3"));+ }).pipe(Effect.scoped),+ );++ it.effect("prefers the worktree .t3 over an ambient T3CODE_HOME", () =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ const root = yield* makeWorktree;+ const home = yield* spawnedHome({+ t3Home: undefined,+ cwd: root,+ ambientHome: "/home/user/.t3",+ });+ assert.equal(home, path.join(path.resolve(root), ".t3"));+ }).pipe(Effect.scoped),+ );++ it.effect("falls back to an ambient T3CODE_HOME outside a worktree", () =>+ Effect.gen(function* () {+ const path = yield* Path.Path;+ const home = yield* spawnedHome({+ t3Home: undefined,+ cwd: NodeOS.tmpdir(),+ ambientHome: "/home/user/.t3",+ });+ assert.equal(home, path.resolve("/home/user/.t3"));+ }),+ );++ it.effect("leaves the home implicit with no worktree and no ambient value", () =>+ Effect.gen(function* () {+ const home = yield* spawnedHome({+ t3Home: undefined,+ cwd: NodeOS.tmpdir(),+ ambientHome: undefined,+ });+ assert.equal(home, undefined);+ }),+ );+ });});});diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.tsindex 193823230..2875cbe88 100644--- a/scripts/dev-runner.ts+++ b/scripts/dev-runner.ts@@ -5,7 +5,8 @@ import * as NodeOS from "node:os";import * as NodeRuntime from "@effect/platform-node/NodeRuntime";import * as NodeServices from "@effect/platform-node/NodeServices";import * as NetService from "@t3tools/shared/Net";-import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";+import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";+import { HostProcessEnvironment, HostProcessWorkingDirectory } from "@t3tools/shared/hostProcess";import { resolveSpawnCommand } from "@t3tools/shared/shell";import * as Config from "effect/Config";import * as Effect from "effect/Effect";@@ -245,7 +246,9 @@ export function createDevRunnerEnv({return Effect.gen(function* () {const serverPort = port ?? BASE_SERVER_PORT + serverOffset;const webPort = BASE_WEB_PORT + webOffset;- const configuredBaseDir = t3Home?.trim() || baseEnv.T3CODE_HOME?.trim() || undefined;+ // Precedence is resolved by the caller. An unset t3Home here genuinely+ // means "use the default" rather than inheriting an ambient value.+ const configuredBaseDir = t3Home?.trim() || undefined;const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);const isDesktopMode = mode === "dev:desktop";@@ -505,12 +508,23 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {});const hostEnvironment = yield* HostProcessEnvironment;+ // A worktree defaults to its own gitignored `.t3`. This deliberately+ // outranks ambient T3CODE_HOME, which otherwise selects the installed+ // app's live userdata database. An explicit --home-dir still wins.+ const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcessWorkingDirectory);+ // Trim before choosing: `--home-dir ""` is not a selection, and treating it+ // as one would skip the worktree default and land on the shared home —+ // exactly the outcome this precedence exists to prevent.+ const resolvedT3Home =+ (input.t3Home?.trim() || undefined) ??+ worktreeHome ??+ (hostEnvironment.T3CODE_HOME?.trim() || undefined);const env = yield* createDevRunnerEnv({mode: input.mode,baseEnv: hostEnvironment,serverOffset,webOffset,- t3Home: input.t3Home,+ t3Home: resolvedT3Home,browser: input.browser,autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,logWebSocketEvents: input.logWebSocketEvents,@@ -592,9 +606,10 @@ const devRunnerCli = Command.make("dev-runner", {),t3Home: Flag.string("home-dir").pipe(Flag.withDescription(- "Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).",+ "Explicit T3 Code data directory; runtime state is stored under userdata. Inside a git worktree this defaults to that worktree's own .t3.",),- Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOME")),+ Flag.optional,+ Flag.map(Option.getOrUndefined),),browser: Flag.boolean("browser").pipe(Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),