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(scripts): add dev status, worktree setup, UI fixtures, and pairing helpers (#180)
Leoa198c60d659e
diff --git a/.agents/skills/test-t3-mobile/scripts/app-identity.mjs b/.agents/skills/test-t3-mobile/scripts/app-identity.mjsnew file mode 100644index 000000000..b1c30db21--- /dev/null+++ b/.agents/skills/test-t3-mobile/scripts/app-identity.mjs@@ -0,0 +1,21 @@+#!/usr/bin/env node++const field = process.argv[2];+const knownFields = ["scheme", "ios-bundle-id", "android-package"];+if (process.argv.length !== 3 || !field || !knownFields.includes(field)) {+ console.error("Usage: app-identity.mjs <scheme|ios-bundle-id|android-package>");+ process.exit(2);+}+// Force the development variant before app.config.ts loads the repository environment.+process.env.APP_VARIANT = "development";+const { default: config } = await import("../../../../apps/mobile/app.config.ts");+const fields = {+ scheme: Array.isArray(config.scheme) ? config.scheme[0] : config.scheme,+ "ios-bundle-id": config.ios?.bundleIdentifier,+ "android-package": config.android?.package,+};+const value = fields[field];+if (!value || !/^[A-Za-z][A-Za-z0-9+.-]*$/.test(value)) {+ throw new Error(`Invalid development app identity: ${field}`);+}+console.log(value);diff --git a/.agents/skills/test-t3-mobile/scripts/pair-client.sh b/.agents/skills/test-t3-mobile/scripts/pair-client.shindex 9caa06072..f584722f6 100755--- a/.agents/skills/test-t3-mobile/scripts/pair-client.sh+++ b/.agents/skills/test-t3-mobile/scripts/pair-client.sh@@ -13,7 +13,12 @@ platform="$1"device_id="$2"server_port="$3"base_dir="$4"-url_scheme="${5:-t3code-dev}"+url_scheme="${5:-}"+script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"++[[ "$server_port" =~ ^[0-9]{1,5}$ ]] || usage+(( 10#$server_port >= 1 && 10#$server_port <= 65535 )) || usage+[[ -n "$device_id" && -n "$base_dir" ]] || usagecase "$platform" inios)@@ -27,9 +32,18 @@ case "$platform" in;;esac-repo_root="$(git rev-parse --show-toplevel)"+repo_root="$(cd "$script_dir/../../../.." && pwd)"cd "$repo_root"+if [[ -z "$url_scheme" ]]; then+ url_scheme="$(node "$script_dir/app-identity.mjs" scheme)"+fi+[[ "$url_scheme" =~ ^[A-Za-z][A-Za-z0-9+.-]*$ ]] || usage+android_package=""+if [[ "$platform" == android ]]; then+ android_package="$(node "$script_dir/app-identity.mjs" android-package)"+fi+if ! pairing_output="$({T3CODE_PORT="$server_port" node apps/server/src/bin.ts auth pairing create \--base-dir "$base_dir" \@@ -64,7 +78,7 @@ case "$platform" in# adb shell re-joins its arguments and evaluates them through the device# shell, so the deep link's `?`/`&` must be quoted once more for that shell.adb -s "$device_id" shell \- "am start -W -a android.intent.action.VIEW -d '$deep_link' com.t3tools.t3code.dev" \+ "am start -W -a android.intent.action.VIEW -d '$deep_link' $android_package" \>/dev/null;;esacdiff --git a/apps/mobile/pair-client.test.ts b/apps/mobile/pair-client.test.tsnew file mode 100644index 000000000..03369a9fa--- /dev/null+++ b/apps/mobile/pair-client.test.ts@@ -0,0 +1,112 @@+// @effect-diagnostics nodeBuiltinImport:off - These tests invoke host helpers with device and pairing commands stubbed.+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 NodeURL from "node:url";+import { afterEach, expect, it } from "vite-plus/test";++// The helper harness spawns bash with shebang stubs; skip those cases on Windows.+// oxlint-disable-next-line t3code/no-global-process-runtime -- Host-platform test guard, not Effect code.+const posixIt = it.skipIf(process.platform === "win32");++const root = NodeURL.fileURLToPath(new URL("../../", import.meta.url));+const scripts = NodePath.join(root, ".agents/skills/test-t3-mobile/scripts");+const directories: string[] = [];+afterEach(() => {+ for (const directory of directories.splice(0))+ NodeFS.rmSync(directory, { recursive: true, force: true });+});++it("reads development identity from app config and respects the personal-team bundle", () => {+ const identity = (field: string, env = {}) =>+ NodeChildProcess.execFileSync(+ process.execPath,+ [NodePath.join(scripts, "app-identity.mjs"), field],+ {+ encoding: "utf8",+ env: { ...process.env, APP_VARIANT: "production", T3CODE_IOS_PERSONAL_TEAM: "0", ...env },+ },+ ).trim();+ expect(identity("scheme")).toBe("akeru-dev");+ expect(identity("android-package")).toBe("dev.leodoes.akeru.dev");+ expect(identity("ios-bundle-id")).toBe("dev.leodoes.akeru.dev");+ expect(+ identity("ios-bundle-id", {+ T3CODE_IOS_PERSONAL_TEAM: "1",+ T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID: "dev.example.personal",+ }),+ ).toBe("dev.example.personal");+});++function harness() {+ const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-pair-helper-"));+ directories.push(directory);+ const log = NodePath.join(directory, "calls.jsonl");+ const stub = `#!${process.execPath}+const fs = require('node:fs');+const path = require('node:path');+const command = path.basename(process.argv[1]);+const args = process.argv.slice(2);+if (command === 'node' && args[0] !== 'apps/server/src/bin.ts') {+ const result = require('node:child_process').spawnSync(${JSON.stringify(process.execPath)}, args, { stdio: 'inherit', env: process.env });+ process.exit(result.status ?? 1);+}+fs.appendFileSync(process.env.CALL_LOG, JSON.stringify({ command, args }) + '\\n');+if (command === 'node') console.log('Pair URL: http://fixture.invalid/pair?token=fake&value=two');+`;+ for (const name of ["node", "adb", "xcrun"])+ NodeFS.writeFileSync(NodePath.join(directory, name), stub, { mode: 0o755 });+ return {+ invoke: (args: string[]) =>+ NodeChildProcess.spawnSync("bash", [NodePath.join(scripts, "pair-client.sh"), ...args], {+ cwd: directory,+ encoding: "utf8",+ env: {+ ...process.env,+ T3CODE_IOS_PERSONAL_TEAM: "0",+ PATH: `${directory}:${process.env.PATH}`,+ CALL_LOG: log,+ },+ }),+ calls: () =>+ NodeFS.readFileSync(log, "utf8")+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line) as { command: string; args: string[] }),+ };+}++posixIt.each(["ios", "android"])(+ "invokes %s with encoded pairing arguments and no real device",+ (platform) => {+ const helper = harness();+ const result = helper.invoke([platform, "test-device", "3777", "/isolated path"]);+ expect(result.status, result.stderr).toBe(0);+ const [pair, open] = helper.calls();+ expect(pair?.args).toContain("/isolated path");+ expect(pair?.args).toContain(+ platform === "ios" ? "http://127.0.0.1:3777" : "http://10.0.2.2:3777",+ );+ expect(open?.command).toBe(platform === "ios" ? "xcrun" : "adb");+ const command = open!.args.join(" ");+ expect(command).toContain("akeru-dev://connections/new?pairingUrl=");+ expect(command).toContain("%26value%3Dtwo&autoConnect=1");+ if (platform === "android") expect(command).toContain("' dev.leodoes.akeru.dev");+ },+);++posixIt("keeps the scheme override and rejects invalid arguments before pairing", () => {+ const helper = harness();+ expect(helper.invoke(["ios", "device", "3777", "/isolated", "custom-dev"]).status).toBe(0);+ expect(helper.calls()[1]?.args.join(" ")).toContain("custom-dev://");+ for (const args of [+ [],+ ["other", "device", "3777", "/isolated"],+ ["ios", "device", "65536", "/isolated"],+ ["android", "device", "3777", "/isolated", "bad' scheme"],+ ]) {+ expect(helper.invoke(args).status).toBe(2);+ }+ expect(helper.calls()).toHaveLength(2);+});diff --git a/apps/server/scripts/migrate-dev-db.ts b/apps/server/scripts/migrate-dev-db.tsindex 57158fbe8..dc918890c 100644--- a/apps/server/scripts/migrate-dev-db.ts+++ b/apps/server/scripts/migrate-dev-db.ts@@ -188,7 +188,7 @@ const isProcessAlive = (pid: number): boolean => {* wal_checkpoint(TRUNCATE) reports busy while another connection holds the* WAL. A leftover -shm alone is not a signal — read-only connections cannot* clean it up on close. */-const ensureNotInUse = Effect.fn("ensureDevDbNotInUse")(function* (databasePath: string) {+export const ensureNotInUse = Effect.fn("ensureDevDbNotInUse")(function* (databasePath: string) {const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;diff --git a/apps/server/scripts/t3-sqlite-state.ts b/apps/server/scripts/t3-sqlite-state.tsindex 37d71d4e5..d4c7bb174 100644--- a/apps/server/scripts/t3-sqlite-state.ts+++ b/apps/server/scripts/t3-sqlite-state.ts@@ -176,6 +176,39 @@ function normalizeSqliteRow(row: RawSqliteRow): typeof SqliteStateRow.Type {);}+export const guardSqliteStateHome = Effect.fn("guardSqliteStateHome")(function* (+ baseDir: string,+ sharedHome = NodeOS.homedir() + "/" + PRODUCT_HOME_DIRNAME,+) {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const canonicalBase = yield* fs.realPath(baseDir);+ const canonicalShared = yield* fs+ .realPath(sharedHome)+ .pipe(Effect.orElseSucceed(() => path.resolve(sharedHome)));+ const relative = path.relative(canonicalShared, canonicalBase);+ if (+ relative === "" ||+ (!relative.startsWith(".." + path.sep) && relative !== ".." && !path.isAbsolute(relative))+ ) {+ return yield* new SqliteStateSharedHomeMutationError();+ }+});++export const backupSqliteState = Effect.fn("backupSqliteState")(function* (databasePath: string) {+ const fs = yield* FileSystem.FileSystem;+ const sql = yield* SqlClient.SqlClient;+ const timestamp = DateTime.formatIso(yield* DateTime.now).replaceAll(":", "-");+ let backupPath = `${databasePath}.backup-${timestamp}`;+ let suffix = 0;+ while (yield* fs.exists(backupPath)) {+ backupPath = `${databasePath}.backup-${timestamp}-${++suffix}`;+ }+ yield* sql`VACUUM INTO ${backupPath}`;+ yield* fs.chmod(backupPath, 0o600);+ return backupPath;+});+export const runSqliteState = Effect.fn("runSqliteState")(function* (input: RunSqliteStateInput,options: RunSqliteStateOptions = {},@@ -193,13 +226,7 @@ export const runSqliteState = Effect.fn("runSqliteState")(function* (return yield* new SqliteStateDatabaseMissingError({ databasePath });}if (input.operation === "exec") {- const [canonicalBaseDir, canonicalSharedHome] = yield* Effect.all([- fs.realPath(baseDir),- fs.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),- ]);- if (canonicalBaseDir === canonicalSharedHome) {- return yield* new SqliteStateSharedHomeMutationError();- }+ yield* guardSqliteStateHome(baseDir, sharedHome);}const program = Effect.gen(function* () {@@ -218,10 +245,7 @@ export const runSqliteState = Effect.fn("runSqliteState")(function* (} as const;}- const timestamp = DateTime.formatIso(yield* DateTime.now).replaceAll(":", "-");- const backupPath = `${databasePath}.backup-${timestamp}`;- yield* sql`VACUUM INTO ${backupPath}`;- yield* fs.chmod(backupPath, 0o600);+ const backupPath = yield* backupSqliteState(databasePath);yield* sql.withTransaction(sql.unsafe(source).unprepared);return {diff --git a/apps/server/scripts/ui-fixture.test.ts b/apps/server/scripts/ui-fixture.test.tsnew file mode 100644index 000000000..baba53a25--- /dev/null+++ b/apps/server/scripts/ui-fixture.test.ts@@ -0,0 +1,220 @@+import * as NodeServices from "@effect/platform-node/NodeServices";+import { assert, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Path from "effect/Path";+import * as Layer from "effect/Layer";+import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";+import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";+import * as ThreadBackgroundLiveness from "../src/orchestration/ThreadBackgroundLiveness.ts";+import * as ThreadPlanProgress from "../src/orchestration/ThreadPlanProgress.ts";+import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityResolver.ts";+import * as SqlClient from "effect/unstable/sql/SqlClient";+import * as Schema from "effect/Schema";++import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts";+import { runSqliteState } from "./t3-sqlite-state.ts";+import { runUiFixture, UI_FIXTURE_CASES } from "./ui-fixture.ts";++const encodeRuntimePid = Schema.encodeEffect(+ Schema.fromJsonString(Schema.Struct({ pid: Schema.Int })),+);++it.layer(NodeServices.layer)("ui-fixture", (it) => {+ it.effect(+ "migrates offline and repeats each bounded projection case without events or credentials",+ () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "akeru-ui-fixture-" });+ for (const scenario of UI_FIXTURE_CASES) {+ const first = yield* runUiFixture({ baseDir, scenario });+ const before = yield* runSqliteState({+ operation: "query",+ baseDir,+ sql: "SELECT * FROM projection_threads ORDER BY thread_id",+ });+ const second = yield* runUiFixture({ baseDir, scenario });+ yield* Effect.gen(function* () {+ const query = yield* ProjectionSnapshotQuery;+ const snapshot = yield* query.getSnapshot();+ assert.equal(+ snapshot.threads.length,+ scenario === "empty" ? 0 : scenario === "edge" ? 3 : 2,+ );+ for (const thread of snapshot.threads.filter((thread) => thread.messages.length > 0)) {+ assert.deepStrictEqual(+ thread.messages.map((message) => message.role),+ ["user", "assistant"],+ );+ }+ }).pipe(+ Effect.provide(+ OrchestrationProjectionSnapshotQueryLive.pipe(+ Layer.provide(ThreadBackgroundLiveness.layer),+ Layer.provide(ThreadPlanProgress.layer),+ Layer.provide(RepositoryIdentityResolver.layer),+ Layer.provide(NodeSqliteClient.layer({ filename: second.database })),+ ),+ ),+ );+ assert.equal(second.kind, "projection-only");+ assert.ok(second.backup);+ assert.notEqual(first.backup, second.backup);+ assert.equal((yield* fs.stat(second.backup!)).mode & 0o777, 0o600);+ const after = yield* runSqliteState({+ operation: "query",+ baseDir,+ sql: "SELECT * FROM projection_threads ORDER BY thread_id",+ });+ assert.deepStrictEqual(before, after);+ if (after.operation === "query") {+ assert.equal(after.rows.length, scenario === "empty" ? 0 : scenario === "edge" ? 3 : 2);+ }+ const counts = yield* runSqliteState({+ operation: "query",+ baseDir,+ sql: `SELECT+ (SELECT COUNT(*) FROM orchestration_events) AS events,+ (SELECT COUNT(*) FROM auth_sessions) AS sessions,+ (SELECT COUNT(*) FROM auth_pairing_links) AS links,+ (SELECT COUNT(*) FROM provider_session_runtime) AS providers,+ (SELECT COUNT(*) FROM projection_thread_messages) AS messages`,+ });+ if (counts.operation === "query")+ assert.deepStrictEqual(counts.rows, [+ {+ events: 0,+ sessions: 0,+ links: 0,+ providers: 0,+ messages: scenario === "empty" ? 0 : 4,+ },+ ]);+ }+ }),+ );++ it.effect("retries a fresh directory that only contains the ownership marker", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "akeru-ui-retry-" });+ // A failed fresh run leaves the marker without userdata; a retry must succeed.+ yield* fs.writeFileString(+ path.join(baseDir, ".ui-fixture"),+ "akeru-ui-projection-fixture-v1\n",+ );+ const result = yield* runUiFixture({ baseDir, scenario: "populated" });+ assert.equal(result.kind, "projection-only");+ assert.equal(result.backup, null);+ }),+ );++ it.effect("repairs a partially migrated database from an interrupted run", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "akeru-ui-partial-" });+ // A run that died mid-migration leaves the marker and an incomplete database.+ yield* fs.writeFileString(+ path.join(baseDir, ".ui-fixture"),+ "akeru-ui-projection-fixture-v1\n",+ );+ yield* fs.makeDirectory(path.join(baseDir, "userdata"), { recursive: true });+ yield* fs.writeFileString(path.join(baseDir, "userdata", "state.sqlite"), "");+ const result = yield* runUiFixture({ baseDir, scenario: "populated" });+ assert.equal(result.kind, "projection-only");+ assert.ok(result.backup);+ }),+ );++ it.effect("refuses shared descendants, aliases, and unowned directories before writes", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const parent = yield* fs.makeTempDirectoryScoped({ prefix: "akeru-ui-guard-" });+ const shared = path.join(parent, "shared");+ const nested = path.join(shared, "dev");+ yield* fs.makeDirectory(nested, { recursive: true });+ const alias = path.join(parent, "alias");+ yield* fs.symlink(nested, alias);+ for (const baseDir of [shared, nested, alias]) {+ const error = yield* runUiFixture(+ { baseDir, scenario: "empty" },+ { sharedHome: shared },+ ).pipe(Effect.flip);+ assert.equal(error._tag, "SqliteStateSharedHomeMutationError");+ }+ assert.deepStrictEqual(yield* fs.readDirectory(nested), []);+ yield* fs.writeFileString(path.join(nested, "keep"), "not fixture data");+ const error = yield* runUiFixture({ baseDir: nested, scenario: "empty" }).pipe(Effect.flip);+ assert.equal(error._tag, "UiFixtureSafetyError");+ assert.deepStrictEqual(yield* fs.readDirectory(nested), ["keep"]);+ }),+ );++ it.effect("refuses a running server descriptor and redirected databases", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "akeru-ui-running-" });+ const fixture = yield* runUiFixture({ baseDir, scenario: "populated" });+ const descriptor = path.join(baseDir, "userdata", "server-runtime.json");+ yield* fs.writeFileString(descriptor, yield* encodeRuntimePid({ pid: process.pid }));+ const before = yield* fs.readDirectory(path.dirname(fixture.database));+ const running = yield* runUiFixture({ baseDir, scenario: "empty" }).pipe(Effect.flip);+ assert.equal(running._tag, "MigrateDevDbServerRunningError");+ assert.deepStrictEqual(yield* fs.readDirectory(path.dirname(fixture.database)), before);+ yield* fs.remove(descriptor);+ const target = path.join(baseDir, "saved.sqlite");+ yield* fs.rename(fixture.database, target);+ yield* fs.symlink(target, fixture.database);+ const redirected = yield* runUiFixture({ baseDir, scenario: "empty" }).pipe(Effect.flip);+ assert.equal(redirected._tag, "UiFixtureSafetyError");+ }),+ );++ it.effect(+ "refuses credential-bearing fixture databases before backup or projection changes",+ () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "akeru-ui-credentials-" });+ const fixture = yield* runUiFixture({ baseDir, scenario: "populated" });+ yield* runSqliteState({+ operation: "exec",+ baseDir,+ sql: `INSERT INTO auth_pairing_links+ (id, credential, method, scopes, subject, created_at, expires_at)+ VALUES ('synthetic', 'not-a-real-credential', 'pairing', '[]', 'test', '2026-01-01', '2026-01-02')`,+ });+ const before = yield* fs.readDirectory(path.dirname(fixture.database));+ const error = yield* runUiFixture({ baseDir, scenario: "empty" }).pipe(Effect.flip);+ assert.equal(error._tag, "UiFixtureSafetyError");+ assert.deepStrictEqual(yield* fs.readDirectory(path.dirname(fixture.database)), before);+ const result = yield* runSqliteState({+ operation: "query",+ baseDir,+ sql: "SELECT COUNT(*) AS count FROM projection_threads",+ });+ if (result.operation === "query") assert.deepStrictEqual(result.rows, [{ count: 2 }]);+ }),+ );++ it.effect("refuses an active SQLite writer without a server descriptor", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "akeru-ui-locked-" });+ const fixture = yield* runUiFixture({ baseDir, scenario: "populated" });+ yield* Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ yield* sql.unsafe("BEGIN IMMEDIATE").unprepared;+ const error = yield* runUiFixture({ baseDir, scenario: "empty" }).pipe(Effect.flip);+ assert.equal(error._tag, "MigrateDevDbDestinationBusyError");+ yield* sql.unsafe("ROLLBACK").unprepared;+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: fixture.database })));+ }),+ );+});diff --git a/apps/server/scripts/ui-fixture.ts b/apps/server/scripts/ui-fixture.tsnew file mode 100644index 000000000..3c486caa2--- /dev/null+++ b/apps/server/scripts/ui-fixture.ts@@ -0,0 +1,200 @@+#!/usr/bin/env node++import * as NodeRuntime from "@effect/platform-node/NodeRuntime";+import * as NodeServices from "@effect/platform-node/NodeServices";+import * as Console from "effect/Console";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Option from "effect/Option";+import * as Path from "effect/Path";+import * as Schema from "effect/Schema";+import * as SqlClient from "effect/unstable/sql/SqlClient";+import { Command, Flag } from "effect/unstable/cli";++import { SHOWCASE_THREADS } from "../../../scripts/mobile-showcase-environment.ts";+import { runMigrations } from "../src/persistence/Migrations.ts";+import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts";+import { ensureNotInUse } from "./migrate-dev-db.ts";+import { backupSqliteState, guardSqliteStateHome } from "./t3-sqlite-state.ts";++export const UI_FIXTURE_CASES = ["empty", "populated", "edge"] as const;+const decodeFixtureCase = Schema.decodeUnknownEffect(Schema.Literals(UI_FIXTURE_CASES));+const MARKER = "akeru-ui-projection-fixture-v1\n";+const TIMESTAMP = "2026-01-15T12:00:00.000Z";+const COMPLETED_AT = "2026-01-15T12:01:00.000Z";++export class UiFixtureSafetyError extends Schema.TaggedErrorClass<UiFixtureSafetyError>()(+ "UiFixtureSafetyError",+ { message: Schema.String },+) {}++// Projection-only display data. No events, credentials, provider sessions, or work are created.+const seedProjections = Effect.fn("seedUiProjections")(function* (+ scenario: (typeof UI_FIXTURE_CASES)[number],+ workspaceRoot: string,+) {+ const sql = yield* SqlClient.SqlClient;+ const tables = yield* sql<{ name: string }>`SELECT name FROM sqlite_master+ WHERE type = 'table' AND name LIKE 'projection_%'`;+ for (const { name } of tables) {+ yield* sql.unsafe(`DELETE FROM "${name.replaceAll('"', '""')}"`).unprepared;+ }+ yield* sql`DELETE FROM sqlite_sequence WHERE name = 'projection_turns'`;+ if (scenario === "empty") return;+ const model = '{"instanceId":"codex","model":"gpt-5.4"}';+ yield* sql`INSERT INTO projection_bots+ (bot_id, name, title, avatar_json, created_at, updated_at)+ VALUES ('ui-scout', 'Scout', 'Code review', '{"kind":"dither","seed":"scout"}', ${TIMESTAMP}, ${TIMESTAMP})`;+ yield* sql`INSERT INTO projection_projects+ (project_id, title, workspace_root, default_model_selection_json, scripts_json, created_at, updated_at)+ VALUES ('ui-project', 'Akeru Bot', ${workspaceRoot}, ${model}, '[]', ${TIMESTAMP}, ${TIMESTAMP})`;+ for (const [index, thread] of SHOWCASE_THREADS.slice(0, 2).entries()) {+ const id = `ui-thread-${index}`;+ const turn = `${id}-turn`;+ const title =+ scenario === "edge" && index === 1+ ? "Review a long chat title with Unicode — 日本語 — and narrow mobile layouts without losing the selected chat"+ : thread.title;+ yield* sql`INSERT INTO projection_threads+ (thread_id, project_id, bot_id, title, model_selection_json, runtime_mode, interaction_mode,+ latest_turn_id, latest_user_message_at, created_at, updated_at, pinned_at, archived_at)+ VALUES (${id}, 'ui-project', 'ui-scout', ${title}, ${model}, 'approval-required', 'default',+ ${turn}, ${TIMESTAMP}, ${TIMESTAMP}, ${TIMESTAMP}, ${index === 0 ? TIMESTAMP : null},+ ${scenario === "edge" && index === 1 ? TIMESTAMP : null})`;+ for (const [role, text] of [+ ["user", thread.request],+ ["assistant", thread.response],+ ] as const) {+ const createdAt = role === "user" ? TIMESTAMP : COMPLETED_AT;+ yield* sql`INSERT INTO projection_thread_messages+ (message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at)+ VALUES (${`${id}-${role}`}, ${id}, ${turn}, ${role}, ${text}, 0, ${createdAt}, ${createdAt})`;+ }+ yield* sql`INSERT INTO projection_turns+ (thread_id, turn_id, assistant_message_id, state, requested_at, started_at, completed_at, checkpoint_files_json)+ VALUES (${id}, ${turn}, ${`${id}-assistant`}, 'completed', ${TIMESTAMP}, ${TIMESTAMP}, ${COMPLETED_AT}, '[]')`;+ }+ if (scenario === "edge") {+ yield* sql`INSERT INTO projection_projects+ (project_id, title, workspace_root, scripts_json, created_at, updated_at)+ VALUES ('ui-empty-project', 'Empty project', ${workspaceRoot}, '[]', ${TIMESTAMP}, ${TIMESTAMP})`;+ yield* sql`INSERT INTO projection_threads+ (thread_id, project_id, bot_id, title, model_selection_json, created_at, updated_at)+ VALUES ('ui-empty-thread', 'ui-project', 'ui-scout', 'Empty chat', ${model}, ${TIMESTAMP}, ${TIMESTAMP})`;+ }+});++export const runUiFixture = Effect.fn("runUiFixture")(function* (+ input: { readonly baseDir: string; readonly scenario: (typeof UI_FIXTURE_CASES)[number] },+ options: { readonly sharedHome?: string } = {},+) {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const scenario = yield* decodeFixtureCase(input.scenario);+ const baseDir = yield* fs.realPath(path.resolve(input.baseDir));+ yield* guardSqliteStateHome(baseDir, options.sharedHome);+ const markerPath = path.join(baseDir, ".ui-fixture");+ const entries = yield* fs.readDirectory(baseDir);+ const fresh = entries.length === 0;+ if (+ !fresh &&+ (yield* fs.readFileString(markerPath).pipe(Effect.orElseSucceed(() => ""))) !== MARKER+ ) {+ return yield* new UiFixtureSafetyError({+ message: "Use an empty isolated directory or a directory created by ui-fixture.",+ });+ }+ const stateDir = path.join(baseDir, "userdata");+ const databasePath = path.join(stateDir, "state.sqlite");+ // A marker without a database is a failed fresh run; migrate it like a fresh one.+ const databaseExists = yield* fs.exists(databasePath);+ // Reject redirected state and hard links before any SQLite connection opens.+ for (const target of [+ markerPath,+ stateDir,+ databasePath,+ `${databasePath}-wal`,+ `${databasePath}-shm`,+ path.join(baseDir, "workspace"),+ ]) {+ if (Option.isSome(yield* fs.readLink(target).pipe(Effect.option))) {+ return yield* new UiFixtureSafetyError({+ message: "Fixture state must not use symbolic links or hard links.",+ });+ }+ if (yield* fs.exists(target)) {+ const canonical = yield* fs.realPath(target);+ const stat = yield* fs.stat(target);+ if (+ canonical !== target ||+ (stat.type === "File" && Option.getOrElse(stat.nlink, () => 1) !== 1)+ ) {+ return yield* new UiFixtureSafetyError({+ message: "Fixture state must not use symbolic links or hard links.",+ });+ }+ }+ }+ yield* ensureNotInUse(databasePath);+ // Mark ownership before creating state so a failed fresh run stays retryable.+ if (fresh) yield* fs.writeFileString(markerPath, MARKER);+ yield* fs.makeDirectory(stateDir, { recursive: true });+ const result = yield* Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ // Refuse protected state before migrations or backups touch the database.+ // A table missing from a partially migrated database counts as empty.+ for (const table of [+ "orchestration_events",+ "auth_sessions",+ "auth_pairing_links",+ "provider_session_runtime",+ ]) {+ const present = yield* sql<{ count: number }>`SELECT COUNT(*) AS count+ FROM sqlite_master WHERE type = 'table' AND name = ${table}`;+ if (Number(present[0]?.count) === 0) continue;+ const rows = yield* sql.unsafe<{ count: number }>(`SELECT COUNT(*) AS count FROM ${table}`)+ .unprepared;+ if (Number(rows[0]?.count) !== 0) {+ return yield* new UiFixtureSafetyError({+ message:+ "Fixture database contains events, credentials, or provider state. Use a new empty directory.",+ });+ }+ }+ // Migrating also repairs a database left behind by an interrupted run.+ yield* runMigrations();+ const backup = databaseExists ? yield* backupSqliteState(databasePath) : null;+ yield* sql.withTransaction(seedProjections(scenario, path.join(baseDir, "workspace")));+ return { database: databasePath, backup, scenario, kind: "projection-only" };+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: databasePath })));+ yield* fs.makeDirectory(path.join(baseDir, "workspace"), { recursive: true });+ yield* fs.writeFileString(markerPath, MARKER);+ return result;+});++export const uiFixtureCommand = Command.make(+ "ui-fixture",+ {+ baseDir: Flag.string("base-dir").pipe(+ Flag.withDescription(+ "Existing empty isolated directory, or a previous UI fixture directory. Stop its server first.",+ ),+ ),+ scenario: Flag.choice("case", UI_FIXTURE_CASES).pipe(Flag.withDefault("populated")),+ },+ (input) =>+ runUiFixture(input).pipe(+ Effect.flatMap((result) => Console.log(JSON.stringify(result, null, 2))),+ ),+).pipe(+ Command.withDescription(+ "Seed deterministic projection-only UI data offline. Not an event-sourced business test.",+ ),+);++if (import.meta.main) {+ Command.run(uiFixtureCommand, { version: "0.0.0" }).pipe(+ Effect.provide(NodeServices.layer),+ NodeRuntime.runMain,+ );+}diff --git a/package.json b/package.jsonindex 8388a693e..eaba6868f 100644--- a/package.json+++ b/package.json@@ -7,6 +7,8 @@"prepare": "node scripts/clean-tsgo-backups.mjs && effect-tsgo patch && vp config --no-agent","dev": "node scripts/dev-runner.ts dev","dev:share": "node scripts/dev-runner.ts dev --share",+ "dev:status": "node scripts/dev-status.ts",+ "dev:fixture": "node apps/server/scripts/ui-fixture.ts","dev:server": "node scripts/dev-runner.ts dev:server","dev:web": "node scripts/dev-runner.ts dev:web","dev:marketing": "vp run --filter @t3tools/marketing dev",diff --git a/scripts/dev-status.test.ts b/scripts/dev-status.test.tsnew file mode 100644index 000000000..5d80cc4a6--- /dev/null+++ b/scripts/dev-status.test.ts@@ -0,0 +1,275 @@+// @effect-diagnostics nodeBuiltinImport:off - Tests use isolated filesystem fixtures.+import * as NodeFS from "node:fs";+import * as NodeOS from "node:os";+import * as NodePath from "node:path";++import * as NodeServices from "@effect/platform-node/NodeServices";+import { describe, expect, it } from "@effect/vitest";+import { afterEach, vi } from "vite-plus/test";+import * as Effect from "effect/Effect";+import * as Logger from "effect/Logger";+import { FetchHttpClient } from "effect/unstable/http";++import {+ collectDevStatus,+ describeStatusClients,+ formatDevStatus,+ probeStatusOrigin,+ resolveDevStatusHome,+ statusOrigin,+} from "./dev-status.ts";++const directories: string[] = [];+function fixture(linked = true) {+ const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-dev-status-"));+ directories.push(root);+ if (linked) {+ NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /repo/.git/worktrees/status\n");+ } else {+ NodeFS.mkdirSync(NodePath.join(root, ".git"));+ }+ return root;+}++function writeRuntime(root: string, extra = {}) {+ const dir = NodePath.join(root, ".akeru", "userdata");+ NodeFS.mkdirSync(dir, { recursive: true });+ const file = NodePath.join(dir, "server-runtime.json");+ NodeFS.writeFileSync(+ file,+ JSON.stringify({+ version: 1,+ pid: 123,+ port: 15432,+ origin: "http://127.0.0.1:15432",+ devUrl: "http://localhost:6543",+ startedAt: "2026-09-04T00:00:00.000Z",+ ...extra,+ }),+ );+ return file;+}++afterEach(() => {+ for (const dir of directories.splice(0)) {+ NodeFS.rmSync(dir, { recursive: true, force: true });+ }+});++describe("dev status home", () => {+ it.effect("uses the linked worktree ahead of ambient homes", () =>+ Effect.gen(function* () {+ const root = fixture();+ const cwd = NodePath.join(root, "scripts");+ NodeFS.mkdirSync(cwd);+ const status = yield* resolveDevStatusHome({+ cwd,+ userHome: "/users/test",+ env: { T3CODE_HOME: "/live", AKERU_HOME: "/other-live" },+ });+ expect(status).toEqual({+ worktree: root,+ home: NodePath.join(root, ".akeru"),+ dataDir: NodePath.join(root, ".akeru/userdata"),+ });+ expect(NodeFS.existsSync(status.home)).toBe(false);+ }).pipe(Effect.provide(NodeServices.layer)),+ );++ it.effect("uses dev for the implicit main checkout home", () =>+ Effect.gen(function* () {+ const root = fixture(false);+ const status = yield* resolveDevStatusHome({+ cwd: root,+ userHome: "/users/test",+ env: { AKERU_HOME: "/ignored-by-dev-runner" },+ });+ expect(status.dataDir).toBe("/users/test/.akeru/dev");+ }).pipe(Effect.provide(NodeServices.layer)),+ );++ it.effect("uses userdata for explicit and ambient homes", () =>+ Effect.gen(function* () {+ const root = fixture(false);+ const resolve = (homeDir?: string) =>+ resolveDevStatusHome({+ cwd: root,+ homeDir,+ userHome: "/users/test",+ env: { T3CODE_HOME: "/configured" },+ });+ expect((yield* resolve()).dataDir).toBe("/configured/userdata");+ expect((yield* resolve("local")).dataDir).toBe(NodePath.join(root, "local/userdata"));+ expect((yield* resolve("~/sandbox")).dataDir).toBe("/users/test/sandbox/userdata");+ const linked = fixture();+ const explicit = yield* resolveDevStatusHome({+ cwd: linked,+ homeDir: "/explicit",+ userHome: "/users/test",+ env: {},+ });+ expect(explicit.dataDir).toBe("/explicit/userdata");+ const blank = yield* resolveDevStatusHome({+ cwd: linked,+ homeDir: " ",+ userHome: "/users/test",+ env: {},+ });+ expect(blank.dataDir).toBe(NodePath.join(linked, ".akeru/userdata"));+ }).pipe(Effect.provide(NodeServices.layer)),+ );+});++describe("dev status discovery", () => {+ it.effect("reports missing runtime without writes or guessed ports", () =>+ Effect.gen(function* () {+ const root = fixture();+ const probe = vi.fn(() => Effect.succeed("unexpected"));+ const status = yield* collectDevStatus({ cwd: root, env: {}, probe });+ expect(status.server.origin).toBeUndefined();+ expect(status.missing).toContain("usable server-runtime.json");+ expect(probe).not.toHaveBeenCalled();+ expect(NodeFS.readdirSync(root)).toEqual([".git"]);+ }).pipe(Effect.provide(NodeServices.layer)),+ );++ it.effect("reports stale runtime and leaves the file unchanged", () =>+ Effect.gen(function* () {+ const root = fixture();+ const file = writeRuntime(root);+ const before = NodeFS.readFileSync(file, "utf8");+ const probe = vi.fn(() => Effect.succeed("unexpected"));+ const status = yield* collectDevStatus({+ cwd: root,+ env: {},+ isProcessAlive: () => false,+ probe,+ });+ expect(status.descriptor).toContain("stale");+ expect(status.server.origin).toBe("http://127.0.0.1:15432");+ expect(status.server.readiness).toContain("unavailable");+ expect(probe).not.toHaveBeenCalled();+ expect(NodeFS.readFileSync(file, "utf8")).toBe(before);+ }).pipe(Effect.provide(NodeServices.layer)),+ );++ it.effect("redacts credentials and uses recorded origins", () =>+ Effect.gen(function* () {+ const root = fixture();+ writeRuntime(root, {+ origin: "http://user:[email protected]:15432/private?token=secret#secret",+ devUrl: "http://user:password@localhost:6543/pair?token=secret#secret",+ token: "secret",+ });+ const probe = vi.fn((_origin: string) => Effect.succeed("responding"));+ const status = yield* collectDevStatus({+ cwd: root,+ env: { OPENAI_API_KEY: "secret", T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT: "secret" },+ isProcessAlive: () => true,+ probe,+ });+ expect(probe.mock.calls).toEqual([["http://127.0.0.1:15432"], ["http://localhost:6543"]]);+ const output = formatDevStatus(status);+ for (const value of ["password", "secret", "/private", "?token", "OPENAI_API_KEY"]) {+ expect(output).not.toContain(value);+ }+ expect(status.desktop).toContain("running unknown");+ expect(status.mobile).toContain("installed/running unknown");+ }).pipe(Effect.provide(NodeServices.layer)),+ );++ it.effect("does not log malformed runtime contents", () =>+ Effect.gen(function* () {+ const root = fixture();+ const file = writeRuntime(root);+ NodeFS.writeFileSync(file, '{"token":"never-print-this",');+ const log = vi.fn();+ const status = yield* collectDevStatus({ cwd: root, env: {} }).pipe(+ Effect.provideService(Logger.CurrentLoggers, new Set([Logger.make(log)])),+ );+ expect(formatDevStatus(status)).not.toContain("never-print-this");+ expect(log).not.toHaveBeenCalled();+ expect(NodeFS.readFileSync(file, "utf8")).toContain("never-print-this");+ }).pipe(Effect.provide(NodeServices.layer)),+ );+});++describe("dev status HTTP checks and client configuration", () => {+ it.effect("never fetches non-loopback or non-HTTP URLs", () =>+ Effect.gen(function* () {+ const fetch = vi.fn();+ const probe = (origin: string) =>+ probeStatusOrigin(origin).pipe(Effect.provideService(FetchHttpClient.Fetch, fetch));+ expect(yield* probe("https://example.com:443/pair?token=secret")).toContain("not checked");+ expect(yield* probe("file:///tmp/secret")).toContain("invalid");+ expect(statusOrigin("not-a-url-secret")).toBeUndefined();+ expect(fetch).not.toHaveBeenCalled();+ }),+ );++ it.effect("uses credential-free HEAD requests without redirects", () =>+ Effect.gen(function* () {+ const fetch = vi.fn(+ async () =>+ new Response(null, {+ status: 302,+ headers: { location: "https://example.com" },+ }),+ );+ const result = yield* probeStatusOrigin(+ "http://user:secret@localhost:6543/pair?token=secret",+ ).pipe(Effect.provideService(FetchHttpClient.Fetch, fetch));+ expect(result).toContain("readiness unverified");+ expect(fetch).toHaveBeenCalledWith(+ new URL("http://127.0.0.1:6543"),+ expect.objectContaining({+ method: "HEAD",+ redirect: "manual",+ credentials: "omit",+ }),+ );+ }),+ );++ it.effect("reports failed checks without exposing errors", () =>+ Effect.gen(function* () {+ const fetch = vi.fn(async () => {+ throw new Error("secret");+ });+ const result = yield* probeStatusOrigin("http://127.0.0.1:6543").pipe(+ Effect.provideService(FetchHttpClient.Fetch, fetch),+ );+ expect(result).toBe("unavailable (loopback HTTP check failed)");+ }),+ );++ it.effect("checks IPv6 when localhost is not listening on IPv4", () =>+ Effect.gen(function* () {+ const fetch = vi+ .fn()+ .mockRejectedValueOnce(new Error("IPv4 unavailable"))+ .mockResolvedValueOnce(new Response(null, { status: 200 }));+ const result = yield* probeStatusOrigin("http://localhost:6543").pipe(+ Effect.provideService(FetchHttpClient.Fetch, fetch),+ );+ expect(result).toContain("HTTP 200");+ expect(fetch.mock.calls.map(([url]) => String(url))).toEqual([+ "http://127.0.0.1:6543/",+ "http://[::1]:6543/",+ ]);+ }),+ );++ it("reports debug configuration and points to the mobile identity source", () => {+ const status = describeStatusClients({+ T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT: "9222",+ APP_VARIANT: "development",+ T3CODE_IOS_PERSONAL_TEAM: "1",+ T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID: "dev.example.personal",+ });+ expect(status.desktop).toBe("debug port 9222 configured; running unknown");+ expect(status.mobile).toContain("app-identity.mjs");+ expect(status.mobile).toContain("installed/running unknown");+ expect(status.mobile).not.toContain("dev.example.personal");+ });+});diff --git a/scripts/dev-status.ts b/scripts/dev-status.tsnew file mode 100644index 000000000..9737f0091--- /dev/null+++ b/scripts/dev-status.ts@@ -0,0 +1,251 @@+#!/usr/bin/env node++import * as NodeOS from "node:os";++import * as NodeRuntime from "@effect/platform-node/NodeRuntime";+import * as NodeServices from "@effect/platform-node/NodeServices";+import {+ PRODUCT_HOME_DIRNAME,+ resolveGitWorktreePath,+ resolveWorktreeT3Home,+} from "@t3tools/shared/devHome";+import * as Console from "effect/Console";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Option from "effect/Option";+import * as Path from "effect/Path";+import * as Schema from "effect/Schema";+import { Command, Flag } from "effect/unstable/cli";+import { FetchHttpClient, HttpClient } from "effect/unstable/http";++import { loadRepoEnv } from "./lib/public-config.ts";++// Read the existing server-runtime.json without importing server implementation code.+const decodeRuntime = Schema.decodeUnknownEffect(+ Schema.fromJsonString(+ Schema.Struct({+ version: Schema.Literal(1),+ pid: Schema.Int,+ origin: Schema.String,+ devUrl: Schema.optional(Schema.String),+ }),+ ),+);++export const resolveDevStatusHome = Effect.fn("resolveDevStatusHome")(function* (input: {+ readonly cwd: string;+ readonly homeDir?: string | undefined;+ readonly env: Readonly<Record<string, string | undefined>>;+ readonly userHome: string;+}) {+ const path = yield* Path.Path;+ const worktree = yield* resolveGitWorktreePath(input.cwd);+ const worktreeHome = yield* resolveWorktreeT3Home(input.cwd);+ const selected = input.homeDir?.trim() || worktreeHome || input.env.T3CODE_HOME?.trim();+ const expanded =+ selected === "~"+ ? input.userHome+ : selected?.startsWith("~/") || selected?.startsWith("~\\")+ ? path.join(input.userHome, selected.slice(2))+ : selected;+ const home = expanded+ ? path.resolve(input.cwd, expanded)+ : path.join(input.userHome, PRODUCT_HOME_DIRNAME);+ return { worktree, home, dataDir: path.join(home, selected ? "userdata" : "dev") };+});++export function statusOrigin(raw: string | undefined): string | undefined {+ if (!raw) return undefined;+ try {+ const url = new URL(raw);+ return url.protocol === "http:" || url.protocol === "https:" ? url.origin : undefined;+ } catch {+ return undefined;+ }+}++export function isStatusProcessAlive(pid: number): boolean {+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return error instanceof Error && "code" in error && error.code === "EPERM";+ }+}++/** Probe only numeric loopback addresses, without credentials or redirects. */+export const probeStatusOrigin = Effect.fn("probeStatusOrigin")(function* (origin: string) {+ const safe = statusOrigin(origin);+ if (!safe) return "unknown (invalid HTTP origin)";+ const url = new URL(safe);+ if (!["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) {+ return "unknown (non-loopback; not checked)";+ }+ const hosts = url.hostname === "localhost" ? ["127.0.0.1", "[::1]"] : [url.hostname];+ for (const host of hosts) {+ const target = new URL(url);+ target.hostname = host;+ const result = yield* HttpClient.head(target).pipe(+ Effect.timeout("1500 millis"),+ Effect.map(+ (response) =>+ `HTTP ${String(response.status)} (responding; application readiness unverified)`,+ ),+ Effect.option,+ Effect.provide(FetchHttpClient.layer),+ Effect.provideService(FetchHttpClient.RequestInit, {+ redirect: "manual",+ credentials: "omit",+ }),+ );+ if (Option.isSome(result)) return result.value;+ }+ return "unavailable (loopback HTTP check failed)";+});++export function describeStatusClients(env: Readonly<Record<string, string | undefined>>) {+ const debugPort = env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();+ const validDebugPort =+ debugPort && /^\d+$/.test(debugPort) && Number(debugPort) > 0 && Number(debugPort) <= 65535;+ return {+ desktop: `${validDebugPort ? `debug port ${String(Number(debugPort))} configured` : debugPort ? "invalid debug port" : "debug port not configured"}; running unknown`,+ mobile:+ "installed/running unknown; resolve development identity with node .agents/skills/test-t3-mobile/scripts/app-identity.mjs <scheme|ios-bundle-id|android-package>",+ };+}++export const collectDevStatus = Effect.fn("collectDevStatus")(function* (input: {+ readonly cwd: string;+ readonly homeDir?: string | undefined;+ readonly env?: Readonly<Record<string, string | undefined>>;+ readonly userHome?: string;+ readonly isProcessAlive?: (pid: number) => boolean;+ readonly probe?: (origin: string) => Effect.Effect<string>;+}) {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ let root = path.resolve(input.cwd);+ while (!(yield* fs.exists(path.join(root, ".git")))) {+ const parent = path.dirname(root);+ if (parent === root) break;+ root = parent;+ }+ const hasRoot = yield* fs.exists(path.join(root, ".git"));+ if (!hasRoot) root = path.resolve(input.cwd);+ const env = input.env ?? loadRepoEnv({ repoRoot: root });+ const home = yield* resolveDevStatusHome({+ ...input,+ env,+ userHome: input.userHome ?? NodeOS.homedir(),+ });+ const runtimePath = path.join(home.dataDir, "server-runtime.json");+ const tracePath = path.join(home.dataDir, "logs", "server.trace.ndjson");+ // Decode diagnostics can contain file contents; status must never print them.+ const runtime = yield* fs+ .readFileString(runtimePath)+ .pipe(Effect.flatMap(decodeRuntime), Effect.option);+ const missing: string[] = [];+ if (!hasRoot) missing.push("Git checkout root not found");+ if (!(yield* fs.exists(path.join(root, "node_modules"))))+ missing.push("dependencies (node_modules)");+ if (Number(process.versions.node.split(".")[0]) < 24) missing.push("Node 24 or newer");+ if (!(yield* fs.exists(home.dataDir))) missing.push("data directory");+ // Desktop artifacts are optional for web-only development; report them separately.+ const desktopArtifactsMissing: string[] = [];+ for (const artifact of [+ "apps/desktop/dist-electron/main.cjs",+ "apps/desktop/dist-electron/preload.cjs",+ "apps/server/dist/bin.mjs",+ ]) {+ if (!(yield* fs.exists(path.join(root, artifact)))) desktopArtifactsMissing.push(artifact);+ }+ const tracePresent = yield* fs.exists(tracePath);+ const clients = describeStatusClients(env);+ let descriptor = "missing, empty, invalid, or unreadable; running unknown";+ let serverOrigin: string | undefined;+ let webOrigin: string | undefined;+ let serverReadiness = "unknown (no usable runtime descriptor)";+ let webReadiness = serverReadiness;+ if (Option.isSome(runtime)) {+ const state = runtime.value;+ serverOrigin = statusOrigin(state.origin);+ webOrigin = statusOrigin(state.devUrl);+ const alive = (input.isProcessAlive ?? isStatusProcessAlive)(state.pid);+ descriptor = alive+ ? `pid ${String(state.pid)} exists (identity unverified)`+ : `stale (pid ${String(state.pid)} is absent or invalid)`;+ const probe = input.probe ?? probeStatusOrigin;+ const recordedServerOrigin = serverOrigin;+ const recordedWebOrigin = webOrigin;+ serverReadiness = !alive+ ? "unavailable (stale descriptor)"+ : recordedServerOrigin+ ? yield* probe(recordedServerOrigin)+ : "unknown (invalid recorded origin)";+ webReadiness = !alive+ ? "unknown (stale descriptor; not checked)"+ : recordedWebOrigin+ ? yield* probe(recordedWebOrigin)+ : "unknown (no dev web origin recorded)";+ } else {+ missing.push("usable server-runtime.json");+ }+ return {+ root,+ ...home,+ runtimePath,+ descriptor,+ server: { origin: serverOrigin, readiness: serverReadiness },+ web: { origin: webOrigin, readiness: webReadiness },+ trace: { path: tracePath, present: tracePresent },+ ...clients,+ missing,+ desktopArtifactsMissing,+ };+});++export function formatDevStatus(+ status: Effect.Success<ReturnType<typeof collectDevStatus>>,+): string {+ return [+ `Root: ${status.root}`,+ `Worktree: ${status.worktree ?? "main checkout or not a linked worktree"}`,+ `Akeru home: ${status.home}`,+ `Data directory: ${status.dataDir}`,+ `Runtime: ${status.runtimePath} — ${status.descriptor}`,+ `Server: ${status.server.origin ?? "unknown"} — ${status.server.readiness}`,+ `Web: ${status.web.origin ?? "unknown"} — ${status.web.readiness}`,+ `Trace: ${status.trace.path} (${status.trace.present ? "present" : "missing"})`,+ `Desktop: ${status.desktop}`,+ `Desktop build (optional): ${status.desktopArtifactsMissing.length ? `not built (${status.desktopArtifactsMissing.join("; ")})` : "built"}`,+ `Mobile configuration: ${status.mobile}`,+ `Missing prerequisites: ${status.missing.length ? status.missing.join("; ") : "none detected (provider and native tools not checked)"}`,+ ].join("\n");+}++const command = Command.make(+ "dev-status",+ {+ homeDir: Flag.string("home-dir").pipe(Flag.optional),+ },+ ({ homeDir }) =>+ collectDevStatus({ cwd: process.cwd(), homeDir: Option.getOrUndefined(homeDir) }).pipe(+ Effect.flatMap((status) => Console.log(formatDevStatus(status))),+ ),+);++if (import.meta.main) {+ Command.run(command, { version: "0.0.0" }).pipe(+ Effect.provide(NodeServices.layer),+ Effect.catchCause(() =>+ Effect.gen(function* () {+ process.exitCode = 1;+ yield* Console.error(+ "Could not read dev status. Check local directory access and configuration.",+ );+ }),+ ),+ NodeRuntime.runMain,+ );+}diff --git a/scripts/setup-worktree-env.test.ts b/scripts/setup-worktree-env.test.tsnew file mode 100644index 000000000..af136428c--- /dev/null+++ b/scripts/setup-worktree-env.test.ts@@ -0,0 +1,55 @@+// @effect-diagnostics nodeBuiltinImport:off+import * as NodeFS from "node:fs";+import * as NodeOS from "node:os";+import * as NodePath from "node:path";+import { assert, it } from "@effect/vitest";+import { setupWorktreeEnv } from "./setup-worktree-env.ts";++function fixture(run: (root: string, worktree: string) => void) {+ const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-setup-"));+ const worktree = NodePath.join(root, "worktree with spaces");+ NodeFS.mkdirSync(worktree);+ try {+ run(root, worktree);+ } finally {+ NodeFS.rmSync(root, { recursive: true, force: true });+ }+}++it("copies private configuration without sharing later writes", () => {+ fixture((root, worktree) => {+ NodeFS.writeFileSync(NodePath.join(root, ".env"), "EXAMPLE=initial\n");+ setupWorktreeEnv(worktree, root);+ const destination = NodePath.join(worktree, ".env");+ assert.isFalse(NodeFS.lstatSync(destination).isSymbolicLink());+ NodeFS.writeFileSync(destination, "EXAMPLE=local\n");+ setupWorktreeEnv(worktree, root);+ assert.equal(NodeFS.readFileSync(destination, "utf8"), "EXAMPLE=local\n");+ assert.equal(NodeFS.readFileSync(NodePath.join(root, ".env"), "utf8"), "EXAMPLE=initial\n");+ });+});++it("accepts missing optional source configuration", () => {+ fixture((root, worktree) => {+ assert.include(setupWorktreeEnv(worktree, undefined), "skipped");+ assert.include(setupWorktreeEnv(worktree, root), "skipped");+ assert.isFalse(NodeFS.existsSync(NodePath.join(worktree, ".env")));+ });+});++it("refuses existing symlinks without modifying their target", () => {+ fixture((root, worktree) => {+ const source = NodePath.join(root, ".env");+ NodeFS.writeFileSync(source, "EXAMPLE=shared\n");+ NodeFS.symlinkSync(source, NodePath.join(worktree, ".env"));+ assert.throws(() => setupWorktreeEnv(worktree, root), "symlink");+ assert.equal(NodeFS.readFileSync(source, "utf8"), "EXAMPLE=shared\n");+ });+});++it("refuses a directory instead of an environment file", () => {+ fixture((root, worktree) => {+ NodeFS.mkdirSync(NodePath.join(worktree, ".env"));+ assert.throws(() => setupWorktreeEnv(worktree, root), "regular file");+ });+});diff --git a/scripts/setup-worktree-env.ts b/scripts/setup-worktree-env.tsnew file mode 100644index 000000000..7cd70dda0--- /dev/null+++ b/scripts/setup-worktree-env.ts@@ -0,0 +1,36 @@+// @effect-diagnostics nodeBuiltinImport:off - worktree setup runs before the application runtime.+import * as NodeFS from "node:fs";+import * as NodePath from "node:path";+import * as NodeURL from "node:url";++/** Copies initial configuration without sharing later edits with the source checkout. */+export function setupWorktreeEnv(worktree: string, projectRoot: string | undefined) {+ const destination = NodePath.join(worktree, ".env");+ try {+ const existing = NodeFS.lstatSync(destination);+ if (existing.isSymbolicLink()) {+ throw new Error(+ "Worktree .env is a symlink. Replace it with a private copy before editing it.",+ );+ }+ if (!existing.isFile()) throw new Error("Worktree .env is not a regular file.");+ return "Kept the existing worktree .env.";+ } catch (error) {+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;+ }+ if (!projectRoot?.trim()) return "No project root supplied; skipped optional .env copy.";+ const source = NodePath.join(NodePath.resolve(projectRoot), ".env");+ if (!NodeFS.existsSync(source)) return "Project has no .env; skipped optional .env copy.";+ NodeFS.copyFileSync(source, destination, NodeFS.constants.COPYFILE_EXCL);+ NodeFS.chmodSync(destination, 0o600);+ return "Copied .env into the worktree; future edits stay local.";+}++if (+ process.argv[1] &&+ NodePath.resolve(process.argv[1]) === NodeURL.fileURLToPath(import.meta.url)+) {+ process.stdout.write(+ `[setup-worktree] ${setupWorktreeEnv(process.cwd(), process.env.T3CODE_PROJECT_ROOT)}\n`,+ );+}diff --git a/t3.json b/t3.jsonindex 022dc84b6..b2e430615 100644--- a/t3.json+++ b/t3.json@@ -4,7 +4,7 @@"scripts": [{"name": "Setup Worktree",- "command": "vp i && ln -sf $T3CODE_PROJECT_ROOT/.env .env && node apps/web/scripts/warm-dep-cache.ts",+ "command": "vp i && node scripts/setup-worktree-env.ts && node apps/web/scripts/warm-dep-cache.ts","icon": "configure","runOnWorktreeCreate": true}