rex-worktrees 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -33453,6 +33453,8 @@ var withTime = /* @__PURE__ */ dual((args2) => isEffect(args2[0]), (self, label)
33453
33453
  }), () => self, () => sync(() => {
33454
33454
  console2.timeEnd(label);
33455
33455
  }))));
33456
+ // src/git.ts
33457
+ import { resolve as resolvePath } from "path";
33456
33458
  // src/contracts.ts
33457
33459
  class AppError extends exports_Schema.TaggedError()("AppError", {
33458
33460
  message: exports_Schema.String,
@@ -33476,9 +33478,19 @@ var ClientIdSchema = exports_Schema.String.pipe(exports_Schema.brand("ClientId")
33476
33478
  var WindowIdSchema = exports_Schema.String.pipe(exports_Schema.brand("WindowId"));
33477
33479
  var BlockIdSchema = exports_Schema.String.pipe(exports_Schema.brand("BlockId"));
33478
33480
  var LayerIdSchema = exports_Schema.String.pipe(exports_Schema.brand("LayerId"));
33479
- var RepositorySchema = exports_Schema.Struct({ path: exports_Schema.String, commonDir: exports_Schema.String, name: exports_Schema.String });
33481
+ var VcsSchema = exports_Schema.Literals(["git", "jj"]);
33482
+ var RepositoryFields = { path: exports_Schema.String, commonDir: exports_Schema.String, name: exports_Schema.String };
33483
+ var GitRepositorySchema = exports_Schema.Struct({ vcs: exports_Schema.Literal("git"), ...RepositoryFields });
33484
+ var JjRepositorySchema = exports_Schema.Struct({ vcs: exports_Schema.Literal("jj"), ...RepositoryFields });
33485
+ var RepositorySchema = exports_Schema.Union([GitRepositorySchema, JjRepositorySchema]);
33486
+ var JjWorkspaceNameSchema = exports_Schema.String.pipe(exports_Schema.brand("JjWorkspaceName"));
33487
+ var JjCommitIdSchema = exports_Schema.String.pipe(exports_Schema.brand("JjCommitId"));
33488
+ var JjChangeIdSchema = exports_Schema.String.pipe(exports_Schema.brand("JjChangeId"));
33489
+ var JjRevisionSchema = exports_Schema.Struct({ commitId: JjCommitIdSchema, changeId: JjChangeIdSchema, description: exports_Schema.String });
33490
+ var JjRevisionChoiceSchema = exports_Schema.Struct({ expression: exports_Schema.String, label: exports_Schema.String, revision: JjRevisionSchema });
33480
33491
  var RepositoryHeadSchema = exports_Schema.Struct({ branch: exports_Schema.NullOr(exports_Schema.String), head: exports_Schema.String });
33481
- var WorktreeSchema = exports_Schema.Struct({
33492
+ var GitWorktreeSchema = exports_Schema.Struct({
33493
+ vcs: exports_Schema.Literal("git"),
33482
33494
  path: exports_Schema.String,
33483
33495
  branch: exports_Schema.mutableKey(exports_Schema.NullOr(exports_Schema.String)),
33484
33496
  head: exports_Schema.mutableKey(exports_Schema.String),
@@ -33486,7 +33498,17 @@ var WorktreeSchema = exports_Schema.Struct({
33486
33498
  locked: exports_Schema.mutableKey(exports_Schema.Boolean),
33487
33499
  prunable: exports_Schema.mutableKey(exports_Schema.Boolean)
33488
33500
  });
33489
- var WorktreePlanSchema = exports_Schema.Struct({ repository: RepositorySchema, path: exports_Schema.String, branch: exports_Schema.String, existing: exports_Schema.Boolean });
33501
+ var JjWorktreeSchema = exports_Schema.Struct({
33502
+ vcs: exports_Schema.Literal("jj"),
33503
+ path: exports_Schema.NullOr(exports_Schema.String),
33504
+ name: JjWorkspaceNameSchema,
33505
+ head: JjCommitIdSchema,
33506
+ changeId: JjChangeIdSchema,
33507
+ present: exports_Schema.Boolean,
33508
+ colocated: exports_Schema.Boolean
33509
+ });
33510
+ var WorktreeSchema = exports_Schema.Union([GitWorktreeSchema, JjWorktreeSchema]);
33511
+ var WorktreePlanSchema = exports_Schema.Struct({ repository: GitRepositorySchema, path: exports_Schema.String, branch: exports_Schema.String, existing: exports_Schema.Boolean });
33490
33512
  var CreateWorktreeOptionsSchema = exports_Schema.Struct({
33491
33513
  startPoint: exports_Schema.optional(exports_Schema.String),
33492
33514
  attachOnly: exports_Schema.optional(exports_Schema.Boolean),
@@ -33508,8 +33530,9 @@ var ResolvedConfigSchema = exports_Schema.Struct({
33508
33530
  worktreeRoot: exports_Schema.UndefinedOr(exports_Schema.String),
33509
33531
  projectRoots: exports_Schema.Array(exports_Schema.Struct({ path: exports_Schema.String, worktreeRoot: exports_Schema.String }))
33510
33532
  });
33511
- var InstallSchema = exports_Schema.Struct({ source: exports_Schema.String, home: exports_Schema.String, configPath: exports_Schema.String, lua: exports_Schema.String, rexBinDir: exports_Schema.String, managedBin: exports_Schema.optional(exports_Schema.String) });
33533
+ var InstallSchema = exports_Schema.Struct({ source: exports_Schema.String, home: exports_Schema.String, configPath: exports_Schema.String, lua: exports_Schema.String, rexBinDir: exports_Schema.String, managedBin: exports_Schema.optional(exports_Schema.String), pathEnv: exports_Schema.optional(exports_Schema.String), allowLinkedConfig: exports_Schema.optional(exports_Schema.Boolean) });
33512
33534
  var AssociationSchema = exports_Schema.Struct({
33535
+ vcs: VcsSchema,
33513
33536
  hostId: ServerHostIdSchema,
33514
33537
  commonDir: exports_Schema.String,
33515
33538
  path: exports_Schema.String,
@@ -33521,27 +33544,106 @@ var SessionTargetSchema = exports_Schema.Struct({ id: SessionIdSchema, label: ex
33521
33544
  var ClientTargetSchema = exports_Schema.Struct({ id: ClientIdSchema, label: exports_Schema.String });
33522
33545
  var MachineSchema = exports_Schema.Struct({ key: exports_Schema.Union([exports_Schema.Literal("local"), RegisteredHostIdSchema]), label: exports_Schema.String, local: exports_Schema.Boolean, selector: exports_Schema.String });
33523
33546
  var DestinationHostSchema = exports_Schema.Struct({ ...MachineSchema.fields, hostId: ServerHostIdSchema });
33524
- var LaunchInputSchema = exports_Schema.Struct({
33547
+ var GitCloneSourceSchema = exports_Schema.Struct({
33548
+ vcs: exports_Schema.Literal("git"),
33549
+ url: exports_Schema.String,
33550
+ sourceHostId: ServerHostIdSchema,
33551
+ branches: exports_Schema.Array(exports_Schema.String),
33552
+ branch: exports_Schema.optional(exports_Schema.String)
33553
+ });
33554
+ var JjCloneSourceSchema = exports_Schema.Struct({
33555
+ vcs: exports_Schema.Literal("jj"),
33556
+ url: exports_Schema.String,
33557
+ sourceHostId: ServerHostIdSchema,
33558
+ revisions: exports_Schema.Array(JjRevisionChoiceSchema),
33559
+ revision: exports_Schema.optional(JjRevisionSchema)
33560
+ });
33561
+ var CloneSourceSchema = exports_Schema.Union([GitCloneSourceSchema, JjCloneSourceSchema]);
33562
+ var GitCloneInputSchema = exports_Schema.Struct({
33563
+ vcs: exports_Schema.Literal("git"),
33564
+ source: GitCloneSourceSchema,
33525
33565
  repo: exports_Schema.String,
33526
33566
  sessionId: SessionIdSchema,
33567
+ clientId: exports_Schema.optional(ClientIdSchema),
33568
+ name: exports_Schema.String,
33569
+ branch: exports_Schema.String,
33570
+ branchMode: exports_Schema.Literals(["existing", "create"]),
33571
+ worktreeName: exports_Schema.optional(exports_Schema.String)
33572
+ });
33573
+ var JjCloneInputSchema = exports_Schema.Struct({
33574
+ vcs: exports_Schema.Literal("jj"),
33575
+ source: JjCloneSourceSchema,
33576
+ repo: exports_Schema.String,
33577
+ sessionId: SessionIdSchema,
33578
+ clientId: exports_Schema.optional(ClientIdSchema),
33527
33579
  name: exports_Schema.String,
33528
- branch: exports_Schema.optional(exports_Schema.String),
33529
33580
  worktreeName: exports_Schema.optional(exports_Schema.String),
33530
- path: exports_Schema.optional(exports_Schema.String),
33581
+ revision: exports_Schema.optional(exports_Schema.String)
33582
+ });
33583
+ var CloneInputSchema = exports_Schema.Union([GitCloneInputSchema, JjCloneInputSchema]);
33584
+ var ClonePlanFields = {
33585
+ hostId: ServerHostIdSchema,
33586
+ sessionId: SessionIdSchema,
33587
+ clientId: exports_Schema.optional(ClientIdSchema),
33588
+ repo: exports_Schema.String,
33589
+ existing: exports_Schema.Boolean,
33590
+ commonDir: exports_Schema.optional(exports_Schema.String),
33591
+ label: exports_Schema.String,
33592
+ detail: exports_Schema.optional(exports_Schema.String),
33593
+ warning: exports_Schema.optional(exports_Schema.String)
33594
+ };
33595
+ var GitClonePlanSchema = exports_Schema.Struct({
33596
+ ...ClonePlanFields,
33597
+ vcs: exports_Schema.Literal("git"),
33598
+ input: GitCloneInputSchema,
33599
+ base: exports_Schema.optional(exports_Schema.String)
33600
+ });
33601
+ var JjClonePlanSchema = exports_Schema.Struct({
33602
+ ...ClonePlanFields,
33603
+ vcs: exports_Schema.Literal("jj"),
33604
+ input: JjCloneInputSchema,
33605
+ base: exports_Schema.optional(JjRevisionSchema)
33606
+ });
33607
+ var ClonePlanSchema = exports_Schema.Union([GitClonePlanSchema, JjClonePlanSchema]);
33608
+ var CloneLaunchResultSchema = exports_Schema.Struct({
33609
+ hostId: ServerHostIdSchema,
33610
+ sessionId: SessionIdSchema,
33611
+ windowId: WindowIdSchema,
33612
+ blockId: BlockIdSchema,
33613
+ repo: exports_Schema.String,
33614
+ pending: exports_Schema.Literal(true),
33615
+ warning: exports_Schema.optional(exports_Schema.String)
33616
+ });
33617
+ var CloneTaskRequestSchema = exports_Schema.Struct({ plan: ClonePlanSchema, rexBinDir: exports_Schema.optional(exports_Schema.String), rexLocalEndpoint: exports_Schema.optional(exports_Schema.String) });
33618
+ var LaunchInputFields = {
33619
+ repo: exports_Schema.String,
33620
+ sessionId: SessionIdSchema,
33621
+ name: exports_Schema.String,
33531
33622
  clientId: exports_Schema.optional(ClientIdSchema),
33532
33623
  additional: exports_Schema.optional(exports_Schema.Boolean),
33533
33624
  split: exports_Schema.optional(exports_Schema.Boolean)
33625
+ };
33626
+ var GitLaunchInputSchema = exports_Schema.Struct({
33627
+ ...LaunchInputFields,
33628
+ vcs: exports_Schema.Literal("git"),
33629
+ branch: exports_Schema.optional(exports_Schema.String),
33630
+ worktreeName: exports_Schema.optional(exports_Schema.String),
33631
+ path: exports_Schema.optional(exports_Schema.String)
33632
+ });
33633
+ var JjLaunchInputSchema = exports_Schema.Struct({
33634
+ ...LaunchInputFields,
33635
+ vcs: exports_Schema.Literal("jj"),
33636
+ path: exports_Schema.optional(exports_Schema.String),
33637
+ worktreeName: exports_Schema.optional(exports_Schema.String),
33638
+ revision: exports_Schema.optional(exports_Schema.String)
33534
33639
  });
33535
- var LaunchPlanSchema = exports_Schema.Struct({
33536
- input: LaunchInputSchema,
33640
+ var LaunchInputSchema = exports_Schema.Union([GitLaunchInputSchema, JjLaunchInputSchema]);
33641
+ var LaunchPlanFields = {
33537
33642
  hostId: ServerHostIdSchema,
33538
33643
  sessionId: SessionIdSchema,
33539
33644
  clientId: exports_Schema.optional(ClientIdSchema),
33540
33645
  path: exports_Schema.String,
33541
- branch: exports_Schema.NullOr(exports_Schema.String),
33542
- checkout: exports_Schema.Literals(["existing", "attach", "create"]),
33543
33646
  worktreeRoot: exports_Schema.optional(exports_Schema.String),
33544
- base: exports_Schema.optional(RepositoryHeadSchema),
33545
33647
  action: exports_Schema.Literals(["focus", "new-tab", "split"]),
33546
33648
  target: exports_Schema.optional(exports_Schema.Struct({ windowId: WindowIdSchema, blockId: BlockIdSchema, label: exports_Schema.String })),
33547
33649
  nameRole: exports_Schema.Literals(["tab", "pane", "none"]),
@@ -33549,7 +33651,24 @@ var LaunchPlanSchema = exports_Schema.Struct({
33549
33651
  label: exports_Schema.String,
33550
33652
  detail: exports_Schema.optional(exports_Schema.String),
33551
33653
  warning: exports_Schema.optional(exports_Schema.String)
33654
+ };
33655
+ var GitLaunchPlanSchema = exports_Schema.Struct({
33656
+ ...LaunchPlanFields,
33657
+ vcs: exports_Schema.Literal("git"),
33658
+ input: GitLaunchInputSchema,
33659
+ branch: exports_Schema.NullOr(exports_Schema.String),
33660
+ checkout: exports_Schema.Literals(["existing", "attach", "create"]),
33661
+ base: exports_Schema.optional(RepositoryHeadSchema)
33662
+ });
33663
+ var JjLaunchPlanSchema = exports_Schema.Struct({
33664
+ ...LaunchPlanFields,
33665
+ vcs: exports_Schema.Literal("jj"),
33666
+ input: JjLaunchInputSchema,
33667
+ checkout: exports_Schema.Literals(["existing", "create"]),
33668
+ workspaceName: JjWorkspaceNameSchema,
33669
+ base: exports_Schema.optional(JjRevisionSchema)
33552
33670
  });
33671
+ var LaunchPlanSchema = exports_Schema.Union([GitLaunchPlanSchema, JjLaunchPlanSchema]);
33553
33672
  var LaunchResultSchema = exports_Schema.Struct({
33554
33673
  hostId: ServerHostIdSchema,
33555
33674
  sessionId: SessionIdSchema,
@@ -33560,7 +33679,7 @@ var LaunchResultSchema = exports_Schema.Struct({
33560
33679
  action: exports_Schema.Literals(["focus", "new-tab", "split"]),
33561
33680
  warning: exports_Schema.optional(exports_Schema.String)
33562
33681
  });
33563
- var TaskRequestSchema = exports_Schema.Struct({
33682
+ var TaskRequestFields = {
33564
33683
  repo: exports_Schema.String,
33565
33684
  hostId: ServerHostIdSchema,
33566
33685
  rexBinDir: exports_Schema.optional(exports_Schema.String),
@@ -33568,27 +33687,48 @@ var TaskRequestSchema = exports_Schema.Struct({
33568
33687
  path: exports_Schema.String,
33569
33688
  commonDir: exports_Schema.String,
33570
33689
  sessionId: SessionIdSchema,
33690
+ worktreeRoot: exports_Schema.optional(exports_Schema.String)
33691
+ };
33692
+ var GitTaskRequestSchema = exports_Schema.Struct({
33693
+ ...TaskRequestFields,
33694
+ vcs: exports_Schema.Literal("git"),
33571
33695
  branch: exports_Schema.optional(exports_Schema.String),
33572
33696
  worktreeName: exports_Schema.optional(exports_Schema.String),
33573
33697
  base: exports_Schema.optional(exports_Schema.String),
33574
- worktreeRoot: exports_Schema.optional(exports_Schema.String),
33575
33698
  checkout: exports_Schema.optional(exports_Schema.Literals(["attach", "existing"]))
33576
33699
  });
33577
- var RequestIdentitySchema = exports_Schema.Struct({ version: exports_Schema.Literal(2), hostId: ServerHostIdSchema });
33700
+ var JjTaskRequestSchema = exports_Schema.Struct({
33701
+ ...TaskRequestFields,
33702
+ vcs: exports_Schema.Literal("jj"),
33703
+ checkout: exports_Schema.Literals(["existing", "create"]),
33704
+ workspaceName: JjWorkspaceNameSchema,
33705
+ base: exports_Schema.optional(JjRevisionSchema)
33706
+ });
33707
+ var TaskRequestSchema = exports_Schema.Union([GitTaskRequestSchema, JjTaskRequestSchema]);
33708
+ var RequestIdentitySchema = exports_Schema.Struct({ version: exports_Schema.Literal(3), hostId: ServerHostIdSchema });
33578
33709
  var RequestSchema = exports_Schema.Union([
33579
33710
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("discover"), context: exports_Schema.optional(exports_Schema.String) }),
33711
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("clone-source"), repo: exports_Schema.String }),
33580
33712
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("project"), path: exports_Schema.String }),
33581
33713
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("worktrees"), repo: exports_Schema.String }),
33714
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("revision"), repo: exports_Schema.String, revision: exports_Schema.String }),
33582
33715
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("branch"), repo: exports_Schema.String, branch: exports_Schema.String, worktreeName: exports_Schema.optional(exports_Schema.String) }),
33583
33716
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("plan"), input: LaunchInputSchema }),
33717
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("clone-plan"), input: CloneInputSchema }),
33718
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("clone-launch"), input: CloneInputSchema, reviewed: ClonePlanSchema }),
33584
33719
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("launch"), input: LaunchInputSchema, reviewed: LaunchPlanSchema })
33585
33720
  ]);
33586
33721
  var ResponseSchema = exports_Schema.Union([
33587
- exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("discover"), sessions: exports_Schema.Array(SessionTargetSchema), clients: exports_Schema.Array(ClientTargetSchema), projects: exports_Schema.Array(RepositorySchema), checkout: exports_Schema.optional(RepositorySchema) }),
33588
- exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("project"), project: RepositorySchema, checkout: RepositorySchema, worktrees: exports_Schema.Array(WorktreeSchema), branches: exports_Schema.Array(exports_Schema.String) }),
33589
- exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("worktrees"), worktrees: exports_Schema.Array(WorktreeSchema), branches: exports_Schema.Array(exports_Schema.String) }),
33722
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("discover"), sessions: exports_Schema.Array(SessionTargetSchema), clients: exports_Schema.Array(ClientTargetSchema), projects: exports_Schema.Array(RepositorySchema), roots: exports_Schema.optional(exports_Schema.Array(exports_Schema.String)), checkout: exports_Schema.optional(RepositorySchema) }),
33723
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("project"), project: RepositorySchema, checkout: RepositorySchema, worktrees: exports_Schema.Array(WorktreeSchema), branches: exports_Schema.Array(exports_Schema.String), revisions: exports_Schema.Array(JjRevisionChoiceSchema) }),
33724
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("project-missing"), path: exports_Schema.String }),
33725
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("clone-source"), source: CloneSourceSchema }),
33726
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("worktrees"), repository: RepositorySchema, worktrees: exports_Schema.Array(WorktreeSchema), branches: exports_Schema.Array(exports_Schema.String), revisions: exports_Schema.Array(JjRevisionChoiceSchema) }),
33590
33727
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("branch"), path: exports_Schema.String, branch: exports_Schema.String, existing: exports_Schema.Boolean }),
33728
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("revision"), revision: JjRevisionSchema }),
33591
33729
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("plan"), plan: LaunchPlanSchema }),
33730
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("clone-plan"), plan: ClonePlanSchema }),
33731
+ exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("clone-launch"), result: CloneLaunchResultSchema }),
33592
33732
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("launch"), result: LaunchResultSchema })
33593
33733
  ]);
33594
33734
  var RexWorktreesResponseSchema = exports_Schema.fromJsonString(exports_Schema.fromJsonString(ResponseSchema));
@@ -33633,19 +33773,21 @@ var RexActionsSchema = exports_Schema.Struct({ actions: exports_Schema.Array(exp
33633
33773
  var RexHelperArgsSchema = exports_Schema.Struct({ properties: exports_Schema.Struct({ request: exports_Schema.Struct({ type: exports_Schema.Literal("string") }) }) });
33634
33774
  var RexConfigCheckSchema = exports_Schema.Struct({ path: exports_Schema.String, exists: exports_Schema.Boolean, diagnostics: exports_Schema.Array(exports_Schema.Unknown) });
33635
33775
  var CliBooleanFlagSchema = exports_Schema.Literals(["--additional", "--split", "--no-context", "--managed-popup"]);
33636
- var CliStringFlagSchema = exports_Schema.Literals(["--bin", "--host", "--repo", "--session", "--name", "--branch", "--worktree", "--worktree-name", "--client", "--context", "--origin-session", "--origin-block", "--origin-client"]);
33776
+ var CliStringFlagSchema = exports_Schema.Literals(["--bin", "--config", "--host", "--repo", "--session", "--name", "--branch", "--revision", "--worktree", "--worktree-name", "--client", "--context", "--origin-session", "--origin-block", "--origin-client"]);
33637
33777
  var CliFlagsSchema = exports_Schema.Struct({
33638
33778
  "--additional": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.Boolean)),
33639
33779
  "--split": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.Boolean)),
33640
33780
  "--no-context": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.Boolean)),
33641
33781
  "--managed-popup": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.Boolean)),
33642
33782
  "--bin": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.String)),
33783
+ "--config": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.String)),
33643
33784
  "--host": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.String)),
33644
33785
  "--repo": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.String)),
33645
33786
  "--session": exports_Schema.mutableKey(exports_Schema.optional(SessionIdSchema)),
33646
33787
  "--name": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.String)),
33647
33788
  "--branch": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.String)),
33648
33789
  "--worktree": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.String)),
33790
+ "--revision": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.String)),
33649
33791
  "--worktree-name": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.String)),
33650
33792
  "--client": exports_Schema.mutableKey(exports_Schema.optional(ClientIdSchema)),
33651
33793
  "--context": exports_Schema.mutableKey(exports_Schema.optional(exports_Schema.String)),
@@ -33671,9 +33813,55 @@ var run4 = exports_Effect.fnUntraced(function* (program, args2, cwd, env) {
33671
33813
  }));
33672
33814
  });
33673
33815
 
33674
- // src/git.ts
33816
+ // src/checkout.ts
33675
33817
  var fail16 = (message) => exports_Effect.fail(new AppError({ message }));
33676
33818
  var missing2 = (error2) => exports_PlatformError.isPlatformError(error2) && error2.reason._tag === "NotFound";
33819
+ var planCheckoutPath = exports_Effect.fnUntraced(function* (primaryPath, metadataDirectories, checkoutPaths, name, worktreeRoot) {
33820
+ const fs = yield* exports_FileSystem.FileSystem;
33821
+ const path = yield* exports_Path.Path;
33822
+ if (worktreeRoot !== undefined && !path.isAbsolute(worktreeRoot))
33823
+ return yield* fail16("Worktree root must be absolute");
33824
+ const base = worktreeRoot === undefined ? `${primaryPath}.worktrees` : path.resolve(worktreeRoot);
33825
+ const destination = path.resolve(base, name);
33826
+ if (destination === base || !destination.startsWith(`${base}${path.sep}`))
33827
+ return yield* fail16("Worktree name escapes worktree directory");
33828
+ const inside = (parent, child) => child === parent || child.startsWith(`${parent}${path.sep}`);
33829
+ for (const checkout of checkoutPaths) {
33830
+ if (inside(checkout, base) || inside(checkout, destination))
33831
+ return yield* fail16(`Worktree root is inside checkout: ${checkout}`);
33832
+ }
33833
+ for (const metadata of metadataDirectories) {
33834
+ if (inside(metadata, base) || inside(metadata, destination))
33835
+ return yield* fail16(`Worktree root is inside metadata directory: ${metadata}`);
33836
+ }
33837
+ const forbidden2 = worktreeRoot === undefined ? [] : yield* exports_Effect.forEach([...checkoutPaths, ...metadataDirectories], (directory) => exports_Effect.catchIf(fs.stat(directory), missing2, () => exports_Effect.succeed(undefined)));
33838
+ if (forbidden2.some((entry) => entry && exports_Option.isNone(entry.ino)))
33839
+ return yield* fail16("Cannot verify worktree root filesystem identity");
33840
+ for (let part = path.parse(destination).root;; ) {
33841
+ const info2 = yield* exports_Effect.catchIf(fs.lstat(part), missing2, () => exports_Effect.succeed(undefined));
33842
+ if (info2?.type === "SymbolicLink")
33843
+ return yield* fail16(`Symlinked worktree path: ${part}`);
33844
+ if (worktreeRoot !== undefined && info2?.type === "Directory" && exports_Option.isNone(info2.ino))
33845
+ return yield* fail16("Cannot verify worktree root filesystem identity");
33846
+ const inode = info2 && exports_Option.getOrUndefined(info2.ino);
33847
+ if (inode !== undefined && forbidden2.some((entry) => entry !== undefined && info2 !== undefined && entry.dev === info2.dev && exports_Option.getOrUndefined(entry.ino) === inode)) {
33848
+ return yield* fail16(`Worktree root aliases a checkout or metadata directory: ${part}`);
33849
+ }
33850
+ if (part === destination) {
33851
+ if (info2)
33852
+ return yield* fail16(`Worktree path already exists: ${part}`);
33853
+ break;
33854
+ }
33855
+ if (info2 && info2.type !== "Directory")
33856
+ return yield* fail16(`Not a directory: ${part}`);
33857
+ part = path.join(part, path.relative(part, destination).split(path.sep)[0]);
33858
+ }
33859
+ return destination;
33860
+ });
33861
+
33862
+ // src/git.ts
33863
+ var fail17 = (message) => exports_Effect.fail(new AppError({ message }));
33864
+ var missing3 = (error2) => exports_PlatformError.isPlatformError(error2) && error2.reason._tag === "NotFound";
33677
33865
  var notRepository = (error2) => exports_Schema.is(CommandError)(error2) && error2.program === "git" && error2.args.includes("rev-parse") && (error2.stderr.startsWith("fatal: not a git repository") || error2.stderr.startsWith("fatal: this operation must be run in a work tree"));
