From 3810b17def53285e6724f7505333cedc8c475cfb Mon Sep 17 00:00:00 2001 From: Roy Sun Date: Wed, 25 Nov 2026 07:18:04 +0900 Subject: [PATCH] fix(server): fall back to t3.json setup script and default project root in setup-worktree --- AGENTS.md | 2 +- .../src/orchestration-v2/runtimeLayer.ts | 1 + .../project/ProjectSetupScriptRunner.test.ts | 352 +++++++++++++++++- .../src/project/ProjectSetupScriptRunner.ts | 57 ++- apps/server/src/terminal/Manager.test.ts | 7 + docs/user/project-settings.md | 8 +- scripts/setup-worktree.test.ts | 210 +++++++++++ scripts/setup-worktree.ts | 62 ++- 8 files changed, 676 insertions(+), 23 deletions(-) create mode 100644 scripts/setup-worktree.test.ts diff --git a/AGENTS.md b/AGENTS.md index 8d6fc41604fc..3bda3624a1c7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,7 +69,7 @@ The most common defect in this repo is a change that works on the path you teste See [00_development.md](docs/operations/00_development.md) for setup, ports, seeding (`vp run migrate-dev-db`), and [reusable dev auth](docs/operations/00_development.md#reusable-dev-credential). Agent-specific rules: -- **Worktree setup:** Wait while `.t3/setup-running` names a live PID; do not run `bun install` concurrently. If no `.t3/setup-*` marker exists, run `bun install` yourself. +- **Worktree setup:** Wait while `.t3/setup-running` names a live PID; do not run `bun install` concurrently. If no `.t3/setup-*` marker exists, run `bun scripts/setup-worktree.ts` (or `bun install`) yourself. - **Process lifecycle:** Start dev servers, Metro, and builds from your own shell so they exit with your session—never detach with `systemd-run`, `nohup`, `setsid`, or `tmux` unless asked. Stop background tasks with your harness's own stop (`vp` does not forward SIGTERM to child Vite/server processes). - **Sharing (`vp run dev --share`):** Wait for `pairingUrl:` and hand the full URL to the user. Never wire `tailscale serve` by hand, open the URL yourself, or consume the user's one-time pairing link. Mint another with `node apps/server/src/bin.ts pair` if needed. - **Test data:** Always copy in (never symlink) and refresh `statev2.sqlite`, not `state.sqlite`. Bring `secrets` / `settings.json` only if the flow under test needs them. diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index ac93f410262f..6f445ad4285a 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -304,6 +304,7 @@ export const layerProjectSetupScriptRunner = ProjectSetupScriptRunner.layer.pipe Layer.provide(layerProjectService), // Whether a thread came from a linked environment, which skips setup. Layer.provide(ProjectionStore.layer), + Layer.provide(T3ProjectFileLoader.layer), ); const layerManagedProjectFoldersProvided = ManagedProjectFolders.layer.pipe( Layer.provide(layerProjectService), diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index 0c4c920d4372..9b4d0588552a 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -2,7 +2,11 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, expect, it } from "@effect/vitest"; import { + DEFAULT_SERVER_SETTINGS, ProjectId, + type ProjectScript, + type ServerSettings as ServerSettingsType, + type T3ProjectFile, TerminalNotRunningError, type TerminalEvent, type TerminalOpenInput, @@ -12,7 +16,10 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; @@ -23,6 +30,7 @@ import * as TerminalManager from "../terminal/Manager.ts"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; import * as ProjectService from "./ProjectService.ts"; import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts"; +import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts"; const threadId = "thread-1"; const terminalId = "setup-setup"; @@ -48,10 +56,22 @@ const makeHarness = Effect.fn(function* (options: { readonly opening?: Deferred.Deferred; readonly previousSession?: TerminalSessionSnapshot; readonly shell?: string | null; + readonly scripts?: ReadonlyArray; + readonly serverSettings?: Parameters[0]; + readonly rawServerSettings?: ServerSettingsType; + readonly projectFile?: T3ProjectFile | null; + readonly trigger?: "setup" | "settle"; + readonly runtimeMode?: "full-access" | "auto" | "auto-accept-edits" | "approval-required" | null; + readonly linkOrigin?: { + readonly linkId: string; + readonly label: string; + readonly access?: "full-access" | "restricted"; + }; }) { const listeners = new Set<(event: TerminalEvent) => Effect.Effect>(); const opens: TerminalOpenInput[] = []; const openedSessions: TerminalSessionSnapshot[] = []; + const loadedProjectFileRoots: string[] = []; let session = options.previousSession; const writes = yield* Queue.unbounded(); const outputLines = yield* Queue.unbounded(); @@ -97,10 +117,35 @@ const makeHarness = Effect.fn(function* (options: { Layer.mergeAll( terminals, Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(T3ProjectFileLoader.T3ProjectFileLoader)({ + load: (workspaceRoot) => + Effect.sync(() => { + loadedProjectFileRoots.push(workspaceRoot); + return Option.fromNullishOr(options.projectFile); + }), + }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ - getThreadShell: () => Effect.succeed(null), + getThreadShell: () => + Effect.succeed( + options.linkOrigin === undefined && options.runtimeMode === undefined + ? null + : options.runtimeMode === null + ? null + : ({ + ...(options.runtimeMode === undefined + ? {} + : { runtimeMode: options.runtimeMode }), + ...(options.linkOrigin === undefined + ? {} + : { linkOrigin: options.linkOrigin }), + } as never), + ), }), - ServerSettings.layerTest(), + options.rawServerSettings === undefined + ? ServerSettings.layerTest(options.serverSettings) + : Layer.mock(ServerSettings.ServerSettingsService)({ + getSettings: Effect.succeed(options.rawServerSettings), + }), NodeCrypto.layer, ), ), @@ -108,11 +153,12 @@ const makeHarness = Effect.fn(function* (options: { const start = runner.runForThread({ threadId, worktreePath: "/repo/.t3/worktrees/feature", + ...(options.trigger === undefined ? {} : { trigger: options.trigger }), observeCompletion: { onOutputLine: (line) => Queue.offer(outputLines, line) }, project: { id: ProjectId.make("project-1"), workspaceRoot: "/repo", - scripts: [ + scripts: options.scripts ?? [ { id: "setup", name: "Setup", @@ -125,7 +171,16 @@ const makeHarness = Effect.fn(function* (options: { }); const emit = (terminalEvent: TerminalEvent) => Effect.forEach([...listeners], (listener) => listener(terminalEvent), { discard: true }); - return { start, listeners, writes, outputLines, emit, openedSessions, opens }; + return { + start, + listeners, + writes, + outputLines, + emit, + openedSessions, + opens, + loadedProjectFileRoots, + }; }); const setup = Effect.fn(function* ( @@ -311,6 +366,295 @@ describe("ProjectSetupScriptRunner", () => { expect(listeners.size).toBe(0); }), ); + + it.effect( + "falls back to the project checkout's t3.json setup script for full-access threads when none is imported", + () => + Effect.gen(function* () { + const { start, opens, loadedProjectFileRoots } = yield* makeHarness({ + scripts: [], + runtimeMode: "full-access", + serverSettings: { projectSettingsFolded: true }, + projectFile: { + scripts: [ + { name: "Dev", command: "vp run dev", icon: "play" }, + { + name: "Setup Worktree", + command: "bun scripts/setup-worktree.ts", + icon: "configure", + runOnWorktreeCreate: true, + async: false, + }, + ], + }, + }); + const result = yield* start; + expect(loadedProjectFileRoots).toEqual(["/repo"]); + expect(result).toMatchObject({ + status: "started", + scriptId: "setup-worktree", + scriptName: "Setup Worktree", + scriptCommand: "bun scripts/setup-worktree.ts", + terminalId: "setup-setup-worktree", + async: false, + }); + expect(opens[0]?.env).toMatchObject({ + T3CODE_PROJECT_ROOT: "/repo", + T3CODE_WORKTREE_PATH: "/repo/.t3/worktrees/feature", + }); + }), + ); + + it.effect("falls back to t3.json when a legacy project script override was reset to null", () => + Effect.gen(function* () { + const { start, loadedProjectFileRoots } = yield* makeHarness({ + runtimeMode: "full-access", + scripts: [ + { + id: "legacy-dev", + name: "Legacy Dev", + command: "vp run dev", + icon: "play", + runOnWorktreeCreate: false, + }, + ], + rawServerSettings: { + ...DEFAULT_SERVER_SETTINGS, + projectSettingsFolded: false, + projectScriptOverrides: { + [ProjectId.make("project-1")]: null, + }, + }, + projectFile: { + scripts: [ + { + name: "Setup Worktree", + command: "bun scripts/setup-worktree.ts", + runOnWorktreeCreate: true, + }, + ], + }, + }); + const result = yield* start; + expect(loadedProjectFileRoots).toEqual(["/repo"]); + expect(result).toMatchObject({ + status: "started", + scriptId: "setup-worktree", + scriptCommand: "bun scripts/setup-worktree.ts", + }); + }), + ); + + it.effect("skips unimported t3.json setup scripts for non-full-access or missing threads", () => + Effect.gen(function* () { + const projectFile: T3ProjectFile = { + scripts: [ + { + name: "Setup Worktree", + command: "bun scripts/setup-worktree.ts", + runOnWorktreeCreate: true, + }, + ], + }; + for (const runtimeMode of ["approval-required", "auto-accept-edits", "auto", null] as const) { + const { start, opens, loadedProjectFileRoots } = yield* makeHarness({ + scripts: [], + runtimeMode, + serverSettings: { projectSettingsFolded: true }, + projectFile, + }); + expect(yield* start).toEqual({ status: "no-script" }); + expect(loadedProjectFileRoots).toEqual([]); + expect(opens).toEqual([]); + } + }), + ); + + it.effect( + "respects an explicit empty project script override instead of falling back to t3.json", + () => + Effect.gen(function* () { + const { start, opens, loadedProjectFileRoots } = yield* makeHarness({ + scripts: [], + runtimeMode: "full-access", + serverSettings: { + projectSettingsFolded: true, + projectSettingsOverrides: { + [ProjectId.make("project-1")]: { defaultProjectScripts: [] }, + }, + }, + projectFile: { + scripts: [ + { + name: "Setup Worktree", + command: "bun scripts/setup-worktree.ts", + runOnWorktreeCreate: true, + }, + ], + }, + }); + const result = yield* start; + expect(result).toEqual({ status: "no-script" }); + expect(loadedProjectFileRoots).toEqual([]); + expect(opens).toEqual([]); + }), + ); + + it.effect("prefers a configured environment setup script over t3.json", () => + Effect.gen(function* () { + const { start, loadedProjectFileRoots } = yield* makeHarness({ + scripts: [], + runtimeMode: "full-access", + serverSettings: { + projectSettingsFolded: true, + defaultProjectScripts: [ + { + id: "env-setup", + name: "Env Setup", + command: "echo env-setup", + icon: "configure", + runOnWorktreeCreate: true, + }, + ], + }, + projectFile: { + scripts: [ + { + name: "Setup Worktree", + command: "bun scripts/setup-worktree.ts", + runOnWorktreeCreate: true, + }, + ], + }, + }); + const result = yield* start; + expect(result).toMatchObject({ + status: "started", + scriptId: "env-setup", + scriptCommand: "echo env-setup", + }); + expect(loadedProjectFileRoots).toEqual([]); + }), + ); + + it.effect("does not fall back to t3.json for settle triggers or fenced links", () => + Effect.gen(function* () { + const projectFile: T3ProjectFile = { + scripts: [ + { + name: "Setup Worktree", + command: "bun scripts/setup-worktree.ts", + runOnWorktreeCreate: true, + runOnSettle: true, + }, + ], + }; + const settleHarness = yield* makeHarness({ + scripts: [], + runtimeMode: "full-access", + serverSettings: { projectSettingsFolded: true }, + projectFile, + trigger: "settle", + }); + expect(yield* settleHarness.start).toEqual({ status: "no-script" }); + expect(settleHarness.loadedProjectFileRoots).toEqual([]); + + const fencedHarness = yield* makeHarness({ + scripts: [], + runtimeMode: "full-access", + serverSettings: { projectSettingsFolded: true }, + projectFile, + linkOrigin: { linkId: "link-1", label: "Peer", access: "restricted" }, + }); + expect(yield* fencedHarness.start).toEqual({ status: "skipped-for-link" }); + expect(fencedHarness.loadedProjectFileRoots).toEqual([]); + }), + ); + + it.effect( + "reads t3.json from project.workspaceRoot rather than worktreePath via T3ProjectFileLoader", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-setup-t3json-" }); + const projectRoot = path.join(root, "project"); + const worktreeRoot = path.join(root, "worktree"); + yield* fs.makeDirectory(projectRoot, { recursive: true }); + yield* fs.makeDirectory(worktreeRoot, { recursive: true }); + yield* fs.writeFileString( + path.join(projectRoot, "t3.json"), + JSON.stringify({ + scripts: [ + { + name: "Setup Worktree", + command: "bun scripts/setup-worktree.ts", + icon: "configure", + runOnWorktreeCreate: true, + }, + ], + }), + ); + yield* fs.writeFileString( + path.join(worktreeRoot, "t3.json"), + JSON.stringify({ + scripts: [ + { + name: "Untrusted Worktree Script", + command: "echo untrusted", + runOnWorktreeCreate: true, + }, + ], + }), + ); + const opens: TerminalOpenInput[] = []; + const runner = yield* ProjectSetupScriptRunner.make.pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(TerminalManager.TerminalManager)({ + open: (input) => + Effect.sync(() => opens.push(input)).pipe(Effect.as(openSnapshot(""))), + getShell: () => Effect.succeed("/bin/zsh"), + subscribe: () => Effect.succeed(() => {}), + write: () => Effect.void, + close: () => Effect.void, + closeIdle: () => Effect.void, + closeOnSettle: () => Effect.void, + }), + Layer.mock(ProjectService.ProjectService)({}), + T3ProjectFileLoader.layer, + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadShell: () => Effect.succeed({ runtimeMode: "full-access" } as never), + }), + ServerSettings.layerTest({ projectSettingsFolded: true }), + NodeCrypto.layer, + ), + ), + ); + const result = yield* runner.runForThread({ + threadId, + worktreePath: worktreeRoot, + project: { + id: ProjectId.make("project-real-t3json"), + workspaceRoot: projectRoot, + scripts: [], + }, + }); + expect(result).toMatchObject({ + status: "started", + scriptId: "setup-worktree", + scriptName: "Setup Worktree", + scriptCommand: "bun scripts/setup-worktree.ts", + terminalId: "setup-setup-worktree", + async: true, + }); + expect(opens[0]?.cwd).toBe(worktreeRoot); + expect(opens[0]?.env).toMatchObject({ + T3CODE_PROJECT_ROOT: projectRoot, + T3CODE_WORKTREE_PATH: worktreeRoot, + }); + }).pipe(Effect.provide(NodeServices.layer)), + ); }); const runObservedSetup = Effect.fnUntraced(function* (command: string) { diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index 861750b7cb85..d790dbf2cfff 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -1,4 +1,11 @@ -import { linkOriginIsFenced, ProjectId, type ProjectScript, ThreadId } from "@t3tools/contracts"; +import { + linkOriginIsFenced, + MAX_SCRIPT_ID_LENGTH, + ProjectId, + type ProjectScript, + type T3ProjectFileScript, + ThreadId, +} from "@t3tools/contracts"; import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import { projectScriptRuntimeEnv, @@ -22,6 +29,7 @@ import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as TerminalManager from "../terminal/Manager.ts"; import * as ProjectService from "./ProjectService.ts"; +import * as T3ProjectFileLoader from "./T3ProjectFileLoader.ts"; export interface ProjectSetupScriptRunnerResultNoScript { readonly status: "no-script"; @@ -258,9 +266,31 @@ function wrapCommandForCompletion( } } +function projectFileSetupScript(fileScript: T3ProjectFileScript): ProjectScript { + const normalized = fileScript.name + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); + const id = + normalized.length === 0 + ? "t3-json-setup" + : normalized.slice(0, MAX_SCRIPT_ID_LENGTH).replace(/-+$/g, "") || "t3-json-setup"; + return { + id, + name: fileScript.name, + command: fileScript.command, + icon: fileScript.icon ?? "configure", + runOnWorktreeCreate: true, + ...(fileScript.stopOnSettle === undefined ? {} : { stopOnSettle: fileScript.stopOnSettle }), + ...(fileScript.async === undefined ? {} : { async: fileScript.async }), + }; +} + /** @public */ export const make = Effect.gen(function* () { const projects = yield* ProjectService.ProjectService; + const projectFiles = yield* T3ProjectFileLoader.T3ProjectFileLoader; const threads = yield* ProjectionStore.ProjectionStoreV2; const terminalManager = yield* TerminalManager.TerminalManager; const serverSettings = yield* ServerSettings.ServerSettingsService; @@ -494,8 +524,29 @@ export const make = Effect.gen(function* () { ); const trigger = input.trigger ?? "setup"; const scripts = resolveProjectScripts(settings, project); - const script = - trigger === "settle" ? settleProjectScript(scripts) : setupProjectScript(scripts); + const legacyOverride = settings.projectScriptOverrides[project.id]; + const hasExplicitProjectOverride = + settings.projectSettingsOverrides[project.id]?.defaultProjectScripts !== undefined || + (!settings.projectSettingsFolded && + legacyOverride !== null && + (legacyOverride !== undefined || project.scripts.length > 0)); + let script = trigger === "settle" ? settleProjectScript(scripts) : setupProjectScript(scripts); + if ( + !script && + trigger === "setup" && + !hasExplicitProjectOverride && + // Require full-access so lower-mode threads cannot run shell commands by editing t3.json. + thread?.runtimeMode === "full-access" + ) { + // Read from the project checkout, not the worktree, so untrusted branches cannot inject setup commands. + const projectFile = yield* projectFiles.load(project.workspaceRoot); + const fileSetupScript = Option.getOrUndefined(projectFile)?.scripts?.find( + (candidate) => candidate.runOnWorktreeCreate === true, + ); + if (fileSetupScript) { + script = projectFileSetupScript(fileSetupScript); + } + } if (!script) { return { status: "no-script", diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index aa0953142aac..954208cd4967 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -49,6 +49,7 @@ import * as ProcessRunner from "../processRunner.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; +import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts"; import * as TerminalManager from "./Manager.ts"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import { makePrepareTerminalLaunch } from "../workspace/restoreMissingWorktree.ts"; @@ -2364,6 +2365,9 @@ it.layer( Layer.mergeAll( Layer.succeed(TerminalManager.TerminalManager, terminals), Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(T3ProjectFileLoader.T3ProjectFileLoader)({ + load: () => Effect.succeedNone, + }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ getThreadShell: () => Effect.succeed(null), }), @@ -2598,6 +2602,9 @@ it.layer( Layer.mergeAll( Layer.succeed(TerminalManager.TerminalManager, manager), Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(T3ProjectFileLoader.T3ProjectFileLoader)({ + load: () => Effect.succeedNone, + }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ getThreadShell: () => Effect.succeed(null), }), diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 7bfe1ed99d1c..d1b817831def 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -190,8 +190,12 @@ project crumb. The Projects category, under Code, holds the project's name, icon, actions, checkouts and removal. Actions belong to a project: editing them creates the project's own list on each selected environment, and reset returns to the environment's shared list. A project's -`t3.json` actions can be imported there. When a project has several checkouts on one environment, -choose one in the scope line at the top to see or change only that checkout's settings. +`t3.json` actions can be imported there. When a project has no saved actions override and the +environment's shared list defines no setup action, new `full-access` worktree threads fall back to a +`runOnWorktreeCreate` action declared in the project checkout's `t3.json`; saving an explicit +project actions list (including an empty list) suppresses that fallback. When a project has several +checkouts on one environment, choose one in the scope line at the top to see or change only that +checkout's settings. Settings a repository can also declare in `t3.json`, such as the workspace for new threads, resolve in one order: a project override, then the environment setting, then `t3.json`, then the diff --git a/scripts/setup-worktree.test.ts b/scripts/setup-worktree.test.ts new file mode 100644 index 000000000000..156edce1eedf --- /dev/null +++ b/scripts/setup-worktree.test.ts @@ -0,0 +1,210 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { afterEach, describe, expect, it } from "vite-plus/test"; + +const scriptSource = NodePath.resolve(import.meta.dirname, "setup-worktree.ts"); +const tempDirs: string[] = []; + +function makeTempDir(prefix: string): string { + const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), prefix)); + tempDirs.push(dir); + return dir; +} + +function writeFakeBun(binDir: string): void { + NodeFS.mkdirSync(binDir, { recursive: true }); + const scriptPath = NodePath.join(binDir, "bun"); + NodeFS.writeFileSync( + scriptPath, + '#!/bin/sh\nmkdir -p node_modules\necho "$*" > node_modules/.bun-args\n', + { mode: 0o755 }, + ); +} + +function runGit(cwd: string, args: ReadonlyArray): void { + const result = NodeChildProcess.spawnSync("git", args, { cwd, encoding: "utf8" }); + if (result.status !== 0) { + throw new Error(`git ${args.join(" ")} failed: ${result.stderr}`); + } +} + +function runSetupScript( + worktree: string, + binDir: string, + envOverrides: Record, +) { + const env: NodeJS.ProcessEnv = { + ...process.env, + PATH: `${binDir}${NodePath.delimiter}${process.env.PATH ?? ""}`, + ...envOverrides, + }; + if (envOverrides.T3CODE_PROJECT_ROOT === undefined) { + delete env.T3CODE_PROJECT_ROOT; + } + return NodeChildProcess.spawnSync( + process.execPath, + [NodePath.join(worktree, "scripts", "setup-worktree.ts")], + { + cwd: worktree, + env, + encoding: "utf8", + }, + ); +} + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + NodeFS.rmSync(dir, { recursive: true, force: true }); + } +}); + +describe.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "scripts/setup-worktree.ts", + () => { + it("defaults T3CODE_PROJECT_ROOT to the main worktree when run by hand", () => { + const root = makeTempDir("t3-setup-worktree-"); + const mainRepo = NodePath.join(root, "main-repo"); + const linkedWorktree = NodePath.join(root, "linked-worktree"); + const binDir = NodePath.join(root, "bin"); + writeFakeBun(binDir); + + NodeFS.mkdirSync(NodePath.join(mainRepo, "scripts"), { recursive: true }); + NodeFS.copyFileSync(scriptSource, NodePath.join(mainRepo, "scripts", "setup-worktree.ts")); + NodeFS.writeFileSync(NodePath.join(mainRepo, ".env"), "SECRET=1\n"); + + runGit(mainRepo, ["init", "-b", "main"]); + runGit(mainRepo, ["config", "user.name", "Test User"]); + runGit(mainRepo, ["config", "user.email", "test@example.com"]); + runGit(mainRepo, ["add", "scripts/setup-worktree.ts"]); + runGit(mainRepo, ["commit", "-m", "initial"]); + runGit(mainRepo, ["worktree", "add", "-b", "feature", linkedWorktree]); + + const result = runSetupScript(linkedWorktree, binDir, { T3CODE_PROJECT_ROOT: undefined }); + expect(result.status).toBe(0); + expect(NodeFS.existsSync(NodePath.join(linkedWorktree, ".t3", "setup-done"))).toBe(true); + expect(NodeFS.existsSync(NodePath.join(linkedWorktree, ".t3", "setup-running"))).toBe(false); + expect( + NodeFS.readFileSync( + NodePath.join(linkedWorktree, "node_modules", ".bun-args"), + "utf8", + ).trim(), + ).toBe("install --frozen-lockfile"); + expect(NodeFS.lstatSync(NodePath.join(linkedWorktree, ".env")).isSymbolicLink()).toBe(true); + expect(NodeFS.realpathSync(NodePath.join(linkedWorktree, ".env"))).toBe( + NodeFS.realpathSync(NodePath.join(mainRepo, ".env")), + ); + }); + + it("prefers an explicit T3CODE_PROJECT_ROOT over git worktree discovery", () => { + const root = makeTempDir("t3-setup-worktree-explicit-"); + const mainRepo = NodePath.join(root, "main-repo"); + const explicitRoot = NodePath.join(root, "explicit-root"); + const linkedWorktree = NodePath.join(root, "linked-worktree"); + const binDir = NodePath.join(root, "bin"); + writeFakeBun(binDir); + + NodeFS.mkdirSync(NodePath.join(mainRepo, "scripts"), { recursive: true }); + NodeFS.mkdirSync(explicitRoot, { recursive: true }); + NodeFS.copyFileSync(scriptSource, NodePath.join(mainRepo, "scripts", "setup-worktree.ts")); + NodeFS.writeFileSync(NodePath.join(mainRepo, ".env"), "SOURCE=main\n"); + NodeFS.writeFileSync(NodePath.join(explicitRoot, ".env"), "SOURCE=explicit\n"); + + runGit(mainRepo, ["init", "-b", "main"]); + runGit(mainRepo, ["config", "user.name", "Test User"]); + runGit(mainRepo, ["config", "user.email", "test@example.com"]); + runGit(mainRepo, ["add", "scripts/setup-worktree.ts"]); + runGit(mainRepo, ["commit", "-m", "initial"]); + runGit(mainRepo, ["worktree", "add", "-b", "feature", linkedWorktree]); + + const result = runSetupScript(linkedWorktree, binDir, { T3CODE_PROJECT_ROOT: explicitRoot }); + expect(result.status).toBe(0); + expect(NodeFS.realpathSync(NodePath.join(linkedWorktree, ".env"))).toBe( + NodeFS.realpathSync(NodePath.join(explicitRoot, ".env")), + ); + }); + + it("throws when T3CODE_PROJECT_ROOT is unset outside a git worktree", () => { + const root = makeTempDir("t3-setup-worktree-nogit-"); + const binDir = NodePath.join(root, "bin"); + writeFakeBun(binDir); + + NodeFS.mkdirSync(NodePath.join(root, "scripts"), { recursive: true }); + NodeFS.copyFileSync(scriptSource, NodePath.join(root, "scripts", "setup-worktree.ts")); + + const result = runSetupScript(root, binDir, { T3CODE_PROJECT_ROOT: undefined }); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("T3CODE_PROJECT_ROOT is not set"); + expect(NodeFS.existsSync(NodePath.join(root, ".t3", "setup-failed"))).toBe(true); + }); + + it("ignores inherited GIT_DIR when discovering the main worktree", () => { + const root = makeTempDir("t3-setup-worktree-gitdir-"); + const mainRepo = NodePath.join(root, "main-repo"); + const otherRepo = NodePath.join(root, "other-repo"); + const linkedWorktree = NodePath.join(root, "linked-worktree"); + const binDir = NodePath.join(root, "bin"); + writeFakeBun(binDir); + + NodeFS.mkdirSync(NodePath.join(mainRepo, "scripts"), { recursive: true }); + NodeFS.mkdirSync(otherRepo, { recursive: true }); + NodeFS.copyFileSync(scriptSource, NodePath.join(mainRepo, "scripts", "setup-worktree.ts")); + NodeFS.writeFileSync(NodePath.join(mainRepo, ".env"), "REPO=main\n"); + NodeFS.writeFileSync(NodePath.join(otherRepo, ".env"), "REPO=other\n"); + + runGit(mainRepo, ["init", "-b", "main"]); + runGit(mainRepo, ["config", "user.name", "Test User"]); + runGit(mainRepo, ["config", "user.email", "test@example.com"]); + runGit(mainRepo, ["add", "scripts/setup-worktree.ts"]); + runGit(mainRepo, ["commit", "-m", "initial"]); + runGit(mainRepo, ["worktree", "add", "-b", "feature", linkedWorktree]); + + runGit(otherRepo, ["init", "-b", "main"]); + runGit(otherRepo, ["config", "user.name", "Test User"]); + runGit(otherRepo, ["config", "user.email", "test@example.com"]); + NodeFS.writeFileSync(NodePath.join(otherRepo, "README.md"), "other\n"); + runGit(otherRepo, ["add", "README.md"]); + runGit(otherRepo, ["commit", "-m", "other"]); + + const result = runSetupScript(linkedWorktree, binDir, { + T3CODE_PROJECT_ROOT: undefined, + GIT_DIR: NodePath.join(otherRepo, ".git"), + GIT_WORK_TREE: otherRepo, + }); + expect(result.status).toBe(0); + expect(NodeFS.realpathSync(NodePath.join(linkedWorktree, ".env"))).toBe( + NodeFS.realpathSync(NodePath.join(mainRepo, ".env")), + ); + }); + + it("skips env symlinking when run in the main checkout via a symlinked path", () => { + const root = makeTempDir("t3-setup-worktree-main-"); + const mainRepo = NodePath.join(root, "main-repo"); + const symlinkedMain = NodePath.join(root, "main-link"); + const envTarget = NodePath.join(root, "shared.env"); + const binDir = NodePath.join(root, "bin"); + writeFakeBun(binDir); + + NodeFS.mkdirSync(NodePath.join(mainRepo, "scripts"), { recursive: true }); + NodeFS.copyFileSync(scriptSource, NodePath.join(mainRepo, "scripts", "setup-worktree.ts")); + NodeFS.writeFileSync(envTarget, "SHARED=1\n"); + NodeFS.symlinkSync(envTarget, NodePath.join(mainRepo, ".env")); + NodeFS.symlinkSync(mainRepo, symlinkedMain); + + runGit(mainRepo, ["init", "-b", "main"]); + runGit(mainRepo, ["config", "user.name", "Test User"]); + runGit(mainRepo, ["config", "user.email", "test@example.com"]); + runGit(mainRepo, ["add", "scripts/setup-worktree.ts"]); + runGit(mainRepo, ["commit", "-m", "initial"]); + + const result = runSetupScript(symlinkedMain, binDir, { T3CODE_PROJECT_ROOT: undefined }); + expect(result.status).toBe(0); + expect(result.stderr).not.toContain("Skipping .env"); + expect(NodeFS.existsSync(NodePath.join(mainRepo, ".t3", "setup-done"))).toBe(true); + expect(NodeFS.readlinkSync(NodePath.join(mainRepo, ".env"))).toBe(envTarget); + }); + }, +); diff --git a/scripts/setup-worktree.ts b/scripts/setup-worktree.ts index e032c6b69199..38472b25eed4 100644 --- a/scripts/setup-worktree.ts +++ b/scripts/setup-worktree.ts @@ -41,7 +41,41 @@ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) { }); } -const projectRoot = process.env.T3CODE_PROJECT_ROOT; +const INHERITED_GIT_REPO_ENV_KEYS = [ + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_COMMON_DIR", + "GIT_INDEX_FILE", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_PREFIX", +] as const; + +function resolveMainWorktree(): string | undefined { + const env: NodeJS.ProcessEnv = { ...process.env }; + for (const key of INHERITED_GIT_REPO_ENV_KEYS) { + delete env[key]; + } + const result = NodeChildProcess.spawnSync("git", ["worktree", "list", "--porcelain"], { + cwd: worktree, + env, + encoding: "utf8", + }); + if (result.error || result.status !== 0) return undefined; + const line = result.stdout.split(/\r?\n/).find((entry) => entry.startsWith("worktree ")); + const mainWorktree = line?.slice("worktree ".length); + return mainWorktree && mainWorktree.length > 0 ? mainWorktree : undefined; +} + +function samePath(a: string, b: string): boolean { + try { + return NodeFS.realpathSync.native(a) === NodeFS.realpathSync.native(b); + } catch { + return NodePath.resolve(a) === NodePath.resolve(b); + } +} + +const projectRoot = process.env.T3CODE_PROJECT_ROOT || resolveMainWorktree(); if (!projectRoot) { throw new Error("T3CODE_PROJECT_ROOT is not set. Run this through the t3.json setup action."); } @@ -75,17 +109,19 @@ if (installStatus !== 0 || cancelSignal) { } // Worktrees link main-checkout env files; replace only symlinks so real files always survive. -for (const file of ENV_FILES) { - const source = NodePath.join(projectRoot, file); - const sourceStat = NodeFS.lstatSync(source, { throwIfNoEntry: false }); - if (!sourceStat) continue; - if (!sourceStat.isFile()) { - process.stderr.write(`Skipping ${file}: ${source} is not a regular file.\n`); - continue; +if (!samePath(projectRoot, worktree)) { + for (const file of ENV_FILES) { + const source = NodePath.join(projectRoot, file); + const sourceStat = NodeFS.lstatSync(source, { throwIfNoEntry: false }); + if (!sourceStat) continue; + if (!sourceStat.isFile()) { + process.stderr.write(`Skipping ${file}: ${source} is not a regular file.\n`); + continue; + } + const target = NodePath.join(worktree, file); + const existing = NodeFS.lstatSync(target, { throwIfNoEntry: false }); + if (existing && !existing.isSymbolicLink()) continue; + if (existing) NodeFS.rmSync(target); + NodeFS.symlinkSync(source, target); } - const target = NodePath.join(worktree, file); - const existing = NodeFS.lstatSync(target, { throwIfNoEntry: false }); - if (existing && !existing.isSymbolicLink()) continue; - if (existing) NodeFS.rmSync(target); - NodeFS.symlinkSync(source, target); }