Open History to see the last commit
1import {
2 type AuthClientPresentationMetadata,
3 ServerPrepareTriageError,
4 type ServerPrepareTriageInput,
5 type ServerPrepareTriageResult,
6} from "@t3tools/contracts";
7import * as Context from "effect/Context";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Path from "effect/Path";
12
13import packageJson from "../../package.json" with { type: "json" };
14import * as ServerConfig from "../config.ts";
15import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
16import { buildTriageAppPrompt, type TriageSourceClone } from "./triagePrompt.ts";
17import { triageSourceCacheDir, writeTriageSession } from "./triageSession.ts";
18
19const T3CODE_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
20
21// No tty: a credential prompt would hang until the timeout, so git must fail
22// instead. An empty GIT_ASKPASS also skips core.askPass and SSH_ASKPASS helpers.
23const GIT_ENV = {
24 GIT_TERMINAL_PROMPT: "0",
25 GIT_ASKPASS: "",
26 LC_ALL: "C",
27} satisfies NodeJS.ProcessEnv;
28
29/** Starts in-app triage sessions: the same files `t3 triage` writes, plus a source clone. */
30export class TriageService extends Context.Service<
31 TriageService,
32 {
33 readonly prepare: (
34 input: ServerPrepareTriageInput,
35 ) => Effect.Effect<ServerPrepareTriageResult, ServerPrepareTriageError>;
36 }
37>()("t3/triage/TriageService") {}
38
39const describeClient = (client: AuthClientPresentationMetadata) =>
40 [
41 client.label ?? "an unknown client",
42 client.appVersion === undefined ? undefined : `version ${client.appVersion}`,
43 client.os === undefined ? undefined : `on ${client.os}`,
44 client.browser === undefined ? undefined : `in ${client.browser}`,
45 client.webDeployment === "hosted" ? "(app.t3.codes)" : undefined,
46 ]
47 .filter((part) => part !== undefined)
48 .join(" ");
49
50/** Picks the release tag for `version`, or `main` when the build has no tag. */
51export const pickSourceRef = (lsRemoteOutput: string, version: string) => {
52 const commits = new Map(
53 lsRemoteOutput
54 .split("\n")
55 .map((line) => line.trim().split("\t"))
56 .filter((fields): fields is [string, string] => fields.length === 2)
57 .map(([commit, ref]) => [ref, commit]),
58 );
59 const tag = `v${version}`;
60 // Annotated tags list the tag object first and the commit as `^{}`.
61 const tagCommit = commits.get(`refs/tags/${tag}^{}`) ?? commits.get(`refs/tags/${tag}`);
62 if (tagCommit !== undefined) return { ref: tag, commit: tagCommit };
63 const mainCommit = commits.get("refs/heads/main");
64 return mainCommit === undefined ? undefined : { ref: "main", commit: mainCommit };
65};
66
67const make = Effect.gen(function* () {
68 const config = yield* ServerConfig.ServerConfig;
69 const git = yield* GitVcsDriver.GitVcsDriver;
70 const fs = yield* FileSystem.FileSystem;
71 const path = yield* Path.Path;
72 const sourceDir = triageSourceCacheDir(config.baseDir, path);
73 // Beside the cache, not in it: the playbook has agents prune the cache, and a
74 // clone in progress must not look like a stale entry. Same filesystem, so the
75 // finished clone moves in with a rename.
76 const stagingDir = `${sourceDir}-staging`;
77 const serverVersion = packageJson.version;
78
79 const runGit = (operation: string, cwd: string, args: ReadonlyArray<string>, timeoutMs: number) =>
80 git.execute({ operation: `TriageService.${operation}`, cwd, args, timeoutMs, env: GIT_ENV });
81
82 // Clones outlive the request that started them: a fresh clone takes tens of
83 // seconds, and the user is writing their description meanwhile.
84 const serviceScope = yield* Effect.scope;
85 // Clones a previous server process left half done.
86 yield* fs.remove(stagingDir, { recursive: true }).pipe(Effect.ignore);
87
88 // Fetches the exact commit `ls-remote` resolved, so the folder the session
89 // names is the one that appears even when main moves meanwhile.
90 const cloneSource = Effect.fn("TriageService.cloneSource")(function* (commit: string) {
91 yield* fs.makeDirectory(stagingDir, { recursive: true });
92 const staging = yield* fs.makeTempDirectory({ directory: stagingDir, prefix: "clone-" });
93 const directory = path.join(sourceDir, commit);
94 yield* Effect.gen(function* () {
95 yield* runGit("initSource", staging, ["init", "--quiet"], 10_000);
96 yield* runGit(
97 "addSourceRemote",
98 staging,
99 ["remote", "add", "origin", T3CODE_REPOSITORY_URL],
100 10_000,
101 );
102 yield* runGit(
103 "fetchSource",
104 staging,
105 ["fetch", "--depth", "1", "--filter=blob:none", "origin", commit],
106 600_000,
107 );
108 yield* runGit("checkoutSource", staging, ["checkout", "--quiet", "FETCH_HEAD"], 600_000);
109 yield* fs.rename(staging, directory).pipe(
110 // A concurrent session cloned the same commit first; keep theirs.
111 Effect.catch((error) =>
112 fs
113 .exists(directory)
114 .pipe(Effect.flatMap((exists) => (exists ? Effect.void : Effect.fail(error)))),
115 ),
116 );
117 }).pipe(
118 // Gone after a successful rename; otherwise a failed or losing clone.
119 Effect.ensuring(fs.remove(staging, { recursive: true }).pipe(Effect.ignore)),
120 );
121 });
122
123 // Release tags never move, so one lookup serves every later session. Builds
124 // with no tag track main, which does move, so they look it up each time.
125 let releaseSource: { readonly ref: string; readonly commit: string } | undefined;
126 const resolveSource = Effect.fn("TriageService.resolveSource")(function* () {
127 if (releaseSource !== undefined) return releaseSource;
128 const tag = `refs/tags/v${serverVersion}`;
129 const listed = yield* runGit(
130 "resolveSourceRef",
131 sourceDir,
132 ["ls-remote", T3CODE_REPOSITORY_URL, tag, `${tag}^{}`, "refs/heads/main"],
133 // Triage still starts without source; a dead network should not stall it.
134 5_000,
135 );
136 const source = pickSourceRef(listed.stdout, serverVersion);
137 if (source?.ref !== "main") releaseSource = source;
138 return source;
139 });
140
141 // Commits with a clone running, so sessions started meanwhile share it.
142 const cloning = new Set<string>();
143
144 // The playbook's own layout: one folder per commit under the source cache, so
145 // the agent finds and reuses this clone instead of making another. The folder
146 // appears only once the clone is complete.
147 const startSourceClone = Effect.fn("TriageService.startSourceClone")(function* () {
148 yield* fs.makeDirectory(sourceDir, { recursive: true });
149 const source = yield* resolveSource();
150 if (source === undefined) {
151 return {
152 _tag: "failed",
153 serverVersion,
154 reason: "the repository listed neither the release tag nor main.",
155 } satisfies TriageSourceClone;
156 }
157 const directory = path.join(sourceDir, source.commit);
158 if (yield* fs.exists(directory)) {
159 // Our clones appear only when complete, but an agent may have cloned
160 // here by hand and stopped partway.
161 // Without its own .git, rev-parse would read a parent repository.
162 const head = (yield* fs.exists(path.join(directory, ".git")))
163 ? yield* runGit("checkSource", directory, ["rev-parse", "HEAD"], 10_000).pipe(
164 Effect.map((result) => result.stdout.trim()),
165 Effect.orElseSucceed(() => ""),
166 )
167 : "";
168 return head === source.commit
169 ? ({ _tag: "cloned", directory, serverVersion, ...source } as const)
170 : ({
171 _tag: "failed",
172 serverVersion,
173 reason: `${directory} exists but is not a complete checkout of ${source.commit}. Remove it first.`,
174 } satisfies TriageSourceClone);
175 }
176 if (!cloning.has(source.commit)) {
177 cloning.add(source.commit);
178 yield* cloneSource(source.commit).pipe(
179 Effect.ignoreCause({ log: true }),
180 Effect.ensuring(Effect.sync(() => cloning.delete(source.commit))),
181 Effect.forkIn(serviceScope),
182 );
183 }
184 return { _tag: "cloning", directory, serverVersion, ...source } as const;
185 });
186
187 const prepare: TriageService["Service"]["prepare"] = Effect.fn("TriageService.prepare")(
188 function* (input) {
189 const sourceClone = yield* startSourceClone().pipe(
190 Effect.catch((error) =>
191 Effect.succeed<TriageSourceClone>({
192 _tag: "failed",
193 serverVersion,
194 reason: error.message,
195 }),
196 ),
197 );
198 const session = yield* writeTriageSession({
199 baseDir: config.baseDir,
200 paths: config,
201 entry: { kind: "app", client: describeClient(input.client) },
202 server: `running (pid ${String(process.pid)}, version ${serverVersion}); this session runs inside it`,
203 sourceClone,
204 }).pipe(
205 Effect.provideService(FileSystem.FileSystem, fs),
206 Effect.provideService(Path.Path, path),
207 Effect.mapError((cause) => new ServerPrepareTriageError({ cause })),
208 );
209 return { prompt: buildTriageAppPrompt(session.promptFilePath) };
210 },
211 );
212
213 return TriageService.of({ prepare });
214});
215
216export const layer = Layer.effect(TriageService, make);