@laoyuehanni/dsh-git-worktree 0.4.14 → 0.4.15

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.
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Deferred worktree creation coordinator for shared-workspace mode
3
+ * (`switchSessionDirectory`).
4
+ *
5
+ * When a user chooses to create a new worktree in shared-workspace mode, no
6
+ * Git branch or checkout directory is written until the Session's first user
7
+ * message actually arrives. On `agent/inbox/inserted`, the coordinator holds
8
+ * the Agent via `agent.runMaintenance`, runs the plugin's full worktree
9
+ * creation pipeline (`.git/info/exclude`, optional fetch, `git worktree add`,
10
+ * `.worktreeinclude` copy, and `workingDirectory.set`), streams phase updates
11
+ * to the browser dock, and lets the user retry or withdraw on failure without
12
+ * losing the waiting message.
13
+ */
14
+ import type { DeferredWorktreePhase, DeferredWorktreeSnapshot, DeferredWorktreeSpec, DeferredWorktreeState } from './wire.ts';
15
+ /** Minimal Host Agent slice needed to hold a turn and switch directory. */
16
+ export interface DeferredAgentLike {
17
+ readonly session: {
18
+ readonly id: string;
19
+ };
20
+ readonly inbox?: {
21
+ readonly nextTurn?: readonly {
22
+ readonly id: string;
23
+ }[];
24
+ readonly nextStep?: readonly {
25
+ readonly id: string;
26
+ readonly source?: {
27
+ readonly kind?: string;
28
+ };
29
+ }[];
30
+ readonly remove?: (id: string) => void;
31
+ };
32
+ readonly runMaintenance?: <T>(task: (signal: AbortSignal) => Promise<T>) => Promise<T>;
33
+ }
34
+ /** Result of creating the worktree before switching the session directory. */
35
+ export interface DeferredCreateOutcome {
36
+ readonly path: string;
37
+ readonly branch: string;
38
+ readonly created: boolean;
39
+ readonly fetchWarning?: string;
40
+ readonly excludeWarning?: string;
41
+ readonly copyWarning?: string;
42
+ }
43
+ /** Host seams injected into {@link DeferredWorktreeCoordinator}. */
44
+ export interface DeferredCoordinatorDeps {
45
+ /** Execute the plugin's worktree creation pipeline and report phase changes. */
46
+ readonly createWorktree: (spec: DeferredWorktreeSpec, onPhase: (phase: Exclude<DeferredWorktreePhase, 'switch'>, resolvedBranch?: string) => void) => Promise<DeferredCreateOutcome>;
47
+ /** Move the Agent's working directory via DSH `ctx.workingDirectory.set`. */
48
+ readonly setWorkingDirectory: (agent: DeferredAgentLike, path: string, signal?: AbortSignal) => Promise<string>;
49
+ }
50
+ type SnapshotListener = (snapshot: DeferredWorktreeSnapshot) => void;
51
+ /**
52
+ * Coordinates armed, running, and failed deferred worktree creations keyed by
53
+ * `sessionId`. Pure in-process state machine with injectable seams.
54
+ */
55
+ export declare class DeferredWorktreeCoordinator {
56
+ private readonly deps;
57
+ private readonly slots;
58
+ private readonly listeners;
59
+ private readonly lifetime;
60
+ private readonly pending;
61
+ constructor(deps: DeferredCoordinatorDeps);
62
+ /** Read the current deferred state of `sessionId`, or null when none is active. */
63
+ get(sessionId: string): DeferredWorktreeState | null;
64
+ /** Subscribe to live state/completion updates for `sessionId`. */
65
+ subscribe(sessionId: string, listener: SnapshotListener): () => void;
66
+ /**
67
+ * Arm (or replace) a deferred worktree creation on a blank session.
68
+ * Rejects while a creation is already running or holding a waiting first turn.
69
+ */
70
+ arm(sessionId: string, spec: DeferredWorktreeSpec): DeferredWorktreeState;
71
+ /**
72
+ * Cancel an armed request before any message arrives, or withdraw a failed
73
+ * attempt so the waiting message continues in the current directory.
74
+ */
75
+ cancel(sessionId: string): boolean;
76
+ /** Retry a failed creation while the first message is waiting in maintenance. */
77
+ retry(sessionId: string): boolean;
78
+ /** Withdraw a failed creation so the waiting message proceeds without a worktree. */
79
+ withdraw(sessionId: string): boolean;
80
+ /**
81
+ * Called from `agent/inbox/inserted`: if the session has an armed deferred
82
+ * request, hold the Agent via `runMaintenance` so the worktree is created and
83
+ * entered before the first turn starts.
84
+ */
85
+ onInboxInserted(agent: DeferredAgentLike, message?: {
86
+ readonly id?: string;
87
+ }): void;
88
+ /**
89
+ * Fallback for `agent/pre-step` (step === 1): if a message somehow bypassed
90
+ * `agent/inbox/inserted` while an armed request is still pending, create and
91
+ * enter the worktree right before the first model call.
92
+ * @returns true when this call actually created and switched the worktree.
93
+ */
94
+ onPreStep(agent: DeferredAgentLike, step: number, signal?: AbortSignal): Promise<boolean>;
95
+ /** Release any waiting maintenance holds when the plugin unloads. */
96
+ dispose(): Promise<void>;
97
+ private runLoop;
98
+ private executeOnce;
99
+ private waitForDecision;
100
+ private clearSlot;
101
+ private emit;
102
+ private track;
103
+ }
104
+ export {};
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Deferred worktree creation coordinator for shared-workspace mode
3
+ * (`switchSessionDirectory`).
4
+ *
5
+ * When a user chooses to create a new worktree in shared-workspace mode, no
6
+ * Git branch or checkout directory is written until the Session's first user
7
+ * message actually arrives. On `agent/inbox/inserted`, the coordinator holds
8
+ * the Agent via `agent.runMaintenance`, runs the plugin's full worktree
9
+ * creation pipeline (`.git/info/exclude`, optional fetch, `git worktree add`,
10
+ * `.worktreeinclude` copy, and `workingDirectory.set`), streams phase updates
11
+ * to the browser dock, and lets the user retry or withdraw on failure without
12
+ * losing the waiting message.
13
+ */
14
+ function createDeferred() {
15
+ let resolve;
16
+ let reject;
17
+ const promise = new Promise((res, rej) => {
18
+ resolve = res;
19
+ reject = rej;
20
+ });
21
+ return { promise, resolve, reject };
22
+ }
23
+ /**
24
+ * Coordinates armed, running, and failed deferred worktree creations keyed by
25
+ * `sessionId`. Pure in-process state machine with injectable seams.
26
+ */
27
+ export class DeferredWorktreeCoordinator {
28
+ deps;
29
+ slots = new Map();
30
+ listeners = new Map();
31
+ lifetime = new AbortController();
32
+ pending = new Set();
33
+ constructor(deps) {
34
+ this.deps = deps;
35
+ }
36
+ /** Read the current deferred state of `sessionId`, or null when none is active. */
37
+ get(sessionId) {
38
+ return this.slots.get(sessionId)?.state ?? null;
39
+ }
40
+ /** Subscribe to live state/completion updates for `sessionId`. */
41
+ subscribe(sessionId, listener) {
42
+ let set = this.listeners.get(sessionId);
43
+ if (set === undefined) {
44
+ set = new Set();
45
+ this.listeners.set(sessionId, set);
46
+ }
47
+ set.add(listener);
48
+ return () => {
49
+ set.delete(listener);
50
+ if (set.size === 0)
51
+ this.listeners.delete(sessionId);
52
+ };
53
+ }
54
+ /**
55
+ * Arm (or replace) a deferred worktree creation on a blank session.
56
+ * Rejects while a creation is already running or holding a waiting first turn.
57
+ */
58
+ arm(sessionId, spec) {
59
+ const existing = this.slots.get(sessionId);
60
+ if (existing !== undefined && (existing.state.kind === 'running' || existing.holding)) {
61
+ throw Object.assign(new Error('Worktree creation is already in progress for this session'), { httpStatus: 409 });
62
+ }
63
+ const state = { kind: 'armed', spec };
64
+ this.slots.set(sessionId, { state, holding: false, decision: undefined, created: undefined });
65
+ this.emit(sessionId, { state });
66
+ return state;
67
+ }
68
+ /**
69
+ * Cancel an armed request before any message arrives, or withdraw a failed
70
+ * attempt so the waiting message continues in the current directory.
71
+ */
72
+ cancel(sessionId) {
73
+ const slot = this.slots.get(sessionId);
74
+ if (slot === undefined)
75
+ return false;
76
+ if (slot.state.kind === 'running')
77
+ return false;
78
+ if (slot.decision !== undefined) {
79
+ slot.decision.resolve('withdraw');
80
+ slot.decision = undefined;
81
+ return true;
82
+ }
83
+ this.slots.delete(sessionId);
84
+ this.emit(sessionId, { state: null });
85
+ return true;
86
+ }
87
+ /** Retry a failed creation while the first message is waiting in maintenance. */
88
+ retry(sessionId) {
89
+ const slot = this.slots.get(sessionId);
90
+ if (slot === undefined || slot.state.kind !== 'failed' || slot.decision === undefined)
91
+ return false;
92
+ const decision = slot.decision;
93
+ slot.decision = undefined;
94
+ decision.resolve('retry');
95
+ return true;
96
+ }
97
+ /** Withdraw a failed creation so the waiting message proceeds without a worktree. */
98
+ withdraw(sessionId) {
99
+ return this.cancel(sessionId);
100
+ }
101
+ /**
102
+ * Called from `agent/inbox/inserted`: if the session has an armed deferred
103
+ * request, hold the Agent via `runMaintenance` so the worktree is created and
104
+ * entered before the first turn starts.
105
+ */
106
+ onInboxInserted(agent, message) {
107
+ if (this.lifetime.signal.aborted)
108
+ return;
109
+ const sessionId = agent.session.id;
110
+ const slot = this.slots.get(sessionId);
111
+ if (slot === undefined || slot.state.kind !== 'armed' || slot.holding)
112
+ return;
113
+ // Ignore next-step internal notices when nextTurn queue info is available.
114
+ if (message?.id !== undefined
115
+ && Array.isArray(agent.inbox?.nextTurn)
116
+ && !agent.inbox.nextTurn.some(queued => queued.id === message.id)) {
117
+ return;
118
+ }
119
+ if (typeof agent.runMaintenance !== 'function')
120
+ return;
121
+ let task;
122
+ try {
123
+ task = agent.runMaintenance(async (maintenanceSignal) => {
124
+ // Yield a microtask so the inbox insertion finishes before touching the session.
125
+ await Promise.resolve();
126
+ const signal = AbortSignal.any([maintenanceSignal, this.lifetime.signal]);
127
+ await this.runLoop(sessionId, agent, slot, signal);
128
+ });
129
+ }
130
+ catch {
131
+ // Agent already busy with another turn/maintenance; pre-step fallback handles it if needed.
132
+ return;
133
+ }
134
+ slot.holding = true;
135
+ this.track(task.finally(() => {
136
+ slot.holding = false;
137
+ }));
138
+ }
139
+ /**
140
+ * Fallback for `agent/pre-step` (step === 1): if a message somehow bypassed
141
+ * `agent/inbox/inserted` while an armed request is still pending, create and
142
+ * enter the worktree right before the first model call.
143
+ * @returns true when this call actually created and switched the worktree.
144
+ */
145
+ async onPreStep(agent, step, signal) {
146
+ if (step !== 1 || this.lifetime.signal.aborted)
147
+ return false;
148
+ const sessionId = agent.session.id;
149
+ const slot = this.slots.get(sessionId);
150
+ if (slot === undefined || slot.state.kind !== 'armed' || slot.holding)
151
+ return false;
152
+ const combined = signal === undefined ? this.lifetime.signal : AbortSignal.any([signal, this.lifetime.signal]);
153
+ try {
154
+ await this.executeOnce(sessionId, agent, slot, combined);
155
+ return true;
156
+ }
157
+ catch (error) {
158
+ this.clearSlot(sessionId, slot);
159
+ throw error;
160
+ }
161
+ }
162
+ /** Release any waiting maintenance holds when the plugin unloads. */
163
+ async dispose() {
164
+ this.lifetime.abort(new Error('git-worktree plugin disposed'));
165
+ for (const [sessionId, slot] of [...this.slots]) {
166
+ slot.decision?.reject(this.lifetime.signal.reason);
167
+ slot.decision = undefined;
168
+ this.slots.delete(sessionId);
169
+ this.emit(sessionId, { state: null });
170
+ }
171
+ await Promise.allSettled(this.pending);
172
+ }
173
+ async runLoop(sessionId, agent, slot, signal) {
174
+ for (;;) {
175
+ if (this.slots.get(sessionId) !== slot)
176
+ return;
177
+ if (signal.aborted) {
178
+ this.clearSlot(sessionId, slot);
179
+ return;
180
+ }
181
+ try {
182
+ await this.executeOnce(sessionId, agent, slot, signal);
183
+ return;
184
+ }
185
+ catch (error) {
186
+ if (signal.aborted || this.slots.get(sessionId) !== slot) {
187
+ this.clearSlot(sessionId, slot);
188
+ return;
189
+ }
190
+ const message = error instanceof Error ? error.message : String(error);
191
+ const currentPhase = slot.state.kind === 'running' ? slot.state.phase : 'create';
192
+ const resolvedBranch = slot.state.kind === 'running' ? slot.state.resolvedBranch : undefined;
193
+ slot.state = {
194
+ kind: 'failed',
195
+ spec: slot.state.spec,
196
+ phase: currentPhase,
197
+ message,
198
+ ...(resolvedBranch === undefined ? {} : { resolvedBranch }),
199
+ };
200
+ this.emit(sessionId, { state: slot.state });
201
+ }
202
+ const decision = await this.waitForDecision(slot, signal);
203
+ if (decision === 'withdraw' || this.slots.get(sessionId) !== slot) {
204
+ this.clearSlot(sessionId, slot);
205
+ return;
206
+ }
207
+ }
208
+ }
209
+ async executeOnce(sessionId, agent, slot, signal) {
210
+ signal.throwIfAborted();
211
+ const spec = slot.state.spec;
212
+ const publishPhase = (phase, resolvedBranch) => {
213
+ if (this.slots.get(sessionId) !== slot)
214
+ return;
215
+ const nextBranch = resolvedBranch ?? (slot.state.kind === 'running' ? slot.state.resolvedBranch : undefined);
216
+ slot.state = {
217
+ kind: 'running',
218
+ spec,
219
+ phase,
220
+ ...(nextBranch === undefined ? {} : { resolvedBranch: nextBranch }),
221
+ };
222
+ this.emit(sessionId, { state: slot.state });
223
+ };
224
+ // A retry after a failed switch reuses the worktree the earlier attempt
225
+ // created: creating again would orphan it (generated names) or fail on
226
+ // the existing branch (explicit names).
227
+ let created = slot.created;
228
+ if (created === undefined) {
229
+ publishPhase('create', spec.cutout ? spec.name : spec.branch);
230
+ created = await this.deps.createWorktree(spec, (phase, branch) => {
231
+ publishPhase(phase, branch);
232
+ });
233
+ slot.created = created;
234
+ signal.throwIfAborted();
235
+ }
236
+ publishPhase('switch', created.branch);
237
+ const committedPath = await this.deps.setWorkingDirectory(agent, created.path, signal);
238
+ signal.throwIfAborted();
239
+ const completed = {
240
+ path: committedPath,
241
+ branch: created.branch,
242
+ created: created.created,
243
+ ...(created.fetchWarning === undefined ? {} : { fetchWarning: created.fetchWarning }),
244
+ ...(created.excludeWarning === undefined ? {} : { excludeWarning: created.excludeWarning }),
245
+ ...(created.copyWarning === undefined ? {} : { copyWarning: created.copyWarning }),
246
+ };
247
+ this.slots.delete(sessionId);
248
+ this.emit(sessionId, { state: null, completed });
249
+ }
250
+ async waitForDecision(slot, signal) {
251
+ if (signal.aborted)
252
+ return 'withdraw';
253
+ const deferred = createDeferred();
254
+ slot.decision = deferred;
255
+ const onAbort = () => { deferred.resolve('withdraw'); };
256
+ signal.addEventListener('abort', onAbort, { once: true });
257
+ try {
258
+ return await deferred.promise;
259
+ }
260
+ catch {
261
+ return 'withdraw';
262
+ }
263
+ finally {
264
+ signal.removeEventListener('abort', onAbort);
265
+ if (slot.decision === deferred)
266
+ slot.decision = undefined;
267
+ }
268
+ }
269
+ clearSlot(sessionId, slot) {
270
+ if (this.slots.get(sessionId) === slot) {
271
+ this.slots.delete(sessionId);
272
+ this.emit(sessionId, { state: null });
273
+ }
274
+ }
275
+ emit(sessionId, snapshot) {
276
+ const set = this.listeners.get(sessionId);
277
+ if (set === undefined)
278
+ return;
279
+ for (const listener of [...set]) {
280
+ try {
281
+ listener(snapshot);
282
+ }
283
+ catch {
284
+ // One broken stream listener must not break other observers.
285
+ }
286
+ }
287
+ }
288
+ track(task) {
289
+ this.pending.add(task);
290
+ void task.finally(() => { this.pending.delete(task); });
291
+ }
292
+ }
package/lib/git.d.ts CHANGED
@@ -129,6 +129,17 @@ export declare function addWorktree(exec: Exec, repoRoot: string, branch: string
129
129
  * @returns the free cutout branch name.
130
130
  */
131
131
  export declare function cutoutBranchName(exec: Exec, repoRoot: string, base: string, folderTaken?: (branch: string) => boolean): Promise<string>;
132
+ /**
133
+ * Plan a random branch name (`<stem>-<4hex>`) to cut out of `base`, avoiding
134
+ * collisions with existing local branches and storage folders. Remote display
135
+ * names (`origin/feat/x`) strip their remote prefix before generating the stem.
136
+ * @param exec - executor seam.
137
+ * @param repoRoot - main worktree directory.
138
+ * @param base - base branch display name (local, `<remote>/<name>`, or `HEAD`).
139
+ * @param folderTaken - storage-folder occupancy probe (branch name → taken).
140
+ * @param randomHex - optional 4-hex generator seam for deterministic tests.
141
+ */
142
+ export declare function randomCutoutBranchName(exec: Exec, repoRoot: string, base: string, folderTaken?: (branch: string) => boolean, randomHex?: () => string): Promise<string>;
132
143
  /**
133
144
  * Create a worktree on a brand-new branch cut out of `base`: the base is
134
145
  * checked out by the main worktree (git forbids a second worktree on it),
@@ -329,6 +340,14 @@ export declare function removeWorktree(exec: Exec, repoRoot: string, worktreePat
329
340
  * binary surfaces the same way — a non-zero exit through the seam).
330
341
  */
331
342
  export declare function probeWorkspaceGit(exec: Exec, path: string): Promise<WorkspaceGitFacts | undefined>;
343
+ /**
344
+ * Best-effort persistence of the base branch a linked worktree was created
345
+ * from, stored inside `<worktreeGitDir>/dsh-worktree-base` so it never dirties
346
+ * the working tree and is removed automatically by `git worktree remove`.
347
+ */
348
+ export declare function writeWorktreeBaseBranch(worktreePath: string, baseBranch: string): Promise<void>;
349
+ /** Read the persisted base branch for a linked worktree, or undefined when absent. */
350
+ export declare function readWorktreeBaseBranch(worktreePath: string): Promise<string | undefined>;
332
351
  /** The one local-ignore rule the project-internal worktree layout needs.
333
352
  * Exactly this pattern — NOT `/.dsh/` — so project-level `.dsh/` files a user
334
353
  * may want to commit stay trackable. */
package/lib/git.js CHANGED
@@ -5,9 +5,9 @@
5
5
  */
6
6
  import { execFile, spawn } from 'node:child_process';
7
7
  import { existsSync, readdirSync } from 'node:fs';
8
- import { appendFile, mkdir, readFile, rm } from 'node:fs/promises';
8
+ import { appendFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
9
9
  import { basename, dirname, isAbsolute, join, normalize, resolve } from 'node:path';
10
- import { localBranchName } from './normalize.js';
10
+ import { generateRandomBranchName, localBranchName } from './normalize.js';
11
11
  import { stripProgress } from './progress.js';
12
12
  /** Failure of one git invocation: non-zero exit with the stderr text. */
13
13
  export class GitError extends Error {
@@ -463,6 +463,28 @@ export async function cutoutBranchName(exec, repoRoot, base, folderTaken) {
463
463
  return candidate;
464
464
  }
465
465
  }
466
+ /**
467
+ * Plan a random branch name (`<stem>-<4hex>`) to cut out of `base`, avoiding
468
+ * collisions with existing local branches and storage folders. Remote display
469
+ * names (`origin/feat/x`) strip their remote prefix before generating the stem.
470
+ * @param exec - executor seam.
471
+ * @param repoRoot - main worktree directory.
472
+ * @param base - base branch display name (local, `<remote>/<name>`, or `HEAD`).
473
+ * @param folderTaken - storage-folder occupancy probe (branch name → taken).
474
+ * @param randomHex - optional 4-hex generator seam for deterministic tests.
475
+ */
476
+ export async function randomCutoutBranchName(exec, repoRoot, base, folderTaken, randomHex) {
477
+ const out = await git(exec, repoRoot, ['for-each-ref', 'refs/heads', '--format=%(refname:short)']);
478
+ const locals = new Set(out.split('\n').map(l => l.trim()).filter(l => l !== ''));
479
+ let stem = base;
480
+ if (base !== 'HEAD' && !locals.has(base) && base.includes('/')) {
481
+ const remoteOut = await gitMaybe(exec, repoRoot, ['for-each-ref', `refs/remotes/${base}`, '--format=%(refname:short)']);
482
+ if (remoteOut !== undefined && remoteOut.trim() !== '') {
483
+ stem = localBranchName(base);
484
+ }
485
+ }
486
+ return generateRandomBranchName(stem, candidate => locals.has(candidate) || (folderTaken?.(candidate) ?? false), randomHex);
487
+ }
466
488
  /**
467
489
  * Create a worktree on a brand-new branch cut out of `base`: the base is
468
490
  * checked out by the main worktree (git forbids a second worktree on it),
@@ -822,13 +844,68 @@ export async function probeWorkspaceGit(exec, path) {
822
844
  // Git outputs carry forward slashes on Windows — normalize every derived
823
845
  // path so consumers can compare against join()-built ones.
824
846
  const gitDir = normalize(resolve(path, commonDir));
847
+ const main = isMainWorktree(toplevel, gitDir);
848
+ const branch = branchName === '' || branchName === 'HEAD' ? null : branchName;
849
+ const rawBaseBranch = main ? undefined : await readWorktreeBaseBranch(toplevel);
850
+ const baseBranch = rawBaseBranch !== undefined && rawBaseBranch !== branch ? rawBaseBranch : undefined;
825
851
  return {
826
852
  repoRoot: dirname(gitDir),
827
853
  repoName: basename(dirname(gitDir)),
828
- branch: branchName === '' || branchName === 'HEAD' ? null : branchName,
829
- main: isMainWorktree(toplevel, gitDir),
854
+ branch,
855
+ main,
856
+ ...(baseBranch === undefined ? {} : { baseBranch }),
830
857
  };
831
858
  }
859
+ /** Filename inside a linked worktree's gitdir storing the base branch it was created from. */
860
+ const WORKTREE_BASE_FILE = 'dsh-worktree-base';
861
+ /** Resolve the linked worktree's private gitdir from its `.git` pointer file. */
862
+ async function resolveWorktreeGitDir(worktreePath) {
863
+ try {
864
+ const raw = await readFile(join(worktreePath, '.git'), 'utf8');
865
+ const match = /^gitdir:\s*(.+)$/m.exec(raw);
866
+ if (match === null)
867
+ return undefined;
868
+ const target = match[1]?.trim();
869
+ if (target === undefined || target === '')
870
+ return undefined;
871
+ return isAbsolute(target) ? normalize(target) : normalize(resolve(worktreePath, target));
872
+ }
873
+ catch {
874
+ return undefined;
875
+ }
876
+ }
877
+ /**
878
+ * Best-effort persistence of the base branch a linked worktree was created
879
+ * from, stored inside `<worktreeGitDir>/dsh-worktree-base` so it never dirties
880
+ * the working tree and is removed automatically by `git worktree remove`.
881
+ */
882
+ export async function writeWorktreeBaseBranch(worktreePath, baseBranch) {
883
+ const trimmed = baseBranch.trim();
884
+ if (trimmed === '')
885
+ return;
886
+ const gitDir = await resolveWorktreeGitDir(worktreePath);
887
+ if (gitDir === undefined)
888
+ return;
889
+ try {
890
+ await writeFile(join(gitDir, WORKTREE_BASE_FILE), `${trimmed}\n`, 'utf8');
891
+ }
892
+ catch {
893
+ // Metadata persistence must never fail worktree creation.
894
+ }
895
+ }
896
+ /** Read the persisted base branch for a linked worktree, or undefined when absent. */
897
+ export async function readWorktreeBaseBranch(worktreePath) {
898
+ const gitDir = await resolveWorktreeGitDir(worktreePath);
899
+ if (gitDir === undefined)
900
+ return undefined;
901
+ try {
902
+ const text = (await readFile(join(gitDir, WORKTREE_BASE_FILE), 'utf8')).trim();
903
+ return text === '' ? undefined : text;
904
+ }
905
+ catch {
906
+ return undefined;
907
+ }
908
+ }
832
909
  /** The one local-ignore rule the project-internal worktree layout needs.
833
910
  * Exactly this pattern — NOT `/.dsh/` — so project-level `.dsh/` files a user
834
911
  * may want to commit stay trackable. */
package/lib/index.d.ts CHANGED
@@ -27,6 +27,13 @@ export interface Config {
27
27
  /** Post-create configuration files to copy when .worktreeinclude is absent;
28
28
  * absent = none. */
29
29
  postCreateCopyFiles?: Volatile<string[]> | string[];
30
+ /** Hide the official top-right new-worktree control in blank sessions; absent = on. */
31
+ hideOfficialWorktreeEntry?: Volatile<boolean> | boolean;
32
+ /** Open worktrees by switching the session working directory under the parent
33
+ * repository workspace instead of creating a standalone workspace; absent = off. */
34
+ switchSessionDirectory?: Volatile<boolean> | boolean;
35
+ /** Include official `<repo>/.agents/worktrees` worktrees in the worktree manager; absent = off. */
36
+ manageOfficialWorktrees?: Volatile<boolean> | boolean;
30
37
  }
31
38
  /** The shipped prune cap (whole storage root, valid git worktrees only). */
32
39
  export declare const KEEP_WORKTREES_DEFAULT = 30;
@@ -64,6 +71,12 @@ export interface SectionConfig {
64
71
  keepWorktrees?: number;
65
72
  /** Post-create configuration files to copy when .worktreeinclude is absent. */
66
73
  postCreateCopyFiles?: string[];
74
+ /** Hide the official top-right new-worktree control in blank sessions; absent = on. */
75
+ hideOfficialWorktreeEntry?: boolean;
76
+ /** Switch session working directory under parent repository workspace instead of creating standalone workspaces; absent = off. */
77
+ switchSessionDirectory?: boolean;
78
+ /** Include official `<repo>/.agents/worktrees` worktrees in the worktree manager; absent = off. */
79
+ manageOfficialWorktrees?: boolean;
67
80
  }
68
81
  /** The section-shaped view of a config: absent keys stay absent
69
82
  * (`exactOptionalPropertyTypes`) except the switches, which spell their