33678
33866
  var git = (cwd, ...args2) => {
33679
33867
  const env = {};
@@ -33684,6 +33872,95 @@ var git = (cwd, ...args2) => {
33684
33872
  env.LC_ALL = "C";
33685
33873
  return run4("git", ["-C", cwd, ...args2], undefined, env);
33686
33874
  };
33875
+ var gitContext = exports_Effect.fnUntraced(function* (directory) {
33876
+ return yield* git(directory, "rev-parse", "--absolute-git-dir").pipe(exports_Effect.map((output) => output.trim()), exports_Effect.catchIf(notRepository, () => exports_Effect.succeed(undefined)));
33877
+ });
33878
+ var safeOrigin = (raw, sameHost, base) => {
33879
+ if (!raw || raw.startsWith("-") || /[\p{ASCII}&&\p{Cc}]/v.test(raw) || /^[a-z][a-z0-9+.-]*::/i.test(raw))
33880
+ throw new Error("Unsafe origin URL");
33881
+ if (raw.startsWith("/") || raw.startsWith("./") || raw.startsWith("../") || raw.startsWith("file://")) {
33882
+ if (!sameHost)
33883
+ throw new Error("Local source origins require the same Rex host");
33884
+ if (raw.startsWith("file://")) {
33885
+ const url = new URL(raw);
33886
+ if (url.host || url.search || url.hash || !url.pathname.startsWith("/"))
33887
+ throw new Error("Unsafe origin URL");
33888
+ const decoded = decodeURIComponent(url.pathname);
33889
+ if (/[\p{ASCII}&&\p{Cc}]/v.test(decoded))
33890
+ throw new Error("Unsafe origin URL");
33891
+ return decoded;
33892
+ }
33893
+ if (!base && !raw.startsWith("/"))
33894
+ throw new Error("Unsafe origin URL");
33895
+ return raw.startsWith("/") ? raw : resolvePath(base, raw);
33896
+ }
33897
+ if (/\s/.test(raw))
33898
+ throw new Error("Unsafe origin URL");
33899
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) {
33900
+ const url = new URL(raw);
33901
+ if (!["https:", "ssh:", "git:"].includes(url.protocol) || !url.hostname || !url.pathname || url.search || url.hash || (url.protocol === "ssh:" ? !!url.password || !!url.username && !/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(url.username) : !!url.username || !!url.password))
33902
+ throw new Error("Unsafe origin URL");
33903
+ return raw;
33904
+ }
33905
+ if (/^(?:[a-zA-Z0-9_][a-zA-Z0-9_.-]*@)?[\w.-]+:[a-zA-Z0-9_./~+%-][a-zA-Z0-9_./~+%:-]*$/.test(raw))
33906
+ return raw;
33907
+ throw new Error("Unsafe origin URL");
33908
+ };
33909
+ var origin = exports_Effect.fnUntraced(function* (repoPath, sameHost) {
33910
+ const raw = yield* git(repoPath, "config", "--get", "remote.origin.url").pipe(exports_Effect.catch(() => fail17("Repository has no usable origin URL")));
33911
+ return yield* exports_Effect.try({
33912
+ try: () => safeOrigin(raw.replace(/\n$/, ""), sameHost, repoPath),
33913
+ catch: () => new AppError({ message: "Repository origin URL is unsafe or local to another Rex host" })
33914
+ });
33915
+ });
33916
+ var cloneSource = exports_Effect.fnUntraced(function* (repoPath, sourceHostId) {
33917
+ const repo = yield* repository(repoPath);
33918
+ const url = yield* origin(repo.path, true);
33919
+ const refs = yield* git(repo.path, "for-each-ref", "--format=%(refname)", "refs/heads", "refs/remotes/origin");
33920
+ const branches = [...new Set(refs.split(`
33921
+ `).flatMap((ref) => ref.startsWith("refs/heads/") ? [ref.slice("refs/heads/".length)] : ref.startsWith("refs/remotes/origin/") && ref !== "refs/remotes/origin/HEAD" ? [ref.slice("refs/remotes/origin/".length)] : []))];
33922
+ const remoteHead = yield* git(repo.path, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD").pipe(exports_Effect.catch(() => exports_Effect.succeed("")));
33923
+ const current = yield* git(repo.path, "branch", "--show-current");
33924
+ const branch = remoteHead.trim().replace(/^refs\/remotes\/origin\//, "") || current.trim() || undefined;
33925
+ const source = { vcs: "git", url, sourceHostId, branches, ...branch ? { branch } : {} };
33926
+ return source;
33927
+ });
33928
+ var remoteBranches = exports_Effect.fnUntraced(function* (repoPath) {
33929
+ const refs = yield* git(repoPath, "for-each-ref", "--format=%(refname)", "refs/remotes/origin");
33930
+ return refs.split(`
33931
+ `).filter((ref) => ref.startsWith("refs/remotes/origin/") && ref !== "refs/remotes/origin/HEAD").map((ref) => ref.slice("refs/remotes/origin/".length));
33932
+ });
33933
+ var remoteBranchHead = exports_Effect.fnUntraced(function* (repoPath, branch) {
33934
+ return (yield* git(repoPath, "rev-parse", "--verify", `refs/remotes/origin/${branch}^{commit}`)).trim();
33935
+ });
33936
+ var originDefaultHead = exports_Effect.fnUntraced(function* (repoPath) {
33937
+ const ref = yield* git(repoPath, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD").pipe(exports_Effect.catch(() => fail17("Cannot determine the existing repository's cached origin default branch")));
33938
+ return (yield* git(repoPath, "rev-parse", "--verify", `${ref.trim()}^{commit}`)).trim();
33939
+ });
33940
+ var cloneRepository = exports_Effect.fnUntraced(function* (url, destination) {
33941
+ const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
33942
+ const env = {};
33943
+ for (const [key5, value3] of Object.entries(process.env))
33944
+ if (!key5.startsWith("GIT_") && value3 !== undefined)
33945
+ env[key5] = value3;
33946
+ env.GIT_TERMINAL_PROMPT = "1";
33947
+ const child = yield* spawner.spawn(exports_ChildProcess.make("git", ["clone", "--origin", "origin", "--", url, destination], {
33948
+ env,
33949
+ stdin: "inherit",
33950
+ stdout: "inherit",
33951
+ stderr: "inherit"
33952
+ }));
33953
+ const code = yield* child.exitCode;
33954
+ if (code !== 0)
33955
+ return yield* fail17(`Git clone failed (exit ${code}); destination retained at ${destination}`);
33956
+ }, exports_Effect.scoped);
33957
+ var validCloneBranch = exports_Effect.fnUntraced(function* (branch, worktreeName) {
33958
+ if (!branch || branch.startsWith("-") || branch.split("/").some((part) => !part || part === "." || part === "..") || /[\p{ASCII}&&\p{Cc}]/v.test(branch))
33959
+ return yield* fail17("Invalid clone branch");
33960
+ yield* run4("git", ["check-ref-format", "--branch", branch]).pipe(exports_Effect.catch(() => fail17("Invalid clone branch")));
33961
+ if (worktreeName !== undefined && (!worktreeName.trim() || worktreeName.startsWith("-") || worktreeName.split(/[\\/]/).some((part) => !part || part === "." || part === "..") || /[\p{ASCII}&&\p{Cc}]/v.test(worktreeName)))
33962
+ return yield* fail17("Invalid worktree name");
33963
+ });
33687
33964
  var listWorktrees = exports_Effect.fnUntraced(function* (repoPath) {
33688
33965
  const output = yield* git(repoPath, "worktree", "list", "--porcelain", "-z");
33689
33966
  const records = [];
@@ -33694,7 +33971,7 @@ var listWorktrees = exports_Effect.fnUntraced(function* (repoPath) {
33694
33971
  records.push(record2);
33695
33972
  record2 = undefined;
33696
33973
  } else if (line.startsWith("worktree ")) {
33697
- record2 = { path: line.slice(9), branch: null, head: "", bare: false, locked: false, prunable: false };
33974
+ record2 = { vcs: "git", path: line.slice(9), branch: null, head: "", bare: false, locked: false, prunable: false };
33698
33975
  } else if (record2) {
33699
33976
  if (line.startsWith("HEAD "))
33700
33977
  record2.head = line.slice(5);
@@ -33709,7 +33986,7 @@ var listWorktrees = exports_Effect.fnUntraced(function* (repoPath) {
33709
33986
  }
33710
33987
  }
33711
33988
  const fs = yield* exports_FileSystem.FileSystem;
33712
- return yield* exports_Effect.forEach(records, (record3) => exports_Effect.catchIf(fs.realPath(record3.path).pipe(exports_Effect.map((real) => ({ ...record3, path: real }))), (error2) => missing2(error2), () => exports_Effect.succeed(record3)));
33989
+ return yield* exports_Effect.forEach(records, (record3) => exports_Effect.catchIf(fs.realPath(record3.path).pipe(exports_Effect.map((real) => ({ ...record3, path: real }))), (error2) => missing3(error2), () => exports_Effect.succeed(record3)));
33713
33990
  });
33714
33991
  var repository = exports_Effect.fnUntraced(function* (input) {
33715
33992
  const fs = yield* exports_FileSystem.FileSystem;
@@ -33717,7 +33994,7 @@ var repository = exports_Effect.fnUntraced(function* (input) {
33717
33994
  const canonical = yield* fs.realPath(input);
33718
33995
  const top = (yield* git(canonical, "rev-parse", "--show-toplevel")).replace(/\n$/, "");
33719
33996
  const common = (yield* git(canonical, "rev-parse", "--path-format=absolute", "--git-common-dir")).replace(/\n$/, "");
33720
- return { path: yield* fs.realPath(top), commonDir: yield* fs.realPath(path.resolve(canonical, common)), name: path.basename(top) };
33997
+ return { vcs: "git", path: yield* fs.realPath(top), commonDir: yield* fs.realPath(path.resolve(canonical, common)), name: path.basename(top) };
33721
33998
  });
33722
33999
  var project = exports_Effect.fnUntraced(function* (input) {
33723
34000
  const checkout = yield* repository(input);
@@ -33727,43 +34004,9 @@ var project = exports_Effect.fnUntraced(function* (input) {
33727
34004
  return checkout;
33728
34005
  if (primary.path === checkout.path)
33729
34006
  return checkout;
33730
- const main = primary.bare ? undefined : yield* exports_Effect.catchIf(exports_Effect.catchIf(repository(primary.path), (error2) => missing2(error2), () => exports_Effect.succeed(undefined)), (error2) => notRepository(error2), () => exports_Effect.succeed(undefined));
34007
+ const main = primary.bare ? undefined : yield* exports_Effect.catchIf(exports_Effect.catchIf(repository(primary.path), (error2) => missing3(error2), () => exports_Effect.succeed(undefined)), (error2) => notRepository(error2), () => exports_Effect.succeed(undefined));
33731
34008
  return main?.commonDir === checkout.commonDir ? main : { ...checkout, name: path.basename(primary.path) };
33732
34009
  });
33733
- var discoverProjects = exports_Effect.fnUntraced(function* (roots, explicitProjects, contextPath) {
33734
- const fs = yield* exports_FileSystem.FileSystem;
33735
- const path = yield* exports_Path.Path;
33736
- const candidates = [...contextPath ? [contextPath] : [], ...explicitProjects];
33737
- for (const root of roots) {
33738
- if (!(yield* fs.exists(root)))
33739
- continue;
33740
- candidates.push(root);
33741
- for (const name of yield* fs.readDirectory(root)) {
33742
- const first = path.join(root, name);
33743
- if (!(yield* fs.exists(first)))
33744
- continue;
33745
- const info2 = yield* fs.stat(first);
33746
- if (info2.type !== "Directory")
33747
- continue;
33748
- candidates.push(first);
33749
- for (const child of yield* fs.readDirectory(first)) {
33750
- const second = path.join(first, child);
33751
- if ((yield* fs.exists(second)) && (yield* fs.stat(second)).type === "Directory")
33752
- candidates.push(second);
33753
- }
33754
- }
33755
- }
33756
- const found = [];
33757
- const seen = new Set;
33758
- for (const candidate of candidates) {
33759
- const repo = yield* exports_Effect.catchIf(exports_Effect.catchIf(project(candidate), (error2) => missing2(error2), () => exports_Effect.succeed(undefined)), (error2) => notRepository(error2), () => exports_Effect.succeed(undefined));
33760
- if (repo && !seen.has(repo.commonDir)) {
33761
- seen.add(repo.commonDir);
33762
- found.push(repo);
33763
- }
33764
- }
33765
- return found;
33766
- });
33767
34010
  var listBranches = exports_Effect.fnUntraced(function* (repoPath) {
33768
34011
  const refs = yield* git(repoPath, "for-each-ref", "--format=%(refname)%00", "refs/heads");
33769
34012
  return refs.split(`\x00
@@ -33778,80 +34021,44 @@ var planWorktree = exports_Effect.fnUntraced(function* (repoPath, branch, worktr
33778
34021
  const fs = yield* exports_FileSystem.FileSystem;
33779
34022
  const path = yield* exports_Path.Path;
33780
34023
  if (!branch || branch.startsWith("-") || branch.includes("\x00") || branch.split("/").some((part) => part === "." || part === ".." || part === "")) {
33781
- return yield* fail16(`Invalid branch name: ${JSON.stringify(branch)}`);
34024
+ return yield* fail17(`Invalid branch name: ${JSON.stringify(branch)}`);
33782
34025
  }
33783
34026
  yield* git(repoPath, "check-ref-format", "--branch", branch);
33784
34027
  if (worktreeName !== undefined && (!worktreeName.trim() || path.isAbsolute(worktreeName) || /[\p{ASCII}&&\p{Cc}]/v.test(worktreeName) || worktreeName.split(/[\\/]/).some((part) => !part || part === "." || part === ".."))) {
33785
- return yield* fail16(`Invalid worktree name: ${JSON.stringify(worktreeName)}`);
34028
+ return yield* fail17(`Invalid worktree name: ${JSON.stringify(worktreeName)}`);
33786
34029
  }
33787
34030
  const repo = yield* repository(repoPath);
33788
34031
  const worktrees = yield* listWorktrees(repo.path);
33789
34032
  const checked = worktrees.find((worktree) => worktree.branch === branch);
33790
34033
  if (checked) {
33791
- const gitFile = yield* exports_Effect.catchIf(fs.stat(path.join(checked.path, ".git")), (error2) => missing2(error2), () => exports_Effect.succeed(undefined));
34034
+ const gitFile = yield* exports_Effect.catchIf(fs.stat(path.join(checked.path, ".git")), (error2) => missing3(error2), () => exports_Effect.succeed(undefined));
33792
34035
  if (checked.prunable || !gitFile) {
33793
- return yield* fail16(`Branch ${branch} is assigned to an unavailable checkout: ${checked.path}`);
34036
+ return yield* fail17(`Branch ${branch} is assigned to an unavailable checkout: ${checked.path}`);
33794
34037
  }
33795
34038
  return { repository: repo, path: checked.path, branch, existing: true };
33796
34039
  }
33797
34040
  const main = worktrees.find((worktree) => !worktree.bare);
33798
34041
  if (!main)
33799
- return yield* fail16("No main checkout exists");
33800
- if (worktreeRoot !== undefined && !path.isAbsolute(worktreeRoot))
33801
- return yield* fail16("Worktree root must be absolute");
33802
- const base = worktreeRoot === undefined ? `${main.path}.worktrees` : path.resolve(worktreeRoot);
33803
- const destination = path.resolve(base, worktreeName ?? branch);
33804
- if (destination === base || !destination.startsWith(`${base}${path.sep}`))
33805
- return yield* fail16("Worktree name escapes worktree directory");
33806
- const inside = (parent, child) => child === parent || child.startsWith(`${parent}${path.sep}`);
33807
- for (const checkout of worktrees) {
33808
- if (inside(checkout.path, base) || inside(checkout.path, destination)) {
33809
- return yield* fail16(`Worktree root is inside checkout: ${checkout.path}`);
33810
- }
33811
- }
33812
- if (inside(repo.commonDir, base) || inside(repo.commonDir, destination))
33813
- return yield* fail16(`Worktree root is inside Git directory: ${repo.commonDir}`);
33814
- const forbidden2 = worktreeRoot === undefined ? [] : yield* exports_Effect.forEach([...worktrees.map((checkout) => checkout.path), repo.commonDir], (directory) => exports_Effect.catchIf(fs.stat(directory), (error2) => missing2(error2), () => exports_Effect.succeed(undefined)));
33815
- if (forbidden2.some((entry) => entry && exports_Option.isNone(entry.ino))) {
33816
- return yield* fail16("Cannot verify worktree root filesystem identity");
33817
- }
33818
- for (let part = path.parse(destination).root;; ) {
33819
- const info2 = yield* exports_Effect.catchIf(fs.lstat(part), (error2) => missing2(error2), () => exports_Effect.succeed(undefined));
33820
- if (info2?.type === "SymbolicLink")
33821
- return yield* fail16(`Symlinked worktree path: ${part}`);
33822
- if (worktreeRoot !== undefined && info2?.type === "Directory" && exports_Option.isNone(info2.ino)) {
33823
- return yield* fail16("Cannot verify worktree root filesystem identity");
33824
- }
33825
- const inode = info2 && exports_Option.getOrUndefined(info2.ino);
33826
- if (inode !== undefined && forbidden2.some((entry) => entry !== undefined && info2 !== undefined && entry.dev === info2.dev && exports_Option.getOrUndefined(entry.ino) === inode))
33827
- return yield* fail16(`Worktree root aliases a checkout or Git directory: ${part}`);
33828
- if (part === destination) {
33829
- if (info2)
33830
- return yield* fail16(`Worktree path already exists: ${part}`);
33831
- break;
33832
- }
33833
- if (info2 && info2.type !== "Directory")
33834
- return yield* fail16(`Not a directory: ${part}`);
33835
- part = path.join(part, path.relative(part, destination).split(path.sep)[0]);
33836
- }
34042
+ return yield* fail17("No main checkout exists");
34043
+ const destination = yield* planCheckoutPath(main.path, [repo.commonDir], worktrees.map((worktree) => worktree.path), worktreeName ?? branch, worktreeRoot);
33837
34044
  return { repository: repo, path: destination, branch, existing: false };
33838
34045
  });
33839
34046
  var createWorktree = exports_Effect.fnUntraced(function* (repoPath, branch, options = {}) {
33840
34047
  const { startPoint: pinned, attachOnly, worktreeRoot, worktreeName } = options;
33841
34048
  if (pinned !== undefined && !/^[0-9a-f]{40,64}$/.test(pinned))
33842
- return yield* fail16("Invalid pinned base commit");
34049
+ return yield* fail17("Invalid pinned base commit");
33843
34050
  if (pinned !== undefined && (yield* listBranches(repoPath)).includes(branch))
33844
- return yield* fail16(`Branch ${branch} appeared after review; inspect before retrying`);
34051
+ return yield* fail17(`Branch ${branch} appeared after review; inspect before retrying`);
33845
34052
  if (attachOnly && !(yield* listBranches(repoPath)).includes(branch))
33846
- return yield* fail16(`Branch ${branch} disappeared after review; inspect before retrying`);
34053
+ return yield* fail17(`Branch ${branch} disappeared after review; inspect before retrying`);
33847
34054
  const plan = yield* planWorktree(repoPath, branch, worktreeRoot, worktreeName);
33848
34055
  if (plan.existing) {
33849
34056
  if (pinned !== undefined || attachOnly)
33850
- return yield* fail16(`Branch ${branch} changed checkout after review; inspect before retrying`);
34057
+ return yield* fail17(`Branch ${branch} changed checkout after review; inspect before retrying`);
33851
34058
  const worktrees = yield* listWorktrees(plan.repository.path);
33852
34059
  const existing = worktrees.find((worktree) => worktree.path === plan.path);
33853
34060
  if (!existing)
33854
- return yield* fail16(`Worktree ${plan.path} disappeared after review; inspect before retrying`);
34061
+ return yield* fail17(`Worktree ${plan.path} disappeared after review; inspect before retrying`);
33855
34062
  return existing;
33856
34063
  }
33857
34064
  const branches = yield* listBranches(plan.repository.path);
@@ -33859,29 +34066,317 @@ var createWorktree = exports_Effect.fnUntraced(function* (repoPath, branch, opti
33859
34066
  const fs = yield* exports_FileSystem.FileSystem;
33860
34067
  const path = yield* exports_Path.Path;
33861
34068
  if (pinned !== undefined && branchExists)
33862
- return yield* fail16(`Branch ${branch} appeared after review; inspect before retrying`);
34069
+ return yield* fail17(`Branch ${branch} appeared after review; inspect before retrying`);
33863
34070
  if (attachOnly && !branchExists)
33864
- return yield* fail16(`Branch ${branch} disappeared after review; inspect before retrying`);
34071
+ return yield* fail17(`Branch ${branch} disappeared after review; inspect before retrying`);
33865
34072
  const current = yield* planWorktree(repoPath, branch, worktreeRoot, worktreeName);
33866
34073
  if (current.existing) {
33867
34074
  if (pinned !== undefined || attachOnly)
33868
- return yield* fail16(`Branch ${branch} changed checkout after review; inspect before retrying`);
34075
+ return yield* fail17(`Branch ${branch} changed checkout after review; inspect before retrying`);
33869
34076
  const existing = (yield* listWorktrees(plan.repository.path)).find((worktree) => worktree.path === current.path);
33870
34077
  if (!existing)
33871
- return yield* fail16(`Worktree ${current.path} disappeared after review; inspect before retrying`);
34078
+ return yield* fail17(`Worktree ${current.path} disappeared after review; inspect before retrying`);
33872
34079
  return existing;
33873
34080
  }
33874
34081
  yield* fs.makeDirectory(path.dirname(current.path), { recursive: true });
33875
34082
  if ((yield* fs.realPath(path.dirname(current.path))) !== path.dirname(current.path)) {
33876
- return yield* fail16(`Symlinked worktree parent: ${path.dirname(current.path)}`);
34083
+ return yield* fail17(`Symlinked worktree parent: ${path.dirname(current.path)}`);
33877
34084
  }
33878
34085
  yield* git(plan.repository.path, "worktree", "add", ...pinned !== undefined || !branchExists && !attachOnly ? ["-b", branch] : [], "--", current.path, ...pinned !== undefined ? [pinned] : branchExists || attachOnly ? [branch] : []);
33879
34086
  const created = (yield* listWorktrees(plan.repository.path)).find((worktree) => worktree.path === current.path);
33880
34087
  if (!created)
33881
- return yield* fail16(`Git did not list created worktree ${current.path}`);
34088
+ return yield* fail17(`Git did not list created worktree ${current.path}`);
33882
34089
  return created;
33883
34090
  });
33884
34091
 
34092
+ // src/jj.ts
34093
+ var fail18 = (message) => exports_Effect.fail(new AppError({ message }));
34094
+ var missing4 = (error2) => exports_PlatformError.isPlatformError(error2) && error2.reason._tag === "NotFound";
34095
+ var isolatedEnv = () => {
34096
+ const env = {};
34097
+ for (const [key5, value3] of Object.entries(process.env))
34098
+ if (!key5.startsWith("GIT_") && value3 !== undefined)
34099
+ env[key5] = value3;
34100
+ env.LC_ALL = "C";
34101
+ return env;
34102
+ };
34103
+ var jj = (repo, ...args2) => run4("jj", ["-R", repo, "--no-pager", "--color=never", ...args2], undefined, isolatedEnv());
34104
+ var inventory = (repo, ...args2) => jj(repo, "--ignore-working-copy", "--at-op=@", ...args2);
34105
+ var version = exports_Effect.fnUntraced(function* () {
34106
+ for (const [program, minimum] of [["jj", [0, 46]], ["git", [2, 42]]]) {
34107
+ const output = yield* run4(program, ["--version"], undefined, isolatedEnv()).pipe(exports_Effect.catchIf((error2) => missing4(error2), () => fail18(`${program} executable not found on this Rex host; install ${program} >= ${minimum.join(".")} and ensure it is on the popup/task PATH`)));
34108
+ const match9 = /\b(\d+)\.(\d+)(?:\.\d+)?\b/.exec(output);
34109
+ if (!match9 || Number(match9[1]) < minimum[0] || Number(match9[1]) === minimum[0] && Number(match9[2]) < minimum[1]) {
34110
+ return yield* fail18(`Requires ${program} >= ${minimum.join(".")}`);
34111
+ }
34112
+ }
34113
+ });
34114
+ var workspaceTemplate = 'json({"name" => name, "path" => root, "commitId" => self.target().commit_id(), "changeId" => self.target().change_id()}) ++ "\\n"';
34115
+ var revisionTemplate = 'json({"commitId" => commit_id, "changeId" => change_id, "description" => description, "conflict" => self.conflict()}) ++ "\\n"';
34116
+ var workspaceRow = exports_Schema.Struct({ name: JjWorkspaceNameSchema, path: exports_Schema.NullOr(exports_Schema.String), commitId: JjCommitIdSchema, changeId: JjChangeIdSchema });
34117
+ var revisionRow = exports_Schema.Struct({ commitId: JjCommitIdSchema, changeId: JjChangeIdSchema, description: exports_Schema.String, conflict: exports_Schema.Boolean });
34118
+ var bookmarkRow = exports_Schema.Struct({ name: exports_Schema.String, remote: exports_Schema.NullOr(exports_Schema.String), present: exports_Schema.Boolean, conflict: exports_Schema.Boolean, target: exports_Schema.String });
34119
+ var bookmarkTemplate = 'json({"name" => name, "remote" => remote, "present" => present, "conflict" => conflict, "target" => try(self.normal_target().commit_id(), "")}) ++ "\\n"';
34120
+ var rows = (schema, raw) => exports_Effect.forEach(raw.split(`
34121
+ `).filter(Boolean), (line) => exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(schema))(line));
34122
+ var validName = exports_Effect.fnUntraced(function* (value3) {
34123
+ if (!value3.trim() || value3 !== value3.trim() || value3.startsWith("-") || /[\\/\p{Cc}]/u.test(value3) || value3 === "." || value3 === "..")
34124
+ return yield* fail18("Invalid JJ workspace name");
34125
+ return yield* exports_Schema.decodeUnknownEffect(JjWorkspaceNameSchema)(value3);
34126
+ });
34127
+ var validPin = exports_Effect.fnUntraced(function* (id2) {
34128
+ if (!/^[0-9a-f]{40,64}$/.test(id2))
34129
+ return yield* fail18("Invalid full JJ base commit ID");
34130
+ return yield* exports_Schema.decodeUnknownEffect(JjCommitIdSchema)(id2);
34131
+ });
34132
+ var marker = exports_Effect.fnUntraced(function* (input) {
34133
+ const fs = yield* exports_FileSystem.FileSystem;
34134
+ const path = yield* exports_Path.Path;
34135
+ let directory = yield* fs.realPath(input);
34136
+ const info2 = yield* fs.stat(directory);
34137
+ if (info2.type !== "Directory")
34138
+ directory = path.dirname(directory);
34139
+ for (;; ) {
34140
+ const dot = path.join(directory, ".jj");
34141
+ const exists2 = yield* fs.stat(dot).pipe(exports_Effect.catchIf(missing4, () => exports_Effect.succeed(undefined)));
34142
+ if (exists2) {
34143
+ if (exists2.type !== "Directory")
34144
+ return yield* fail18("Invalid JJ workspace metadata");
34145
+ return { directory, dot };
34146
+ }
34147
+ const parent = path.dirname(directory);
34148
+ if (parent === directory)
34149
+ return yield* fail18("Not a JJ repository");
34150
+ directory = parent;
34151
+ }
34152
+ });
34153
+ var metadata = exports_Effect.fnUntraced(function* (dot) {
34154
+ const fs = yield* exports_FileSystem.FileSystem;
34155
+ const path = yield* exports_Path.Path;
34156
+ const pointer = path.join(dot, "repo");
34157
+ const entry = yield* fs.stat(pointer).pipe(exports_Effect.catchIf(missing4, () => fail18("JJ workspace has no repository metadata")));
34158
+ if (entry.type === "Directory")
34159
+ return yield* fs.realPath(pointer);
34160
+ if (entry.type !== "File")
34161
+ return yield* fail18("Invalid JJ repository pointer");
34162
+ const text = (yield* fs.readFileString(pointer)).trim();
34163
+ if (!text || text.includes("\x00"))
34164
+ return yield* fail18("Invalid JJ repository pointer");
34165
+ const target = yield* fs.realPath(path.resolve(dot, text));
34166
+ if ((yield* fs.stat(target)).type !== "Directory")
34167
+ return yield* fail18("Invalid JJ repository pointer");
34168
+ return target;
34169
+ });
34170
+ var repository2 = exports_Effect.fnUntraced(function* (input) {
34171
+ yield* version();
34172
+ const path = yield* exports_Path.Path;
34173
+ const { directory, dot } = yield* marker(input);
34174
+ return { vcs: "jj", path: directory, commonDir: yield* metadata(dot), name: path.basename(directory) };
34175
+ });
34176
+ var listWorkspaces = exports_Effect.fnUntraced(function* (repo) {
34177
+ const current = yield* repository2(repo);
34178
+ const fs = yield* exports_FileSystem.FileSystem;
34179
+ const path = yield* exports_Path.Path;
34180
+ const parsed = yield* rows(workspaceRow, yield* inventory(current.path, "workspace", "list", "-T", workspaceTemplate));
34181
+ return yield* exports_Effect.forEach(parsed, (item) => exports_Effect.gen(function* () {
34182
+ if (!item.path)
34183
+ return { vcs: "jj", path: null, name: item.name, head: item.commitId, changeId: item.changeId, present: false, colocated: false };
34184
+ const location = path.resolve(item.path);
34185
+ const real = yield* fs.realPath(location).pipe(exports_Effect.catchIf(missing4, () => exports_Effect.succeed(undefined)));
34186
+ let present = false;
34187
+ if (real) {
34188
+ const dot = yield* fs.stat(path.join(real, ".jj")).pipe(exports_Effect.catchIf(missing4, () => exports_Effect.succeed(undefined)));
34189
+ if (dot?.type === "Directory") {
34190
+ const linked = yield* metadata(path.join(real, ".jj"));
34191
+ present = linked === current.commonDir;
34192
+ }
34193
+ }
34194
+ const colocated = present && !!(yield* fs.stat(path.join(real, ".git")).pipe(exports_Effect.catchIf(missing4, () => exports_Effect.succeed(undefined))));
34195
+ return { vcs: "jj", path: real ?? location, name: item.name, head: item.commitId, changeId: item.changeId, present, colocated };
34196
+ }));
34197
+ });
34198
+ var project2 = exports_Effect.fnUntraced(function* (input) {
34199
+ const current = yield* repository2(input);
34200
+ const fs = yield* exports_FileSystem.FileSystem;
34201
+ const path = yield* exports_Path.Path;
34202
+ const primaryPath = path.dirname(path.dirname(current.commonDir));
34203
+ const primary = (yield* listWorkspaces(current.path)).find((item) => item.path === primaryPath);
34204
+ if (!primary?.present)
34205
+ return current;
34206
+ return { ...current, path: yield* fs.realPath(primaryPath), name: path.basename(primaryPath) };
34207
+ });
34208
+ var resolveRevision = exports_Effect.fnUntraced(function* (repo, expression) {
34209
+ if (!expression.trim() || expression.startsWith("-") || /[\p{Cc}]/u.test(expression))
34210
+ return yield* fail18("Invalid JJ base revision");
34211
+ const current = yield* repository2(repo);
34212
+ const revset = /^[0-9a-f]{40,64}$/.test(expression) ? `commit_id("${expression}")` : expression;
34213
+ const parsed = yield* rows(revisionRow, yield* inventory(current.path, "log", "-r", revset, "--no-graph", "--limit", "2", "-T", revisionTemplate));
34214
+ if (parsed.length !== 1 || parsed[0].conflict)
34215
+ return yield* fail18("JJ base must resolve to one non-conflicted revision");
34216
+ const { commitId, changeId, description } = parsed[0];
34217
+ return { commitId, changeId, description };
34218
+ });
34219
+ var listRevisions = exports_Effect.fnUntraced(function* (repo) {
34220
+ const current = yield* repository2(repo);
34221
+ const bookmarks = (yield* rows(bookmarkRow, yield* inventory(current.path, "bookmark", "list", "-T", bookmarkTemplate))).filter((item) => item.present && !item.conflict && /^[0-9a-f]{40,64}$/.test(item.target));
34222
+ const choices = [];
34223
+ const mainline = yield* inventory(current.path, "log", "-r", "trunk()", "--no-graph", "--limit", "2", "-T", revisionTemplate).pipe(exports_Effect.catchIf((error2) => exports_Schema.is(CommandError)(error2) && error2.program === "jj" && /^Error: (?:Failed to (?:parse|resolve) revset|Invalid revset|Revision |Revset |Cannot resolve |No such revision)/i.test(error2.stderr), () => exports_Effect.succeed("")));
34224
+ const mainlineRows = yield* rows(revisionRow, mainline);
34225
+ if (mainlineRows.length === 1 && !mainlineRows[0].conflict && !/^0+$/.test(mainlineRows[0].commitId)) {
34226
+ const item = mainlineRows[0];
34227
+ choices.push({
34228
+ expression: "trunk()",
34229
+ label: `Mainline \xB7 ${item.description.trim() || item.changeId.slice(0, 12)} \xB7 ${item.commitId.slice(0, 12)}`,
34230
+ revision: { commitId: item.commitId, changeId: item.changeId, description: item.description }
34231
+ });
34232
+ }
34233
+ const candidates = ["@-", "bookmarks()", "remote_bookmarks()"];
34234
+ for (const expression of candidates) {
34235
+ const raw = yield* inventory(current.path, "log", "-r", expression, "--no-graph", "--limit", "40", "-T", revisionTemplate);
34236
+ for (const item of yield* rows(revisionRow, raw)) {
34237
+ if (item.conflict || choices.some((choice) => choice.revision.commitId === item.commitId))
34238
+ continue;
34239
+ const revision = { commitId: item.commitId, changeId: item.changeId, description: item.description };
34240
+ const ref = bookmarks.find((bookmark) => bookmark.target === item.commitId && (expression === "remote_bookmarks()" ? bookmark.remote !== null : bookmark.remote === null));
34241
+ const label = expression === "@-" ? "Parent" : ref ? `${ref.name}${ref.remote ? `@${ref.remote}` : ""}` : expression === "bookmarks()" ? "Bookmark" : "Remote bookmark";
34242
+ choices.push({ expression: item.commitId, label: `${label} \xB7 ${item.description.trim() || item.changeId.slice(0, 12)} \xB7 ${item.commitId.slice(0, 12)}`, revision });
34243
+ }
34244
+ }
34245
+ return choices;
34246
+ });
34247
+ var gitRoot = exports_Effect.fnUntraced(function* (repo) {
34248
+ const fs = yield* exports_FileSystem.FileSystem;
34249
+ const raw = (yield* inventory(repo, "git", "root")).trim();
34250
+ if (!raw)
34251
+ return yield* fail18("JJ backing Git directory is unavailable");
34252
+ return yield* fs.realPath(raw);
34253
+ });
34254
+ var cloneSource2 = exports_Effect.fnUntraced(function* (repo, sourceHostId) {
34255
+ const current = yield* repository2(repo);
34256
+ const raw = yield* run4("git", ["--git-dir", yield* gitRoot(current.path), "config", "--get", "remote.origin.url"], undefined, isolatedEnv()).pipe(exports_Effect.catch(() => fail18("JJ repository has no usable origin URL")));
34257
+ const url = yield* exports_Effect.try({ try: () => safeOrigin(raw.replace(/\n$/, ""), true, current.path), catch: () => new AppError({ message: "JJ origin URL is unsafe or local to another Rex host" }) });
34258
+ const revisions = yield* listRevisions(current.path);
34259
+ const remote = (yield* rows(bookmarkRow, yield* inventory(current.path, "bookmark", "list", "-T", bookmarkTemplate))).filter((item) => item.present && !item.conflict && item.remote === "origin");
34260
+ const revision = remote.length === 1 ? revisions.find((choice) => choice.revision.commitId === remote[0].target)?.revision : undefined;
34261
+ return { vcs: "jj", url, sourceHostId, revisions, ...revision ? { revision } : {} };
34262
+ });
34263
+ var planWorkspace = exports_Effect.fnUntraced(function* (repo, name, revision, worktreeRoot) {
34264
+ const workspaceName = yield* validName(name);
34265
+ const source = yield* repository2(repo);
34266
+ const primary = yield* project2(source.path);
34267
+ const workspaces = yield* listWorkspaces(source.path);
34268
+ if (workspaces.some((item) => item.name === workspaceName))
34269
+ return yield* fail18(`JJ workspace ${name} already registered; inspect it before retrying`);
34270
+ const base = yield* resolveRevision(source.path, revision);
34271
+ const gitDirectory = yield* gitRoot(primary.path);
34272
+ const path = yield* planCheckoutPath(primary.path, [primary.commonDir, gitDirectory], workspaces.flatMap((item) => item.path === null ? [] : [item.path]), name, worktreeRoot);
34273
+ return { repository: source, path, workspaceName, base };
34274
+ });
34275
+ var createWorkspace = exports_Effect.fnUntraced(function* (repo, name, base, worktreeRoot) {
34276
+ const pin = yield* validPin(base.commitId);
34277
+ const planned = yield* planWorkspace(repo, name, pin, worktreeRoot);
34278
+ if (planned.base.changeId !== base.changeId || planned.base.commitId !== pin)
34279
+ return yield* fail18("JJ base changed since review; inspect before retrying");
34280
+ const fs = yield* exports_FileSystem.FileSystem;
34281
+ const path = yield* exports_Path.Path;
34282
+ yield* fs.makeDirectory(path.dirname(planned.path), { recursive: true });
34283
+ if ((yield* fs.realPath(path.dirname(planned.path))) !== path.dirname(planned.path))
34284
+ return yield* fail18("Symlinked JJ workspace parent");
34285
+ yield* jj(planned.repository.path, "workspace", "add", "--name", name, "-r", `commit_id("${pin}")`, planned.path);
34286
+ const created = (yield* listWorkspaces(planned.repository.path)).find((item) => item.name === name && item.path === planned.path);
34287
+ if (!created?.present)
34288
+ return yield* fail18(`JJ did not list created workspace at ${planned.path}; inspect before retrying`);
34289
+ return created;
34290
+ });
34291
+ var newChange = exports_Effect.fnUntraced(function* (repo, base) {
34292
+ const pin = yield* validPin(base.commitId);
34293
+ const current = yield* repository2(repo);
34294
+ const resolved = yield* resolveRevision(current.path, pin);
34295
+ if (resolved.changeId !== base.changeId)
34296
+ return yield* fail18("Selected JJ base is unavailable in destination clone; clone retained");
34297
+ const before = (yield* listWorkspaces(current.path)).find((item) => item.path === current.path);
34298
+ if (!before?.present)
34299
+ return yield* fail18("Cloned JJ default workspace is unavailable");
34300
+ yield* jj(current.path, "new", "-r", `commit_id("${pin}")`);
34301
+ const after = (yield* listWorkspaces(current.path)).find((item) => item.name === before.name);
34302
+ if (!after?.present)
34303
+ return yield* fail18("JJ did not list cloned default workspace after new change");
34304
+ return after;
34305
+ });
34306
+ var cloneRepository2 = exports_Effect.fnUntraced(function* (url, destination) {
34307
+ yield* version();
34308
+ const safe = yield* exports_Effect.try({ try: () => safeOrigin(url, true), catch: () => new AppError({ message: "Unsafe JJ clone URL" }) });
34309
+ const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
34310
+ const child = yield* spawner.spawn(exports_ChildProcess.make("jj", ["git", "clone", safe, destination], {
34311
+ env: isolatedEnv(),
34312
+ stdin: "inherit",
34313
+ stdout: "inherit",
34314
+ stderr: "inherit"
34315
+ })).pipe(exports_Effect.mapError(() => new AppError({ message: "Unable to launch JJ clone; destination may need inspection" })));
34316
+ const code = yield* child.exitCode;
34317
+ if (code !== 0)
34318
+ return yield* fail18(`JJ clone failed (exit ${code}); destination retained at ${destination}`);
34319
+ }, exports_Effect.scoped);
34320
+
34321
+ // src/repositories.ts
34322
+ var missing5 = (error2) => exports_PlatformError.isPlatformError(error2) && error2.reason._tag === "NotFound";
34323
+ var backend = exports_Effect.fnUntraced(function* (input) {
34324
+ const fs = yield* exports_FileSystem.FileSystem;
34325
+ const path = yield* exports_Path.Path;
34326
+ const canonical = yield* fs.realPath(input);
34327
+ let current = (yield* fs.stat(canonical)).type === "Directory" ? canonical : path.dirname(canonical);
34328
+ for (;; ) {
34329
+ if (yield* fs.lstat(path.join(current, ".jj")).pipe(exports_Effect.map(() => true), exports_Effect.catchIf(missing5, () => exports_Effect.succeed(false))))
34330
+ return "jj";
34331
+ if (yield* fs.lstat(path.join(current, ".git")).pipe(exports_Effect.map(() => true), exports_Effect.catchIf(missing5, () => exports_Effect.succeed(false))))
34332
+ return "git";
34333
+ const parent = path.dirname(current);
34334
+ if (parent === current)
34335
+ return "git";
34336
+ current = parent;
34337
+ }
34338
+ });
34339
+ var repository3 = exports_Effect.fnUntraced(function* (input) {
34340
+ return (yield* backend(input)) === "jj" ? yield* repository2(input) : yield* repository(input);
34341
+ });
34342
+ var project3 = exports_Effect.fnUntraced(function* (input) {
34343
+ return (yield* backend(input)) === "jj" ? yield* project2(input) : yield* project(input);
34344
+ });
34345
+ var discoverProjects = exports_Effect.fnUntraced(function* (roots, explicitProjects, contextPath) {
34346
+ const fs = yield* exports_FileSystem.FileSystem;
34347
+ const path = yield* exports_Path.Path;
34348
+ const candidates = [...contextPath ? [contextPath] : [], ...explicitProjects];
34349
+ for (const root of roots) {
34350
+ if (!(yield* fs.exists(root)))
34351
+ continue;
34352
+ candidates.push(root);
34353
+ for (const name of yield* fs.readDirectory(root)) {
34354
+ const first = path.join(root, name);
34355
+ if (!(yield* fs.exists(first)))
34356
+ continue;
34357
+ const info2 = yield* fs.stat(first);
34358
+ if (info2.type !== "Directory")
34359
+ continue;
34360
+ candidates.push(first);
34361
+ for (const child of yield* fs.readDirectory(first)) {
34362
+ const second = path.join(first, child);
34363
+ if ((yield* fs.exists(second)) && (yield* fs.stat(second)).type === "Directory")
34364
+ candidates.push(second);
34365
+ }
34366
+ }
34367
+ }
34368
+ const found = [];
34369
+ const seen = new Set;
34370
+ for (const candidate of candidates) {
34371
+ const repo = yield* exports_Effect.catchIf(exports_Effect.catchIf(project3(candidate), (error2) => missing5(error2), () => exports_Effect.succeed(undefined)), (error2) => notRepository(error2), () => exports_Effect.succeed(undefined));
34372
+ if (repo && !seen.has(`${repo.vcs}\x00${repo.commonDir}`)) {
34373
+ seen.add(`${repo.vcs}\x00${repo.commonDir}`);
34374
+ found.push(repo);
34375
+ }
34376
+ }
34377
+ return found;
34378
+ });
34379
+
33885
34380
  // src/config.ts
33886
34381
  var loadConfig = exports_Effect.gen(function* () {
33887
34382
  const fs = yield* exports_FileSystem.FileSystem;
@@ -33909,10 +34404,10 @@ var loadConfig = exports_Effect.gen(function* () {
33909
34404
  });
33910
34405
  var resolveWorktreeRoot = exports_Effect.fnUntraced(function* (repoPath) {
33911
34406
  const config = yield* loadConfig;
33912
- const target = yield* project(repoPath);
34407
+ const target = yield* project3(repoPath);
33913
34408
  for (const entry of config.projectRoots) {
33914
- const candidate = yield* exports_Effect.catchIf(exports_Effect.catchIf(repository(entry.path), (error2) => missing2(error2), () => exports_Effect.succeed(undefined)), (error2) => notRepository(error2), () => exports_Effect.succeed(undefined));
33915
- if (candidate?.commonDir === target.commonDir)
34409
+ const candidate = yield* exports_Effect.catchIf(exports_Effect.catchIf(repository3(entry.path), (error2) => missing3(error2), () => exports_Effect.succeed(undefined)), (error2) => notRepository(error2), () => exports_Effect.succeed(undefined));
34410
+ if (candidate?.vcs === target.vcs && candidate.commonDir === target.commonDir)
33916
34411
  return entry.worktreeRoot;
33917
34412
  }
33918
34413
  const path = yield* exports_Path.Path;
@@ -33923,6 +34418,8 @@ var resolveWorktreeRoot = exports_Effect.fnUntraced(function* (repoPath) {
33923
34418
  import { hostname } from "os";
33924
34419
  var localName = hostname().toLowerCase().replace(/\.$/, "").replace(/\.local$/, "");
33925
34420
  var localDirectoryUri = (raw) => {
34421
+ if (raw.startsWith("/"))
34422
+ return raw.includes("\x00") ? undefined : raw;
33926
34423
  try {
33927
34424
  const url = new URL(raw);
33928
34425
  const authority = url.hostname.toLowerCase().replace(/\.$/, "").replace(/\.local$/, "");
@@ -34008,9 +34505,11 @@ var originDirectory = exports_Effect.fnUntraced(function* (sessionId, blockId) {
34008
34505
  return;
34009
34506
  const raw = yield* rex(["block", "call", "-s", sessionId, "-b", blockId, "pwd"]);
34010
34507
  const result4 = yield* parse3(RexDirectorySchema, raw);
34011
- if (!result4.pwd)
34012
- return;
34013
- return localDirectoryUri(result4.pwd);
34508
+ if (result4.pwd)
34509
+ return localDirectoryUri(result4.pwd);
34510
+ const processInfo = yield* parse3(RexProcessSchema, yield* rex(["block", "call", "-s", sessionId, "-b", blockId, "process"]));
34511
+ const cwd = processInfo.foreground?.cwd;
34512
+ return cwd?.startsWith("/") && !cwd.includes("\x00") ? cwd : undefined;
34014
34513
  });
34015
34514
  var fitPopupBounds = (bounds, preferred, observed) => {
34016
34515
  if (![...bounds, preferred.columns, preferred.rows, observed.columns, observed.rows].every(Number.isFinite) || bounds[2] <= 0 || bounds[3] <= 0 || observed.columns <= 0 || observed.rows <= 0 || preferred.columns <= 0 || preferred.rows <= 0)
@@ -34093,8 +34592,9 @@ var makePopupSizer = exports_Effect.gen(function* () {
34093
34592
  }))));
34094
34593
  return resize;
34095
34594
  });
34595
+ var commandWithPath = (command) => process.env.PATH ? ["/usr/bin/env", `PATH=${process.env.PATH}`, ...command] : command;
34096
34596
  var createTab = exports_Effect.fnUntraced(function* (sessionId, name, cwd, command) {
34097
- const result4 = yield* parse3(RexCreatedSchema, yield* rex(["window", "new", "-s", sessionId, name, "-c", cwd, "--shell=none", "--keep-open", "--json", "--", ...command]));
34597
+ const result4 = yield* parse3(RexCreatedSchema, yield* rex(["window", "new", "-s", sessionId, name, "-c", cwd, "--shell=none", "--keep-open", "--json", "--", ...commandWithPath(command)]));
34098
34598
  const blockId = result4.block_ids[0];
34099
34599
  if (!blockId)
34100
34600
  return yield* exports_Effect.fail(new AppError({ message: "Rex created a tab without a terminal block" }));
@@ -34103,7 +34603,7 @@ var createTab = exports_Effect.fnUntraced(function* (sessionId, name, cwd, comma
34103
34603
  return { windowId: result4.window_id, blockId };
34104
34604
  });
34105
34605
  var createSplit = exports_Effect.fnUntraced(function* (sessionId, windowId, blockId, name, cwd, command) {
34106
- const result4 = yield* parse3(RexCreatedSchema, yield* rex(["split", "-s", sessionId, "-b", blockId, "--split=right", "--label", name, "-c", cwd, "--shell=none", "--keep-open", "--json", "--", ...command]));
34606
+ const result4 = yield* parse3(RexCreatedSchema, yield* rex(["split", "-s", sessionId, "-b", blockId, "--split=right", "--label", name, "-c", cwd, "--shell=none", "--keep-open", "--json", "--", ...commandWithPath(command)]));
34107
34607
  const created = result4.block_ids.find((id2) => id2 !== blockId);
34108
34608
  if (!created)
34109
34609
  return yield* exports_Effect.fail(new AppError({ message: "Rex created a split without a new terminal block" }));
@@ -34126,29 +34626,29 @@ var focus = exports_Effect.fnUntraced(function* (sessionId, windowId, clientId,
34126
34626
  }
34127
34627
  return warnings.length ? warnings.join("; ") : undefined;
34128
34628
  });
34129
- var openPopup = exports_Effect.fnUntraced(function* (command, sessionId, origin = {}) {
34629
+ var openPopup = exports_Effect.fnUntraced(function* (command, sessionId, origin2 = {}) {
34130
34630
  const path = yield* exports_Path.Path;
34131
34631
  const endpoint = (yield* localIdentity).endpoint;
34132
34632
  const program = yield* binary(path);
34133
34633
  const localRex = (args3) => run4(program, ["-S", endpoint, "--autostart=false", ...args3], undefined, nativeEnv());
34134
34634
  const view = yield* parse3(RexViewSchema, yield* localRex(["api", "call", "-s", sessionId, "session.view", JSON.stringify({ session_id: sessionId })]));
34135
- const source = origin.blockId ? view.windows.find((window) => window.layers.some((layer12) => layer12.blocks.some((block) => block.block_id === origin.blockId))) : undefined;
34136
- if (origin.blockId && !source)
34635
+ const source = origin2.blockId ? view.windows.find((window) => window.layers.some((layer12) => layer12.blocks.some((block) => block.block_id === origin2.blockId))) : undefined;
34636
+ if (origin2.blockId && !source)
34137
34637
  return yield* exports_Effect.fail(new AppError({ message: "Source pane is no longer in the selected Rex session" }));
34138
34638
  const windowId = source?.window_id ?? view.active_window_id;
34139
34639
  if (!windowId || !view.windows.some((window) => window.window_id === windowId)) {
34140
34640
  return yield* exports_Effect.fail(new AppError({ message: "No active Rex window for the popup" }));
34141
34641
  }
34142
- const sourceOwner = source?.layers.flatMap((layer12) => layer12.blocks).find((block) => block.block_id === origin.blockId)?.owner;
34642
+ const sourceOwner = source?.layers.flatMap((layer12) => layer12.blocks).find((block) => block.block_id === origin2.blockId)?.owner;
34143
34643
  const clients = (yield* parse3(RexClientsSchema, yield* localRex(["client", "ls", "--json"]))).clients.filter((client) => client.info?.kind === "app" && client.connection_state === "connected");
34144
- const clientId = [sourceOwner, origin.clientId].find((id2) => id2 && clients.some((client) => client.client_id === id2));
34644
+ const clientId = [sourceOwner, origin2.clientId].find((id2) => id2 && clients.some((client) => client.client_id === id2));
34145
34645
  const popupCommand = clientId ? [...command, "--managed-popup", "--origin-client", clientId] : [...command, "--managed-popup"];
34146
34646
  const width2 = 0.68, height = 0.35;
34147
34647
  const args2 = {
34148
34648
  session_id: sessionId,
34149
34649
  window_id: windowId,
34150
34650
  bounds: [(1 - width2) / 2, (1 - height) / 2, width2, height],
34151
- layout: { block: { flavor: "com.superlogical.terminal.shell", options: { command: popupCommand, shell: "none", cwd: process.cwd(), exit: { on_completion: true } } } },
34651
+ layout: { block: { flavor: "com.superlogical.terminal.shell", options: { command: commandWithPath(popupCommand), shell: "none", cwd: process.cwd(), exit: { on_completion: true } } } },
34152
34652
  focus: true
34153
34653
  };
34154
34654
  const created = yield* parse3(RexLayerSchema, yield* localRex(["api", "call", "-s", sessionId, "session.new_layer", JSON.stringify(args2)]));
@@ -34209,7 +34709,7 @@ var associations = exports_Effect.gen(function* () {
34209
34709
  });
34210
34710
 
34211
34711
  // src/worktrees.ts
34212
- var fail17 = (message) => exports_Effect.fail(new AppError({ message }));
34712
+ var fail19 = (message) => exports_Effect.fail(new AppError({ message }));
34213
34713
  var canonical = exports_Effect.fnUntraced(function* (path) {
34214
34714
  const fs = yield* exports_FileSystem.FileSystem;
34215
34715
  return yield* fs.realPath(path);
@@ -34241,56 +34741,83 @@ var liveBlock = exports_Effect.fnUntraced(function* (sessionId, windowId, blockI
34241
34741
  const pathname = localDirectoryUri(reported.pwd);
34242
34742
  if (!pathname)
34243
34743
  return false;
34244
- const cwd = yield* exports_Effect.catchIf(canonical(pathname), (error2) => missing2(error2), () => exports_Effect.succeed(""));
34744
+ const cwd = yield* exports_Effect.catchIf(canonical(pathname), (error2) => missing3(error2), () => exports_Effect.succeed(""));
34245
34745
  return cwd === path ? window.label : false;
34246
34746
  });
34247
34747
  var planLaunch = exports_Effect.fnUntraced(function* (input, expectedHostId) {
34248
34748
  const host = yield* localHost;
34249
34749
  if (expectedHostId && host.id !== expectedHostId)
34250
- return yield* fail17(`Wrong Rex host: expected ${expectedHostId}, got ${host.id}`);
34750
+ return yield* fail19(`Wrong Rex host: expected ${expectedHostId}, got ${host.id}`);
34251
34751
  if (!(yield* listSessions).some((item) => item.id === input.sessionId))
34252
- return yield* fail17(`Rex session ${input.sessionId} does not exist locally`);
34752
+ return yield* fail19(`Rex session ${input.sessionId} does not exist locally`);
34253
34753
  const clients = yield* listClients;
34254
34754
  if (input.clientId && !clients.some((item) => item.id === input.clientId))
34255
- return yield* fail17(`Rex app client ${input.clientId} is not connected locally`);
34755
+ return yield* fail19(`Rex app client ${input.clientId} is not connected locally`);
34256
34756
  const clientId = input.clientId ?? (clients.length === 1 ? clients[0]?.id : undefined);
34257
- if (!!input.branch === !!input.path)
34258
- return yield* fail17("Select exactly one branch or existing worktree path");
34259
- if (input.path && input.worktreeName !== undefined)
34260
- return yield* fail17("Worktree name only applies to a branch checkout");
34261
- const repo = yield* repository(input.repo);
34262
- const worktreeRoot = input.branch ? yield* resolveWorktreeRoot(repo.path) : undefined;
34757
+ const repo = yield* repository3(input.repo);
34758
+ if (repo.vcs !== input.vcs)
34759
+ return yield* fail19("Repository backend changed since selection");
34263
34760
  let path;
34264
- let branch;
34265
34761
  let checkout;
34762
+ let branch = null;
34763
+ let workspaceName;
34266
34764
  let base;
34267
- if (input.branch) {
34268
- const destination = yield* planWorktree(repo.path, input.branch, worktreeRoot, input.worktreeName);
34269
- path = destination.path;
34270
- branch = input.branch;
34271
- checkout = destination.existing ? "existing" : (yield* listBranches(repo.path)).includes(branch) ? "attach" : "create";
34272
- if (checkout === "create")
34273
- base = yield* repositoryHead(repo.path);
34765
+ let gitBase;
34766
+ let worktreeRoot;
34767
+ let detail;
34768
+ if (input.vcs === "git") {
34769
+ if (!!input.branch === !!input.path)
34770
+ return yield* fail19("Select exactly one branch or existing worktree path");
34771
+ if (input.path && input.worktreeName !== undefined)
34772
+ return yield* fail19("Worktree name only applies to a branch checkout");
34773
+ worktreeRoot = input.branch ? yield* resolveWorktreeRoot(repo.path) : undefined;
34774
+ if (input.branch) {
34775
+ const destination = yield* planWorktree(repo.path, input.branch, worktreeRoot, input.worktreeName);
34776
+ path = destination.path;
34777
+ branch = input.branch;
34778
+ checkout = destination.existing ? "existing" : (yield* listBranches(repo.path)).includes(branch) ? "attach" : "create";
34779
+ if (checkout === "create")
34780
+ gitBase = yield* repositoryHead(repo.path);
34781
+ } else {
34782
+ if (!input.path)
34783
+ return yield* fail19("Select an existing worktree path");
34784
+ path = yield* canonical(input.path);
34785
+ const tree = (yield* listWorktrees(repo.path)).find((entry) => entry.path === path);
34786
+ if (!tree)
34787
+ return yield* fail19(`${path} is not a Git worktree of ${repo.path}`);
34788
+ branch = tree.branch;
34789
+ checkout = "existing";
34790
+ }
34791
+ detail = checkout === "existing" && !!input.branch ? `Branch ${branch} is already checked out; opening its existing worktree.` : checkout === "attach" ? `Branch ${branch} already exists; attaching a checkout, not creating the branch.` : undefined;
34274
34792
  } else {
34275
- if (!input.path)
34276
- return yield* fail17("Select an existing worktree path");
34277
- path = yield* canonical(input.path);
34278
- const tree = (yield* listWorktrees(repo.path)).find((entry) => entry.path === path);
34279
- if (!tree)
34280
- return yield* fail17(`${path} is not a Git worktree of ${repo.path}`);
34281
- branch = tree.branch;
34282
- checkout = "existing";
34793
+ if (!!input.path === !!input.worktreeName || input.path && input.revision || !input.path && !input.revision)
34794
+ return yield* fail19("Select an existing workspace path or a new workspace name and base revision");
34795
+ if (input.path) {
34796
+ path = yield* canonical(input.path);
34797
+ const tree = (yield* listWorkspaces(repo.path)).find((entry) => entry.path === path && entry.present);
34798
+ if (!tree)
34799
+ return yield* fail19(`${path} is not an available JJ workspace of ${repo.path}`);
34800
+ workspaceName = tree.name;
34801
+ checkout = "existing";
34802
+ } else {
34803
+ worktreeRoot = yield* resolveWorktreeRoot(repo.path);
34804
+ const planned = yield* planWorkspace(repo.path, input.worktreeName, input.revision, worktreeRoot);
34805
+ path = planned.path;
34806
+ workspaceName = planned.workspaceName;
34807
+ base = planned.base;
34808
+ checkout = "create";
34809
+ }
34283
34810
  }
34284
34811
  let warning;
34285
34812
  const records = yield* associations.pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => {
34286
- warning = exports_Cause.pretty(exports_Cause.fail(error2));
34813
+ warning = [warning, exports_Cause.pretty(exports_Cause.fail(error2))].filter(Boolean).join("; ");
34287
34814
  return [];
34288
34815
  })));
34289
34816
  if (!clientId && clients.length > 1)
34290
34817
  warning = [warning, "Multiple Rex apps are connected; select the session in the intended app"].filter(Boolean).join("; ");
34291
34818
  let target;
34292
34819
  for (const entry of records) {
34293
- if (entry.hostId !== host.id || entry.commonDir !== repo.commonDir || entry.path !== path || entry.sessionId !== input.sessionId)
34820
+ if (entry.vcs !== repo.vcs || entry.hostId !== host.id || entry.commonDir !== repo.commonDir || entry.path !== path || entry.sessionId !== input.sessionId)
34294
34821
  continue;
34295
34822
  const label = yield* liveBlock(entry.sessionId, entry.windowId, entry.blockId, host.id, path);
34296
34823
  if (label !== false) {
@@ -34300,42 +34827,57 @@ var planLaunch = exports_Effect.fnUntraced(function* (input, expectedHostId) {
34300
34827
  }
34301
34828
  const action = input.split && target ? "split" : target && !input.additional && !input.split ? "focus" : "new-tab";
34302
34829
  const nameRole = action === "focus" ? "none" : action === "split" ? "pane" : "tab";
34303
- if (nameRole !== "none" && (!input.name.trim() || input.name.startsWith("-") || /[\p{ASCII}&&\p{Cc}]/v.test(input.name))) {
34304
- return yield* fail17(`Invalid Rex ${nameRole} name`);
34305
- }
34306
- const detail = input.split && !target ? "No live tab for this checkout; opening a new tab instead." : checkout === "existing" && !!input.branch ? `Branch ${branch} is already checked out; ${action === "focus" ? "focusing its existing tab" : "opening its existing worktree"}.` : checkout === "attach" ? `Branch ${branch} already exists; attaching a checkout, not creating the branch.` : undefined;
34307
- const plan = {
34308
- input: { ...input, repo: repo.path, ...input.path ? { path } : {} },
34830
+ if (nameRole !== "none" && (!input.name.trim() || input.name.startsWith("-") || /[\p{ASCII}&&\p{Cc}]/v.test(input.name)))
34831
+ return yield* fail19(`Invalid Rex ${nameRole} name`);
34832
+ if (input.split && !target)
34833
+ detail = "No live tab for this checkout; opening a new tab instead.";
34834
+ if (input.vcs === "jj" && checkout === "create")
34835
+ detail = [detail, `Creating a JJ workspace snapshots ${repo.path}; its working-copy commit and colocated Git index intent-to-add entries may change.`].filter(Boolean).join(" ");
34836
+ const common = {
34309
34837
  hostId: host.id,
34310
34838
  sessionId: input.sessionId,
34311
34839
  ...clientId ? { clientId } : {},
34312
34840
  path,
34313
- branch,
34314
- checkout,
34315
34841
  ...worktreeRoot ? { worktreeRoot } : {},
34316
- ...base ? { base } : {},
34317
34842
  action,
34318
34843
  ...target ? { target } : {},
34319
34844
  nameRole,
34320
34845
  ...nameRole !== "none" ? { name: input.name } : {},
34321
- label: action === "focus" ? "Focus existing tab" : checkout === "create" ? "Create worktree & open" : checkout === "attach" ? "Attach branch & open" : action === "split" ? "Open pane" : "Open tab",
34322
34846
  ...detail ? { detail } : {},
34323
34847
  ...warning ? { warning } : {}
34324
34848
  };
34325
- return plan;
34849
+ if (input.vcs === "git")
34850
+ return {
34851
+ ...common,
34852
+ vcs: "git",
34853
+ input: { ...input, repo: repo.path, ...input.path ? { path } : {} },
34854
+ branch,
34855
+ checkout,
34856
+ ...gitBase ? { base: gitBase } : {},
34857
+ label: action === "focus" ? "Focus existing tab" : checkout === "create" ? "Create worktree & open" : checkout === "attach" ? "Attach branch & open" : action === "split" ? "Open pane" : "Open tab"
34858
+ };
34859
+ return {
34860
+ ...common,
34861
+ vcs: "jj",
34862
+ checkout: checkout === "create" ? "create" : "existing",
34863
+ input: { ...input, repo: repo.path, ...input.path ? { path } : {} },
34864
+ workspaceName,
34865
+ ...base ? { base } : {},
34866
+ label: action === "focus" ? "Focus existing tab" : checkout === "create" ? "Create workspace & open" : action === "split" ? "Open pane" : "Open tab"
34867
+ };
34326
34868
  });
34327
- var sameLaunchPlan = (a, b) => a.hostId === b.hostId && a.worktreeRoot === b.worktreeRoot && a.sessionId === b.sessionId && a.clientId === b.clientId && a.input.repo === b.input.repo && a.input.sessionId === b.input.sessionId && a.input.branch === b.input.branch && a.input.path === b.input.path && a.input.worktreeName === b.input.worktreeName && a.input.name === b.input.name && a.input.clientId === b.input.clientId && a.input.additional === b.input.additional && a.input.split === b.input.split && a.path === b.path && a.branch === b.branch && a.checkout === b.checkout && a.action === b.action && a.nameRole === b.nameRole && a.name === b.name && a.base?.head === b.base?.head && a.base?.branch === b.base?.branch && a.target?.windowId === b.target?.windowId && a.target?.blockId === b.target?.blockId && a.target?.label === b.target?.label;
34869
+ var sameLaunchPlan = (a, b) => a.vcs === b.vcs && a.input.vcs === b.input.vcs && a.hostId === b.hostId && a.worktreeRoot === b.worktreeRoot && a.sessionId === b.sessionId && a.clientId === b.clientId && a.input.repo === b.input.repo && a.input.sessionId === b.input.sessionId && a.input.path === b.input.path && a.input.worktreeName === b.input.worktreeName && a.input.name === b.input.name && a.input.clientId === b.input.clientId && a.input.additional === b.input.additional && a.input.split === b.input.split && a.path === b.path && a.checkout === b.checkout && a.action === b.action && a.nameRole === b.nameRole && a.name === b.name && a.target?.windowId === b.target?.windowId && a.target?.blockId === b.target?.blockId && a.target?.label === b.target?.label && (a.vcs === "git" && b.vcs === "git" && a.input.vcs === "git" && b.input.vcs === "git" ? a.input.branch === b.input.branch && a.branch === b.branch && a.base?.head === b.base?.head && a.base?.branch === b.base?.branch : a.vcs === "jj" && b.vcs === "jj" && a.input.vcs === "jj" && b.input.vcs === "jj" && a.input.revision === b.input.revision && a.workspaceName === b.workspaceName && a.base?.commitId === b.base?.commitId && a.base?.changeId === b.base?.changeId);
34328
34870
  var launch = exports_Effect.fnUntraced(function* (input, command, reviewed, expectedHostId) {
34329
34871
  const pathService = yield* exports_Path.Path;
34330
34872
  if (!command[0] || !pathService.isAbsolute(command[0]))
34331
- return yield* fail17("The task executable must be an absolute path");
34873
+ return yield* fail19("The task executable must be an absolute path");
34332
34874
  const plan = yield* planLaunch(input, expectedHostId);
34333
34875
  if (reviewed && !sameLaunchPlan(reviewed, plan))
34334
- return yield* fail17("Launch plan changed since review; inspect the destination before submitting again");
34876
+ return yield* fail19("Launch plan changed since review; inspect the destination before submitting again");
34335
34877
  if (plan.action === "focus") {
34336
34878
  const target2 = plan.target;
34337
34879
  if (!target2)
34338
- return yield* fail17("The reviewed focus target is no longer available");
34880
+ return yield* fail19("The reviewed focus target is no longer available");
34339
34881
  const warning2 = [plan.warning, yield* focus(plan.sessionId, target2.windowId, plan.clientId, target2.blockId)].filter(Boolean).join("; ") || undefined;
34340
34882
  const result5 = {
34341
34883
  hostId: plan.hostId,
@@ -34349,8 +34891,10 @@ var launch = exports_Effect.fnUntraced(function* (input, command, reviewed, expe
34349
34891
  };
34350
34892
  return result5;
34351
34893
  }
34352
- const repo = yield* repository(plan.input.repo);
34353
- const request3 = {
34894
+ const repo = yield* repository3(plan.input.repo);
34895
+ if (repo.vcs !== plan.vcs)
34896
+ return yield* fail19("Repository backend changed since review");
34897
+ const common = {
34354
34898
  repo: repo.path,
34355
34899
  path: plan.path,
34356
34900
  commonDir: repo.commonDir,
@@ -34358,18 +34902,28 @@ var launch = exports_Effect.fnUntraced(function* (input, command, reviewed, expe
34358
34902
  hostId: plan.hostId,
34359
34903
  ...process.env.REX_BIN_DIR ? { rexBinDir: process.env.REX_BIN_DIR } : {},
34360
34904
  ...process.env.REX_WORKTREES_LOCAL_ENDPOINT ? { rexLocalEndpoint: process.env.REX_WORKTREES_LOCAL_ENDPOINT } : {},
34905
+ ...plan.worktreeRoot ? { worktreeRoot: plan.worktreeRoot } : {}
34906
+ };
34907
+ const request3 = plan.vcs === "git" ? {
34908
+ ...common,
34909
+ vcs: "git",
34361
34910
  ...plan.input.branch ? { branch: plan.input.branch } : {},
34362
34911
  ...plan.input.worktreeName !== undefined ? { worktreeName: plan.input.worktreeName } : {},
34363
34912
  ...plan.base ? { base: plan.base.head } : {},
34364
- ...plan.worktreeRoot ? { worktreeRoot: plan.worktreeRoot } : {},
34365
34913
  ...plan.checkout !== "create" ? { checkout: plan.checkout } : {}
34914
+ } : {
34915
+ ...common,
34916
+ vcs: "jj",
34917
+ checkout: plan.checkout,
34918
+ workspaceName: plan.workspaceName,
34919
+ ...plan.base ? { base: plan.base } : {}
34366
34920
  };
34367
34921
  const argv = [...command, "task", JSON.stringify(request3)];
34368
34922
  const target = plan.target;
34369
34923
  const name = plan.name;
34370
34924
  if (!name)
34371
- return yield* fail17("The reviewed Rex tab name is no longer available");
34372
- const created = plan.action === "split" ? target ? yield* createSplit(plan.sessionId, target.windowId, target.blockId, name, plan.path, argv) : yield* fail17("The reviewed split target is no longer available") : yield* createTab(plan.sessionId, name, plan.checkout === "existing" ? plan.path : repo.path, argv);
34925
+ return yield* fail19("The reviewed Rex tab name is no longer available");
34926
+ const created = plan.action === "split" ? target ? yield* createSplit(plan.sessionId, target.windowId, target.blockId, name, plan.path, argv) : yield* fail19("The reviewed split target is no longer available") : yield* createTab(plan.sessionId, name, plan.checkout === "existing" ? plan.path : repo.path, argv);
34373
34927
  const warning = [plan.warning, yield* focus(plan.sessionId, created.windowId, plan.clientId, created.blockId)].filter(Boolean).join("; ") || undefined;
34374
34928
  const result4 = {
34375
34929
  hostId: plan.hostId,
@@ -34387,7 +34941,7 @@ var shell = exports_Effect.fnUntraced(function* (cwd) {
34387
34941
  const path = yield* exports_Path.Path;
34388
34942
  const program = process.env.SHELL || "/bin/sh";
34389
34943
  if (!path.isAbsolute(program))
34390
- return yield* fail17("SHELL must be an absolute executable path");
34944
+ return yield* fail19("SHELL must be an absolute executable path");
34391
34945
  const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
34392
34946
  const child = yield* spawner.spawn(exports_ChildProcess.make(program, path.basename(program) === "sh" ? ["-i"] : ["-l", "-i"], {
34393
34947
  cwd,
@@ -34397,35 +34951,54 @@ var shell = exports_Effect.fnUntraced(function* (cwd) {
34397
34951
  }));
34398
34952
  const code = yield* child.exitCode;
34399
34953
  if (code !== 0)
34400
- return yield* fail17(`Shell exited with status ${code}`);
34954
+ return yield* fail19(`Shell exited with status ${code}`);
34401
34955
  }, exports_Effect.scoped);
34402
34956
  var task = exports_Effect.fnUntraced(function* (request3) {
34403
34957
  if (request3.rexBinDir) {
34404
34958
  const path2 = yield* exports_Path.Path;
34405
34959
  if (!path2.isAbsolute(request3.rexBinDir))
34406
- return yield* fail17("REX_BIN_DIR must be an absolute directory");
34960
+ return yield* fail19("REX_BIN_DIR must be an absolute directory");
34407
34961
  process.env.REX_BIN_DIR = request3.rexBinDir;
34408
34962
  }
34409
34963
  if (request3.rexLocalEndpoint)
34410
34964
  process.env.REX_WORKTREES_LOCAL_ENDPOINT = request3.rexLocalEndpoint;
34411
34965
  const host = yield* localHost;
34412
34966
  if (host.id !== request3.hostId)
34413
- return yield* fail17(`Wrong Rex task host: expected ${request3.hostId}, got ${host.id}`);
34414
- if (!request3.branch && request3.worktreeName !== undefined)
34415
- return yield* fail17("Worktree name only applies to a branch checkout");
34967
+ return yield* fail19(`Wrong Rex task host: expected ${request3.hostId}, got ${host.id}`);
34968
+ if (request3.vcs === "git" && !request3.branch && request3.worktreeName !== undefined)
34969
+ return yield* fail19("Worktree name only applies to a branch checkout");
34416
34970
  if (process.env.REX_SESSION !== request3.sessionId || !process.env.REX_BLOCK)
34417
- return yield* fail17("Task must run in its requested Rex session and terminal");
34971
+ return yield* fail19("Task must run in its requested Rex session and terminal");
34418
34972
  const blockId = yield* exports_Schema.decodeUnknownEffect(BlockIdSchema)(process.env.REX_BLOCK);
34419
34973
  if (!(yield* listSessions).some((item) => item.id === request3.sessionId))
34420
- return yield* fail17("Requested Rex session no longer exists");
34421
- const current = yield* repository(request3.repo);
34422
- if (current.commonDir !== request3.commonDir || current.path !== request3.repo)
34423
- return yield* fail17("Repository identity changed since launch");
34974
+ return yield* fail19("Requested Rex session no longer exists");
34975
+ const current = yield* repository3(request3.repo);
34976
+ if (current.vcs !== request3.vcs || current.commonDir !== request3.commonDir || current.path !== request3.repo)
34977
+ return yield* fail19("Repository identity changed since launch");
34424
34978
  let path;
34425
- if (request3.branch) {
34979
+ if (request3.vcs === "jj") {
34980
+ if (request3.checkout === "create") {
34981
+ if (!request3.base)
34982
+ return yield* fail19("New JJ workspace requires a pinned base revision");
34983
+ const planned = yield* planWorkspace(request3.repo, request3.workspaceName, request3.base.commitId, request3.worktreeRoot);
34984
+ if (planned.path !== request3.path || planned.workspaceName !== request3.workspaceName || planned.base.commitId !== request3.base.commitId || planned.base.changeId !== request3.base.changeId)
34985
+ return yield* fail19("JJ workspace destination or pinned base changed since launch");
34986
+ const created = yield* createWorkspace(request3.repo, request3.workspaceName, request3.base, request3.worktreeRoot);
34987
+ if (!created.path || !created.present)
34988
+ return yield* fail19(`JJ workspace registration has no available checkout; inspect ${request3.path}`);
34989
+ path = yield* canonical(created.path);
34990
+ } else {
34991
+ if (request3.base)
34992
+ return yield* fail19("Existing JJ workspace cannot change its base revision");
34993
+ path = yield* canonical(request3.path);
34994
+ const tree = (yield* listWorkspaces(request3.repo)).find((entry2) => entry2.path === path && entry2.name === request3.workspaceName && entry2.present);
34995
+ if (!tree)
34996
+ return yield* fail19("Selected JJ workspace no longer belongs to repository");
34997
+ }
34998
+ } else if (request3.branch) {
34426
34999
  const plan = yield* planWorktree(request3.repo, request3.branch, request3.worktreeRoot, request3.worktreeName);
34427
35000
  if (plan.path !== request3.path || request3.checkout === "existing" && !plan.existing)
34428
- return yield* fail17("Worktree destination changed since launch");
35001
+ return yield* fail19("Worktree destination changed since launch");
34429
35002
  if (request3.checkout === "existing") {
34430
35003
  path = yield* canonical(request3.path);
34431
35004
  } else {
@@ -34441,23 +35014,257 @@ var task = exports_Effect.fnUntraced(function* (request3) {
34441
35014
  path = yield* canonical(request3.path);
34442
35015
  const trees = yield* listWorktrees(request3.repo);
34443
35016
  if (!trees.some((tree) => tree.path === path))
34444
- return yield* fail17("Selected worktree no longer belongs to repository");
35017
+ return yield* fail19("Selected worktree no longer belongs to repository");
34445
35018
  }
34446
35019
  if (path !== request3.path)
34447
- return yield* fail17(`Worktree path changed; checkout remains at ${path}`);
35020
+ return yield* fail19(`Worktree path changed; checkout remains at ${path}`);
34448
35021
  const windows = yield* windowList(request3.sessionId).pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => {
34449
35022
  console.error(`Worktree ${path} is available; cannot inspect Rex terminal for association: ${exports_Cause.pretty(exports_Cause.fail(error2))}`);
34450
35023
  return [];
34451
35024
  })));
34452
35025
  const entry = windows.find((window) => window.layers.some((layer12) => layer12.blocks?.some((block) => block.block_id === blockId && block.host_id === host.id)));
34453
35026
  if (entry) {
34454
- yield* saveAssociation({ hostId: host.id, commonDir: current.commonDir, path, sessionId: request3.sessionId, windowId: entry.window_id, blockId }).pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => {
35027
+ yield* saveAssociation({ vcs: request3.vcs, hostId: host.id, commonDir: current.commonDir, path, sessionId: request3.sessionId, windowId: entry.window_id, blockId }).pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => {
34455
35028
  console.error(`Worktree ${path} is available; association not saved: ${exports_Cause.pretty(exports_Cause.fail(error2))}`);
34456
35029
  })));
34457
35030
  } else
34458
35031
  console.error(`Worktree ${path} is available; Rex block could not be associated, select this worktree by path next time.`);
34459
35032
  yield* shell(path);
34460
35033
  });
35034
+ var cloneDestination = exports_Effect.fnUntraced(function* (destination, url, vcs = "git", sourceHostId) {
35035
+ const fs = yield* exports_FileSystem.FileSystem;
35036
+ const path = yield* exports_Path.Path;
35037
+ if (!path.isAbsolute(destination) || path.resolve(destination) !== destination || destination === path.parse(destination).root)
35038
+ return yield* fail19("Clone destination must be a normalized absolute directory");
35039
+ const parts2 = destination.slice(path.parse(destination).root.length).split(path.sep);
35040
+ let current = path.parse(destination).root;
35041
+ for (let index2 = 0;index2 < parts2.length; index2++) {
35042
+ const parent = current;
35043
+ current = path.join(current, parts2[index2]);
35044
+ const info2 = yield* exports_Effect.catchIf(fs.lstat(current), missing3, () => exports_Effect.succeed(undefined));
35045
+ if (info2?.type === "SymbolicLink")
35046
+ return yield* fail19(`Symlinked clone destination: ${current}`);
35047
+ if (index2 < parts2.length - 1 && info2 && info2.type !== "Directory")
35048
+ return yield* fail19(`Not a directory: ${current}`);
35049
+ if (index2 < parts2.length - 1 && info2 && ((yield* gitContext(current)) || (yield* fs.exists(path.join(current, ".jj")))))
35050
+ return yield* fail19(vcs === "git" ? `Clone destination is inside a checkout or Git metadata: ${current}` : `Clone destination is inside a checkout or VCS metadata: ${current}`);
35051
+ if (index2 === parts2.length - 1 && info2) {
35052
+ if (info2.type !== "Directory")
35053
+ return yield* fail19(`Clone destination already exists: ${current}`);
35054
+ const repo = yield* repository3(current).pipe(exports_Effect.catchIf((error2) => missing3(error2) || exports_Schema.is(CommandError)(error2) && error2.args.includes("rev-parse"), () => fail19(`Clone destination already exists and is not a repository: ${current}`)));
35055
+ if (repo.path !== current || repo.vcs !== vcs)
35056
+ return yield* fail19(`Clone destination is not the requested ${vcs} repository: ${current}`);
35057
+ const actual = repo.vcs === "git" ? yield* origin(current, true) : (yield* cloneSource2(current, sourceHostId ?? (yield* localHost).id)).url;
35058
+ if (actual !== url)
35059
+ return yield* fail19(`Clone destination belongs to a different origin: ${current}`);
35060
+ return repo.commonDir;
35061
+ }
35062
+ if (parent === current)
35063
+ return yield* fail19("Invalid clone destination");
35064
+ }
35065
+ return;
35066
+ });
35067
+ var planClone = exports_Effect.fnUntraced(function* (input, expectedHostId) {
35068
+ const host = yield* localHost;
35069
+ if (expectedHostId && host.id !== expectedHostId)
35070
+ return yield* fail19("Wrong Rex clone host");
35071
+ if (input.vcs !== input.source.vcs)
35072
+ return yield* fail19("Clone source backend does not match request");
35073
+ if (!(yield* listSessions).some((item) => item.id === input.sessionId))
35074
+ return yield* fail19("Requested Rex session does not exist");
35075
+ const clients = yield* listClients;
35076
+ if (input.clientId && !clients.some((item) => item.id === input.clientId))
35077
+ return yield* fail19("Requested Rex app client is not connected");
35078
+ if (!input.name.trim() || input.name.startsWith("-") || /[\p{ASCII}&&\p{Cc}]/v.test(input.name))
35079
+ return yield* fail19("Invalid Rex tab name");
35080
+ if (input.vcs === "git")
35081
+ yield* validCloneBranch(input.branch, input.worktreeName);
35082
+ else if (input.worktreeName !== undefined && !input.worktreeName.trim())
35083
+ return yield* fail19("JJ workspace name cannot be blank");
35084
+ const url = yield* exports_Effect.try({
35085
+ try: () => safeOrigin(input.source.url, input.source.sourceHostId === host.id),
35086
+ catch: () => new AppError({ message: "Clone source URL is unsafe or local to another Rex host" })
35087
+ });
35088
+ const commonDir = yield* cloneDestination(input.repo, url, input.vcs, host.id);
35089
+ const existing = commonDir !== undefined;
35090
+ let gitBase;
35091
+ let base;
35092
+ if (input.vcs === "git") {
35093
+ gitBase = existing && input.branchMode === "create" ? yield* originDefaultHead(input.repo) : undefined;
35094
+ } else if (input.revision !== undefined) {
35095
+ if (!/^[0-9a-f]{40,64}$/.test(input.revision))
35096
+ return yield* fail19("Clone base must be a full source-resolved commit ID");
35097
+ base = [input.source.revision, ...input.source.revisions.map((choice) => choice.revision)].find((candidate) => candidate?.commitId === input.revision);
35098
+ if (!base)
35099
+ return yield* fail19("Clone base must be resolved on the source host before transfer");
35100
+ if (existing) {
35101
+ const reached = yield* resolveRevision(input.repo, base.commitId);
35102
+ if (reached.commitId !== base.commitId || reached.changeId !== base.changeId)
35103
+ return yield* fail19("Selected source revision is not available at the destination");
35104
+ }
35105
+ }
35106
+ if (input.vcs === "jj" && existing && !base)
35107
+ base = yield* resolveRevision(input.repo, "@-");
35108
+ const clientId = input.clientId ?? (clients.length === 1 ? clients[0]?.id : undefined);
35109
+ const warning = !clientId && clients.length > 1 ? "Multiple Rex apps are connected; select the intended app" : undefined;
35110
+ const snapshotDetail = input.vcs === "jj" && (input.worktreeName || existing) ? `JJ ${input.worktreeName ? "workspace creation" : "new change"} snapshots the destination workspace at ${input.repo}; its working-copy commit and colocated Git index intent-to-add entries may change.` : undefined;
35111
+ const common = {
35112
+ hostId: host.id,
35113
+ sessionId: input.sessionId,
35114
+ ...clientId ? { clientId } : {},
35115
+ repo: input.repo,
35116
+ existing,
35117
+ ...commonDir ? { commonDir } : {},
35118
+ label: existing ? "Open existing repository" : "Clone & Open",
35119
+ detail: [`Source ${url} \u2192 ${input.repo}. Only pushed history transfers; credentials stay on this machine.`, snapshotDetail].filter(Boolean).join(" "),
35120
+ ...warning ? { warning } : {}
35121
+ };
35122
+ if (input.vcs === "git")
35123
+ return {
35124
+ ...common,
35125
+ vcs: "git",
35126
+ input: { ...input, source: { ...input.source, url } },
35127
+ ...gitBase ? { base: gitBase } : {}
35128
+ };
35129
+ return {
35130
+ ...common,
35131
+ vcs: "jj",
35132
+ input: { ...input, source: { ...input.source, url } },
35133
+ ...base ? { base } : {}
35134
+ };
35135
+ });
35136
+ var sameClonePlan = (a, b) => a.vcs === b.vcs && a.input.vcs === b.input.vcs && a.hostId === b.hostId && a.sessionId === b.sessionId && a.clientId === b.clientId && a.repo === b.repo && a.existing === b.existing && a.commonDir === b.commonDir && a.input.repo === b.input.repo && a.input.sessionId === b.input.sessionId && a.input.clientId === b.input.clientId && a.input.name === b.input.name && a.input.worktreeName === b.input.worktreeName && a.input.source.url === b.input.source.url && a.input.source.sourceHostId === b.input.source.sourceHostId && (a.vcs === "git" && b.vcs === "git" && a.input.vcs === "git" && b.input.vcs === "git" ? a.base === b.base && a.input.branch === b.input.branch && a.input.branchMode === b.input.branchMode && a.input.source.branch === b.input.source.branch && a.input.source.branches.length === b.input.source.branches.length && a.input.source.branches.every((branch, index2) => branch === b.input.source.branches[index2]) : a.vcs === "jj" && b.vcs === "jj" && a.input.vcs === "jj" && b.input.vcs === "jj" && a.base?.commitId === b.base?.commitId && a.base?.changeId === b.base?.changeId && a.input.revision === b.input.revision && a.input.source.revision?.commitId === b.input.source.revision?.commitId && a.input.source.revision?.changeId === b.input.source.revision?.changeId && a.input.source.revisions.length === b.input.source.revisions.length && a.input.source.revisions.every((choice, index2) => choice.expression === b.input.source.revisions[index2]?.expression && choice.revision.commitId === b.input.source.revisions[index2]?.revision.commitId && choice.revision.changeId === b.input.source.revisions[index2]?.revision.changeId));
35137
+ var launchClone = exports_Effect.fnUntraced(function* (input, command, reviewed, expectedHostId) {
35138
+ const path = yield* exports_Path.Path;
35139
+ if (!command[0] || !path.isAbsolute(command[0]))
35140
+ return yield* fail19("The task executable must be an absolute path");
35141
+ const plan = yield* planClone(input, expectedHostId);
35142
+ if (reviewed && !sameClonePlan(reviewed, plan))
35143
+ return yield* fail19("Clone plan changed since review; inspect before submitting again");
35144
+ const request3 = {
35145
+ plan,
35146
+ ...process.env.REX_BIN_DIR ? { rexBinDir: process.env.REX_BIN_DIR } : {},
35147
+ ...process.env.REX_WORKTREES_LOCAL_ENDPOINT ? { rexLocalEndpoint: process.env.REX_WORKTREES_LOCAL_ENDPOINT } : {}
35148
+ };
35149
+ const home = process.env.HOME;
35150
+ if (!home || !path.isAbsolute(home))
35151
+ return yield* fail19("Target HOME must be an absolute directory");
35152
+ const created = yield* createTab(plan.sessionId, input.name, home, [...command, "clone-task", JSON.stringify(request3)]);
35153
+ const warning = [plan.warning, yield* focus(plan.sessionId, created.windowId, plan.clientId, created.blockId)].filter(Boolean).join("; ") || undefined;
35154
+ const result4 = { hostId: plan.hostId, sessionId: plan.sessionId, windowId: created.windowId, blockId: created.blockId, repo: plan.repo, pending: true, ...warning ? { warning } : {} };
35155
+ return result4;
35156
+ });
35157
+ var prepareCloneCheckout = exports_Effect.fnUntraced(function* (plan) {
35158
+ if (plan.vcs === "git")
35159
+ yield* validCloneBranch(plan.input.branch, plan.input.worktreeName);
35160
+ const url = yield* exports_Effect.try({
35161
+ try: () => safeOrigin(plan.input.source.url, plan.input.source.sourceHostId === plan.hostId),
35162
+ catch: () => new AppError({ message: "Clone source URL is unsafe or local to another Rex host" })
35163
+ });
35164
+ if (url !== plan.input.source.url || plan.input.vcs !== plan.vcs)
35165
+ return yield* fail19("Clone source changed since review");
35166
+ const observed = yield* cloneDestination(plan.repo, url, plan.vcs, plan.hostId);
35167
+ if (observed !== plan.commonDir || observed !== undefined !== plan.existing)
35168
+ return yield* fail19("Clone destination identity changed since review");
35169
+ if (plan.vcs === "git" && plan.existing && plan.input.branchMode === "create" && (!plan.base || plan.base !== (yield* originDefaultHead(plan.repo))))
35170
+ return yield* fail19("Origin default branch changed since review");
35171
+ if (plan.vcs === "jj" && plan.existing && plan.base) {
35172
+ const reached = yield* resolveRevision(plan.repo, plan.base.commitId);
35173
+ if (reached.commitId !== plan.base.commitId || reached.changeId !== plan.base.changeId)
35174
+ return yield* fail19("JJ clone base changed since review");
35175
+ }
35176
+ const fs = yield* exports_FileSystem.FileSystem;
35177
+ const pathService = yield* exports_Path.Path;
35178
+ if (!plan.existing) {
35179
+ const parent = pathService.dirname(plan.repo);
35180
+ yield* fs.makeDirectory(parent, { recursive: true });
35181
+ if ((yield* cloneDestination(plan.repo, url, plan.vcs, plan.hostId)) !== undefined)
35182
+ return yield* fail19("Clone target appeared since launch; destination left untouched");
35183
+ if ((yield* fs.realPath(parent)) !== parent)
35184
+ return yield* fail19("Clone parent changed to a symlink");
35185
+ yield* fs.makeDirectory(plan.repo);
35186
+ if ((yield* fs.realPath(parent)) !== parent || (yield* fs.realPath(plan.repo)) !== plan.repo)
35187
+ return yield* fail19(`Clone path changed; reserved destination retained at ${plan.repo}`);
35188
+ if (plan.vcs === "git")
35189
+ yield* cloneRepository(url, plan.repo);
35190
+ else
35191
+ yield* cloneRepository2(url, plan.repo);
35192
+ }
35193
+ const repo = yield* repository3(plan.repo);
35194
+ if (repo.path !== plan.repo || repo.vcs !== plan.vcs || plan.existing && repo.commonDir !== plan.commonDir)
35195
+ return yield* fail19(`Clone repository changed; retained at ${plan.repo}`);
35196
+ const actual = repo.vcs === "git" ? yield* origin(repo.path, true) : (yield* cloneSource2(repo.path, plan.hostId)).url;
35197
+ if (actual !== url)
35198
+ return yield* fail19(`Clone origin changed; retained at ${plan.repo}`);
35199
+ if (plan.vcs === "jj") {
35200
+ const base = plan.base ?? (yield* resolveRevision(repo.path, "@-"));
35201
+ let cwd2;
35202
+ if (plan.input.worktreeName) {
35203
+ const planned = yield* planWorkspace(repo.path, plan.input.worktreeName, base.commitId, yield* resolveWorktreeRoot(repo.path));
35204
+ if (planned.base.commitId !== base.commitId || planned.base.changeId !== base.changeId)
35205
+ return yield* fail19(`JJ clone base is unavailable; clone retained at ${plan.repo}`);
35206
+ const created = yield* createWorkspace(repo.path, planned.workspaceName, base, yield* resolveWorktreeRoot(repo.path));
35207
+ if (!created.path || !created.present || created.path !== planned.path)
35208
+ return yield* fail19(`JJ workspace registration changed; clone retained at ${plan.repo}`);
35209
+ cwd2 = created.path;
35210
+ } else if (plan.existing || plan.input.revision) {
35211
+ const created = yield* newChange(repo.path, base);
35212
+ if (!created.path || !created.present || created.path !== repo.path)
35213
+ return yield* fail19(`JJ default workspace changed; clone retained at ${plan.repo}`);
35214
+ cwd2 = created.path;
35215
+ } else {
35216
+ cwd2 = repo.path;
35217
+ }
35218
+ return { repo, cwd: yield* fs.realPath(cwd2) };
35219
+ }
35220
+ const local = yield* listBranches(repo.path);
35221
+ const remote = yield* remoteBranches(repo.path);
35222
+ const { branch, branchMode } = plan.input;
35223
+ let cwd;
35224
+ if (branchMode === "existing") {
35225
+ if (!local.includes(branch) && !remote.includes(branch))
35226
+ return yield* fail19(`Branch ${branch} was not pushed to origin; clone retained at ${plan.repo}`);
35227
+ const worktreeRoot = yield* resolveWorktreeRoot(repo.path);
35228
+ if (local.includes(branch)) {
35229
+ const planned = yield* planWorktree(repo.path, branch, worktreeRoot, plan.input.worktreeName);
35230
+ cwd = planned.existing ? planned.path : (yield* createWorktree(repo.path, branch, { attachOnly: true, worktreeRoot, worktreeName: plan.input.worktreeName })).path;
35231
+ } else {
35232
+ cwd = (yield* createWorktree(repo.path, branch, { startPoint: yield* remoteBranchHead(repo.path, branch), worktreeRoot, worktreeName: plan.input.worktreeName })).path;
35233
+ }
35234
+ } else {
35235
+ if (local.includes(branch) || remote.includes(branch))
35236
+ return yield* fail19(`Branch ${branch} already exists; clone retained at ${plan.repo}`);
35237
+ const base = plan.existing ? plan.base : (yield* repositoryHead(repo.path)).head;
35238
+ if (!base)
35239
+ return yield* fail19("Origin default branch changed since review");
35240
+ cwd = (yield* createWorktree(repo.path, branch, { startPoint: base, worktreeRoot: yield* resolveWorktreeRoot(repo.path), worktreeName: plan.input.worktreeName })).path;
35241
+ }
35242
+ return { repo, cwd: yield* fs.realPath(cwd) };
35243
+ });
35244
+ var cloneTask = exports_Effect.fnUntraced(function* (request3) {
35245
+ if (request3.rexBinDir) {
35246
+ const path = yield* exports_Path.Path;
35247
+ if (!path.isAbsolute(request3.rexBinDir))
35248
+ return yield* fail19("REX_BIN_DIR must be absolute");
35249
+ process.env.REX_BIN_DIR = request3.rexBinDir;
35250
+ }
35251
+ if (request3.rexLocalEndpoint)
35252
+ process.env.REX_WORKTREES_LOCAL_ENDPOINT = request3.rexLocalEndpoint;
35253
+ const { plan } = request3;
35254
+ if (process.env.REX_SESSION !== plan.sessionId || !process.env.REX_BLOCK)
35255
+ return yield* fail19("Clone task must run in its requested Rex terminal");
35256
+ const blockId = yield* exports_Schema.decodeUnknownEffect(BlockIdSchema)(process.env.REX_BLOCK);
35257
+ if (!sameClonePlan(plan, yield* planClone(plan.input, plan.hostId)))
35258
+ return yield* fail19("Clone target changed since launch; destination left untouched");
35259
+ const { repo, cwd } = yield* prepareCloneCheckout(plan);
35260
+ const windows = yield* windowList(plan.sessionId).pipe(exports_Effect.catch(() => exports_Effect.succeed([])));
35261
+ const window = windows.find((entry) => entry.layers.some((layer12) => layer12.blocks?.some((block) => block.block_id === blockId && block.host_id === plan.hostId)));
35262
+ if (window)
35263
+ yield* saveAssociation({ vcs: repo.vcs, hostId: plan.hostId, commonDir: repo.commonDir, path: cwd, sessionId: plan.sessionId, windowId: window.window_id, blockId }).pipe(exports_Effect.catch((error2) => exports_Effect.sync(() => console.error(`Checkout ${cwd} is available; association not saved: ${exports_Cause.pretty(exports_Cause.fail(error2))}`))));
35264
+ else
35265
+ console.error(`Checkout ${cwd} is available; Rex block could not be associated`);
35266
+ yield* shell(cwd);
35267
+ });
34461
35268
 
34462
35269
  // src/host.ts
34463
35270
  var dispatchHost = exports_Effect.fnUntraced(function* (request3, command) {
@@ -34465,41 +35272,85 @@ var dispatchHost = exports_Effect.fnUntraced(function* (request3, command) {
34465
35272
  if (host.id !== request3.hostId)
34466
35273
  return yield* exports_Effect.fail(new AppError({ message: `Wrong Rex host: expected ${request3.hostId}, got ${host.id}` }));
34467
35274
  const path = yield* exports_Path.Path;
34468
- const paths = request3.kind === "discover" ? request3.context ? [request3.context] : [] : request3.kind === "project" ? [request3.path] : request3.kind === "plan" || request3.kind === "launch" ? [request3.input.repo, ...request3.input.path ? [request3.input.path] : []] : [request3.repo];
35275
+ const paths = request3.kind === "discover" ? request3.context ? [request3.context] : [] : request3.kind === "project" ? [request3.path] : request3.kind === "clone-plan" || request3.kind === "clone-launch" ? [request3.input.repo] : request3.kind === "plan" || request3.kind === "launch" ? [request3.input.repo, ...request3.input.path ? [request3.input.path] : []] : [request3.repo];
34469
35276
  if (paths.some((value3) => !path.isAbsolute(value3)))
34470
35277
  return yield* exports_Effect.fail(new AppError({ message: "Destination repository and worktree paths must be absolute" }));
34471
- const identity3 = { version: 2, hostId: host.id };
35278
+ const identity3 = { version: 3, hostId: host.id };
34472
35279
  let result4;
34473
35280
  switch (request3.kind) {
34474
35281
  case "discover": {
34475
35282
  const config = yield* loadConfig;
34476
- const checkoutEffect = request3.context ? exports_Effect.catchIf(exports_Effect.catchIf(repository(request3.context), (error2) => missing2(error2), () => exports_Effect.succeed(undefined)), (error2) => notRepository(error2), () => exports_Effect.succeed(undefined)) : exports_Effect.succeed(undefined);
35283
+ const checkoutEffect = request3.context ? exports_Effect.catchIf(exports_Effect.catchIf(repository3(request3.context), (error2) => missing3(error2), () => exports_Effect.succeed(undefined)), (error2) => notRepository(error2), () => exports_Effect.succeed(undefined)) : exports_Effect.succeed(undefined);
34477
35284
  const { checkout, sessions, clients, projects } = yield* exports_Effect.all({
34478
35285
  checkout: checkoutEffect,
34479
35286
  sessions: listSessions,
34480
35287
  clients: listClients,
34481
35288
  projects: discoverProjects(config.roots, config.projects, request3.context)
34482
35289
  }, { concurrency: 4 });
34483
- result4 = { ...identity3, kind: "discover", sessions, clients, projects, ...checkout ? { checkout } : {} };
35290
+ result4 = { ...identity3, kind: "discover", sessions, clients, projects, roots: config.roots, ...checkout ? { checkout } : {} };
34484
35291
  break;
34485
35292
  }
34486
35293
  case "project": {
34487
- const checkout = yield* repository(request3.path);
34488
- const canonical2 = yield* project(request3.path);
34489
- result4 = { ...identity3, kind: "project", project: canonical2, checkout, worktrees: yield* listWorktrees(canonical2.path), branches: yield* listBranches(canonical2.path) };
35294
+ const fs = yield* exports_FileSystem.FileSystem;
35295
+ const info2 = yield* fs.stat(request3.path).pipe(exports_Effect.catchIf(missing3, () => exports_Effect.succeed(undefined)));
35296
+ if (!info2) {
35297
+ result4 = { ...identity3, kind: "project-missing", path: request3.path };
35298
+ break;
35299
+ }
35300
+ const checkout = yield* repository3(request3.path);
35301
+ const canonical2 = yield* project3(request3.path);
35302
+ result4 = {
35303
+ ...identity3,
35304
+ kind: "project",
35305
+ project: canonical2,
35306
+ checkout,
35307
+ worktrees: canonical2.vcs === "git" ? yield* listWorktrees(canonical2.path) : yield* listWorkspaces(canonical2.path),
35308
+ branches: canonical2.vcs === "git" ? yield* listBranches(canonical2.path) : [],
35309
+ revisions: canonical2.vcs === "jj" ? yield* listRevisions(canonical2.path) : []
35310
+ };
35311
+ break;
35312
+ }
35313
+ case "clone-source": {
35314
+ const repo = yield* repository3(request3.repo);
35315
+ result4 = { ...identity3, kind: "clone-source", source: repo.vcs === "git" ? yield* cloneSource(repo.path, host.id) : yield* cloneSource2(repo.path, host.id) };
34490
35316
  break;
34491
35317
  }
34492
- case "worktrees":
34493
- result4 = { ...identity3, kind: "worktrees", worktrees: yield* listWorktrees(request3.repo), branches: yield* listBranches(request3.repo) };
35318
+ case "worktrees": {
35319
+ const repo = yield* repository3(request3.repo);
35320
+ result4 = {
35321
+ ...identity3,
35322
+ kind: "worktrees",
35323
+ repository: repo,
35324
+ worktrees: repo.vcs === "git" ? yield* listWorktrees(repo.path) : yield* listWorkspaces(repo.path),
35325
+ branches: repo.vcs === "git" ? yield* listBranches(repo.path) : [],
35326
+ revisions: repo.vcs === "jj" ? yield* listRevisions(repo.path) : []
35327
+ };
34494
35328
  break;
35329
+ }
35330
+ case "revision": {
35331
+ const repo = yield* repository3(request3.repo);
35332
+ if (repo.vcs !== "jj")
35333
+ return yield* exports_Effect.fail(new AppError({ message: "Base revision requires a JJ repository" }));
35334
+ result4 = { ...identity3, kind: "revision", revision: yield* resolveRevision(repo.path, request3.revision) };
35335
+ break;
35336
+ }
34495
35337
  case "branch": {
34496
- const planned = yield* planWorktree(request3.repo, request3.branch, yield* resolveWorktreeRoot(request3.repo), request3.worktreeName);
35338
+ const repo = yield* repository3(request3.repo);
35339
+ if (repo.vcs !== "git")
35340
+ return yield* exports_Effect.fail(new AppError({ message: "Branch checkout requires a Git repository" }));
35341
+ const planned = yield* planWorktree(repo.path, request3.branch, yield* resolveWorktreeRoot(repo.path), request3.worktreeName);
34497
35342
  result4 = { ...identity3, kind: "branch", path: planned.path, branch: planned.branch, existing: planned.existing };
34498
35343
  break;
34499
35344
  }
34500
35345
  case "plan":
34501
35346
  result4 = { ...identity3, kind: "plan", plan: yield* planLaunch(request3.input, host.id) };
34502
35347
  break;
35348
+ case "clone-plan":
35349
+ result4 = { ...identity3, kind: "clone-plan", plan: yield* planClone(request3.input, host.id) };
35350
+ break;
35351
+ case "clone-launch":
35352
+ result4 = { ...identity3, kind: "clone-launch", result: yield* launchClone(request3.input, command, request3.reviewed, host.id) };
35353
+ break;
34503
35354
  case "launch":
34504
35355
  result4 = { ...identity3, kind: "launch", result: yield* launch(request3.input, command, request3.reviewed, host.id) };
34505
35356
  break;
@@ -34512,7 +35363,7 @@ var hostRequest = exports_Effect.fnUntraced(function* (raw, command) {
34512
35363
  });
34513
35364
 
34514
35365
  // src/client.ts
34515
- var fail18 = (message) => exports_Effect.fail(new AppError({ message }));
35366
+ var fail20 = (message) => exports_Effect.fail(new AppError({ message }));
34516
35367
  var listMachines = exports_Effect.gen(function* () {
34517
35368
  const registry = yield* machinesRegistry;
34518
35369
  const machines = [
@@ -34525,75 +35376,103 @@ var connectMachine = exports_Effect.fnUntraced(function* (machine) {
34525
35376
  const choices = yield* listMachines;
34526
35377
  const current = choices.find((choice) => choice.key === machine.key && choice.local === machine.local);
34527
35378
  if (!current)
34528
- return yield* fail18(`Rex machine ${machine.label} is no longer registered; choose another machine`);
35379
+ return yield* fail20(`Rex machine ${machine.label} is no longer registered; choose another machine`);
34529
35380
  if (current.local)
34530
35381
  return { ...current, hostId: (yield* localHost).id };
34531
35382
  const identity3 = yield* remoteIdentity(current.selector);
34532
35383
  const registered = (yield* machinesRegistry).hosts.find((entry) => entry.host.id === current.key);
34533
35384
  if (!registered?.host.endpoints.includes(identity3.endpoint)) {
34534
- return yield* fail18(`Rex machine ${current.label} resolved to an unexpected server; refusing to route remotely`);
35385
+ return yield* fail20(`Rex machine ${current.label} resolved to an unexpected server; refusing to route remotely`);
34535
35386
  }
34536
35387
  const raw = yield* remoteRex(current.selector, ["actions", "--json"]);
34537
35388
  const actions = yield* exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(RexActionsSchema))(raw);
34538
35389
  const helper = actions.actions.find((action) => action.name === "worktrees_request");
34539
35390
  if (!helper) {
34540
- return yield* fail18(`rex-worktrees is not installed on ${current.label}. Build and run rex-worktrees setup on that machine, then reload its Rex config.`);
35391
+ return yield* fail20(`rex-worktrees is not installed on ${current.label}. Build and run rex-worktrees setup on that machine, then reload its Rex config.`);
34541
35392
  }
34542
35393
  yield* exports_Schema.decodeUnknownEffect(RexHelperArgsSchema)(helper.args);
34543
35394
  return { ...current, hostId: identity3.host_id };
34544
35395
  });
34545
35396
  var request3 = exports_Effect.fnUntraced(function* (host, command, body) {
34546
- const encoded = { version: 2, hostId: host.hostId, ...body };
35397
+ const encoded = { version: 3, hostId: host.hostId, ...body };
34547
35398
  let response;
34548
35399
  if (host.local) {
34549
35400
  response = yield* dispatchHost(encoded, command);
34550
35401
  } else {
34551
35402
  const current = yield* connectMachine(host);
34552
35403
  if (current.hostId !== host.hostId)
34553
- return yield* fail18(`Rex host identity changed for ${host.label}; reconnect before continuing`);
35404
+ return yield* fail20(`Rex host identity changed for ${host.label}; reconnect before continuing`);
34554
35405
  const raw = yield* remoteRex(current.selector, ["do", "worktrees_request", "--args", JSON.stringify({ request: JSON.stringify(encoded) }), "--json"]);
34555
35406
  response = yield* exports_Schema.decodeUnknownEffect(RexWorktreesResponseSchema)(raw);
34556
35407
  }
34557
- if (response.hostId !== host.hostId || response.version !== 2 || response.kind !== body.kind)
34558
- return yield* fail18(`Unexpected Rex host/protocol response from ${host.label}; update rex-worktrees on that machine, run setup, and reload its Rex config`);
35408
+ if (response.hostId !== host.hostId || response.version !== 3 || response.kind !== body.kind && !(body.kind === "project" && response.kind === "project-missing" && response.path === body.path))
35409
+ return yield* fail20(`Unexpected Rex host/protocol response from ${host.label}; update rex-worktrees on that machine, run setup, and reload its Rex config`);
34559
35410
  return response;
34560
35411
  });
34561
35412
  var discover = exports_Effect.fnUntraced(function* (host, command, context3) {
34562
35413
  const result4 = yield* request3(host, command, { kind: "discover", ...host.local && context3 ? { context: context3 } : {} });
34563
35414
  if (result4.kind !== "discover")
34564
- return yield* fail18("Unexpected discovery response");
34565
- return { sessions: result4.sessions, clients: result4.clients, projects: result4.projects, ...result4.checkout ? { checkout: result4.checkout } : {} };
35415
+ return yield* fail20("Unexpected discovery response");
35416
+ return { sessions: result4.sessions, clients: result4.clients, projects: result4.projects, roots: result4.roots ?? [], ...result4.checkout ? { checkout: result4.checkout } : {} };
34566
35417
  });
34567
35418
  var inspectProject = exports_Effect.fnUntraced(function* (host, command, path) {
34568
35419
  const result4 = yield* request3(host, command, { kind: "project", path });
35420
+ if (result4.kind === "project-missing")
35421
+ return yield* fail20(`Project directory does not exist: ${result4.path}`);
34569
35422
  if (result4.kind !== "project")
34570
- return yield* fail18("Unexpected project response");
34571
- return { project: result4.project, checkout: result4.checkout, worktrees: result4.worktrees, branches: result4.branches };
35423
+ return yield* fail20("Unexpected project response");
35424
+ return { project: result4.project, checkout: result4.checkout, worktrees: result4.worktrees, branches: result4.branches, revisions: result4.revisions };
34572
35425
  });
34573
35426
  var inspectWorktrees = exports_Effect.fnUntraced(function* (host, command, repo) {
34574
35427
  const result4 = yield* request3(host, command, { kind: "worktrees", repo });
34575
35428
  if (result4.kind !== "worktrees")
34576
- return yield* fail18("Unexpected worktree response");
34577
- return { worktrees: result4.worktrees, branches: result4.branches };
35429
+ return yield* fail20("Unexpected worktree response");
35430
+ return { repository: result4.repository, worktrees: result4.worktrees, branches: result4.branches, revisions: result4.revisions };
35431
+ });
35432
+ var inspectRevision = exports_Effect.fnUntraced(function* (host, command, repo, revision) {
35433
+ const result4 = yield* request3(host, command, { kind: "revision", repo, revision });
35434
+ if (result4.kind !== "revision")
35435
+ return yield* fail20("Unexpected revision response");
35436
+ return result4.revision;
34578
35437
  });
34579
35438
  var inspectBranch = exports_Effect.fnUntraced(function* (host, command, repo, branch, worktreeName) {
34580
35439
  const result4 = yield* request3(host, command, { kind: "branch", repo, branch, ...worktreeName !== undefined ? { worktreeName } : {} });
34581
35440
  if (result4.kind !== "branch")
34582
- return yield* fail18("Unexpected branch response");
35441
+ return yield* fail20("Unexpected branch response");
34583
35442
  return { path: result4.path, branch: result4.branch, existing: result4.existing };
34584
35443
  });
34585
35444
  var review = exports_Effect.fnUntraced(function* (host, command, input) {
34586
35445
  const result4 = yield* request3(host, command, { kind: "plan", input });
34587
35446
  if (result4.kind !== "plan")
34588
- return yield* fail18("Unexpected review response");
35447
+ return yield* fail20("Unexpected review response");
34589
35448
  return result4.plan;
34590
35449
  });
34591
35450
  var submit = exports_Effect.fnUntraced(function* (host, command, input, reviewed) {
34592
35451
  if (reviewed.hostId !== host.hostId)
34593
- return yield* fail18("Reviewed destination belongs to another host");
35452
+ return yield* fail20("Reviewed destination belongs to another host");
34594
35453
  const result4 = yield* request3(host, command, { kind: "launch", input, reviewed });
34595
35454
  if (result4.kind !== "launch")
34596
- return yield* fail18("Unexpected launch response");
35455
+ return yield* fail20("Unexpected launch response");
35456
+ return result4.result;
35457
+ });
35458
+ var sourceForClone = exports_Effect.fnUntraced(function* (host, command, repo) {
35459
+ const result4 = yield* request3(host, command, { kind: "clone-source", repo });
35460
+ if (result4.kind !== "clone-source")
35461
+ return yield* fail20("Unexpected clone source response");
35462
+ return result4.source;
35463
+ });
35464
+ var reviewClone = exports_Effect.fnUntraced(function* (host, command, input) {
35465
+ const result4 = yield* request3(host, command, { kind: "clone-plan", input });
35466
+ if (result4.kind !== "clone-plan")
35467
+ return yield* fail20("Unexpected clone review response");
35468
+ return result4.plan;
35469
+ });
35470
+ var submitClone = exports_Effect.fnUntraced(function* (host, command, input, reviewed) {
35471
+ if (reviewed.hostId !== host.hostId)
35472
+ return yield* fail20("Reviewed clone destination belongs to another host");
35473
+ const result4 = yield* request3(host, command, { kind: "clone-launch", input, reviewed });
35474
+ if (result4.kind !== "clone-launch")
35475
+ return yield* fail20("Unexpected clone launch response");
34597
35476
  return result4.result;
34598
35477
  });
34599
35478
 
@@ -34603,7 +35482,8 @@ import { randomUUID as randomUUID2 } from "crypto";
34603
35482
  // lua/rex-worktrees.lua
34604
35483
  var rex_worktrees_default = `-- rex-worktrees: managed module
34605
35484
  local installed_rex_bin_dir = false
34606
- -- Additive Rex action; no key is bound unless setup({ key = ... }) requests one.
35485
+ local installed_path_env = false
35486
+ -- Opening is opt-in via opts.key.
34607
35487
  local M = {}
34608
35488
 
34609
35489
  function M.setup(opts)
@@ -34621,6 +35501,7 @@ function M.setup(opts)
34621
35501
  local function worktrees_request(request)
34622
35502
  local exec_opts = { stdin = request, timeout = 20, env = {} }
34623
35503
  if rex_bin_dir then exec_opts.env.REX_BIN_DIR = rex_bin_dir end
35504
+ if installed_path_env ~= false then exec_opts.env.PATH = installed_path_env end
34624
35505
  if os.getenv("REX_WORKTREES_LOCAL_ENDPOINT") then exec_opts.env.REX_WORKTREES_LOCAL_ENDPOINT = os.getenv("REX_WORKTREES_LOCAL_ENDPOINT") end
34625
35506
  local result, run_err = rex.exec({ bin, "host-request" }, exec_opts)
34626
35507
  if not result then error(run_err, 0) end
@@ -34646,7 +35527,7 @@ function M.setup(opts)
34646
35527
  rex.action{
34647
35528
  name = "worktrees_open",
34648
35529
  title = "Open Worktree\u2026",
34649
- description = "Choose an existing Rex machine and open its Git worktree in its Rex session",
35530
+ description = "Choose a project, Rex machine, checkout, and exact session",
34650
35531
  run = function(ctx)
34651
35532
  local session_id = ctx.session_id or rex.session_id
34652
35533
  if type(session_id) ~= "string" then error("Select a Rex session first", 0) end
@@ -34664,6 +35545,7 @@ function M.setup(opts)
34664
35545
  end
34665
35546
  local exec_opts = { timeout = 20, env = {} }
34666
35547
  if rex_bin_dir then exec_opts.env.REX_BIN_DIR = rex_bin_dir end
35548
+ if installed_path_env ~= false then exec_opts.env.PATH = installed_path_env end
34667
35549
  if os.getenv("REX_WORKTREES_LOCAL_ENDPOINT") then exec_opts.env.REX_WORKTREES_LOCAL_ENDPOINT = os.getenv("REX_WORKTREES_LOCAL_ENDPOINT") end
34668
35550
  local result, run_err = rex.exec(command, exec_opts)
34669
35551
  if not result then error(run_err, 0) end
@@ -34680,6 +35562,7 @@ function M.setup(opts)
34680
35562
  end,
34681
35563
  }
34682
35564
 
35565
+
34683
35566
  if opts.key then rex.bind(opts.key, "worktrees_open") end
34684
35567
  end
34685
35568
 
@@ -34697,21 +35580,27 @@ require("rex-worktrees").setup()
34697
35580
  -- END rex-worktrees
34698
35581
  `;
34699
35582
  var managedRegistration = /^-- BEGIN rex-worktrees\nrequire\("rex-worktrees"\)\.setup\(\{ bin = "(?:\\.|[^"\\])*" \}\)\n-- END rex-worktrees\n$/;
34700
- var marker = `-- rex-worktrees: managed module
35583
+ var marker2 = `-- rex-worktrees: managed module
34701
35584
  `;
34702
35585
  var rexBinPlaceholder = "local installed_rex_bin_dir = false";
34703
- var fail19 = (message) => exports_Effect.fail(new AppError({ message }));
34704
- var installSetup = exports_Effect.fnUntraced(function* ({ source, home, configPath, lua: module, rexBinDir, managedBin }) {
35586
+ var pathEnvPlaceholder = "local installed_path_env = false";
35587
+ var luaLiteral = (value3) => JSON.stringify(value3).replace(/\\u00([0-1][0-9a-f])/gi, (_, hex) => `\\${parseInt(hex, 16).toString().padStart(3, "0")}`);
35588
+ var fail21 = (message) => exports_Effect.fail(new AppError({ message }));
35589
+ var installSetup = exports_Effect.fnUntraced(function* ({ source, home, configPath, lua: module, rexBinDir, managedBin, pathEnv, allowLinkedConfig = true }) {
34705
35590
  const fs = yield* exports_FileSystem.FileSystem;
34706
35591
  const path = yield* exports_Path.Path;
34707
35592
  if (!path.isAbsolute(configPath) || !path.isAbsolute(home) || !path.isAbsolute(source) || !path.isAbsolute(rexBinDir) || managedBin !== undefined && !path.isAbsolute(managedBin))
34708
35593
  return yield* new AppError({ message: "Setup requires absolute paths" });
34709
- if (!module.startsWith(marker))
35594
+ if (!module.startsWith(marker2))
34710
35595
  return yield* new AppError({ message: "Embedded Lua module is missing its install marker" });
34711
- if (!module.startsWith(`${marker}${rexBinPlaceholder}
35596
+ if (!module.startsWith(`${marker2}${rexBinPlaceholder}
34712
35597
  `) || module.split(rexBinPlaceholder).length !== 2)
34713
35598
  return yield* new AppError({ message: "Embedded Lua module must contain exactly one Rex CLI directory placeholder after its marker" });
34714
- const installedLua = module.replace(rexBinPlaceholder, `local installed_rex_bin_dir = ${JSON.stringify(rexBinDir).replace(/\\u00([0-1][0-9a-f])/gi, (_, hex) => `\\${parseInt(hex, 16).toString().padStart(3, "0")}`)}`);
35599
+ if (!module.startsWith(`${marker2}${rexBinPlaceholder}
35600
+ ${pathEnvPlaceholder}
35601
+ `) || module.split(pathEnvPlaceholder).length !== 2)
35602
+ return yield* new AppError({ message: "Embedded Lua module must contain exactly one host PATH placeholder after its Rex CLI directory placeholder" });
35603
+ const installedLua = module.replace(rexBinPlaceholder, `local installed_rex_bin_dir = ${luaLiteral(rexBinDir)}`).replace(pathEnvPlaceholder, `local installed_path_env = ${pathEnv === undefined ? "false" : luaLiteral(pathEnv)}`);
34715
35604
  const bin = managedBin ?? path.join(home, ".local", "bin", "rex-worktrees");
34716
35605
  const registration = managedBin === undefined ? manualRegistration : `-- BEGIN rex-worktrees
34717
35606
  require("rex-worktrees").setup({ bin = ${JSON.stringify(managedBin)} })
@@ -34722,35 +35611,37 @@ require("rex-worktrees").setup({ bin = ${JSON.stringify(managedBin)} })
34722
35611
  const binaryInfo = managedBin === undefined ? yield* info2(bin) : undefined;
34723
35612
  const luaInfo = yield* info2(luaPath);
34724
35613
  if (binaryInfo && binaryInfo.type !== "File")
34725
- return yield* fail19(`Refusing to replace non-file binary: ${bin}`);
35614
+ return yield* fail21(`Refusing to replace non-file binary: ${bin}`);
34726
35615
  if (luaInfo && luaInfo.type !== "File")
34727
- return yield* fail19(`Refusing to replace non-file Lua module: ${luaPath}`);
34728
- if (luaInfo && !(yield* fs.readFileString(luaPath)).startsWith(marker))
34729
- return yield* fail19(`Refusing to replace unrelated Lua module: ${luaPath}`);
35616
+ return yield* fail21(`Refusing to replace non-file Lua module: ${luaPath}`);
35617
+ if (luaInfo && !(yield* fs.readFileString(luaPath)).startsWith(marker2))
35618
+ return yield* fail21(`Refusing to replace unrelated Lua module: ${luaPath}`);
34730
35619
  const initInfo = yield* info2(configPath);
34731
35620
  if (initInfo && initInfo.type !== "File" && initInfo.type !== "SymbolicLink")
34732
- return yield* fail19(`Rex init is not a file: ${configPath}`);
35621
+ return yield* fail21(`Rex init is not a file: ${configPath}`);
35622
+ if (initInfo?.type === "SymbolicLink" && !allowLinkedConfig)
35623
+ return yield* fail21(`Refusing linked Rex init: ${configPath}`);
34733
35624
  const current = initInfo ? yield* fs.readFileString(configPath) : "";
34734
35625
  const begin = "-- BEGIN rex-worktrees";
34735
35626
  const end3 = "-- END rex-worktrees";
34736
35627
  const start = current.indexOf(begin);
34737
35628
  const finish = current.indexOf(end3);
34738
35629
  if (start < 0 !== finish < 0 || start >= 0 && (current.indexOf(begin, start + begin.length) !== -1 || current.indexOf(end3, finish + end3.length) !== -1 || current.slice(start, finish + end3.length + 1) !== manualRegistration && !managedRegistration.test(current.slice(start, finish + end3.length + 1))))
34739
- return yield* fail19(`Malformed rex-worktrees registration in ${configPath}`);
35630
+ return yield* fail21(`Malformed rex-worktrees registration in ${configPath}`);
34740
35631
  if (start < 0 && /require\s*\(?\s*["']rex-worktrees["']/.test(current))
34741
- return yield* fail19(`Existing rex-worktrees registration in ${configPath}; remove it before setup`);
35632
+ return yield* fail21(`Existing rex-worktrees registration in ${configPath}; remove it before setup`);
34742
35633
  const sourceInfo = yield* fs.stat(source);
34743
35634
  if (sourceInfo.type !== "File")
34744
- return yield* fail19(`Installer source is not a file: ${source}`);
35635
+ return yield* fail21(`Installer source is not a file: ${source}`);
34745
35636
  if (managedBin !== undefined) {
34746
35637
  const target = yield* info2(managedBin);
34747
35638
  if (!target)
34748
- return yield* fail19(`Managed binary does not exist: ${managedBin}`);
35639
+ return yield* fail21(`Managed binary does not exist: ${managedBin}`);
34749
35640
  const managedInfo = yield* fs.stat(managedBin);
34750
35641
  if (managedInfo.type !== "File" || (managedInfo.mode & 73) === 0)
34751
- return yield* fail19(`Managed binary must be an executable file: ${managedBin}`);
35642
+ return yield* fail21(`Managed binary must be an executable file: ${managedBin}`);
34752
35643
  if ((yield* fs.realPath(managedBin)) !== (yield* fs.realPath(source)))
34753
- return yield* fail19(`Managed binary must resolve to the running executable: ${managedBin}`);
35644
+ return yield* fail21(`Managed binary must resolve to the running executable: ${managedBin}`);
34754
35645
  } else
34755
35646
  yield* fs.makeDirectory(path.dirname(bin), { recursive: true });
34756
35647
  yield* fs.makeDirectory(path.dirname(luaPath), { recursive: true });
@@ -34773,18 +35664,20 @@ require("rex-worktrees").setup({ bin = ${JSON.stringify(managedBin)} })
34773
35664
  yield* fs.writeFileString(configPath, `${current.slice(0, start)}${registration}${current.slice(finish + end3.length + 1)}`);
34774
35665
  return { bin, luaPath, configPath };
34775
35666
  });
34776
- var setup = exports_Effect.fnUntraced(function* (managedBin) {
35667
+ var setup = exports_Effect.fnUntraced(function* (managedBin, configPath) {
34777
35668
  const home = process.env.HOME;
34778
35669
  if (!home)
34779
- return yield* fail19("HOME is required");
35670
+ return yield* fail21("HOME is required");
34780
35671
  const fs = yield* exports_FileSystem.FileSystem;
34781
35672
  const path = yield* exports_Path.Path;
35673
+ if (configPath !== undefined && !path.isAbsolute(configPath))
35674
+ return yield* fail21(`--config must be an absolute path: ${configPath}`);
34782
35675
  const executable = (dir2) => exports_Effect.catchIf(fs.stat(path.join(dir2, "rex")).pipe(exports_Effect.map((info2) => info2.type === "File" && (info2.mode & 73) !== 0)), (error2) => exports_PlatformError.isPlatformError(error2) && error2.reason._tag === "NotFound", () => exports_Effect.succeed(false));
34783
35676
  const configured = process.env.REX_BIN_DIR;
34784
35677
  let rexBinDir;
34785
35678
  if (configured) {
34786
35679
  if (!path.isAbsolute(configured) || !(yield* executable(configured)))
34787
- return yield* fail19(`REX_BIN_DIR must be an absolute directory containing an executable rex: ${configured}`);
35680
+ return yield* fail21(`REX_BIN_DIR must be an absolute directory containing an executable rex: ${configured}`);
34788
35681
  rexBinDir = configured;
34789
35682
  } else {
34790
35683
  for (const entry of (process.env.PATH ?? "").split(":")) {
@@ -34795,12 +35688,16 @@ var setup = exports_Effect.fnUntraced(function* (managedBin) {
34795
35688
  }
34796
35689
  }
34797
35690
  if (!rexBinDir)
34798
- return yield* fail19("Rex CLI not found: set REX_BIN_DIR or add an executable rex to PATH");
34799
- const response = yield* rex(["config", "check", "--json"]);
34800
- const checked = yield* exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(RexConfigCheckSchema))(response);
34801
- if (checked.diagnostics.length)
34802
- return yield* fail19("Rex config has diagnostics; fix it before setup");
34803
- return yield* installSetup({ source: process.execPath, home, configPath: checked.path, lua: rex_worktrees_default, rexBinDir, managedBin });
35691
+ return yield* fail21("Rex CLI not found: set REX_BIN_DIR or add an executable rex to PATH");
35692
+ let target = configPath;
35693
+ if (target === undefined) {
35694
+ const response = yield* rex(["config", "check", "--json"]);
35695
+ const checked = yield* exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(RexConfigCheckSchema))(response);
35696
+ if (checked.diagnostics.length)
35697
+ return yield* fail21("Rex config has diagnostics; fix it before setup");
35698
+ target = checked.path;
35699
+ }
35700
+ return yield* installSetup({ source: process.execPath, home, configPath: target, lua: rex_worktrees_default, rexBinDir, managedBin, allowLinkedConfig: configPath === undefined, ...process.env.PATH !== undefined ? { pathEnv: process.env.PATH } : {} });
34804
35701
  });
34805
35702
  // node_modules/effect/dist/cli/Prompt.js
34806
35703
  var exports_Prompt = {};
@@ -34886,12 +35783,12 @@ var cursorMove = (column, row = 0) => {
34886
35783
  }
34887
35784
  return command;
34888
35785
  };
34889
- var eraseLines = (rows) => {
35786
+ var eraseLines = (rows2) => {
34890
35787
  let command = "";
34891
- for (let i = 0;i < rows; i++) {
34892
- command += `${ESC}2K` + (i < rows - 1 ? `${ESC}1A` : "");
35788
+ for (let i = 0;i < rows2; i++) {
35789
+ command += `${ESC}2K` + (i < rows2 - 1 ? `${ESC}1A` : "");
34893
35790
  }
34894
- if (rows > 0) {
35791
+ if (rows2 > 0) {
34895
35792
  command += `${ESC}G`;
34896
35793
  }
34897
35794
  return command;
@@ -35341,12 +36238,12 @@ var eraseText = (text, columns) => {
35341
36238
  if (columns === 0) {
35342
36239
  return eraseLine + cursorTo(0);
35343
36240
  }
35344
- let rows = 0;
36241
+ let rows2 = 0;
35345
36242
  const lines = text.split(NEWLINE_REGEXP);
35346
36243
  for (const line of lines) {
35347
- rows += 1 + Math.floor(Math.max(line.length - 1, 0) / columns);
36244
+ rows2 += 1 + Math.floor(Math.max(line.length - 1, 0) / columns);
35348
36245
  }
35349
- return eraseLines(rows);
36246
+ return eraseLines(rows2);
35350
36247
  };
35351
36248
  var lines = (prompt, columns) => {
35352
36249
  const lines2 = prompt.split(NEWLINE_REGEXP);
@@ -37469,7 +38366,7 @@ var safeDisplayText = (text, preserveWhitespace = false) => {
37469
38366
  };
37470
38367
  var fit = (text, width2) => Bun.stringWidth(text) > width2 ? Bun.sliceAnsi(text, 0, Math.max(0, width2), { ellipsis: "\u2026" }) : text;
37471
38368
  var pad = (text, width2) => text + " ".repeat(Math.max(0, width2 - Bun.stringWidth(text)));
37472
- var renderFormFrame = (view, focused, editing, columns, rows, colors2 = !process.env.NO_COLOR, fill = true) => {
38369
+ var renderFormFrame = (view, focused, editing, columns, rows2, colors2 = !process.env.NO_COLOR, fill = true) => {
37473
38370
  const width2 = Math.max(20, columns);
37474
38371
  const inside = width2 - 4;
37475
38372
  const screen = [];
@@ -37477,10 +38374,10 @@ var renderFormFrame = (view, focused, editing, columns, rows, colors2 = !process
37477
38374
  const line = (left, right) => color(`${left}${"\u2500".repeat(width2 - 2)}${right}`, "muted", colors2);
37478
38375
  const add4 = (text) => screen.push(border(fit(text, inside)));
37479
38376
  screen.push(line("\u250C", "\u2510"));
37480
- const heading = `${color("REX", "cyan", colors2)} ${color("/ WORKTREES", "bold", colors2)}`;
37481
- add4(`${heading}${" ".repeat(Math.max(1, inside - Bun.stringWidth(heading) - 5))}${color("HOSTS", "amber", colors2)}`);
38377
+ const heading = `${color("REX", "cyan", colors2)} ${color("/ WORKTREES", "bold", colors2)}`;
38378
+ add4(heading);
37482
38379
  screen.push(line("\u251C", "\u2524"));
37483
- const budget = Math.max(0, rows - (editing ? rows >= 20 ? 11 : 9 : 7));
38380
+ const budget = Math.max(0, rows2 - (editing ? rows2 >= 20 ? 11 : 9 : 7));
37484
38381
  const body = [];
37485
38382
  const addBody = (text) => body.push(border(fit(text, inside)));
37486
38383
  const addWrapped = (text, tone, limit = budget) => {
@@ -37493,12 +38390,12 @@ var renderFormFrame = (view, focused, editing, columns, rows, colors2 = !process
37493
38390
  };
37494
38391
  for (const row of view.rows) {
37495
38392
  const active = focused === row.id;
37496
- const label = pad(fit(safeDisplayText(row.label).toUpperCase(), 12), 12);
38393
+ const label = pad(fit(safeDisplayText(row.label).toUpperCase(), 13), 13);
37497
38394
  const value3 = safeDisplayText(row.value) || "\u2014";
37498
- const room = Math.max(1, inside - 18);
38395
+ const room = Math.max(1, inside - 19);
37499
38396
  const indicator = active ? color("\u203A", "cyan", colors2) : " ";
37500
38397
  addBody(`${indicator} ${color(label, row.disabled ? "muted" : active ? "cyan" : "bold", colors2)} ${color(fit(value3, room), row.disabled ? "muted" : active ? "bold" : "muted", colors2)}`);
37501
- if (!editing && !view.error && (active || row.id === "destination") && row.detail && body.length < budget - 3)
38398
+ if (!editing && !view.error && active && row.detail && body.length < budget - 3)
37502
38399
  addWrapped(row.detail, "muted", budget - 3);
37503
38400
  }
37504
38401
  if (view.error) {
@@ -37520,7 +38417,7 @@ var renderFormFrame = (view, focused, editing, columns, rows, colors2 = !process
37520
38417
  const cancel = focused === "cancel" ? color("\u203A", "cyan", colors2) : " ";
37521
38418
  add4(`${submit2} ${color(fit(safeDisplayText(view.submitLabel), Math.max(1, inside - 19)), view.submitDisabled ? "muted" : "cyan", colors2)} ${cancel} ${color("Cancel", focused === "cancel" ? "cyan" : "muted", colors2)}`);
37522
38419
  if (!editing)
37523
- add4(color(" \u2191\u2193 / jk move \xB7 Tab next \xB7 Enter select \xB7 Esc close", "muted", colors2));
38420
+ add4(color(" \u2191\u2193 / jk move \xB7 Tab next \xB7 Enter select \xB7 Ctrl+S submit \xB7 Esc close", "muted", colors2));
37524
38421
  screen.push(line("\u2514", "\u2518"));
37525
38422
  return screen.join(`\r
37526
38423
  `) + (editing ? `\r
@@ -37557,7 +38454,7 @@ var advanceInputChoice = (state, event, choices, selectionOnly = false) => {
37557
38454
  const next = matches[(current + (key5.name === "up" ? -1 : 1) + matches.length) % matches.length];
37558
38455
  return next === undefined ? { _tag: "Beep" } : { _tag: "NextFrame", state: { ...state, selected: next } };
37559
38456
  }
37560
- if (key5.name === "enter" || key5.name === "return") {
38457
+ if (key5.name === "enter" || key5.name === "return" || key5.ctrl && key5.name === "s") {
37561
38458
  const picked = state.selected === null ? undefined : choices[state.selected];
37562
38459
  if (picked && state.selected !== null && matches.includes(state.selected))
37563
38460
  return { _tag: "Submit", value: { kind: "selected", value: picked.value } };
@@ -37572,10 +38469,10 @@ var advanceInputChoice = (state, event, choices, selectionOnly = false) => {
37572
38469
  return { _tag: "Beep" };
37573
38470
  return { _tag: "NextFrame", state: { text: state.text + text, selected: selectionOnly ? state.selected : null } };
37574
38471
  };
37575
- var renderInputChoice = (message, state, choices, columns, rows, colors2 = !process.env.NO_COLOR, selectionOnly = false) => {
38472
+ var renderInputChoice = (message, state, choices, columns, rows2, colors2 = !process.env.NO_COLOR, selectionOnly = false) => {
37576
38473
  const width2 = Math.max(20, columns) - 2;
37577
38474
  const matches = matchingChoices(choices, state.text);
37578
- const count2 = rows >= 20 ? 3 : 1;
38475
+ const count2 = rows2 >= 20 ? 3 : 1;
37579
38476
  const selected = matches.indexOf(state.selected ?? -1);
37580
38477
  const start = selected < 0 ? 0 : Math.max(0, Math.min(selected, matches.length - count2));
37581
38478
  const lines2 = [
@@ -37618,45 +38515,106 @@ var acknowledge = (title, lines2, tone) => exports_Prompt.run(exports_Prompt.Cus
37618
38515
  clear: () => exports_Effect.succeed(""),
37619
38516
  process: (input) => exports_Effect.succeed(input.key.name === "enter" || input.key.name === "return" || input.key.name === "space" || input.key.name === "escape" || input.key.ctrl && input.key.name === "c" ? { _tag: "Submit", value: undefined } : { _tag: "Beep" })
37620
38517
  })).pipe(exports_Effect.catch(() => exports_Effect.void));
37621
- var problem = (error2) => exports_Cause.pretty(exports_Cause.fail(error2));
38518
+ var problem = (error2) => error2 instanceof AppError ? error2.message : exports_Cause.pretty(exports_Cause.fail(error2));
37622
38519
  var selected = (value3, current, title, description) => ({ value: value3, selected: current, title, description });
37623
- var generatedName = (draft) => draft.worktreeName ?? draft.destination?.label ?? draft.projectChoice?.name ?? "Worktree";
37624
- var inputFor = (draft) => draft.host && draft.project && draft.projectChoice && draft.destination && draft.sessionId ? {
37625
- repo: draft.project.path,
37626
- sessionId: draft.sessionId,
37627
- name: generatedName(draft),
37628
- ...draft.destination.branch ? { branch: draft.destination.branch, ...draft.worktreeName ? { worktreeName: draft.worktreeName } : {} } : { path: draft.destination.path },
37629
- clientId: draft.clientId,
37630
- additional: draft.mode === "new-tab",
37631
- split: draft.mode === "split"
37632
- } : undefined;
38520
+ var generatedName = (draft) => draft.worktreeName ?? (draft.clone?.vcs === "jj" ? draft.projectChoice?.name : draft.destination?.label) ?? draft.projectChoice?.name ?? "Worktree";
38521
+ var inputFor = (draft) => {
38522
+ if (!draft.host || !draft.project || !draft.projectChoice || !draft.destination || !draft.sessionId)
38523
+ return;
38524
+ const common = {
38525
+ repo: draft.project.vcs === "jj" ? draft.sourcePath ?? draft.project.path : draft.project.path,
38526
+ sessionId: draft.sessionId,
38527
+ name: generatedName(draft),
38528
+ clientId: draft.clientId,
38529
+ additional: draft.mode === "new-tab",
38530
+ split: draft.mode === "split"
38531
+ };
38532
+ if (draft.project.vcs === "jj")
38533
+ return draft.destination.path ? { ...common, vcs: "jj", path: draft.destination.path } : draft.worktreeName && draft.destination.revision ? { ...common, vcs: "jj", worktreeName: draft.worktreeName, revision: draft.destination.revision } : undefined;
38534
+ return draft.destination.branch ? { ...common, vcs: "git", branch: draft.destination.branch, ...draft.worktreeName ? { worktreeName: draft.worktreeName } : {} } : { ...common, vcs: "git", path: draft.destination.path };
38535
+ };
37633
38536
  var changeMachine = (draft, machine) => draft.machine?.key === machine.key ? { ...draft, machine } : { machine, projectChoice: draft.projectChoice, mode: draft.mode };
37634
38537
  var changeProjectChoice = (draft, projectChoice) => ({
37635
38538
  ...draft,
37636
38539
  projectChoice,
37637
38540
  project: undefined,
38541
+ clone: undefined,
37638
38542
  destination: undefined,
37639
- worktreeName: undefined
38543
+ worktreeName: undefined,
38544
+ sourcePath: undefined
37640
38545
  });
37641
38546
  var changeProject = (draft, candidate) => ({
37642
38547
  ...draft,
37643
38548
  project: candidate,
37644
- destination: draft.project?.commonDir === candidate.commonDir ? draft.destination : undefined,
37645
- worktreeName: draft.project?.commonDir === candidate.commonDir ? draft.worktreeName : undefined
38549
+ clone: undefined,
38550
+ destination: draft.project?.vcs === candidate.vcs && draft.project.commonDir === candidate.commonDir ? draft.destination : undefined,
38551
+ worktreeName: draft.project?.vcs === candidate.vcs && draft.project.commonDir === candidate.commonDir ? draft.worktreeName : undefined,
38552
+ sourcePath: candidate.vcs === "jj" && draft.project?.vcs === "jj" && draft.project.commonDir === candidate.commonDir ? draft.sourcePath : undefined
37646
38553
  });
37647
38554
  var changeDestination = (draft, candidate, worktreeName) => ({
37648
38555
  ...draft,
37649
38556
  destination: candidate,
37650
38557
  worktreeName: candidate.path ? undefined : worktreeName
37651
38558
  });
37652
- var selectWorktree = (draft, tree) => changeDestination(draft, { path: tree.path, label: tree.path.split("/").filter(Boolean).at(-1) ?? tree.path });
37653
- var typeWorktreeName = (draft, name) => ({
38559
+ var selectWorktree = (draft, tree) => {
38560
+ if (!tree.path || tree.vcs === "jj" && !tree.present)
38561
+ throw new AppError({ message: `Workspace ${tree.vcs === "jj" ? tree.name : tree.path} is unavailable; inspect its registered location before opening` });
38562
+ return {
38563
+ ...changeDestination(draft, { path: tree.path, label: tree.vcs === "jj" ? tree.name : tree.path.split("/").filter(Boolean).at(-1) ?? tree.path }),
38564
+ ...tree.vcs === "jj" ? {
38565
+ sourcePath: tree.path,
38566
+ projectChoice: draft.projectChoice?.source && draft.projectChoice.source.hostId === draft.host?.hostId ? { ...draft.projectChoice, source: { ...draft.projectChoice.source, checkoutPath: tree.path } } : draft.projectChoice
38567
+ } : {}
38568
+ };
38569
+ };
38570
+ var typeWorktreeName = (draft, name, mainline) => ({
37654
38571
  ...draft,
37655
38572
  worktreeName: name,
37656
- destination: draft.destination?.path ? undefined : draft.destination
38573
+ destination: draft.destination && !draft.destination.path ? draft.destination : draft.project?.vcs === "jj" && !draft.clone && mainline ? { revision: mainline.revision.commitId, label: mainline.label } : undefined
37657
38574
  });
37658
38575
  var resolveBranch = (draft, branch, path, existing) => existing ? changeDestination(draft, { path, label: path.split("/").filter(Boolean).at(-1) ?? path }) : changeDestination(draft, { branch, label: branch }, draft.worktreeName ?? branch);
37659
- var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect.scoped(exports_Effect.suspend(() => {
38576
+ var selectRevision = (draft, choice) => changeDestination(draft, { revision: choice.revision.commitId, label: choice.label }, draft.worktreeName);
38577
+ var cloneInputFor = (draft) => {
38578
+ if (!draft.host || !draft.clone || !draft.sessionId || !draft.clone.repo.startsWith("/"))
38579
+ return;
38580
+ if (draft.clone.vcs === "jj")
38581
+ return {
38582
+ vcs: "jj",
38583
+ source: {
38584
+ vcs: "jj",
38585
+ url: draft.clone.url,
38586
+ sourceHostId: draft.clone.sourceHostId,
38587
+ revisions: draft.clone.revisions,
38588
+ ...draft.clone.revision ? { revision: draft.clone.revision } : {}
38589
+ },
38590
+ repo: draft.clone.repo,
38591
+ sessionId: draft.sessionId,
38592
+ clientId: draft.clientId,
38593
+ name: generatedName(draft),
38594
+ ...draft.worktreeName ? { worktreeName: draft.worktreeName } : {},
38595
+ ...draft.destination?.revision ? { revision: draft.destination.revision } : {}
38596
+ };
38597
+ if (!draft.destination?.branch)
38598
+ return;
38599
+ return {
38600
+ vcs: "git",
38601
+ source: {
38602
+ vcs: "git",
38603
+ url: draft.clone.url,
38604
+ sourceHostId: draft.clone.sourceHostId,
38605
+ branches: draft.clone.branches,
38606
+ branch: draft.clone.branch
38607
+ },
38608
+ repo: draft.clone.repo,
38609
+ sessionId: draft.sessionId,
38610
+ clientId: draft.clientId,
38611
+ name: generatedName(draft),
38612
+ branch: draft.destination.branch,
38613
+ branchMode: draft.clone.branches.includes(draft.destination.branch) ? "existing" : "create",
38614
+ ...draft.worktreeName ? { worktreeName: draft.worktreeName } : {}
38615
+ };
38616
+ };
38617
+ var popup = (command, context3, origin2 = {}, preferredMachine) => exports_Effect.scoped(exports_Effect.suspend(() => {
37660
38618
  let launchAcknowledged = false;
37661
38619
  return exports_Effect.gen(function* () {
37662
38620
  const terminal = yield* exports_Terminal.Terminal;
@@ -37667,20 +38625,23 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37667
38625
  let focused = "project";
37668
38626
  let error2;
37669
38627
  let plan;
38628
+ let clonePlan;
38629
+ let cloneRoots = [];
38630
+ let submitAfterEdit = false;
37670
38631
  let contextPath;
37671
38632
  const resizePopup = yield* makePopupSizer;
37672
38633
  let activeView;
37673
38634
  let repaint;
37674
38635
  const fitRequests = yield* exports_Queue.sliding(1);
37675
38636
  yield* exports_Effect.forever(exports_Effect.gen(function* () {
37676
- const { view, columns, rows, editing } = yield* exports_Queue.take(fitRequests);
37677
- const warning = yield* resizePopup({ columns: 96, rows: popupTargetRows(view, columns, editing) }, { columns, rows });
38637
+ const { view, columns, rows: rows2, editing } = yield* exports_Queue.take(fitRequests);
38638
+ const warning = yield* resizePopup({ columns: 96, rows: popupTargetRows(view, columns, editing) }, { columns, rows: rows2 });
37678
38639
  if (activeView !== view)
37679
38640
  return;
37680
38641
  const changed = view.fitWarning !== warning;
37681
38642
  view.fitWarning = warning;
37682
38643
  if (changed && repaint)
37683
- yield* exports_Queue.offer(repaint, { columns, rows });
38644
+ yield* exports_Queue.offer(repaint, { columns, rows: rows2 });
37684
38645
  })).pipe(exports_Effect.forkScoped);
37685
38646
  const chooseField = exports_Effect.fnUntraced(function* (view, initialFocus) {
37686
38647
  const terminal2 = yield* exports_Terminal.Terminal;
@@ -37697,9 +38658,9 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37697
38658
  const prompt = exports_Prompt.Custom(initial, resized, {
37698
38659
  render: (index2, action) => action._tag === "Submit" ? exports_Effect.succeed("") : exports_Effect.gen(function* () {
37699
38660
  const columns = yield* terminal2.columns;
37700
- const rows = yield* terminal2.rows;
37701
- yield* exports_Queue.offer(fitRequests, { view, columns, rows, editing: false });
37702
- return `\x1B[H\x1B[2J${renderFormFrame(view, fields[index2], false, columns, rows)}`;
38661
+ const rows2 = yield* terminal2.rows;
38662
+ yield* exports_Queue.offer(fitRequests, { view, columns, rows: rows2, editing: false });
38663
+ return `\x1B[H\x1B[2J${renderFormFrame(view, fields[index2], false, columns, rows2)}`;
37703
38664
  }),
37704
38665
  clear: () => exports_Effect.succeed(""),
37705
38666
  process: (event, index2) => {
@@ -37708,6 +38669,8 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37708
38669
  const { key: key5 } = event.input;
37709
38670
  if (key5.name === "escape" || key5.ctrl && key5.name === "c")
37710
38671
  return exports_Effect.succeed({ _tag: "Submit", value: "cancel" });
38672
+ if (key5.ctrl && key5.name === "s")
38673
+ return exports_Effect.succeed(view.submitDisabled ? { _tag: "Beep" } : { _tag: "Submit", value: "submit" });
37711
38674
  if (key5.name === "enter" || key5.name === "return") {
37712
38675
  const selected2 = fields[index2];
37713
38676
  return exports_Effect.succeed(selected2 === "submit" && view.submitDisabled || view.rows.some((row) => row.id === selected2 && row.disabled) ? { _tag: "Beep" } : { _tag: "Submit", value: selected2 });
@@ -37732,17 +38695,24 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37732
38695
  const result4 = yield* exports_Prompt.run(exports_Prompt.Custom({ text: "", selected: options.selected === undefined || options.selected < 0 ? null : options.selected }, resized, {
37733
38696
  render: (state, action) => action._tag === "Submit" ? exports_Effect.succeed("") : exports_Effect.gen(function* () {
37734
38697
  const columns = yield* terminal2.columns;
37735
- const rows = yield* terminal2.rows;
38698
+ const rows2 = yield* terminal2.rows;
37736
38699
  const view = activeView;
37737
38700
  if (view)
37738
- yield* exports_Queue.offer(fitRequests, { view, columns, rows, editing: true });
37739
- const editor = renderInputChoice(options.message, state, options.choices, columns, rows, !process.env.NO_COLOR, options.selectionOnly);
38701
+ yield* exports_Queue.offer(fitRequests, { view, columns, rows: rows2, editing: true });
38702
+ const editor = renderInputChoice(options.message, state, options.choices, columns, rows2, !process.env.NO_COLOR, options.selectionOnly);
37740
38703
  if (!view)
37741
38704
  return "";
37742
- return `\x1B[H\x1B[2J${renderFormFrame(view, focused, true, columns, rows)}${editor}`;
38705
+ return `\x1B[H\x1B[2J${renderFormFrame(view, focused, true, columns, rows2)}${editor}`;
37743
38706
  }),
37744
38707
  clear: () => exports_Effect.succeed(""),
37745
- process: (event, state) => exports_Effect.succeed(event._tag === "Event" ? { _tag: "NextFrame", state } : advanceInputChoice(state, event.input, options.choices, options.selectionOnly))
38708
+ process: (event, state) => {
38709
+ if (event._tag === "Event")
38710
+ return exports_Effect.succeed({ _tag: "NextFrame", state });
38711
+ const action = advanceInputChoice(state, event.input, options.choices, options.selectionOnly);
38712
+ if (event.input.key.ctrl && event.input.key.name === "s" && action._tag === "Submit" && action.value)
38713
+ submitAfterEdit = true;
38714
+ return exports_Effect.succeed(action);
38715
+ }
37746
38716
  }));
37747
38717
  return result4 === null ? yield* exports_Effect.fail(new exports_Terminal.QuitError({})) : result4;
37748
38718
  }, exports_Effect.scoped);
@@ -37758,7 +38728,7 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37758
38728
  return picked.value;
37759
38729
  });
37760
38730
  let projects = [];
37761
- const focusClient = (clients) => clients.some((item) => item.id === draft.clientId) ? draft.clientId : draft.host?.local && clients.some((item) => item.id === origin.clientId) ? origin.clientId : clients.length === 1 ? clients[0]?.id : undefined;
38731
+ const focusClient = (clients) => clients.some((item) => item.id === draft.clientId) ? draft.clientId : draft.host?.local && clients.some((item) => item.id === origin2.clientId) ? origin2.clientId : clients.length === 1 ? clients[0]?.id : undefined;
37762
38732
  const loadMachines = exports_Effect.gen(function* () {
37763
38733
  const found = yield* exports_Effect.result(listMachines);
37764
38734
  if (exports_Result.isFailure(found))
@@ -37770,8 +38740,21 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37770
38740
  });
37771
38741
  const refresh = exports_Effect.gen(function* () {
37772
38742
  plan = undefined;
38743
+ clonePlan = undefined;
38744
+ if (!draft.host)
38745
+ return;
38746
+ const cloneInput = cloneInputFor(draft);
38747
+ if (cloneInput) {
38748
+ const result5 = yield* exports_Effect.result(reviewClone(draft.host, command, cloneInput));
38749
+ if (exports_Result.isSuccess(result5)) {
38750
+ clonePlan = result5.success;
38751
+ error2 = undefined;
38752
+ } else
38753
+ error2 = problem(result5.failure);
38754
+ return;
38755
+ }
37773
38756
  const input = inputFor(draft);
37774
- if (!draft.host || !input)
38757
+ if (!input)
37775
38758
  return;
37776
38759
  const result4 = yield* exports_Effect.result(review(draft.host, command, input));
37777
38760
  if (exports_Result.isSuccess(result4)) {
@@ -37780,28 +38763,82 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37780
38763
  } else
37781
38764
  error2 = problem(result4.failure);
37782
38765
  });
37783
- const known = (host, repository2) => ({
37784
- name: repository2.name,
37785
- source: { machineKey: host.key, hostId: host.hostId, repository: repository2 }
38766
+ const known = (host, repository4, checkout) => ({
38767
+ name: repository4.name,
38768
+ source: {
38769
+ machineKey: host.key,
38770
+ hostId: host.hostId,
38771
+ repository: repository4,
38772
+ ...repository4.vcs === "jj" && checkout?.vcs === "jj" && checkout.commonDir === repository4.commonDir ? { checkoutPath: checkout.path } : {}
38773
+ }
38774
+ });
38775
+ const proposeClone = exports_Effect.fnUntraced(function* (choice, host, repo) {
38776
+ const reference = choice.source;
38777
+ if (!reference)
38778
+ return yield* exports_Effect.fail(new AppError({ message: "Choose a known source project before cloning" }));
38779
+ const sourceMachine = machines.find((item) => item.key === reference.machineKey);
38780
+ if (!sourceMachine)
38781
+ return yield* exports_Effect.fail(new AppError({ message: "Source Rex machine is no longer registered" }));
38782
+ const sourceHost = yield* connectMachine(sourceMachine);
38783
+ if (sourceHost.hostId !== reference.hostId)
38784
+ return yield* exports_Effect.fail(new AppError({ message: "Source Rex host identity changed; select the project again" }));
38785
+ const source = yield* sourceForClone(sourceHost, command, reference.checkoutPath ?? reference.repository.path);
38786
+ draft = {
38787
+ ...draft,
38788
+ projectChoice: choice,
38789
+ host,
38790
+ project: undefined,
38791
+ clone: { ...source, repo },
38792
+ destination: source.vcs === "git" && source.branch ? { branch: source.branch, label: source.branch } : undefined,
38793
+ worktreeName: undefined
38794
+ };
38795
+ });
38796
+ const cloneDestination2 = exports_Effect.fnUntraced(function* (choice, host) {
38797
+ const picked = yield* inputChoice({
38798
+ message: `Clone destination on ${host.label} (absolute path; only pushed history transfers)`,
38799
+ choices: cloneRoots.map((root) => ({
38800
+ value: `${root.replace(/\/$/, "")}/${choice.name}`,
38801
+ title: choice.name,
38802
+ description: `${root.replace(/\/$/, "")}/${choice.name} \xB7 configured root suggestion`
38803
+ }))
38804
+ });
38805
+ const repo = picked.kind === "selected" ? picked.value : picked.text.trim();
38806
+ if (!repo.startsWith("/"))
38807
+ return yield* exports_Effect.fail(new AppError({ message: "Clone destination must be an absolute path on the selected machine" }));
38808
+ yield* proposeClone(choice, host, repo);
37786
38809
  });
37787
38810
  const bindProject = exports_Effect.fnUntraced(function* (choice, host, available) {
37788
38811
  const source = choice.source;
37789
- let path = source?.machineKey === host.key && source.hostId === host.hostId ? source.repository.path : undefined;
38812
+ let path = source?.machineKey === host.key && source.hostId === host.hostId ? source.checkoutPath ?? source.repository.path : undefined;
37790
38813
  if (!path && choice.path?.startsWith("/"))
37791
38814
  path = choice.path;
37792
38815
  if (!path) {
37793
38816
  const directory = yield* inputChoice({
37794
- message: `Project directory on ${host.label} (select an exact path or type an absolute path)`,
37795
- choices: available.map((repo) => ({ value: repo.path, title: repo.name, description: repo.path }))
38817
+ message: `Project directory on ${host.label} (existing checkout or missing clone destination; absolute path)`,
38818
+ choices: [
38819
+ ...available.map((repo) => ({ value: repo.path, title: repo.name, description: repo.path })),
38820
+ ...cloneRoots.map((root) => ({
38821
+ value: `${root.replace(/\/$/, "")}/${choice.name}`,
38822
+ title: choice.name,
38823
+ description: `${root.replace(/\/$/, "")}/${choice.name} \xB7 configured root suggestion`
38824
+ }))
38825
+ ]
37796
38826
  });
37797
38827
  path = directory.kind === "selected" ? directory.value : directory.text.trim();
37798
38828
  }
37799
38829
  if (!path.startsWith("/"))
37800
38830
  return yield* exports_Effect.fail(new AppError({ message: "Project directory must be an absolute path on this machine" }));
37801
- const inspected = yield* inspectProject(host, command, path);
37802
- if (source?.machineKey === host.key && source.hostId === host.hostId && inspected.project.commonDir !== source.repository.commonDir)
38831
+ const inspected = yield* exports_Effect.result(inspectProject(host, command, path));
38832
+ if (exports_Result.isFailure(inspected)) {
38833
+ if (choice.source && inspected.failure instanceof AppError && inspected.failure.message.startsWith("Project directory does not exist:")) {
38834
+ yield* proposeClone(choice, host, path);
38835
+ return;
38836
+ }
38837
+ return yield* exports_Effect.fail(inspected.failure);
38838
+ }
38839
+ if (source?.machineKey === host.key && source.hostId === host.hostId && (inspected.success.project.vcs !== source.repository.vcs || inspected.success.project.commonDir !== source.repository.commonDir))
37803
38840
  return yield* exports_Effect.fail(new AppError({ message: "Project directory changed; select the exact project directory again" }));
37804
- return inspected;
38841
+ return inspected.success;
37805
38842
  });
37806
38843
  const activate2 = exports_Effect.fnUntraced(function* (machine) {
37807
38844
  const previousHostId = draft.host?.hostId;
@@ -37813,6 +38850,8 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37813
38850
  draft = { machine, projectChoice: draft.projectChoice, mode: draft.mode };
37814
38851
  sessions = [];
37815
38852
  plan = undefined;
38853
+ clonePlan = undefined;
38854
+ cloneRoots = [];
37816
38855
  error2 = problem(connected.failure);
37817
38856
  return;
37818
38857
  }
@@ -37820,6 +38859,7 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37820
38859
  draft = { machine, projectChoice: draft.projectChoice, mode: draft.mode };
37821
38860
  sessions = [];
37822
38861
  plan = undefined;
38862
+ clonePlan = undefined;
37823
38863
  }
37824
38864
  draft = { ...draft, host: connected.success };
37825
38865
  const discovered = yield* exports_Effect.result(discover(connected.success, command, discoveredContext));
@@ -37827,26 +38867,35 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37827
38867
  draft = { machine, projectChoice: draft.projectChoice, mode: draft.mode };
37828
38868
  sessions = [];
37829
38869
  plan = undefined;
38870
+ clonePlan = undefined;
38871
+ cloneRoots = [];
37830
38872
  error2 = problem(discovered.failure);
37831
38873
  return;
37832
38874
  }
37833
38875
  const found = discovered.success;
38876
+ cloneRoots = found.roots;
37834
38877
  projects = [
37835
38878
  ...projects.filter((item) => item.source?.machineKey !== machine.key || item.source.hostId !== connected.success.hostId),
37836
- ...found.projects.map((repo) => known(connected.success, repo))
38879
+ ...found.projects.map((repo) => known(connected.success, repo, found.checkout))
37837
38880
  ];
37838
38881
  sessions = found.sessions;
37839
38882
  draft = {
37840
38883
  ...draft,
37841
- sessionId: sessions.some((item) => item.id === draft.sessionId) ? draft.sessionId : connected.success.local && origin.sessionId && sessions.some((item) => item.id === origin.sessionId) ? origin.sessionId : sessions.length === 1 ? sessions[0]?.id : undefined,
38884
+ sessionId: sessions.some((item) => item.id === draft.sessionId) ? draft.sessionId : connected.success.local && origin2.sessionId && sessions.some((item) => item.id === origin2.sessionId) ? origin2.sessionId : sessions.length === 1 ? sessions[0]?.id : undefined,
37842
38885
  clientId: focusClient(found.clients)
37843
38886
  };
37844
38887
  if (!draft.projectChoice && found.checkout && discoveredContext) {
37845
38888
  const inspected = yield* exports_Effect.result(inspectProject(connected.success, command, found.checkout.path));
38889
+ if (exports_Result.isFailure(inspected)) {
38890
+ error2 = problem(inspected.failure);
38891
+ return;
38892
+ }
37846
38893
  if (exports_Result.isSuccess(inspected)) {
37847
- draft = changeProjectChoice(draft, known(connected.success, inspected.success.project));
38894
+ draft = changeProjectChoice(draft, known(connected.success, inspected.success.project, inspected.success.checkout));
37848
38895
  draft = changeProject(draft, inspected.success.project);
37849
- const tree = inspected.success.worktrees.find((item) => item.path === found.checkout?.path && !item.bare && !item.prunable);
38896
+ if (inspected.success.checkout.vcs === "jj")
38897
+ draft = { ...draft, sourcePath: inspected.success.checkout.path };
38898
+ const tree = inspected.success.worktrees.find((item) => item.path === found.checkout?.path && (item.vcs === "jj" ? item.present : !item.bare && !item.prunable));
37850
38899
  if (tree)
37851
38900
  draft = selectWorktree(draft, tree);
37852
38901
  }
@@ -37857,19 +38906,18 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37857
38906
  error2 = problem(inspected.failure);
37858
38907
  return;
37859
38908
  }
37860
- draft = changeProject(draft, inspected.success.project);
38909
+ if (inspected.success) {
38910
+ draft = changeProject(draft, inspected.success.project);
38911
+ if (inspected.success.checkout.vcs === "jj" && !draft.sourcePath)
38912
+ draft = { ...draft, sourcePath: inspected.success.checkout.path };
38913
+ }
37861
38914
  }
37862
38915
  error2 = undefined;
37863
38916
  yield* refresh;
37864
38917
  });
37865
38918
  const formView = (initializing = false) => {
37866
- const rows = [
37867
- {
37868
- id: "project",
37869
- label: "Project",
37870
- value: draft.projectChoice?.name ?? "Choose a project",
37871
- detail: draft.project?.path ?? (draft.projectChoice ? "Choose its directory on this machine" : undefined)
37872
- },
38919
+ const rows2 = [
38920
+ { id: "project", label: "Project", value: draft.projectChoice?.name ?? "Choose a project" },
37873
38921
  {
37874
38922
  id: "machine",
37875
38923
  label: "Machine",
@@ -37878,16 +38926,15 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37878
38926
  },
37879
38927
  {
37880
38928
  id: "destination",
37881
- label: "Worktree",
37882
- value: draft.worktreeName ?? draft.destination?.label ?? "Choose checkout or type new directory name",
37883
- detail: plan?.path ?? draft.destination?.path ?? (draft.worktreeName ? "New checkout directory" : undefined),
37884
- disabled: !draft.host || !draft.project
38929
+ label: draft.project?.vcs === "jj" || draft.clone?.vcs === "jj" ? "Workspace" : "Worktree",
38930
+ value: draft.clone ? draft.worktreeName ?? (draft.clone.vcs === "jj" ? "Use cloned default workspace" : "Use branch checkout after clone") : draft.worktreeName ?? draft.destination?.label ?? "Choose checkout or type new directory name",
38931
+ disabled: !draft.host || !(draft.project || draft.clone)
37885
38932
  },
37886
38933
  {
37887
38934
  id: "branch",
37888
- label: "Branch",
37889
- value: draft.destination?.branch ?? (draft.destination?.path ? plan?.branch ?? "Existing checkout" : "Select or type branch"),
37890
- disabled: !draft.host || !draft.project || !(draft.worktreeName || draft.destination?.path)
38935
+ label: draft.project?.vcs === "jj" || draft.clone?.vcs === "jj" ? "Start from" : "Branch",
38936
+ value: draft.project?.vcs === "jj" || draft.clone?.vcs === "jj" ? draft.destination?.revision ? draft.destination.label : draft.clone ? "Cloned default" : "Select or type a revision" : draft.destination?.branch ?? (draft.destination?.path && plan?.vcs === "git" ? plan.branch ?? "Existing checkout" : "Select or type branch"),
38937
+ disabled: !draft.host || !(draft.project || draft.clone) || (draft.project?.vcs === "jj" ? !draft.worktreeName : draft.clone?.vcs === "jj" ? false : !(draft.clone || draft.worktreeName || draft.destination?.path))
37891
38938
  },
37892
38939
  {
37893
38940
  id: "session",
@@ -37896,14 +38943,14 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37896
38943
  detail: draft.sessionId,
37897
38944
  disabled: !draft.host
37898
38945
  },
37899
- { id: "mode", label: "Mode", value: draft.mode === "auto" ? "Reuse matching tab, otherwise new tab" : draft.mode === "new-tab" ? "Always new tab" : "Split matching tab, otherwise new tab", disabled: !draft.host }
38946
+ { id: "mode", label: "Mode", value: draft.clone ? "New tab (clone task)" : draft.mode === "auto" ? "Reuse matching tab, otherwise new tab" : draft.mode === "new-tab" ? "Always new tab" : "Split matching tab, otherwise new tab", disabled: !draft.host || !!draft.clone }
37900
38947
  ];
37901
38948
  return {
37902
- rows: rows.map((row) => ({ ...row, disabled: initializing || row.disabled })),
37903
- submitLabel: plan?.label ?? "Open worktree",
37904
- submitDisabled: initializing || !draft.host || !plan,
37905
- notice: [plan?.detail, plan?.warning].filter(Boolean).join(" \xB7 ") || undefined,
37906
- error: initializing ? undefined : error2 ?? (!draft.projectChoice ? "Select a project" : !draft.machine ? "Select a Rex machine" : !draft.host ? "Connect to the selected machine and install its worktrees helper if missing" : !draft.project ? "Select the exact project directory on this machine" : !draft.destination ? "Select a worktree and branch" : !draft.sessionId ? "Select an exact Rex session" : undefined),
38949
+ rows: rows2.filter((row) => !(row.id === "branch" && draft.project?.vcs === "jj" && !draft.clone && !!draft.destination?.path)).map((row) => ({ ...row, disabled: initializing || row.disabled })),
38950
+ submitLabel: clonePlan?.label ?? plan?.label ?? (draft.clone ? "Clone & Open" : "Open worktree"),
38951
+ submitDisabled: initializing || !draft.host || !(clonePlan || plan),
38952
+ notice: [clonePlan?.detail, clonePlan?.warning, plan?.detail, plan?.warning].filter(Boolean).join(" \xB7 ") || undefined,
38953
+ error: initializing ? undefined : error2 ?? (!draft.projectChoice ? "Select a project" : !draft.machine ? "Select a Rex machine" : !draft.host ? "Connect to the selected machine and install its worktrees helper if missing" : !(draft.project || draft.clone) ? "Select the exact project directory on this machine" : !draft.destination && draft.project?.vcs !== "jj" && draft.clone?.vcs !== "jj" ? "Select a branch" : draft.project?.vcs === "jj" && (!draft.worktreeName && !draft.destination?.path || !!draft.worktreeName && !draft.destination?.revision) ? "Choose an existing workspace or a new workspace name and starting revision" : !draft.sessionId ? "Select an exact Rex session" : undefined),
37907
38954
  fitWarning: activeView?.fitWarning
37908
38955
  };
37909
38956
  };
@@ -37922,14 +38969,48 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37922
38969
  const initialAction = yield* exports_Effect.raceFirst(initialize, chooseField(initialView, "project").pipe(exports_Effect.catchTag("QuitError", () => exports_Effect.succeed("cancel"))));
37923
38970
  if (initialAction === "cancel")
37924
38971
  return;
38972
+ let queuedSubmit = false;
37925
38973
  while (true) {
37926
38974
  const view = formView();
37927
38975
  activeView = view;
37928
- const action = yield* chooseField(view, focused).pipe(exports_Effect.catchTag("QuitError", () => exports_Effect.succeed("cancel")));
38976
+ const action = queuedSubmit ? "submit" : yield* chooseField(view, focused).pipe(exports_Effect.catchTag("QuitError", () => exports_Effect.succeed("cancel")));
38977
+ queuedSubmit = false;
37929
38978
  focused = action;
37930
38979
  if (action === "cancel")
37931
38980
  return;
37932
38981
  if (action === "submit") {
38982
+ const cloneInput = cloneInputFor(draft);
38983
+ if (draft.host && cloneInput && clonePlan) {
38984
+ const current2 = yield* exports_Effect.result(reviewClone(draft.host, command, cloneInput));
38985
+ if (exports_Result.isFailure(current2)) {
38986
+ error2 = problem(current2.failure);
38987
+ clonePlan = undefined;
38988
+ continue;
38989
+ }
38990
+ if (!sameClonePlan(current2.success, clonePlan)) {
38991
+ clonePlan = current2.success;
38992
+ error2 = "Clone destination or Rex target changed; review the updated URL and destination before submitting again";
38993
+ continue;
38994
+ }
38995
+ const launched2 = yield* exports_Effect.result(submitClone(draft.host, command, cloneInput, clonePlan));
38996
+ if (exports_Result.isFailure(launched2)) {
38997
+ launchAcknowledged = true;
38998
+ yield* acknowledge("Clone needs inspection", [
38999
+ problem(launched2.failure),
39000
+ `Destination: ${clonePlan.repo}`,
39001
+ "A clone or Rex tab may already exist. Inspect the destination and session before opening again."
39002
+ ], "error");
39003
+ return yield* exports_Effect.fail(launched2.failure);
39004
+ }
39005
+ if (launched2.success.warning)
39006
+ yield* acknowledge("Clone task submitted with warning", [
39007
+ `Session: ${launched2.success.sessionId}`,
39008
+ `Destination: ${launched2.success.repo}`,
39009
+ "The clone task was created; Rex may not have focused its tab. Inspect the session before opening again.",
39010
+ launched2.success.warning
39011
+ ], "warning");
39012
+ return;
39013
+ }
37933
39014
  const input = inputFor(draft);
37934
39015
  if (!draft.host || !input || !plan)
37935
39016
  continue;
@@ -37959,13 +39040,14 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37959
39040
  `Session: ${launched.success.sessionId}`,
37960
39041
  `Destination: ${launched.success.path}`,
37961
39042
  `Action: ${launched.success.action}`,
37962
- launched.success.pending ? "Task submitted; Git setup may still be running." : "Existing task focused.",
37963
- ...[plan.warning, launched.success.warning].filter((line) => !!line)
39043
+ launched.success.pending ? `Task submitted; ${plan.vcs === "jj" ? "JJ" : "Git"} setup may still be running.` : "Existing task focused.",
39044
+ ...new Set([plan.warning, launched.success.warning].filter((line) => !!line))
37964
39045
  ], "warning");
37965
39046
  return;
37966
39047
  }
37967
39048
  if (view.rows.find((row) => row.id === action)?.disabled)
37968
39049
  continue;
39050
+ const hadCloneReview = !!clonePlan;
37969
39051
  const editing = yield* exports_Effect.result(exports_Effect.gen(function* () {
37970
39052
  if (action === "machine") {
37971
39053
  yield* loadMachines;
@@ -37992,10 +39074,18 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
37992
39074
  const host = draft.host;
37993
39075
  if (host) {
37994
39076
  const found = yield* discover(host, command);
39077
+ cloneRoots = found.roots;
37995
39078
  const inspected = yield* bindProject(choice, host, found.projects);
37996
- draft = changeProjectChoice(draft, choice);
37997
- draft = changeProject(draft, inspected.project);
37998
- projects = [...projects.filter((item) => item.source?.machineKey !== host.key || item.source.hostId !== host.hostId), ...found.projects.map((repo) => known(host, repo))];
39079
+ if (inspected) {
39080
+ draft = changeProjectChoice(draft, choice);
39081
+ draft = changeProject(draft, inspected.project);
39082
+ if (inspected.checkout.vcs === "jj")
39083
+ draft = { ...draft, sourcePath: inspected.checkout.path };
39084
+ }
39085
+ projects = [
39086
+ ...projects.filter((item) => item.source?.machineKey !== host.key || item.source.hostId !== host.hostId),
39087
+ ...found.projects.map((repo) => known(host, repo, found.checkout))
39088
+ ];
37999
39089
  sessions = found.sessions;
38000
39090
  if (!sessions.some((item) => item.id === draft.sessionId))
38001
39091
  draft = { ...draft, sessionId: sessions.length === 1 ? sessions[0]?.id : undefined };
@@ -38003,48 +39093,150 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
38003
39093
  } else
38004
39094
  draft = changeProjectChoice(draft, choice);
38005
39095
  } else if (action === "destination") {
38006
- if (!draft.host || !draft.project)
39096
+ if (!draft.host || !(draft.project || draft.clone))
38007
39097
  return yield* exports_Effect.fail(new AppError({ message: "Select a project and machine before choosing a worktree" }));
38008
- const found = yield* inspectWorktrees(draft.host, command, draft.project.path);
38009
- const trees = found.worktrees.filter((tree) => !tree.bare && !tree.prunable);
38010
- const picked = yield* inputChoice({
38011
- message: "Worktree (select checkout or type new directory name)",
38012
- choices: trees.map((tree) => ({
38013
- value: tree,
38014
- title: tree.path.split("/").filter(Boolean).at(-1) ?? tree.path,
38015
- description: `${tree.branch ?? "Detached HEAD"} \xB7 ${tree.path}`
38016
- }))
38017
- });
38018
- if (picked.kind === "selected") {
38019
- draft = selectWorktree(draft, picked.value);
39098
+ if (draft.clone) {
39099
+ const clone = draft.clone;
39100
+ const picked = yield* inputChoice({
39101
+ message: clone.vcs === "jj" ? "Clone destination: absolute path or optional separate workspace name (none to clear)" : "Clone destination: type absolute path; type checkout name for optional separate worktree",
39102
+ choices: [
39103
+ { value: clone.repo, title: "Current clone destination", description: clone.repo },
39104
+ ...cloneRoots.map((root) => ({
39105
+ value: `${root.replace(/\/$/, "")}/${draft.projectChoice?.name ?? "project"}`,
39106
+ title: "Configured root suggestion",
39107
+ description: `${root.replace(/\/$/, "")}/${draft.projectChoice?.name ?? "project"}`
39108
+ }))
39109
+ ]
39110
+ });
39111
+ if (picked.kind === "selected" || picked.text.startsWith("/")) {
39112
+ const repo = picked.kind === "selected" ? picked.value : picked.text.trim();
39113
+ draft = { ...draft, clone: { ...clone, repo } };
39114
+ } else {
39115
+ const name = picked.text.trim();
39116
+ if (name === "none")
39117
+ draft = { ...draft, worktreeName: undefined };
39118
+ else {
39119
+ if (!name || /[\p{ASCII}&&\p{Cc}]/v.test(name) || name.split(/[\\/]/).some((part) => !part || part === "." || part === ".."))
39120
+ return yield* exports_Effect.fail(new AppError({ message: "Type an absolute clone destination or valid checkout name (none to clear)" }));
39121
+ draft = { ...draft, worktreeName: name };
39122
+ }
39123
+ }
38020
39124
  } else {
38021
- const name = picked.text;
38022
- if (!name.trim() || name.startsWith("/") || /[\p{ASCII}&&\p{Cc}]/v.test(name) || name.split(/[\\/]/).some((part) => !part || part === "." || part === ".."))
38023
- return yield* exports_Effect.fail(new AppError({ message: "Invalid worktree directory name" }));
38024
- const candidate = typeWorktreeName(draft, name);
38025
- if (candidate.destination?.branch) {
38026
- const inspected = yield* inspectBranch(draft.host, command, draft.project.path, candidate.destination.branch, name);
38027
- draft = resolveBranch(candidate, inspected.branch, inspected.path, inspected.existing);
38028
- } else
38029
- draft = candidate;
39125
+ const found = yield* inspectWorktrees(draft.host, command, draft.project.vcs === "jj" ? draft.sourcePath ?? draft.project.path : draft.project.path);
39126
+ const trees = found.worktrees.filter((tree) => tree.vcs === "jj" || !tree.bare && !tree.prunable);
39127
+ const picked = yield* inputChoice({
39128
+ message: draft.project.vcs === "jj" ? "Workspace (select existing, Clone this project, or type new workspace name)" : "Worktree (select checkout, Clone this project, or type new directory name)",
39129
+ choices: [
39130
+ ...trees.map((tree) => ({
39131
+ value: tree,
39132
+ title: tree.vcs === "jj" ? tree.name : tree.path.split("/").filter(Boolean).at(-1) ?? tree.path,
39133
+ description: tree.vcs === "jj" ? tree.present && tree.path ? `${tree.changeId.slice(0, 12)} \xB7 ${tree.path}` : `Unavailable \xB7 ${tree.path ?? "location unknown"}` : `${tree.branch ?? "Detached HEAD"} \xB7 ${tree.path}`
39134
+ })),
39135
+ ...draft.projectChoice?.source ? [{
39136
+ value: "clone",
39137
+ title: "Clone this project\u2026",
39138
+ description: "Choose a new absolute destination; only published history transfers"
39139
+ }] : []
39140
+ ]
39141
+ });
39142
+ if (picked.kind === "selected") {
39143
+ if (picked.value === "clone")
39144
+ yield* cloneDestination2(draft.projectChoice, draft.host);
39145
+ else {
39146
+ if (picked.value.vcs === "jj" && (!picked.value.present || !picked.value.path))
39147
+ return yield* exports_Effect.fail(new AppError({ message: `Workspace ${picked.value.name} is unavailable; inspect its registered location before opening` }));
39148
+ draft = selectWorktree(draft, picked.value);
39149
+ }
39150
+ } else {
39151
+ const name = picked.text.trim();
39152
+ if (!name || name.startsWith("/") || /[\p{ASCII}&&\p{Cc}]/v.test(name) || name.split(/[\\/]/).some((part) => !part || part === "." || part === ".."))
39153
+ return yield* exports_Effect.fail(new AppError({ message: "Invalid workspace or worktree name" }));
39154
+ const candidate = typeWorktreeName(draft, name, draft.project.vcs === "jj" ? found.revisions.find((choice) => choice.expression === "trunk()") : undefined);
39155
+ if (draft.project.vcs === "git" && candidate.destination?.branch) {
39156
+ const inspected = yield* inspectBranch(draft.host, command, draft.project.path, candidate.destination.branch, name);
39157
+ draft = resolveBranch(candidate, inspected.branch, inspected.path, inspected.existing);
39158
+ } else
39159
+ draft = candidate;
39160
+ }
38030
39161
  }
38031
39162
  } else if (action === "branch") {
38032
- if (!draft.host || !draft.project)
38033
- return yield* exports_Effect.fail(new AppError({ message: "Select a project and machine before choosing a branch" }));
38034
- const found = yield* inspectWorktrees(draft.host, command, draft.project.path);
38035
- const picked = yield* inputChoice({
38036
- message: "Branch (select existing or type new branch)",
38037
- choices: found.branches.map((branch2) => ({
38038
- value: branch2,
38039
- title: branch2,
38040
- description: found.worktrees.find((tree) => tree.branch === branch2)?.path ?? "Free branch \u2014 attach new checkout"
38041
- }))
38042
- });
38043
- const branch = picked.kind === "selected" ? picked.value : picked.text;
38044
- if (!branch.trim())
38045
- return yield* exports_Effect.fail(new AppError({ message: "Branch name is required" }));
38046
- const inspected = yield* inspectBranch(draft.host, command, draft.project.path, branch, draft.worktreeName);
38047
- draft = resolveBranch(draft, inspected.branch, inspected.path, inspected.existing);
39163
+ if (!draft.host || !(draft.project || draft.clone))
39164
+ return yield* exports_Effect.fail(new AppError({ message: "Select a project and machine before choosing a base or branch" }));
39165
+ const jjClone = draft.clone?.vcs === "jj" ? draft.clone : undefined;
39166
+ if (draft.project?.vcs === "jj" || jjClone) {
39167
+ if (draft.destination?.path)
39168
+ return yield* exports_Effect.fail(new AppError({ message: "Opening an existing workspace does not change its revision" }));
39169
+ const found = jjClone ? undefined : yield* inspectWorktrees(draft.host, command, draft.sourcePath ?? draft.project.path);
39170
+ const revisions = jjClone ? jjClone.revisions : found.revisions;
39171
+ const picked = yield* inputChoice({
39172
+ message: jjClone ? "Start from source revision (or cloned default)" : "Start from revision for new workspace",
39173
+ choices: [
39174
+ ...jjClone ? [{ value: null, title: "Cloned default", description: "Use the clone's native default" }] : [],
39175
+ ...revisions.map((choice) => ({
39176
+ value: choice,
39177
+ title: choice.label,
39178
+ description: `${choice.expression} \xB7 ${choice.revision.commitId.slice(0, 12)}`
39179
+ }))
39180
+ ]
39181
+ });
39182
+ if (picked.kind === "selected" && picked.value === null)
39183
+ draft = { ...draft, destination: undefined };
39184
+ else {
39185
+ let choice;
39186
+ if (picked.kind === "selected")
39187
+ choice = picked.value;
39188
+ else {
39189
+ const expression = picked.text.trim();
39190
+ if (!expression)
39191
+ return yield* exports_Effect.fail(new AppError({ message: "A singular starting revision is required" }));
39192
+ let sourceHost = draft.host;
39193
+ let repo = draft.sourcePath ?? draft.project?.path;
39194
+ if (jjClone) {
39195
+ const reference = draft.projectChoice?.source;
39196
+ const machine = machines.find((item) => item.key === reference?.machineKey);
39197
+ if (!reference || !machine)
39198
+ return yield* exports_Effect.fail(new AppError({ message: "Clone source machine is no longer registered" }));
39199
+ sourceHost = yield* connectMachine(machine);
39200
+ if (sourceHost.hostId !== reference.hostId || sourceHost.hostId !== jjClone.sourceHostId)
39201
+ return yield* exports_Effect.fail(new AppError({ message: "Clone source host identity changed; reselect the project" }));
39202
+ repo = reference.checkoutPath ?? reference.repository.path;
39203
+ }
39204
+ const revision = yield* inspectRevision(sourceHost, command, repo, expression);
39205
+ choice = { expression, label: expression, revision };
39206
+ }
39207
+ draft = selectRevision(draft, choice);
39208
+ if (jjClone)
39209
+ draft = { ...draft, clone: { ...jjClone, revision: choice.revision } };
39210
+ }
39211
+ } else if (draft.clone?.vcs === "git") {
39212
+ const picked = yield* inputChoice({
39213
+ message: "Branch (select source branch or type new branch; only pushed history transfers)",
39214
+ choices: draft.clone.branches.map((branch2) => ({
39215
+ value: branch2,
39216
+ title: branch2,
39217
+ description: "Use this branch from the cloned origin"
39218
+ }))
39219
+ });
39220
+ const branch = picked.kind === "selected" ? picked.value : picked.text.trim();
39221
+ if (!branch || branch.startsWith("-") || /[\p{ASCII}&&\p{Cc}]/v.test(branch))
39222
+ return yield* exports_Effect.fail(new AppError({ message: "Branch name must be a valid Git branch" }));
39223
+ draft = { ...draft, destination: { branch, label: branch } };
39224
+ } else {
39225
+ const found = yield* inspectWorktrees(draft.host, command, draft.project.path);
39226
+ const picked = yield* inputChoice({
39227
+ message: "Branch (select existing or type new branch)",
39228
+ choices: found.branches.map((branch2) => ({
39229
+ value: branch2,
39230
+ title: branch2,
39231
+ description: found.worktrees.find((tree) => tree.vcs === "git" && tree.branch === branch2)?.path ?? "Free branch \u2014 attach new checkout"
39232
+ }))
39233
+ });
39234
+ const branch = picked.kind === "selected" ? picked.value : picked.text;
39235
+ if (!branch.trim())
39236
+ return yield* exports_Effect.fail(new AppError({ message: "Branch name is required" }));
39237
+ const inspected = yield* inspectBranch(draft.host, command, draft.project.path, branch, draft.worktreeName);
39238
+ draft = resolveBranch(draft, inspected.branch, inspected.path, inspected.existing);
39239
+ }
38048
39240
  } else if (action === "session") {
38049
39241
  if (!draft.host)
38050
39242
  return yield* exports_Effect.fail(new AppError({ message: "Select a machine before choosing a session" }));
@@ -38063,6 +39255,7 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
38063
39255
  }
38064
39256
  }));
38065
39257
  if (exports_Result.isFailure(editing)) {
39258
+ submitAfterEdit = false;
38066
39259
  if (!exports_Terminal.isQuitError(editing.failure))
38067
39260
  error2 = problem(editing.failure);
38068
39261
  } else {
@@ -38070,6 +39263,8 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
38070
39263
  error2 = undefined;
38071
39264
  yield* refresh;
38072
39265
  }
39266
+ queuedSubmit = submitAfterEdit && !formView().submitDisabled && (!draft.clone || hadCloneReview);
39267
+ submitAfterEdit = false;
38073
39268
  }
38074
39269
  }
38075
39270
  }).pipe(exports_Effect.catchCause((cause) => exports_Cause.hasInterrupts(cause) || launchAcknowledged ? exports_Effect.failCause(cause) : acknowledge("Could not open worktrees", [exports_Cause.pretty(cause)], "error").pipe(exports_Effect.andThen(exports_Effect.failCause(cause)))));
@@ -38077,14 +39272,18 @@ var popup = (command, context3, origin = {}, preferredMachine) => exports_Effect
38077
39272
 
38078
39273
  // src/main.ts
38079
39274
  var compiled = true;
38080
- var help = `rex-worktrees \u2014 Git worktrees on existing Rex machines
38081
- setup [--bin /absolute/path/rex-worktrees] install Lua module; copy binary to ~/.local/bin unless --bin is set
39275
+ var help = `rex-worktrees \u2014 Git worktrees and JJ workspaces on existing Rex machines
39276
+ setup [--bin /absolute/path/rex-worktrees] [--config /absolute/path/init.lua]
39277
+ install Lua module; copy binary to ~/.local/bin unless --bin is set
38082
39278
  popup [--host HOST] [--context PATH | --no-context] [--origin-session ID [--origin-block ID]] [--origin-client ID]
38083
39279
  interactive terminal chooser
38084
39280
  launch-popup [--session ID] [--origin-block ID | --no-context] [--origin-client ID] [--host HOST]
38085
39281
  open a floating chooser in the source window
38086
- open --repo PATH --session ID --name NAME (--branch NAME | --worktree PATH)
38087
- [--worktree-name NAME (branch only)] [--host HOST] [--client ID] [--additional | --split]
39282
+ open --repo PATH --session ID --name NAME (--branch NAME | --worktree PATH) [--worktree-name NAME]
39283
+ Git: branch checkout or existing worktree
39284
+ open --repo PATH --session ID --name NAME (--worktree PATH | --worktree-name NAME --revision EXPR)
39285
+ JJ: existing workspace or new workspace at base revision
39286
+ [--host HOST] [--client ID] [--additional | --split]
38088
39287
  host-request read a JSON request on stdin, write a JSON response
38089
39288
  help
38090
39289
 
@@ -38126,15 +39325,16 @@ var main = exports_Effect.gen(function* () {
38126
39325
  }
38127
39326
  if (verb === "setup") {
38128
39327
  const flags = yield* parseFlags(args2);
38129
- if (Object.keys(flags).some((key5) => key5 !== "--bin"))
38130
- return yield* exports_Effect.fail(new AppError({ message: "Invalid setup flags" }));
39328
+ if (Object.keys(flags).some((key5) => key5 !== "--bin" && key5 !== "--config") || flags["--config"] && !flags["--bin"])
39329
+ return yield* exports_Effect.fail(new AppError({ message: "Invalid setup flags: --config requires --bin" }));
38131
39330
  if (!compiled)
38132
39331
  return yield* exports_Effect.fail(new AppError({ message: "Build first with bun run build, then run ./dist/rex-worktrees setup" }));
38133
- const installed = yield* setup(flags["--bin"]);
39332
+ const installed = yield* setup(flags["--bin"], flags["--config"]);
38134
39333
  yield* exports_Console.log(`${flags["--bin"] ? "Registered binary" : "Installed binary"}: ${installed.bin}
38135
39334
  Installed Lua module: ${installed.luaPath}
38136
- Updated Rex config: ${installed.configPath}
38137
- Run rex config reload to activate.`);
39335
+ Updated Rex config: ${installed.configPath}${flags["--config"] ? `
39336
+ Rex will load the registration when it next starts.` : `
39337
+ Run rex config reload to activate.`}`);
38138
39338
  return;
38139
39339
  }
38140
39340
  if (verb === "popup") {
@@ -38149,13 +39349,13 @@ Run rex config reload to activate.`);
38149
39349
  const envSession = process.env.REX_SESSION === undefined ? undefined : yield* exports_Schema.decodeUnknownEffect(SessionIdSchema)(process.env.REX_SESSION);
38150
39350
  const sessionId = flags["--origin-session"] ?? envSession;
38151
39351
  const blockId = flags["--origin-block"] ?? (!flags["--no-context"] && sessionId === envSession && process.env.REX_BLOCK !== undefined ? yield* exports_Schema.decodeUnknownEffect(BlockIdSchema)(process.env.REX_BLOCK) : undefined);
38152
- const origin = {
39352
+ const origin2 = {
38153
39353
  sessionId,
38154
39354
  blockId,
38155
39355
  clientId: flags["--origin-client"] ?? (process.env.REX_CLIENT === undefined ? undefined : yield* exports_Schema.decodeUnknownEffect(ClientIdSchema)(process.env.REX_CLIENT))
38156
39356
  };
38157
39357
  const context3 = typeof flags["--context"] === "string" ? exports_Effect.succeed(resolve6(flags["--context"])) : flags["--no-context"] ? exports_Effect.succeed(undefined) : args2.length && sessionId && blockId ? originDirectory(sessionId, blockId) : exports_Effect.succeed(process.cwd());
38158
- yield* popup(executable, context3, origin, flags["--host"]);
39358
+ yield* popup(executable, context3, origin2, flags["--host"]);
38159
39359
  if (flags["--managed-popup"])
38160
39360
  yield* closeManagedPopup;
38161
39361
  return;
@@ -38178,9 +39378,14 @@ Run rex config reload to activate.`);
38178
39378
  return yield* exports_Effect.fail(new AppError({ message: `Rex host ${selected2} is not registered` }));
38179
39379
  const palette = typeof flags["--origin-block"] === "string";
38180
39380
  const command = [...executable, "popup", "--origin-session", sessionId];
38181
- if (palette && blockId)
39381
+ if (palette && blockId) {
39382
+ const context3 = yield* originDirectory(sessionId, blockId);
38182
39383
  command.push("--origin-block", blockId);
38183
- else if (flags["--no-context"])
39384
+ if (context3)
39385
+ command.push("--context", context3);
39386
+ else
39387
+ command.push("--no-context");
39388
+ } else if (flags["--no-context"])
38184
39389
  command.push("--no-context");
38185
39390
  else
38186
39391
  command.push("--context", process.cwd());
@@ -38198,35 +39403,53 @@ Run rex config reload to activate.`);
38198
39403
  return yield* exports_Effect.fail(new AppError({ message: "--bin is only supported by setup" }));
38199
39404
  if (!flags["--repo"] || !flags["--session"] || !flags["--name"])
38200
39405
  return yield* exports_Effect.fail(new AppError({ message: "open requires --repo PATH --session ID --name NAME" }));
38201
- if (Boolean(flags["--branch"]) === Boolean(flags["--worktree"]))
38202
- return yield* exports_Effect.fail(new AppError({ message: "Choose exactly one of --branch NAME or --worktree PATH" }));
38203
- if (flags["--worktree-name"] !== undefined && flags["--worktree"] !== undefined)
38204
- return yield* exports_Effect.fail(new AppError({ message: "--worktree-name requires --branch, not --worktree" }));
38205
39406
  if (flags["--additional"] && flags["--split"])
38206
39407
  return yield* exports_Effect.fail(new AppError({ message: "--additional and --split are mutually exclusive" }));
38207
- const input = {
38208
- repo: flags["--repo"],
38209
- sessionId: flags["--session"],
38210
- name: flags["--name"],
38211
- branch: flags["--branch"],
38212
- worktreeName: flags["--worktree-name"],
38213
- path: flags["--worktree"],
38214
- clientId: flags["--client"],
38215
- additional: flags["--additional"],
38216
- split: flags["--split"]
38217
- };
38218
- if (!input.repo.trim() || !input.name.trim() || !input.sessionId.trim())
38219
- return yield* exports_Effect.fail(new AppError({ message: "Required values cannot be blank" }));
38220
39408
  const selected2 = flags["--host"];
38221
39409
  const machine = (yield* listMachines).find((machine2) => !selected2 ? machine2.local : machine2.key === selected2 || machine2.label === selected2 || machine2.selector === selected2);
38222
39410
  if (!machine)
38223
39411
  return yield* exports_Effect.fail(new AppError({ message: `Rex host ${selected2} is not registered` }));
38224
39412
  const host = yield* connectMachine(machine);
38225
- if (!host.local && (!isAbsolute2(input.repo) || input.path && !isAbsolute2(input.path)))
39413
+ if (!host.local && (!isAbsolute2(flags["--repo"]) || flags["--worktree"] && !isAbsolute2(flags["--worktree"])))
38226
39414
  return yield* exports_Effect.fail(new AppError({ message: "Remote repository and worktree paths must be absolute on the destination machine" }));
38227
- const launchInput = { ...input, repo: host.local ? resolve6(input.repo) : input.repo, path: input.path && (host.local ? resolve6(input.path) : input.path) };
38228
- const reviewed = yield* review(host, executable, launchInput);
38229
- yield* exports_Console.log(JSON.stringify(yield* submit(host, executable, launchInput, reviewed), null, 2));
39415
+ const repoPath = host.local ? resolve6(flags["--repo"]) : flags["--repo"];
39416
+ const vcs = host.local ? (yield* repository3(repoPath)).vcs : (yield* inspectProject(host, executable, repoPath)).checkout.vcs;
39417
+ let input;
39418
+ if (vcs === "git") {
39419
+ if (flags["--revision"] || Boolean(flags["--branch"]) === Boolean(flags["--worktree"]))
39420
+ return yield* exports_Effect.fail(new AppError({ message: "Git requires exactly one of --branch NAME or --worktree PATH; --revision is JJ-only" }));
39421
+ if (flags["--worktree-name"] !== undefined && flags["--worktree"] !== undefined)
39422
+ return yield* exports_Effect.fail(new AppError({ message: "--worktree-name requires --branch, not --worktree" }));
39423
+ input = {
39424
+ vcs,
39425
+ repo: repoPath,
39426
+ sessionId: flags["--session"],
39427
+ name: flags["--name"],
39428
+ branch: flags["--branch"],
39429
+ worktreeName: flags["--worktree-name"],
39430
+ path: flags["--worktree"] && (host.local ? resolve6(flags["--worktree"]) : flags["--worktree"]),
39431
+ clientId: flags["--client"],
39432
+ additional: flags["--additional"],
39433
+ split: flags["--split"]
39434
+ };
39435
+ } else {
39436
+ if (flags["--branch"] || Boolean(flags["--worktree"]) === Boolean(flags["--worktree-name"]) || flags["--worktree"] && flags["--revision"] || flags["--worktree-name"] && !flags["--revision"])
39437
+ return yield* exports_Effect.fail(new AppError({ message: "JJ requires --worktree PATH or --worktree-name NAME with --revision EXPR; --branch is Git-only" }));
39438
+ input = {
39439
+ vcs,
39440
+ repo: repoPath,
39441
+ sessionId: flags["--session"],
39442
+ name: flags["--name"],
39443
+ worktreeName: flags["--worktree-name"],
39444
+ revision: flags["--revision"],
39445
+ path: flags["--worktree"] && (host.local ? resolve6(flags["--worktree"]) : flags["--worktree"]),
39446
+ clientId: flags["--client"],
39447
+ additional: flags["--additional"],
39448
+ split: flags["--split"]
39449
+ };
39450
+ }
39451
+ const reviewed = yield* review(host, executable, input);
39452
+ yield* exports_Console.log(JSON.stringify(yield* submit(host, executable, input, reviewed), null, 2));
38230
39453
  return;
38231
39454
  }
38232
39455
  if (verb === "task") {
@@ -38236,6 +39459,13 @@ Run rex config reload to activate.`);
38236
39459
  yield* task(request4);
38237
39460
  return;
38238
39461
  }
39462
+ if (verb === "clone-task") {
39463
+ if (args2.length !== 1)
39464
+ return yield* exports_Effect.fail(new AppError({ message: "clone-task requires one JSON argument" }));
39465
+ const request4 = yield* exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(CloneTaskRequestSchema))(args2[0]);
39466
+ yield* cloneTask(request4);
39467
+ return;
39468
+ }
38239
39469
  if (verb === "host-request") {
38240
39470
  if (args2.length)
38241
39471
  return yield* exports_Effect.fail(new AppError({ message: "host-request reads JSON from stdin" }));