Open History to see the last commit
1import {
2 type ModelSelection,
3 PROJECT_FILE_BACKED_SETTINGS,
4 PROJECT_SCOPED_SERVER_SETTING_KEYS,
5 type ProjectFileBackedSettingKey,
6 type ProjectId,
7 type ProjectScopedServerSettingKey,
8 type ProjectSettingsOverrides,
9 type ResolvedServerSettings,
10 type ServerSettings,
11 type T3ProjectFile,
12 type ThreadEnvMode,
13 type WorktreeCleanupRules,
14} from "@t3tools/contracts";
15import { normalizeProjectPathForComparison } from "./path.ts";
16import { isModelSelectionProviderEnabled } from "./serverSettings.ts";
17
18/**
19 * Where a project-scoped value came from. The order is the priority order:
20 * a project override, then the environment value, then the repository's
21 * t3.json for keys in `PROJECT_FILE_BACKED_SETTINGS`, then the built-in
22 * default (reported as "environment", since that is what the environment
23 * value is when nothing set it).
24 */
25export type ProjectSettingSource = "environment" | "project" | "t3.json";
26
27export type ProjectSettingSources = Readonly<
28 Record<ProjectScopedServerSettingKey, ProjectSettingSource>
29>;
30
31export interface ResolvedProjectSettings<Settings extends ServerSettings = ServerSettings> {
32 /** Environment settings with the project's overrides applied. */
33 readonly settings: Settings;
34 /** Where each scopable key's effective value came from. */
35 readonly sources: ProjectSettingSources;
36 /** The project's raw override entry; `{}` when it has none. */
37 readonly overrides: ProjectSettingsOverrides;
38}
39
40const EMPTY_OVERRIDES: ProjectSettingsOverrides = {};
41
42const ENVIRONMENT_SOURCES: ProjectSettingSources = Object.fromEntries(
43 PROJECT_SCOPED_SERVER_SETTING_KEYS.map((key) => [key, "environment"]),
44) as Record<ProjectScopedServerSettingKey, ProjectSettingSource>;
45
46/** Cheap check so hot paths skip the projectId lookup when nothing is overridden. */
47export function hasProjectSettingsOverrides(
48 settings: Pick<ServerSettings, "projectSettingsOverrides">,
49): boolean {
50 for (const entry of Object.values(settings.projectSettingsOverrides)) {
51 // A forward-compatible decode can leave an unknown value as a present
52 // undefined; that is not an override.
53 if (Object.values(entry).some((value) => value !== undefined)) return true;
54 }
55 return false;
56}
57
58/**
59 * The project aggregate's own model and workspace fields. They remain the
60 * source of truth until the server has folded them into the override record;
61 * after the fold the record alone decides, so a reset there cannot be undone
62 * by a stale aggregate value.
63 */
64export interface LegacyProjectSettingsFields {
65 readonly defaultModelSelection?: ModelSelection | null | undefined;
66 readonly defaultThreadEnvMode?: ThreadEnvMode | null | undefined;
67}
68
69/**
70 * Apply one project's overrides on top of environment settings. A model
71 * override whose provider is disabled on this environment falls back to the
72 * environment value, the same guard the environment-level selection gets.
73 */
74export function resolveProjectSettings(
75 settings: ServerSettings,
76 projectId: ProjectId | null,
77 // Nullable, not just optional: the mobile new-task flow passes its selected
78 // project straight through, and that is null until the shell snapshot lands.
79 project?: LegacyProjectSettingsFields | null,
80): ResolvedProjectSettings;
81/**
82 * With the checkout's decoded t3.json (or null for a missing or invalid
83 * one), every file-backed key resolves to a concrete value: the file fills
84 * keys whose project and environment tiers are both unset, and the built-in
85 * default fills what is left.
86 */
87export function resolveProjectSettings(
88 settings: ServerSettings,
89 projectId: ProjectId | null,
90 project: LegacyProjectSettingsFields | null | undefined,
91 projectFile: T3ProjectFile | null,
92): ResolvedProjectSettings<ResolvedServerSettings>;
93export function resolveProjectSettings(
94 settings: ServerSettings,
95 projectId: ProjectId | null,
96 project?: LegacyProjectSettingsFields | null,
97 projectFile?: T3ProjectFile | null,
98): ResolvedProjectSettings {
99 const resolved = resolveProjectOverrides(settings, projectId, project);
100 return projectFile === undefined ? resolved : applyProjectFile(resolved, projectFile);
101}
102
103function applyProjectFile(
104 resolved: ResolvedProjectSettings,
105 projectFile: T3ProjectFile | null,
106): ResolvedProjectSettings {
107 let effective: Record<string, unknown> | null = null;
108 let sources: Record<ProjectScopedServerSettingKey, ProjectSettingSource> | null = null;
109 for (const key of Object.keys(PROJECT_FILE_BACKED_SETTINGS) as ProjectFileBackedSettingKey[]) {
110 if (resolved.settings[key] !== null) continue;
111 const { value, source } = resolveProjectFileBackedSetting(key, null, projectFile);
112 effective ??= { ...resolved.settings };
113 sources ??= { ...resolved.sources };
114 effective[key] = value;
115 // A project override of null defers like an unset one, so the value did
116 // not come from the project either way.
117 sources[key] = source;
118 }
119 return effective === null || sources === null
120 ? resolved
121 : { ...resolved, settings: effective as ServerSettings, sources };
122}
123
124/**
125 * The file and built-in tiers for one key, given the project-over-environment
126 * value (`null` when neither is set). For callers that hold the settings tier
127 * but only see the file later, such as the git driver reading the t3.json of
128 * the checkout it just created. Same chain as `resolveProjectSettings`.
129 */
130export function resolveProjectFileBackedSetting<K extends ProjectFileBackedSettingKey>(
131 key: K,
132 setting: ServerSettings[K],
133 projectFile: T3ProjectFile | null,
134): { value: ResolvedServerSettings[K]; source: ProjectSettingSource } {
135 if (setting !== null) {
136 return { value: setting as ResolvedServerSettings[K], source: "environment" };
137 }
138 const { field, builtIn } = PROJECT_FILE_BACKED_SETTINGS[key];
139 const fromFile = projectFile?.[field] as ResolvedServerSettings[K] | undefined;
140 return fromFile === undefined
141 ? { value: builtIn as ResolvedServerSettings[K], source: "environment" }
142 : { value: fromFile, source: "t3.json" };
143}
144
145function resolveProjectOverrides(
146 settings: ServerSettings,
147 projectId: ProjectId | null,
148 project?: LegacyProjectSettingsFields | null,
149): ResolvedProjectSettings {
150 const stored = projectId === null ? undefined : settings.projectSettingsOverrides[projectId];
151 const overrides: ProjectSettingsOverrides =
152 project == null || settings.projectSettingsFolded
153 ? (stored ?? EMPTY_OVERRIDES)
154 : {
155 ...(project.defaultModelSelection != null
156 ? { defaultModelSelection: project.defaultModelSelection }
157 : {}),
158 ...(project.defaultThreadEnvMode != null
159 ? { defaultThreadEnvMode: project.defaultThreadEnvMode }
160 : {}),
161 ...stored,
162 };
163 if (Object.keys(overrides).length === 0) {
164 return { settings, sources: ENVIRONMENT_SOURCES, overrides: EMPTY_OVERRIDES };
165 }
166 const sources: Record<ProjectScopedServerSettingKey, ProjectSettingSource> = {
167 ...ENVIRONMENT_SOURCES,
168 };
169 const effective: Record<string, unknown> = { ...settings };
170 for (const key of PROJECT_SCOPED_SERVER_SETTING_KEYS) {
171 if (!Object.hasOwn(overrides, key)) continue;
172 const value = overrides[key];
173 // A forward-compatible decode leaves an unknown value as a present
174 // undefined; that is not an override.
175 if (value === undefined) continue;
176 // A model on a disabled provider falls back to the environment, like the
177 // environment-level guards do for these keys.
178 if (
179 (key === "textGenerationModelSelection" || key === "defaultModelSelection") &&
180 value !== undefined &&
181 value !== null &&
182 !isModelSelectionProviderEnabled(settings, value as ModelSelection)
183 ) {
184 continue;
185 }
186 effective[key] = value;
187 sources[key] = "project";
188 }
189 return { settings: effective as ServerSettings, sources, overrides };
190}
191
192/**
193 * The workspace mode a new thread starts in. A project the environment made
194 * from just a name (a folder directly inside `ServerConfig.newProjectsRoot`)
195 * has only its first commit, so until it has a thread, a new thread works in
196 * the project checkout even when the environment default is a new worktree.
197 * Only that environment default is replaced: a project override still wins,
198 * and so does a t3.json when the environment sets no default (the usual
199 * precedence; the scaffold writes no t3.json).
200 */
201export function resolveNewThreadEnvMode(input: {
202 readonly projectSettings: ResolvedProjectSettings<ResolvedServerSettings>;
203 readonly workspaceRoot: string | null;
204 readonly newProjectsRoot: string | null | undefined;
205 readonly projectHasThreads: boolean;
206}): ThreadEnvMode {
207 const configured = input.projectSettings.settings.defaultThreadEnvMode;
208 if (
209 configured === "local" ||
210 input.projectHasThreads ||
211 input.projectSettings.sources.defaultThreadEnvMode !== "environment" ||
212 input.workspaceRoot === null ||
213 input.newProjectsRoot == null
214 ) {
215 return configured;
216 }
217 const root = normalizeProjectPathForComparison(input.newProjectsRoot);
218 const folder = normalizeProjectPathForComparison(input.workspaceRoot);
219 const separator = root.includes("\\") ? "\\" : "/";
220 const prefix = root.endsWith(separator) ? root : `${root}${separator}`;
221 const isNewProjectFolder =
222 folder.startsWith(prefix) &&
223 folder.length > prefix.length &&
224 !folder.slice(prefix.length).includes(separator);
225 return isNewProjectFolder ? "local" : configured;
226}
227
228/** Replace the project's entry, dropping it entirely when nothing is overridden. */
229export function withProjectSettingsOverrides(
230 settings: Pick<ServerSettings, "projectSettingsOverrides">,
231 projectId: ProjectId,
232 next: ProjectSettingsOverrides | null,
233): ServerSettings["projectSettingsOverrides"] {
234 const { [projectId]: _removed, ...rest } = settings.projectSettingsOverrides;
235 return next === null || Object.keys(next).length === 0 ? rest : { ...rest, [projectId]: next };
236}
237
238/** The project's entry with `keys` removed; `null` when that leaves it empty. */
239export function clearProjectSettingsOverrides(
240 settings: Pick<ServerSettings, "projectSettingsOverrides">,
241 projectId: ProjectId,
242 keys: readonly ProjectScopedServerSettingKey[],
243): ProjectSettingsOverrides | null {
244 const current = settings.projectSettingsOverrides[projectId];
245 if (current === undefined) return null;
246 const next = { ...current };
247 for (const key of keys) delete next[key];
248 return Object.keys(next).length === 0 ? null : next;
249}
250
251/** Worktree rules are project-scoped; artifact and log retention stays environment-wide. */
252export function resolveWorktreeCleanup(
253 settings: ServerSettings,
254 projectId: ProjectId | null,
255): WorktreeCleanupRules {
256 const policy = resolveProjectSettings(settings, projectId).settings.worktreeCleanup;
257 if (policy?.mode === "custom") return policy.rules;
258 if (policy?.mode === "off")
259 return {
260 worktreeKeepWhen: settings.storageCleanup.worktreeKeepWhen,
261 worktreeAfterDays: null,
262 worktreeOnMerge: false,
263 worktreeOnDelete: false,
264 worktreeUnchanged: false,
265 };
266 const {
267 worktreeKeepWhen,
268 worktreeAfterDays,
269 worktreeOnMerge,
270 worktreeOnDelete,
271 worktreeUnchanged,
272 } = settings.storageCleanup;
273 return {
274 worktreeKeepWhen,
275 worktreeAfterDays,
276 worktreeOnMerge,
277 worktreeOnDelete,
278 worktreeUnchanged,
279 };
280}