Repository navigation
Expand file tree
/
Copy pathTaskFolders.ts
More file actions
1768 lines (1718 loc) · 74.9 KB
/
Copy pathTaskFolders.ts
File metadata and controls
1768 lines (1718 loc) · 74.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
GitCommandError,
isRuntimeModeAbove,
linkOriginIsFenced,
managedPolicyDeniedMessage,
managedRuntimeModeDenial,
type OrchestrationV2LinkOrigin,
type ProjectId,
type ProjectTrackedFolder,
type ProviderInteractionMode,
type RuntimeMode,
TASK_FOLDER_DEFAULT_REPOSITORIES_MAX,
type TaskFolder,
TaskFolderError,
type TaskFolderRepository,
type ThreadId,
type VcsCreateWorktreeInput,
type VcsCreateWorktreeResult,
type WorkspaceLayoutCommandsResult,
type WorktreeLayoutCommandKind,
T3_PROJECT_FILE_NAME,
} from "@t3tools/contracts";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { flattenTemporaryWorktreeBranchName, isTemporaryWorktreeBranch } from "@t3tools/shared/git";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { windowsSystem32Path } from "@t3tools/shared/windowsSystem";
import * as KeyedLock from "@t3tools/shared/KeyedLock";
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Digest from "effect/crypto/Digest";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Hex from "effect/encoding/Hex";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import type * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as ServerConfig from "../config.ts";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import {
removeEmptyDirectory,
type RemoveEmptyDirectoryError,
} from "../vcs/removeEmptyDirectory.ts";
import { resolveWorktreesDirectory } from "../worktreesDirectory.ts";
import { isWithinRoot } from "./KnownWorkspaces.ts";
import * as LayoutCommandApprovals from "./LayoutCommandApprovals.ts";
import * as TaskFolderStore from "./TaskFolderStore.ts";
import { projectFolders, parseGitmodulesPaths } from "./WorkspaceFolders.ts";
import { withWorkspaceLease } from "./workspaceLease.ts";
// Each worktree is a checkout: enough at once to finish four repositories together, few enough
// to leave Git's server-wide process slots to running threads.
const REPOSITORY_CONCURRENCY = 4;
const LAYOUT_COMMAND_TIMEOUT_MS = 600_000;
const BRANCH_NAME_ATTEMPTS = 50;
/** What a new task folder will hold, decided before anything is created. */
export interface TaskFolderPlan {
readonly projectId: ProjectId;
readonly projectRoot: string;
readonly projectIsRepository: boolean;
readonly anchor: string;
/** The tracked Git folders that get a worktree. */
readonly repositories: ReadonlyArray<ProjectTrackedFolder>;
/** Every tracked Git folder. None is linked into a plain project folder: a link is the original. */
readonly trackedRepositories: ReadonlyArray<string>;
}
interface TaskFolderRemoval {
readonly removed: ReadonlyArray<string>;
readonly kept: ReadonlyArray<{ readonly path: string; readonly reason: string }>;
}
/**
* Whether removal keeps a checkout. Verdicts can be reused, so `recheck` reruns the checkout's
* quick checks right before the layout command and before deletion; `prepare` runs after the
* guard, right before deletion.
*/
interface TaskFolderVerdict {
readonly keep: string | null;
readonly force: boolean;
readonly recheck?: Effect.Effect<string | null> | undefined;
readonly prepare?: Effect.Effect<string | null> | undefined;
}
/** One checkout of a task folder, as removal sees it. */
interface TaskFolderCheckout {
readonly worktreePath: string;
/** The checkout this is a worktree of. */
readonly repositoryPath: string;
}
export class TaskFolders extends Context.Service<
TaskFolders,
{
/**
* Null when the project tracks no Git folder: its worktree is then a single checkout, made as
* it always was. Omitted `repositories` selects every tracked Git folder up to
* `TASK_FOLDER_DEFAULT_REPOSITORIES_MAX`, and none beyond that.
*/
readonly plan: (input: {
readonly projectId: ProjectId;
readonly repositories?: ReadonlyArray<{ readonly path: string }> | undefined;
}) => Effect.Effect<TaskFolderPlan | null, TaskFolderError>;
/**
* Creates the folder and every worktree on one branch name, which is `branch` unless a
* selected repository already has it. A failure removes what this call created.
*/
readonly create: (input: {
readonly plan: TaskFolderPlan;
readonly branch: string;
/** Where the project folder's branch starts; unused when it is not a repository. */
readonly projectStart: { readonly refName: string; readonly baseRefName: string };
/**
* The branch the thread starts from. A repository that has it starts there; one that does
* not starts from its own default branch.
*/
readonly baseBranch?: string | undefined;
readonly startFromOrigin: boolean;
/**
* Whether the project's own layout command may run for whoever asks. A project that
* declares one gets no worktree without it: the default layout is not what it asked for.
*/
readonly projectCommands: ProjectCommandsNow;
readonly projectProgress?: GitVcsDriver.CreateWorktreeProgress;
/** As soon as the folder is recorded, so a cancelled caller knows what to remove. */
readonly onClaimed?: (taskFolder: TaskFolder, branch: string) => Effect.Effect<void>;
readonly onRepository?: (progress: {
readonly name: string;
readonly done: number;
readonly total: number;
}) => Effect.Effect<void>;
}) => Effect.Effect<
{
readonly taskFolder: TaskFolder;
readonly branch: string;
/** The project's own command made the checkouts, from whatever start it chose. */
readonly laidOutByProject: boolean;
/** A repository's worktree starts from the commit just fetched from its remote. */
readonly repositoriesStartedFromOrigin: boolean;
},
TaskFolderError
>;
/**
* The worktree an existing thread asks for in its project folder: a task folder with the
* default repositories when the project there tracks Git folders. Null otherwise, and for a
* request that names its path or checks out an existing branch, which stay a single worktree.
*/
readonly createForProjectFolder: (
input: VcsCreateWorktreeInput,
options: { readonly projectCommands: ProjectCommandsNow },
) => Effect.Effect<VcsCreateWorktreeResult | null, TaskFolderError>;
/**
* Gives a tracked Git folder its worktree in a thread's task folder, on the thread's branch.
* `startFromOrigin` defaults to the project's setting for new worktrees.
*/
readonly addRepository: (input: {
readonly threadId: ThreadId;
readonly repositoryPath: string;
readonly startFromOrigin?: boolean | undefined;
}) => Effect.Effect<TaskFolder, TaskFolderError>;
/** The task folder that is, or contains, `target`. */
readonly find: (target: string) => Effect.Effect<TaskFolder | null, TaskFolderError>;
/**
* Removes repository worktrees, then the project folder, then the links and the folder.
* `inspect` may keep a checkout, with the reason to report, or allow forcing it; without it
* every checkout is removed with `force`. `forget` drops the record, shrinking it to what was
* kept; otherwise the record stays so the folder can be restored when its thread resumes.
*/
readonly remove: (input: {
readonly root: string;
readonly force: boolean;
readonly forget: boolean;
/** Anything but permitted leaves the project's teardown command out. */
readonly projectCommands: ProjectCommandsNow;
readonly deleteBranch?: string | undefined;
readonly inspect?: (checkout: TaskFolderCheckout) => Effect.Effect<TaskFolderVerdict>;
/** Runs before the layout command, in its turn, and before each deletion; a reason keeps the rest. */
readonly guard?: Effect.Effect<string | null>;
}) => Effect.Effect<TaskFolderRemoval, TaskFolderError>;
/**
* Removes the task folder `path` is the root or the project folder of, for good. False when
* it is neither, and a failure naming what could not be removed.
*/
readonly removeIfTaskFolder: (input: {
readonly path: string;
readonly force: boolean;
readonly projectCommands: ProjectCommandsNow;
}) => Effect.Effect<boolean, TaskFolderError>;
/** Renames the branch in every checkout to one name free in all of them. */
readonly renameBranch: (input: {
readonly root: string;
readonly oldBranch: string;
readonly newBranch: string;
readonly exactName?: boolean;
}) => Effect.Effect<{ readonly branch: string }, TaskFolderError>;
/**
* Puts back whatever is missing; `recreate` checks a branch out again at a path. When the
* project's layout command may not run, every missing checkout comes back plain.
*/
readonly restore: <E>(input: {
readonly taskFolder: TaskFolder;
readonly projectCommands: ProjectCommandsNow;
/** The thread's branch, for a project that lays its folder out with its own command. */
readonly branch: string;
readonly recreate: (checkout: TaskFolderCheckout) => Effect.Effect<void, E>;
}) => Effect.Effect<void, TaskFolderError | E>;
/** The project's layout commands as its `t3.json` holds them now, and whether each is approved. */
readonly layoutCommands: (
projectId: ProjectId,
) => Effect.Effect<WorkspaceLayoutCommandsResult, TaskFolderError>;
}
>()("t3/workspace/TaskFolders") {}
const isTaskFolderError = Schema.is(TaskFolderError);
/**
* A caller's answer for who asked. Whether a person approved the command's text and whether
* policy allows it are not the caller's to answer: this service checks both at every run.
*/
export type ProjectCommands = "permitted" | "request-not-permitted" | "agent-below-full-access";
/**
* The answer as a caller hands it over: settled when it cannot change while the request lasts,
* or one to ask again each time a command's turn comes, as for a thread whose modes can change.
*/
export type ProjectCommandsNow = ProjectCommands | Effect.Effect<ProjectCommands>;
/**
* A layout command is the project owner's own code. A link paired below full access grants T3's
* tools only (see `mcp/linkOrigin.ts`), so work it started never runs one.
*/
export const projectCommandsForLink = (
origin: OrchestrationV2LinkOrigin | undefined,
): ProjectCommands =>
origin === undefined || !linkOriginIsFenced(origin) ? "permitted" : "request-not-permitted";
/**
* For a worktree an agent asked for. Below Full access the agent's own commands wait for a
* person, so the project's do not run for it either, approved or not. `maxRuntimeMode` is the
* administrator's limit: a thread recorded above it starts no work in that mode, so it is not in
* Full access here whatever it records.
*/
export const projectCommandsForAgent = (
origin: OrchestrationV2LinkOrigin | undefined,
modes: {
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
},
maxRuntimeMode: RuntimeMode | undefined,
): ProjectCommands => {
const link = projectCommandsForLink(origin);
if (link !== "permitted") return link;
return modes.runtimeMode === "full-access" &&
!isRuntimeModeAbove(modes.runtimeMode, maxRuntimeMode) &&
modes.interactionMode === "default"
? "permitted"
: "agent-below-full-access";
};
/** Only `layoutCommand` makes one, so nothing runs that was not checked there. */
const cleared: unique symbol = Symbol("t3/workspace/TaskFolders/cleared");
interface ClearedLayoutCommand {
readonly [cleared]: true;
readonly text: string;
/** The same check again, for the moment the command's turn comes. */
readonly recheck: Effect.Effect<
{ readonly command: ClearedLayoutCommand } | { readonly refusal: string } | null
>;
}
const layoutRefusedDetail = (refusal: string) =>
`This project lays out its worktrees with its own command (worktreeLayout in ${T3_PROJECT_FILE_NAME}), ${refusal}`;
const failureDetail = (cause: unknown) =>
typeof cause === "object" &&
cause !== null &&
"detail" in cause &&
typeof cause.detail === "string"
? cause.detail
: cause instanceof Error
? cause.message
: String(cause);
/** The deepest folder that holds every one of `folders`, or null when they share none. */
export const commonAncestor = (path: Path.Path, folders: ReadonlyArray<string>) => {
let ancestor = folders[0]!;
for (const folder of folders.slice(1)) {
while (!isWithinRoot(path, folder, ancestor)) {
const parent = path.dirname(ancestor);
// Two Windows drives meet nowhere, and a drive root is its own parent.
if (parent === ancestor) return null;
ancestor = parent;
}
}
return ancestor;
};
/**
* The folder a task folder mirrors: the deepest one holding the project and every tracked
* repository that shares a root with it. The rest are `unreachable` and cannot be laid out.
*/
export const layoutAnchor = (
path: Path.Path,
projectRoot: string,
repositories: ReadonlyArray<string>,
) => {
let anchor = projectRoot;
const unreachable: string[] = [];
for (const repository of repositories) {
const shared = commonAncestor(path, [anchor, repository]);
if (shared === null) unreachable.push(repository);
else anchor = shared;
}
return { anchor, unreachable };
};
const isGitCommandError = Schema.is(GitCommandError);
const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const digest = yield* Digest.Digest;
const config = yield* ServerConfig.ServerConfig;
const settings = yield* ServerSettings.ServerSettingsService;
const projects = yield* ProjectStore.ProjectStoreV2;
const git = yield* GitWorkflowService.GitWorkflowService;
const gitDriver = yield* GitVcsDriver.GitVcsDriver;
const store = yield* TaskFolderStore.TaskFolderStore;
const processes = yield* VcsProcess.VcsProcess;
const hostEnvironment = yield* HostProcess.Environment;
const hostPlatform = yield* HostProcess.Platform;
const onWindows = yield* HostProcess.isWindows;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const approvals = yield* LayoutCommandApprovals.LayoutCommandApprovals;
const managedPolicy = yield* ManagedPolicy.ManagedPolicy;
const layoutCommandsOffBy = ManagedPolicy.deniedBy(managedPolicy, "worktreeLayoutCommands");
// Set when the administrator's limit leaves no thread in Full access: "Example Corp limits…".
const fullAccessOff = managedRuntimeModeDenial(managedPolicy.summary, "full-access");
const exists = (target: string) =>
fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false));
const isRepository = (folder: string) => exists(path.join(folder, ".git"));
const occupied = Effect.fnUntraced(function* (target: string) {
if (!(yield* exists(target))) return false;
const isDirectory = (yield* fileSystem.stat(target).pipe(Effect.option)).pipe(
Option.exists((info) => info.type === "Directory"),
);
if (!isDirectory) return true;
return (
(yield* fileSystem.readDirectory(target).pipe(Effect.orElseSucceed(() => [""]))).length > 0
);
});
const trackedFolders = (project: {
readonly workspaceRoot: string;
readonly trackedFolders: ReadonlyArray<ProjectTrackedFolder>;
}) =>
projectFolders(project).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
);
// The repository that pins a submodule owns its checkout: Git, a hook or a setup script puts it
// in that repository's worktree, so it never gets one of its own here.
const isSubmodule = Effect.fnUntraced(function* (folder: string) {
for (
let owner = path.dirname(folder);
owner !== path.dirname(owner);
owner = path.dirname(owner)
) {
if (!(yield* isRepository(owner))) continue;
const declared = yield* fileSystem
.readFileString(path.join(owner, ".gitmodules"))
.pipe(Effect.orElseSucceed(() => ""));
return parseGitmodulesPaths(declared).includes(
path.relative(owner, folder).split(path.sep).join("/"),
);
}
return false;
});
const fail =
(operation: TaskFolderError["operation"], prefix: string) =>
(cause: unknown): TaskFolderError =>
new TaskFolderError({ operation, detail: `${prefix}: ${failureDetail(cause)}`, cause });
// A project that lays its own thread folder out says so in its `t3.json`.
const projectFile = (projectRoot: string) =>
fileSystem.readFileString(path.join(projectRoot, T3_PROJECT_FILE_NAME)).pipe(
Effect.map(parseT3ProjectFile),
Effect.orElseSucceed(() => null),
);
const worktreeLayout = (projectRoot: string) =>
projectFile(projectRoot).pipe(Effect.map((config) => config?.worktreeLayout ?? null));
/**
* The project's command for `kind` as its file holds it now: cleared to run, or the reason it
* stays unrun, worded to end a sentence about the command. Null when the project declares none.
* The text checked is the text run, so a file that changes in between changes nothing.
* Untraced: every caller is a traced operation, and its span covers these reads.
*/
const layoutCommand: (
project: { readonly projectId: ProjectId; readonly projectRoot: string },
kind: WorktreeLayoutCommandKind,
projectCommands: ProjectCommandsNow,
) => ClearedLayoutCommand["recheck"] = Effect.fnUntraced(
function* (project, kind, projectCommands) {
const text = (yield* worktreeLayout(project.projectRoot))?.[kind];
if (text === undefined) return null;
const refuse = (refusal: string) => ({ refusal }) as const;
const asked = typeof projectCommands === "string" ? projectCommands : yield* projectCommands;
if (asked === "request-not-permitted")
return refuse("which this request is not permitted to run.");
if (asked === "agent-below-full-access")
return refuse(
`which an agent can only have run from a thread in Full access. ${
fullAccessOff === undefined
? "Switch the calling thread to Full access, or start the worktree thread yourself."
: `${fullAccessOff} Start the worktree thread yourself.`
}`,
);
if (layoutCommandsOffBy !== undefined)
return refuse(
`and ${managedPolicyDeniedMessage(layoutCommandsOffBy, "project worktree layout commands")}`,
);
const approved = yield* (
approvals
.isApproved({ projectId: project.projectId, kind, command: text })
// An approval that cannot be read is not one.
.pipe(
Effect.catch((cause) =>
Effect.logWarning(cause.detail, { cause }).pipe(Effect.as(false)),
),
)
);
if (!approved)
return refuse(
"which nobody has approved as it is written now. Review and approve it in the web or desktop app, under Worktree layout in the project's settings or when starting a worktree thread there.",
);
const command: ClearedLayoutCommand = {
[cleared]: true,
text,
recheck: Effect.suspend(() => layoutCommand(project, kind, projectCommands)),
};
return { command } as const;
},
);
// One at a time per project: the commands share the project folder, and its workspace files.
const layoutLocks = yield* KeyedLock.make<string>();
const runLayoutCommand = (
operation: TaskFolderError["operation"],
command: ClearedLayoutCommand,
taskFolder: Pick<TaskFolder, "root" | "projectRoot" | "projectPath">,
branch: string,
baseBranch: string | undefined,
repositories: ReadonlyArray<string>,
/**
* What the caller does once the command's turn has come, before the check below. It answers
* with what to note when the command is cleared to start, or null when the command is no
* longer wanted: it is then left unrun.
*/
inItsTurn: Effect.Effect<(() => void) | null, TaskFolderError> = Effect.succeed(() => {}),
) =>
layoutLocks.withLock(
taskFolder.projectRoot,
Effect.gen(function* () {
const noteStart = yield* inItsTurn;
if (noteStart === null) return null;
// The wait for a turn can be long: who asked, the file and the approval are read again
// once it comes, and only the text that passes then is run. Nothing else comes between
// this check and the command's start, so no other work can outlast what it read.
const now = yield* command.recheck;
if (now === null || !("command" in now) || now.command.text !== command.text) {
return yield* new TaskFolderError({
operation,
detail: layoutRefusedDetail(
now !== null && "refusal" in now
? now.refusal
: "which changed while this request waited for its turn. Try again.",
),
});
}
noteStart();
return yield* processes
.run({
operation: "TaskFolders.worktreeLayout",
command: onWindows ? windowsSystem32Path(hostEnvironment, "cmd.exe") : "sh",
args: onWindows ? ["/d", "/s", "/c", now.command.text] : ["-c", now.command.text],
cwd: taskFolder.projectRoot,
env: {
...hostEnvironment,
// A `GIT_DIR` the server inherited would point the command's Git at another repository.
...VcsProcess.unsetInheritedRepositoryEnv(hostEnvironment, hostPlatform),
T3_PROJECT_ROOT: taskFolder.projectRoot,
T3_WORKTREE_ROOT: taskFolder.root,
T3_WORKTREE_PROJECT_PATH: taskFolder.projectPath,
T3_WORKTREE_BRANCH: branch,
T3_WORKTREE_BASE: baseBranch ?? "",
T3_WORKTREE_REPOSITORIES: repositories.join("\n"),
},
timeoutMs: LAYOUT_COMMAND_TIMEOUT_MS,
})
.pipe(Effect.mapError(fail(operation, "The project's worktree layout command failed")));
}),
);
/** Where a folder's `.git` file points, or null when `.git` is a directory or absent. */
const gitDirPointer = Effect.fnUntraced(function* (folder: string) {
const pointer = yield* fileSystem
.readFileString(path.join(folder, ".git"))
.pipe(Effect.orElseSucceed(() => ""));
const gitDir = /^gitdir:\s*(.+?)\s*$/m.exec(pointer)?.[1];
return gitDir === undefined ? null : path.resolve(folder, gitDir);
});
// A repository that is itself a linked worktree registers worktrees under the Git dir it shares.
const commonGitDir = Effect.fnUntraced(function* (repositoryPath: string) {
const gitDir = yield* gitDirPointer(repositoryPath);
if (gitDir === null) return path.join(repositoryPath, ".git");
const common = (yield* fileSystem
.readFileString(path.join(gitDir, "commondir"))
.pipe(Effect.orElseSucceed(() => ""))).trim();
return common === "" ? gitDir : path.resolve(gitDir, common);
});
// What a layout command leaves must be a checkout this service can later remove, restore and
// rename: a worktree linked to the repository, on the thread's branch. Null when it is.
/** The checkout's own Git directory when it is a worktree linked to its repository. */
const linkedGitDir = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {
const real = (target: string) =>
fileSystem.realPath(target).pipe(Effect.orElseSucceed(() => target));
const resolved = yield* gitDirPointer(checkout.worktreePath);
if (
resolved === null ||
!isWithinRoot(
path,
yield* real(resolved),
path.join(yield* real(yield* commonGitDir(checkout.repositoryPath)), "worktrees"),
)
)
return null;
// Git registers one path per worktree: a copy of the checkout elsewhere points here too.
const registered = (yield* fileSystem
.readFileString(path.join(resolved, "gitdir"))
.pipe(Effect.orElseSucceed(() => ""))).trim();
return registered !== "" &&
(yield* real(path.dirname(registered))) === (yield* real(checkout.worktreePath))
? resolved
: null;
});
const unadoptable = Effect.fnUntraced(function* (checkout: TaskFolderCheckout, branch: string) {
const resolved = yield* linkedGitDir(checkout);
if (resolved === null)
return `${checkout.worktreePath} is not a Git worktree of ${checkout.repositoryPath}`;
const head = (yield* fileSystem
.readFileString(path.join(resolved, "HEAD"))
.pipe(Effect.orElseSucceed(() => ""))).trim();
return head === `ref: refs/heads/${branch}`
? null
: `${checkout.worktreePath} is not on the branch ${branch}`;
});
const mapped = (taskFolder: Pick<TaskFolder, "root" | "anchor">, source: string) =>
path.join(taskFolder.root, path.relative(taskFolder.anchor, source));
const depth = (target: string) => path.resolve(target).split(path.sep).length;
const readProject = Effect.fn("TaskFolders.readProject")(function* (
operation: TaskFolderError["operation"],
projectId: ProjectId,
) {
const row = yield* projects
.get(projectId)
.pipe(Effect.mapError(fail(operation, "Could not read the project")));
if (Option.isNone(row)) {
return yield* new TaskFolderError({
operation,
detail: `Project ${projectId} was not found.`,
});
}
return row.value;
});
const plan: TaskFolders["Service"]["plan"] = Effect.fn("TaskFolders.plan")(function* (input) {
const project = yield* readProject("plan", input.projectId);
const projectRoot = path.resolve(project.workspaceRoot);
const classified = yield* Effect.forEach(
yield* trackedFolders(project),
(folder) => {
const folderPath = path.resolve(folder.path);
return Effect.all([isRepository(folderPath), isSubmodule(folderPath)]).pipe(
Effect.map(([git, submodule]) => ({
name: folder.name,
path: folderPath,
git,
submodule,
})),
);
},
{ concurrency: 8 },
);
const tracked = classified.filter(
(folder) => folder.git && !folder.submodule && folder.path !== projectRoot,
);
// A project that lays its own thread folder out gets one even with nothing else to check out.
// An explicit choice still goes through the checks below, so it is refused, not dropped.
if (
tracked.length === 0 &&
(input.repositories ?? []).length === 0 &&
(yield* worktreeLayout(projectRoot)) === null
)
return null;
// A repository on another Windows drive has no place in the folder; only choosing it fails.
const { anchor, unreachable } = layoutAnchor(
path,
projectRoot,
tracked.map((folder) => folder.path),
);
const reachable = tracked.filter((folder) => !unreachable.includes(folder.path));
let repositories: ReadonlyArray<ProjectTrackedFolder>;
if (input.repositories === undefined) {
repositories = reachable.length <= TASK_FOLDER_DEFAULT_REPOSITORIES_MAX ? reachable : [];
} else {
const selected = new Map<string, ProjectTrackedFolder>();
for (const requested of input.repositories) {
const requestedPath = path.resolve(requested.path);
const folder = classified.find((candidate) => candidate.path === requestedPath);
// A submodule comes with its repository's worktree; clients cannot tell one apart.
if (folder?.submodule === true) continue;
if (folder === undefined || !folder.git || folder.path === projectRoot) {
return yield* new TaskFolderError({
operation: "plan",
detail:
folder === undefined
? `"${requested.path}" is not a tracked folder of project "${project.title}".`
: `"${requested.path}" is not a Git repository, so it cannot get a worktree.`,
});
}
if (unreachable.includes(folder.path)) {
return yield* new TaskFolderError({
operation: "plan",
detail: `"${folder.path}" shares no common root with the project folder ${projectRoot}, so the two cannot be laid out in one worktree folder.`,
});
}
selected.set(folder.path, folder);
}
repositories = [...selected.values()];
}
// A repository with no commit yet has nothing to branch from, so it is left out.
repositories = yield* Effect.filter(
repositories,
(folder) =>
git.hasCommit({ cwd: folder.path, refName: "HEAD" }).pipe(Effect.orElseSucceed(() => true)),
{ concurrency: REPOSITORY_CONCURRENCY },
);
return {
projectId: project.projectId,
projectRoot,
projectIsRepository: yield* isRepository(projectRoot),
anchor,
repositories: repositories.map(({ name, path: folderPath }) => ({ name, path: folderPath })),
trackedRepositories: reachable.map((folder) => folder.path),
};
});
const branchNames = (cwds: ReadonlyArray<string>) =>
Effect.forEach(cwds, (cwd) => git.listLocalBranchNames(cwd), {
concurrency: REPOSITORY_CONCURRENCY,
});
// Git stores branches as files, so a name also collides with one it nests under or contains.
const collides = (existing: string, candidate: string) =>
existing === candidate ||
existing.startsWith(`${candidate}/`) ||
candidate.startsWith(`${existing}/`);
const freeBranchName = (
operation: TaskFolderError["operation"],
branch: string,
names: ReadonlyArray<ReadonlyArray<string>>,
) => {
for (let attempt = 1; attempt <= BRANCH_NAME_ATTEMPTS; attempt++) {
const candidate = attempt === 1 ? branch : `${branch}-${attempt}`;
if (!names.some((list) => list.some((existing) => collides(existing, candidate))))
return Effect.succeed(candidate);
}
return Effect.fail(
new TaskFolderError({
operation,
detail: `No branch name based on "${branch}" is free in every repository.`,
}),
);
};
/**
* Where a repository's branch starts: `baseBranch` when the repository has it, else its
* default branch. The remote commit of either when starting from origin.
*/
const repositoryStart = Effect.fn("TaskFolders.repositoryStart")(function* (
cwd: string,
startFromOrigin: boolean,
baseBranch?: string,
) {
// Clients send `HEAD` when no base was chosen; as a name it would match `origin/HEAD`.
const wanted = baseBranch?.replace(/^refs\/heads\//, "").replace(/^origin\//, "");
const defaultBranch =
wanted !== undefined &&
wanted !== "" &&
wanted !== "HEAD" &&
((yield* git.hasCommit({ cwd, refName: `refs/heads/${wanted}` })) ||
(yield* git.hasCommit({ cwd, refName: `refs/remotes/origin/${wanted}` })))
? wanted
: ((yield* gitDriver.resolveDefaultBranchName(cwd, "origin")) ??
(yield* git.currentBranch(cwd)));
let baseRef = "HEAD";
if (defaultBranch !== null) {
if (yield* git.hasCommit({ cwd, refName: `refs/heads/${defaultBranch}` }))
baseRef = defaultBranch;
else if (yield* git.hasCommit({ cwd, refName: `refs/remotes/origin/${defaultBranch}` }))
baseRef = `origin/${defaultBranch}`;
}
const remoteBase =
startFromOrigin && baseRef !== "HEAD"
? yield* git.fetchWorktreeBaseCommit({ cwd, refName: baseRef })
: null;
return remoteBase === null
? { refName: baseRef, baseRefName: baseRef }
: { refName: remoteBase.commitSha, baseRefName: `refs/remotes/${remoteBase.remoteRefName}` };
});
/**
* Stands in for a folder that is not a repository: every entry links to the original, so
* nothing is copied, except the folders that lead to a tracked repository, which are real so a
* worktree can sit in them.
*/
const linkFolder: (
source: string,
target: string,
trackedRepositories: ReadonlyArray<string>,
skip?: string,
) => Effect.Effect<void, PlatformError.PlatformError> = Effect.fnUntraced(
function* (source, target, trackedRepositories, skip) {
yield* fileSystem.makeDirectory(target, { recursive: true });
for (const name of yield* fileSystem.readDirectory(source)) {
const entry = path.join(source, name);
const link = path.join(target, name);
if (name === ".git" || name === skip || trackedRepositories.includes(entry)) continue;
if (yield* exists(link)) continue;
if (trackedRepositories.some((repository) => isWithinRoot(path, repository, entry))) {
yield* linkFolder(entry, link, trackedRepositories);
} else {
yield* fileSystem.symlink(entry, link);
}
}
},
);
/**
* Makes room for a worktree at `relative` inside a linked folder: a link on the way becomes a
* real folder linking its other entries. Anything there that this service did not link stays.
*/
const openLinkedPath = Effect.fnUntraced(function* (
source: string,
target: string,
relative: string,
) {
const segments = relative.split(path.sep);
for (const [index, segment] of segments.entries()) {
source = path.join(source, segment);
target = path.join(target, segment);
const last = index === segments.length - 1;
const link = yield* fileSystem.readLink(target).pipe(Effect.option);
if (Option.isSome(link)) {
if (path.resolve(path.dirname(target), link.value) !== source) return false;
yield* fileSystem.remove(target);
if (!last) yield* linkFolder(source, target, [], segments[index + 1]);
} else if (!last) {
yield* fileSystem.makeDirectory(target, { recursive: true });
}
}
return true;
});
/** Unlinks links and removes the folders that leaves empty; files and checkouts stay. */
const removeLinks: (
target: string,
) => Effect.Effect<boolean, PlatformError.PlatformError | RemoveEmptyDirectoryError> =
Effect.fnUntraced(function* (target) {
if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) {
yield* fileSystem.remove(target);
return true;
}
if (!(yield* exists(target))) return true;
if ((yield* fileSystem.stat(target)).type !== "Directory") return false;
if (yield* isRepository(target)) return false;
let empty = true;
for (const name of yield* fileSystem.readDirectory(target)) {
if (!(yield* removeLinks(path.join(target, name)))) empty = false;
}
return empty && (yield* removeEmptyDirectory(target));
});
/** Whether `removeLinks` would leave nothing: only links and folders of links are inside. */
const holdsOnlyLinks: (target: string) => Effect.Effect<boolean, PlatformError.PlatformError> =
Effect.fnUntraced(function* (target) {
if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) return true;
if (!(yield* exists(target))) return true;
if ((yield* fileSystem.stat(target)).type !== "Directory") return false;
if (yield* isRepository(target)) return false;
for (const name of yield* fileSystem.readDirectory(target)) {
if (!(yield* holdsOnlyLinks(path.join(target, name)))) return false;
}
return true;
});
const allocateRoot = Effect.fn("TaskFolders.allocateRoot")(function* (
taskPlan: TaskFolderPlan,
branch: string,
) {
const parent = resolveWorktreesDirectory(
(yield* settings.getSettings.pipe(Effect.orElseSucceed(() => ({ worktreesDirectory: "" }))))
.worktreesDirectory,
config.worktreesDir,
path,
yield* HostProcess.HomeDirectory,
);
if (parent === null) {
return yield* new TaskFolderError({
operation: "create",
detail:
"The worktree location must be an absolute folder on this machine, not a drive root. Change it in Settings → Worktrees.",
});
}
const hash = yield* digest.digest(
Digest.sha256,
new TextEncoder().encode(`${taskPlan.projectId}\0${taskPlan.anchor}\0${branch}`),
);
// UTF-8 bytes bound UTF-16 length too, leaving room for files on Windows.
let prefix = "";
for (const character of branch.replace(/\//g, "-")) {
if (Buffer.byteLength(prefix + character) > 23) break;
prefix += character;
}
const base = path.join(
parent,
path.basename(taskPlan.anchor) || "workspace",
`${prefix}-${Hex.encode(hash).slice(0, 16)}`,
);
const allocateFailed = fail("create", "Could not create the worktree folder");
yield* fileSystem
.makeDirectory(path.dirname(base), { recursive: true })
.pipe(Effect.mapError(allocateFailed));
// Made here, not just found free: two creations on one branch must not share a folder.
for (let suffix = 1; ; suffix++) {
const root = suffix === 1 ? base : `${base}-${suffix}`;
const claimed = yield* fileSystem.makeDirectory(root).pipe(
Effect.as(true),
Effect.catchIf(
(cause) => cause.reason._tag === "AlreadyExists",
() => Effect.succeed(false),
),
Effect.mapError(allocateFailed),
);
if (claimed) return root;
}
});
const removeCheckout = Effect.fnUntraced(function* (
checkout: TaskFolderCheckout,
force: boolean,
deleteBranch: string | undefined,
) {
yield* git.removeWorktree({
cwd: checkout.repositoryPath,
path: checkout.worktreePath,
force,
});
if (deleteBranch !== undefined) {
yield* git
.deleteLocalBranch({ cwd: checkout.repositoryPath, refName: deleteBranch, force: true })
.pipe(Effect.ignoreCause({ log: true }));
}
});
// Folders whose creation ended before the project's layout command started, while their
// record is still there: a later removal has nothing of the project's to tear down either.
const neverLaidOut = new Set<string>();
const removeLocked = Effect.fn("TaskFolders.remove")(function* (
taskFolder: TaskFolder,
input: Omit<Parameters<TaskFolders["Service"]["remove"]>[0], "root">,
/** Repositories whose `deleteBranch` is not this folder's to delete. */
keepBranchIn: ReadonlySet<string> = new Set(),
/** False when the folder's layout command never started: nothing to tear down. */
laidOut = !neverLaidOut.has(taskFolder.root),
) {
const removed: string[] = [];
const kept: Array<{ path: string; reason: string }> = [];
let remaining = taskFolder.repositories;
const guard = input.guard ?? Effect.succeed(null);
const verdicts = new Map<string, TaskFolderVerdict>();
const verdict = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {
const known = verdicts.get(checkout.worktreePath);
if (known !== undefined) return known;
const decided: TaskFolderVerdict =
input.inspect === undefined
? { keep: null, force: input.force }
: yield* input.inspect(checkout);
verdicts.set(checkout.worktreePath, decided);
return decided;
});
// The project's own teardown goes first; what it leaves is removed below as usual. Only when
// every checkout may go: the command cannot be told which ones to keep.
const layout = laidOut
? yield* layoutCommand(taskFolder, "remove", input.projectCommands)
: null;
if (layout !== null && "refusal" in layout) {
yield* Effect.logInfo("The project's worktree layout remove command was left out", {
root: taskFolder.root,
reason: layout.refusal,
});
} else if (layout !== null) {
const checkouts = [
...taskFolder.repositories,
...(taskFolder.projectIsWorktree
? [{ worktreePath: taskFolder.projectPath, repositoryPath: taskFolder.projectRoot }]
: []),
];
const allGo = Effect.gen(function* () {
const rechecks: Array<Effect.Effect<string | null>> = [];
for (const checkout of checkouts) {
if (!(yield* exists(checkout.worktreePath))) continue;
const { keep, recheck } = yield* verdict(checkout);
if (keep !== null) return false;
if (recheck !== undefined) rechecks.push(recheck);
}
// The guard reads asynchronously: files are looked at last, right before the teardown.
if ((yield* guard) !== null) return false;
for (const recheck of rechecks) if ((yield* recheck) !== null) return false;
return true;
});
if (yield* allGo) {
yield* runLayoutCommand(
"remove",
layout.command,
taskFolder,
input.deleteBranch ?? "",
undefined,
taskFolder.repositories.map((repository) => repository.repositoryPath),
// The wait for a turn can be long: a checkout that gained work during it is looked at
// again, and the command stays unrun when one is now kept.
Effect.suspend(() => {
verdicts.clear();
return Effect.map(allGo, (go) => (go ? () => {} : null));
}),
).pipe(Effect.ignoreCause({ log: true }));
// The command took its time: what it left is looked at again before it is removed.
verdicts.clear();
}
}
const removeOne = Effect.fnUntraced(function* (checkout: TaskFolderCheckout) {
if (!(yield* exists(checkout.worktreePath))) {
yield* git
.pruneWorktrees({ cwd: checkout.repositoryPath })
.pipe(Effect.ignoreCause({ log: true }));
return true;
}
const { keep, force, recheck, prepare } = yield* verdict(checkout);
const reason =
keep ??
(yield* guard) ??
(recheck === undefined ? null : yield* recheck) ??
(prepare === undefined ? null : yield* prepare);
if (reason !== null) {
kept.push({ path: checkout.worktreePath, reason });
return false;
}
return yield* removeCheckout(
checkout,
force,
keepBranchIn.has(checkout.repositoryPath) ? undefined : input.deleteBranch,
).pipe(
Effect.as(true),
Effect.tap(() => Effect.sync(() => removed.push(checkout.worktreePath))),
Effect.catch((cause) =>
Effect.sync(() => {
kept.push({ path: checkout.worktreePath, reason: failureDetail(cause) });
return false;
}),
),
);
});
// Children first: a worktree nested in another must go before the one that holds it.
for (const repository of taskFolder.repositories.toSorted(
(left, right) => depth(right.worktreePath) - depth(left.worktreePath),
)) {