Open History to see the last commit
1import {
2 type CommandId,
3 type EventId,
4 MAX_SCRIPT_ID_LENGTH,
5 type ModelSelection,
6 type ProjectIconOverride,
7 ProjectId,
8 type ProjectScript,
9 type ProjectTrackedFolder,
10 SCRIPT_RUN_COMMAND_PATTERN,
11 type ThreadEnvMode,
12} from "@t3tools/contracts";
13import * as DateTime from "effect/DateTime";
14import * as Result from "effect/Result";
15import * as Schema from "effect/Schema";
16
17import type { UnsequencedProjectEvent } from "../persistence/OrchestrationEventStore.ts";
18import type { ProjectRow } from "./ProjectStore.ts";
19
20export interface ProjectCreateCommand {
21 readonly type: "project.create";
22 readonly commandId: CommandId;
23 readonly projectId: ProjectId;
24 readonly title: string;
25 readonly workspaceRoot: string;
26 readonly scripts?: ReadonlyArray<ProjectScript>;
27 readonly trackedFolders?: ReadonlyArray<ProjectTrackedFolder>;
28}
29
30export interface ProjectMetaUpdateCommand {
31 readonly type: "project.meta.update";
32 readonly commandId: CommandId;
33 readonly projectId: ProjectId;
34 readonly title?: string;
35 readonly workspaceRoot?: string;
36 readonly defaultModelSelection?: ModelSelection | null;
37 readonly defaultThreadEnvMode?: ThreadEnvMode | null;
38 readonly autoPull?: boolean;
39 readonly faviconPath?: string | null;
40 readonly projectIcon?: ProjectIconOverride | null;
41 readonly scripts?: ReadonlyArray<ProjectScript>;
42 readonly trackedFolders?: ReadonlyArray<ProjectTrackedFolder>;
43 readonly pinned?: boolean;
44 readonly archived?: boolean;
45}
46
47export interface ProjectDeleteCommand {
48 readonly type: "project.delete";
49 readonly commandId: CommandId;
50 readonly projectId: ProjectId;
51}
52
53export type ProjectCommand = ProjectCreateCommand | ProjectMetaUpdateCommand | ProjectDeleteCommand;
54
55export class ProjectCommandInvariantError extends Schema.TaggedError<ProjectCommandInvariantError>()(
56 "ProjectCommandInvariantError",
57 {
58 commandType: Schema.String,
59 detail: Schema.String,
60 },
61) {
62 override get message(): string {
63 return `Project command invariant failed (${this.commandType}): ${this.detail}`;
64 }
65}
66
67export class ProjectCommandMissingProjectError extends Schema.TaggedError<ProjectCommandMissingProjectError>()(
68 "ProjectCommandMissingProjectError",
69 {
70 commandType: Schema.String,
71 projectId: ProjectId,
72 },
73) {
74 override get message(): string {
75 return `Project '${this.projectId}' does not exist for command '${this.commandType}'.`;
76 }
77}
78
79export class ProjectWorkspaceConflictError extends Schema.TaggedError<ProjectWorkspaceConflictError>()(
80 "ProjectWorkspaceConflictError",
81 {
82 workspaceRoot: Schema.String,
83 conflictingProjectId: ProjectId,
84 },
85) {
86 override get message(): string {
87 return `Active project '${this.conflictingProjectId}' already exists for workspace root '${this.workspaceRoot}'.`;
88 }
89}
90
91export const ProjectCommandRejection = Schema.Union([
92 ProjectCommandInvariantError,
93 ProjectCommandMissingProjectError,
94 ProjectWorkspaceConflictError,
95]);
96export type ProjectCommandRejection = typeof ProjectCommandRejection.Type;
97
98const ProjectCommandRejectionJson = Schema.fromJsonString(ProjectCommandRejection);
99export const encodeProjectCommandRejection = Schema.encodeSync(ProjectCommandRejectionJson);
100export const decodeProjectCommandRejection = Schema.decodeUnknownOption(
101 ProjectCommandRejectionJson,
102);
103
104export interface ProjectCommandState {
105 readonly project: ProjectRow | undefined;
106 readonly workspaceOwner: ProjectRow | undefined;
107}
108
109const monogramSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
110const isScriptRunCommand = Schema.is(SCRIPT_RUN_COMMAND_PATTERN);
111
112/** Read state and commit the planned event under the project lock. */
113export function planProjectCommand(input: {
114 readonly command: ProjectCommand;
115 readonly state: ProjectCommandState;
116 readonly eventId: EventId;
117 readonly now: DateTime.Utc;
118}): Result.Result<UnsequencedProjectEvent, ProjectCommandRejection> {
119 const { command, state } = input;
120 const invariant = (detail: string) =>
121 Result.fail(new ProjectCommandInvariantError({ commandType: command.type, detail }));
122 const missingProject = () =>
123 Result.fail(
124 new ProjectCommandMissingProjectError({
125 commandType: command.type,
126 projectId: command.projectId,
127 }),
128 );
129 const activeProject = state.project?.deletedAt === null ? state.project : undefined;
130 const requireWorkspaceAvailable = (workspaceRoot: string) =>
131 state.workspaceOwner === undefined || state.workspaceOwner.projectId === command.projectId
132 ? undefined
133 : new ProjectWorkspaceConflictError({
134 workspaceRoot,
135 conflictingProjectId: state.workspaceOwner.projectId,
136 });
137 const occurredAt = DateTime.formatIso(input.now);
138 const base = {
139 eventId: input.eventId,
140 aggregateKind: "project" as const,
141 aggregateId: command.projectId,
142 occurredAt,
143 commandId: command.commandId,
144 causationEventId: null,
145 correlationId: command.commandId,
146 metadata: {},
147 };
148
149 switch (command.type) {
150 case "project.create": {
151 if (state.project !== undefined) {
152 return invariant(
153 `Project '${command.projectId}' already exists and cannot be created twice.`,
154 );
155 }
156 const conflict = requireWorkspaceAvailable(command.workspaceRoot);
157 if (conflict !== undefined) return Result.fail(conflict);
158 return Result.succeed({
159 ...base,
160 type: "project.created",
161 payload: {
162 projectId: command.projectId,
163 title: command.title,
164 workspaceRoot: command.workspaceRoot,
165 defaultModelSelection: null,
166 faviconPath: null,
167 projectIcon: null,
168 scripts: command.scripts ?? [],
169 ...(command.trackedFolders === undefined || command.trackedFolders.length === 0
170 ? {}
171 : { trackedFolders: command.trackedFolders }),
172 createdAt: occurredAt,
173 updatedAt: occurredAt,
174 },
175 });
176 }
177
178 case "project.meta.update": {
179 const project = activeProject;
180 if (project === undefined) return missingProject();
181 if (
182 command.projectIcon?.kind === "monogram" &&
183 Array.from(monogramSegmenter.segment(command.projectIcon.text)).length > 2
184 ) {
185 return invariant("Project monograms must contain at most two characters.");
186 }
187 if (command.scripts !== undefined) {
188 // Allow editing or removing persisted invalid script ids, while rejecting new invalid ids.
189 const existingIds = new Set(project.scripts.map((script) => script.id));
190 for (const script of command.scripts) {
191 if (!existingIds.has(script.id) && !isScriptRunCommand(`script.${script.id}.run`)) {
192 return invariant(
193 `Script IDs must be 1-${MAX_SCRIPT_ID_LENGTH} lowercase letters, digits or hyphens, starting with a letter or digit (got ${script.id.length} characters).`,
194 );
195 }
196 }
197 }
198 if (command.workspaceRoot !== undefined) {
199 const conflict = requireWorkspaceAvailable(command.workspaceRoot);
200 if (conflict !== undefined) return Result.fail(conflict);
201 }
202 return Result.succeed({
203 ...base,
204 type: "project.meta-updated",
205 payload: {
206 projectId: command.projectId,
207 ...(command.title === undefined ? {} : { title: command.title }),
208 ...(command.workspaceRoot === undefined ? {} : { workspaceRoot: command.workspaceRoot }),
209 ...(command.defaultModelSelection === undefined
210 ? {}
211 : { defaultModelSelection: command.defaultModelSelection }),
212 ...(command.defaultThreadEnvMode === undefined
213 ? {}
214 : { defaultThreadEnvMode: command.defaultThreadEnvMode }),
215 ...(command.autoPull === undefined ? {} : { autoPull: command.autoPull }),
216 ...(command.faviconPath === undefined ? {} : { faviconPath: command.faviconPath }),
217 ...(command.projectIcon === undefined ? {} : { projectIcon: command.projectIcon }),
218 ...(command.scripts === undefined ? {} : { scripts: command.scripts }),
219 ...(command.trackedFolders === undefined
220 ? {}
221 : { trackedFolders: command.trackedFolders }),
222 // Repeating a pin or archive keeps the original time.
223 ...(command.pinned === undefined
224 ? {}
225 : { pinnedAt: command.pinned ? (project.pinnedAt ?? occurredAt) : null }),
226 ...(command.archived === undefined
227 ? {}
228 : { archivedAt: command.archived ? (project.archivedAt ?? occurredAt) : null }),
229 updatedAt: occurredAt,
230 },
231 });
232 }
233
234 case "project.delete": {
235 if (activeProject === undefined) return missingProject();
236 // Thread children are deleted by ProjectService before this event commits.
237 return Result.succeed({
238 ...base,
239 type: "project.deleted",
240 payload: { projectId: command.projectId, deletedAt: occurredAt },
241 });
242 }
243 }
244}