Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .vite-hooks/pre-push
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,5 @@ if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
fi
# With no base found, check:changed falls back to the nearest remote main.
echo "pre-push: vp run check:changed ${base:-<nearest remote main>}"
unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_COMMON_DIR GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES
vp run check:changed ${base:+"$base"}
2 changes: 1 addition & 1 deletion apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1350,7 +1350,7 @@ export const layerPullRequestsToolkit = toolkitRegistration(
PullRequestsHandlers.layer,
).pipe(Layer.provide(PullRequestWatchService.layer));

export const layerEventsToolkit = toolkitRegistration(EventsToolkit, EventsHandlers.layer).pipe(
const layerEventsToolkit = toolkitRegistration(EventsToolkit, EventsHandlers.layer).pipe(
Layer.provide(PullRequestWatchService.layer),
);

Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/orchestration-v2/contextBoundary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3too
import { cancelledBeforeStart } from "./RestartBackgroundNote.ts";

/** A fresh-session schedule run starts a side conversation; the thread's own one continues past it. */
export function isScheduledFreshRun(
function isScheduledFreshRun(
run: Pick<OrchestrationV2Run, "freshContext" | "userMessageId">,
turnItems: OrchestrationV2ThreadProjection["turnItems"],
): boolean {
Expand Down
13 changes: 5 additions & 8 deletions apps/server/src/orchestration-v2/eventSubscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,20 @@ export const emptyCursor = (): SubscriptionCursor => ({
deliveredSignatures: {},
});

export function canonicalAuthor(login: string): string {
function canonicalAuthor(login: string): string {
return login
.trim()
.toLowerCase()
.replace(/\[bot\]$/i, "");
}

export function authorIgnored(
login: string | null | undefined,
ignore: readonly string[],
): boolean {
function authorIgnored(login: string | null | undefined, ignore: readonly string[]): boolean {
if (login == null || login.trim() === "") return false;
const key = canonicalAuthor(login);
return ignore.some((entry) => canonicalAuthor(entry) === key);
}

export function normalizePullRequestUrl(raw: string): string {
function normalizePullRequestUrl(raw: string): string {
const url = new URL(raw);
url.hash = "";
url.search = "";
Expand Down Expand Up @@ -95,7 +92,7 @@ export interface DeliveryInput {
readonly maxWakesPerHour?: number | null | undefined;
}

export function normalizeDelivery(
function normalizeDelivery(
input: DeliveryInput | undefined,
):
| { readonly ok: true; readonly delivery: EventDeliveryPolicy }
Expand Down Expand Up @@ -159,7 +156,7 @@ function validateQuietHours(hours: QuietHours): string | null {
}

/** Minutes from midnight in the zone. Throws when the zone is invalid. */
export function minutesInZone(nowMs: number, timeZone: string): number {
function minutesInZone(nowMs: number, timeZone: string): number {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone,
hour: "2-digit",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@ import {
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { ChildProcess, ChildProcessSpawner } from "effect/process";

import { ClaudeOrchestratorReplayHarness } from "../Adapters/ClaudeAdapterV2.testkit.ts";
import { CodexOrchestratorReplayHarness } from "../Adapters/CodexAdapterV2.testkit.ts";
Expand All @@ -32,6 +28,7 @@ import {
decodeProviderReplayNdjson,
materializeReplayTranscriptWorkspace,
} from "@t3tools/provider-testing/replayTranscript";
import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";

const CODEX_MODEL_SELECTION = {
instanceId: ProviderInstanceId.make("codex"),
Expand All @@ -54,51 +51,6 @@ const CODEX_READ_ONLY_NEVER_POLICY = {
},
} as const;

class ThreadForkGitCommandError extends Schema.TaggedError<ThreadForkGitCommandError>()(
"ThreadForkGitCommandError",
{
command: Schema.String,
exitCode: Schema.Number,
},
) {
override get message(): string {
return `${this.command} failed with exit ${this.exitCode}.`;
}
}

function runGit(
cwd: string,
args: ReadonlyArray<string>,
): Effect.Effect<
void,
ThreadForkGitCommandError | PlatformError.PlatformError,
ChildProcessSpawner.ChildProcessSpawner
> {
return Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const exitCode = yield* spawner.exitCode(ChildProcess.make("git", args, { cwd }));
if (Number(exitCode) !== 0) {
return yield* new ThreadForkGitCommandError({
command: `git ${args.join(" ")}`,
exitCode: Number(exitCode),
});
}
});
}

const makeCheckpointWorkspace = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const cwd = yield* fs.makeTempDirectory({ prefix: "t3-orchestrator-v2-thread-fork-" });
yield* runGit(cwd, ["init"]);
yield* runGit(cwd, ["config", "user.name", "T3 Code Test"]);
yield* runGit(cwd, ["config", "user.email", "t3code-test@example.com"]);
yield* fs.writeFileString(path.join(cwd, "README.md"), "# thread fork\n");
yield* runGit(cwd, ["add", "README.md"]);
yield* runGit(cwd, ["commit", "-m", "initial"]);
return cwd;
});

function readTranscript(transcriptPath: string) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
Expand Down Expand Up @@ -145,12 +97,7 @@ describe("orchestration V2 thread fork", () => {
const rawTranscript = yield* readTranscript(CLAUDE_TRANSCRIPT_PATH);
const transcript = yield* ClaudeOrchestratorReplayHarness.decodeTranscript(rawTranscript);
const forkedNativeSessionId = metadataString(transcript, "forkedNativeSessionId");
const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) =>
Effect.service(FileSystem.FileSystem).pipe(
Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
Effect.orDie,
),
);
const cwd = yield* checkpointWorkspace("thread-fork");

const materialized = yield* Effect.gen(function* () {
const ids = yield* IdAllocator.IdAllocatorV2;
Expand Down Expand Up @@ -283,12 +230,7 @@ describe("orchestration V2 thread fork", () => {
it.effect("forks a Codex native thread at the selected native turn boundary", () =>
Effect.gen(function* () {
const rawTranscript = yield* readTranscript(PRIOR_TURN_TRANSCRIPT_PATH);
const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) =>
Effect.service(FileSystem.FileSystem).pipe(
Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
Effect.orDie,
),
);
const cwd = yield* checkpointWorkspace("thread-fork");
const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript(
materializeReplayTranscriptWorkspace(rawTranscript, cwd),
);
Expand Down Expand Up @@ -469,12 +411,7 @@ describe("orchestration V2 thread fork", () => {
transcript,
"sourceAssistantMessageUuids",
);
const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) =>
Effect.service(FileSystem.FileSystem).pipe(
Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
Effect.orDie,
),
);
const cwd = yield* checkpointWorkspace("thread-fork");

const materialized = yield* Effect.gen(function* () {
const ids = yield* IdAllocator.IdAllocatorV2;
Expand Down Expand Up @@ -678,12 +615,7 @@ describe("orchestration V2 thread fork", () => {
throw new Error("Claude fork-local rollback transcript is missing expected prompts.");
}

const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) =>
Effect.service(FileSystem.FileSystem).pipe(
Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
Effect.orDie,
),
);
const cwd = yield* checkpointWorkspace("thread-fork");

const materialized = yield* Effect.gen(function* () {
const ids = yield* IdAllocator.IdAllocatorV2;
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/provider/agentContextBudget.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"claudeSystemAppendBytes": 5930,
"codexAdditionalContextBytes": 7324,
"mcpToolListJsonBytes": 61564
"mcpToolListJsonBytes": 61917
}
133 changes: 133 additions & 0 deletions apps/server/src/testUtils/gitConfig.setup.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { afterEach, describe, expect, it, vi } from "@effect/vitest";
import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/process";

import { configureTestGitEnv } from "./gitConfig.setup.ts";

const runCleanGit = (cwd: string, args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const env: NodeJS.ProcessEnv = { ...process.env };
configureTestGitEnv(env);
const handle = yield* spawner.spawn(
ChildProcess.make("git", args, { cwd, env, extendEnv: false }),
);
const [stdout, exitCode] = yield* Effect.all(
[
Stream.runCollect(handle.stdout).pipe(
Effect.map((chunks) => Buffer.concat(chunks).toString("utf8").trim()),
),
handle.exitCode,
],
{ concurrency: "unbounded" },
);
expect(Number(exitCode)).toBe(0);
return stdout;
}).pipe(Effect.scoped);

describe("git test environment scrub", () => {
afterEach(() => {
vi.unstubAllEnvs();
});

it("strips inherited GIT_* variables and sets deterministic fixture git config", () => {
const env: NodeJS.ProcessEnv = {
PATH: "/usr/bin",
GIT_DIR: "/scratch/.git",
GIT_WORK_TREE: "/scratch",
GIT_INDEX_FILE: "/scratch/.git/index",
GIT_COMMON_DIR: "/scratch/.git",
git_object_directory: "/scratch/.git/objects",
GIT_CONFIG_PARAMETERS: "'user.name=Leaked'",
GIT_CONFIG_COUNT: "1",
GIT_CONFIG_KEY_0: "user.name",
GIT_CONFIG_VALUE_0: "Leaked",
};

configureTestGitEnv(env);

expect(env.PATH).toBe("/usr/bin");
expect(env.GIT_DIR).toBeUndefined();
expect(env.GIT_WORK_TREE).toBeUndefined();
expect(env.GIT_INDEX_FILE).toBeUndefined();
expect(env.GIT_COMMON_DIR).toBeUndefined();
expect(env.git_object_directory).toBeUndefined();
expect(env.GIT_CONFIG_PARAMETERS).toBeUndefined();
expect(env.GIT_CONFIG_COUNT).toBe("6");
expect(env.GIT_CONFIG_KEY_0).toBe("core.autocrlf");
expect(env.GIT_CONFIG_VALUE_0).toBe("false");
expect(env.GIT_CONFIG_KEY_3).toBe("commit.gpgsign");
expect(env.GIT_CONFIG_VALUE_3).toBe("false");
expect(env.GIT_CONFIG_KEY_5).toBe("init.defaultBranch");
expect(env.GIT_CONFIG_VALUE_5).toBe("main");
});

it.effect(
"prevents checkpointWorkspace from leaking into a scratch non-bare repo under GIT_DIR and GIT_INDEX_FILE",
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const scratchDir = yield* fs.makeTempDirectoryScoped({
prefix: "t3-git-scrub-non-bare-",
});
yield* runCleanGit(scratchDir, ["init"]);
yield* runCleanGit(scratchDir, ["config", "user.name", "Scratch Owner"]);
yield* runCleanGit(scratchDir, ["config", "user.email", "scratch@example.invalid"]);
yield* fs.writeFileString(path.join(scratchDir, "scratch.txt"), "baseline\n");
yield* runCleanGit(scratchDir, ["add", "scratch.txt"]);
yield* runCleanGit(scratchDir, ["commit", "-m", "scratch baseline"]);

const beforeHead = yield* runCleanGit(scratchDir, ["rev-parse", "HEAD"]);
const scratchGitDir = path.join(scratchDir, ".git");
vi.stubEnv("GIT_DIR", scratchGitDir);
vi.stubEnv("GIT_WORK_TREE", scratchDir);
vi.stubEnv("GIT_COMMON_DIR", scratchGitDir);
vi.stubEnv("GIT_INDEX_FILE", path.join(scratchGitDir, "index"));

const workspace = yield* checkpointWorkspace("scrub-non-bare");

expect(yield* runCleanGit(workspace, ["log", "-1", "--format=%s"])).toBe("initial");
expect(yield* runCleanGit(scratchDir, ["rev-parse", "HEAD"])).toBe(beforeHead);
expect(yield* runCleanGit(scratchDir, ["rev-list", "--count", "HEAD"])).toBe("1");
expect(yield* runCleanGit(scratchDir, ["config", "--local", "user.name"])).toBe(
"Scratch Owner",
);
expect(yield* runCleanGit(scratchDir, ["config", "--local", "user.email"])).toBe(
"scratch@example.invalid",
);
expect(yield* runCleanGit(scratchDir, ["status", "--porcelain"])).toBe("");
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

it.effect(
"prevents checkpointWorkspace from leaking into a scratch bare repo under GIT_DIR and GIT_INDEX_FILE",
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const bareDir = yield* fs.makeTempDirectoryScoped({
prefix: "t3-git-scrub-bare-",
});
yield* runCleanGit(bareDir, ["init", "--bare"]);

const scratchIndex = path.join(bareDir, "index");
vi.stubEnv("GIT_DIR", bareDir);
vi.stubEnv("GIT_INDEX_FILE", scratchIndex);

const workspace = yield* checkpointWorkspace("scrub-bare");

expect(yield* runCleanGit(workspace, ["log", "-1", "--format=%s"])).toBe("initial");
expect(yield* runCleanGit(bareDir, ["for-each-ref"])).toBe("");
expect(yield* runCleanGit(bareDir, ["config", "--local", "--list"])).not.toContain(
"T3 Code Test",
);
expect(yield* fs.exists(scratchIndex)).toBe(false);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
21 changes: 14 additions & 7 deletions apps/server/src/testUtils/gitConfig.setup.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// Override inherited autocrlf, signing and init-branch settings through env so every git child gets stable fixtures.
const entries: ReadonlyArray<readonly [key: string, value: string]> = [
["core.autocrlf", "false"],
["core.filemode", "false"],
Expand All @@ -8,9 +7,17 @@ const entries: ReadonlyArray<readonly [key: string, value: string]> = [
["init.defaultBranch", "main"],
];

const existing = Number(process.env.GIT_CONFIG_COUNT ?? "0");
process.env.GIT_CONFIG_COUNT = String(existing + entries.length);
entries.forEach(([key, value], index) => {
process.env[`GIT_CONFIG_KEY_${existing + index}`] = key;
process.env[`GIT_CONFIG_VALUE_${existing + index}`] = value;
});
export function configureTestGitEnv(env: NodeJS.ProcessEnv): void {
for (const key of Object.keys(env)) {
if (key.toUpperCase().startsWith("GIT_")) {
delete env[key];
}
}
env.GIT_CONFIG_COUNT = String(entries.length);
entries.forEach(([key, value], index) => {
env[`GIT_CONFIG_KEY_${index}`] = key;
env[`GIT_CONFIG_VALUE_${index}`] = value;
});
}

configureTestGitEnv(process.env);
16 changes: 0 additions & 16 deletions packages/client-runtime/src/operations/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -630,22 +630,6 @@ export const setThreadStanding = Effect.fn("EnvironmentCommands.setThreadStandin
});
});

export interface SetThreadDelegationNudgeInput extends ThreadCommandInput {
readonly enabled: boolean;
readonly thresholds?: ReadonlyArray<number>;
}
export const setThreadDelegationNudge = Effect.fn("EnvironmentCommands.setThreadDelegationNudge")(
function* (input: SetThreadDelegationNudgeInput) {
return yield* dispatch({
type: "thread.delegation-nudge.set",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
enabled: input.enabled,
...(input.thresholds === undefined ? {} : { thresholds: [...input.thresholds] }),
});
},
);

export interface SetThreadAutoSettleInput extends ThreadCommandInput {
readonly enabled: boolean;
}
Expand Down
Loading
Loading