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