dsh-worktree-switch 0.3.1 → 0.4.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.
package/README.md CHANGED
@@ -7,6 +7,10 @@
7
7
  在 **Worktrees 面板**里把它丢弃,或者自己把分支合回源仓库。会话在副本里时,宿主半还会
8
8
  给模型一条工作区说明,并拒绝把 git 指向主检出的 shell 调用(可关)。
9
9
 
10
+ 新建副本默认以创建前刚拉取到的 `origin/<默认分支>` 为基点,而不是主检出的本地 `HEAD`
11
+ (见「创建基点」)。语义基线与有意偏离见
12
+ [ADR-0005](../../docs/adr/0005-worktree-base-ref-deviates-from-claude-code.md)。
13
+
10
14
  ## 它做什么
11
15
 
12
16
  - **开关**(`conversation.input.left` 槽,只在空白新会话的 hero 上出现):显示本会话
@@ -14,8 +18,9 @@
14
18
  重试)/ 不可用(项目不是 Git 仓库)。开关位置本身记的是"这个项目的新会话要不要隔离"。
15
19
  - **创建**发生在开关打开的那一刻,早于第一条消息;**关闭**发生在第一条消息之前时,
16
20
  会话被切回项目目录,开关在这次打开中建的那份干净副本被删除(脏副本或开关之前就存在
17
- 的副本留在池里,交给面板处理)。副本名 = 分支名 = 池内目录名,形如
18
- `quiet-harbor-3fa9`,由插件生成,短且唯一。
21
+ 的副本留在池里,交给面板处理)。副本默认从创建前刚拉取到的 `origin/<默认分支>` 起;
22
+ `baseRef: 'head'` 或远端取不到时回退为本地 `HEAD`(见「创建基点」)。副本名 = 分支名 = 池内
23
+ 目录名,形如 `quiet-harbor-3fa9`,由插件生成,短且唯一。
19
24
  - **创建失败不回落**:提示词不发送,错误就地显示。从检查开始、到副本就绪之前、离开副本
20
25
  的过程中(或失败之后),开关通过 `ctx.conversation.blocks` 把该会话的输入框置为"暂停
21
26
  发送";重试成功、关掉开关(确认不要隔离)或副本就绪时才解除。关掉开关是明确的退出
@@ -102,12 +107,45 @@ profile 的 patch 层里按上面的写法重新声明 `directory`,否则池
102
107
  改完重启 profile 生效。已经在旧目录里的副本不会消失:面板列的是仓库的所有 linked
103
108
  worktree,所以新旧目录的副本都会出现,可以照常丢弃。
104
109
 
105
- ### 开关默认
110
+ ### 开关默认与基点
106
111
 
107
112
  | 字段 | 默认 | 含义 |
108
113
  |---|---|---|
109
114
  | `defaultEnabled` | `true` | 用户从未在这个项目上拨过开关时,新会话是否默认隔离。用户拨过一次后,按项目记在浏览器 localStorage 里,优于此项。 |
110
115
  | `guardSourceCheckout` | `true` | 会话在副本里时,用 `tools/pre-execute` 拒绝把 git 指向主检出的 bash 调用。关掉就只剩提示。 |
116
+ | `baseRef` | `'fresh'` | 创建副本前从 `origin` 拉取默认分支作为基点;`head` 则直接基于本地 HEAD、不联网。 |
117
+
118
+ ### 创建基点
119
+
120
+ 新建的副本默认**不从本地 HEAD 起**。开关真正要建副本之前(拨开开关、且只有那一刻),
121
+ 宿主半只从 `origin` 拉一个分支——默认分支。解析顺序是 `refs/remotes/origin/HEAD` →
122
+ `main` → `master`,拉取带 5 秒超时,副本以拉取到的那个提交为基点。只拉这一个分支,其他
123
+ 分支和 tag 都不动。
124
+
125
+ - `baseRef` 默认是 `fresh`:如上所述。主检出落后于远端时,新会话仍从团队已经推上来的
126
+ 代码开始。
127
+ - `baseRef: 'head'`:完全跳过默认分支解析与 fetch,直接基于主检出的本地 `HEAD`,不联网。
128
+ 这是「把 feature 分支里未推送的工作带进副本」的逃生门,也是离线时的确定行为。
129
+
130
+ **回退一律不阻断创建**:没有 `origin` 远端、远端没有可识别的默认分支、fetch 失败或超时,
131
+ 都静默回退到本地 HEAD,副本照建。唯一会显式说出来的是「有远端、找到了默认分支、fetch 没
132
+ 成功」这一种:开关的 hover 提示里会多一句「基点:本地 HEAD(远端未取到)」,开关本身的
133
+ 文案不变。
134
+
135
+ 只有「即将创建副本」会联网:已经在副本里的会话、`status`、`release`、`discard` 都不 fetch。
136
+
137
+ 在 profile 自己的 patch 层设置(和 `defaultEnabled` 一样,没有 GUI 控件):
138
+
139
+ ```yaml
140
+ # ~/.dsh/profiles/web/cordis.patch.yml
141
+ - id: dsh-worktree-switch
142
+ name: dsh-worktree-switch
143
+ config:
144
+ baseRef: 'head'
145
+ ```
146
+
147
+ `baseRef` 只接受 `fresh` / `head` 两个字面量,写成别的会让插件在挂载时失败、profile 起不
148
+ 来,而不是静默选另一个基点。
111
149
 
112
150
  ## 目录与命名
113
151
 
@@ -160,9 +198,10 @@ pnpm --filter dsh-worktree-switch test
160
198
  pnpm build # 构建全部包并校验 exports / bundle patch 文件存在
161
199
  ```
162
200
 
163
- 测试只有两条接缝:宿主半的五个动词(真实临时 Git 仓库 + 真实服务,`tests/host.spec.ts`)
164
- 和浏览器半的槽注册与渲染(真实 `SlotRegistry` + 假 `connection`/`conversation`,
165
- `tests/*.client.spec.tsx`)。不断言内部 Git 调用次数,也不测上游 worktree 服务自己的
201
+ 测试有三条接缝:宿主半的五个动词(真实临时 Git 仓库 + 真实服务,`tests/host.spec.ts`)、
202
+ 浏览器半的槽注册与渲染(真实 `SlotRegistry` + 假 `connection`/`conversation`,
203
+ `tests/*.client.spec.tsx`),以及插件公开的配置契约(`tests/config.spec.ts`:`baseRef`
204
+ 只接受 `fresh` / `head`)。不断言内部 Git 调用次数,也不测上游 worktree 服务自己的
166
205
  Git 细节。
167
206
 
168
207
  浏览器半为什么自带一个 `tests/client-harness.ts` 而不是用官方的
package/lib/client.js CHANGED
@@ -53,6 +53,7 @@ function chipHint(state, t) {
53
53
  branch: state.worktree?.branch ?? "",
54
54
  path: state.worktree?.path ?? ""
55
55
  })];
56
+ if (state.base?.kind === "fallback") parts.push(t("chip.hint.baseFallback"));
56
57
  if (!state.intent) parts.push(t("chip.hint.intentOff", { name: state.worktree?.name ?? "" }));
57
58
  if (state.sourceDirty > 0) parts.push(t("chip.hint.dirty", { count: state.sourceDirty }));
58
59
  if (state.error !== null) parts.push(state.error);
@@ -425,6 +426,7 @@ const en = {
425
426
  "chip.hint.creating": "Creating a checkout inside the project…",
426
427
  "chip.hint.reverting": "Moving this session back to the project directory…",
427
428
  "chip.hint.ready": "Branch {branch} at {path}",
429
+ "chip.hint.baseFallback": "Base: local HEAD (the remote default branch could not be fetched).",
428
430
  "chip.hint.failed": "The copy was not created, so this session is still in the project directory.",
429
431
  "chip.hint.disabled": "This project is not a Git repository, so there is nothing to copy.",
430
432
  "chip.hint.dirty": "The source checkout has {count} uncommitted change(s); the copy starts from the last commit.",
@@ -472,6 +474,7 @@ const zh = {
472
474
  "chip.hint.creating": "正在项目里创建检出…",
473
475
  "chip.hint.reverting": "正在把本会话切回项目目录…",
474
476
  "chip.hint.ready": "分支 {branch},位于 {path}",
477
+ "chip.hint.baseFallback": "基点:本地 HEAD(远端未取到)。",
475
478
  "chip.hint.failed": "副本没有创建成功,本会话仍然在项目目录里。",
476
479
  "chip.hint.disabled": "这个项目不是 Git 仓库,没有可复制的内容。",
477
480
  "chip.hint.dirty": "源仓库有 {count} 处未提交改动;副本会从最后一次提交开始。",
@@ -581,6 +584,7 @@ const INITIAL = {
581
584
  worktree: null,
582
585
  repositoryRoot: null,
583
586
  sourceDirty: 0,
587
+ base: null,
584
588
  error: null
585
589
  };
586
590
  /** A thrown value's message, without leaking `undefined`. */
@@ -689,6 +693,7 @@ var InternalBinding = class {
689
693
  worktree: status.sessionWorktree,
690
694
  repositoryRoot: status.repositoryRoot,
691
695
  sourceDirty: status.sourceDirty,
696
+ base: null,
692
697
  error: null
693
698
  };
694
699
  if (status.sessionWorktree !== null) {
@@ -738,6 +743,7 @@ var InternalBinding = class {
738
743
  worktree: prepared.worktree,
739
744
  repositoryRoot: prepared.repositoryRoot,
740
745
  sourceDirty: prepared.sourceDirty,
746
+ base: prepared.state === "created" ? prepared.base : null,
741
747
  error: null
742
748
  });
743
749
  } catch (error) {
@@ -787,6 +793,7 @@ var InternalBinding = class {
787
793
  phase: "off",
788
794
  intent: false,
789
795
  worktree: null,
796
+ base: null,
790
797
  error: null
791
798
  });
792
799
  } catch (error) {
package/lib/index.d.ts CHANGED
@@ -1,5 +1,15 @@
1
1
  import Schema from "@deepseek-ai/schemastery";
2
2
  import { Context } from "@deepseek-ai/cordis";
3
+ /**
4
+ * Wire vocabulary shared by the host half, the browser half, and the tests.
5
+ *
6
+ * Both halves are built separately; these are the only values that cross
7
+ * between them, so they live in one module and nothing here imports Node or
8
+ * React.
9
+ * @module dsh-worktree-switch/types
10
+ */
11
+ /** The two configured base points: fetch the remote default branch, or use local HEAD. */
12
+ type BaseRef = 'fresh' | 'head';
3
13
  /** Plugin id: package name, bundle row id, browser module id. */
4
14
  export declare const name = "dsh-worktree-switch";
5
15
  /**
@@ -15,6 +25,8 @@ export interface Config {
15
25
  defaultEnabled: boolean;
16
26
  /** Refuse shell commands that run Git against the project checkout while the session is in a copy. */
17
27
  guardSourceCheckout: boolean;
28
+ /** Commit a new copy starts from: the fetched remote default branch, or local HEAD. */
29
+ baseRef: BaseRef;
18
30
  }
19
31
  /** Schemastery schema for {@link Config}. */
20
32
  export declare const Config: Schema<Config>;
@@ -24,4 +36,5 @@ export declare const Config: Schema<Config>;
24
36
  * @param config - validated row config.
25
37
  */
26
38
  export declare function apply(ctx: Context, config: Config): void;
39
+ export type { BaseRef };
27
40
  //# sourceMappingURL=index.d.ts.map
package/lib/index.js CHANGED
@@ -280,6 +280,127 @@ async function changedFileCount(ctx, directory, signal) {
280
280
  "--untracked-files=normal"
281
281
  ], { signal })).stdout.split("\n").filter((line) => line.trim() !== "").length;
282
282
  }
283
+ // src/host/base.ts
284
+ /** Whole-command deadline for the plugin's one network call. */
285
+ const FETCH_TIMEOUT_MS = 5e3;
286
+ /** Local HEAD, used by `head` mode and by every silent failure. */
287
+ const LOCAL_HEAD = {
288
+ from: "HEAD",
289
+ base: { kind: "head" }
290
+ };
291
+ /**
292
+ * Resolve the default branch `origin` advertises, if it has one.
293
+ *
294
+ * `origin/HEAD` is the clone's own answer; clones that lost it still commonly
295
+ * default to `main` or `master`, so those two are probed before giving up. A
296
+ * repository with no `origin` is a normal local-only project, not a failure:
297
+ * the caller skips fetching entirely and leaves no notice behind.
298
+ * @param ctx - Host context carrying the subprocess provider.
299
+ * @param root - canonical repository root to ask.
300
+ * @param signal - caller cancellation.
301
+ * @returns the branch name without its `origin/` prefix, or null.
302
+ */
303
+ async function defaultBranch(ctx, root, signal) {
304
+ const remote = await runGit(ctx, root, [
305
+ "remote",
306
+ "get-url",
307
+ "origin"
308
+ ], {
309
+ signal,
310
+ allowedExitCodes: [
311
+ 0,
312
+ 1,
313
+ 2
314
+ ]
315
+ });
316
+ if (remote.exitCode !== 0 || remote.stdout.trim() === "") return null;
317
+ const symbolic = await runGit(ctx, root, [
318
+ "symbolic-ref",
319
+ "--short",
320
+ "refs/remotes/origin/HEAD"
321
+ ], {
322
+ signal,
323
+ allowedExitCodes: [
324
+ 0,
325
+ 1,
326
+ 128
327
+ ]
328
+ });
329
+ if (symbolic.exitCode === 0) {
330
+ const name = symbolic.stdout.trim();
331
+ if (name.startsWith("origin/") && name.length > 7) return name.slice(7);
332
+ }
333
+ for (const candidate of ["main", "master"]) {
334
+ const known = await runGit(ctx, root, [
335
+ "rev-parse",
336
+ "--verify",
337
+ "--quiet",
338
+ `refs/remotes/origin/${candidate}`
339
+ ], {
340
+ signal,
341
+ allowedExitCodes: [0, 1]
342
+ });
343
+ if (known.exitCode === 0 && known.stdout.trim() !== "") return candidate;
344
+ }
345
+ return null;
346
+ }
347
+ /**
348
+ * Choose the base commit for a copy that is about to be created.
349
+ *
350
+ * `head` mode never touches the network. `fresh` mode fetches only the default
351
+ * branch, with an explicit refspec so a rewritten `remote.origin.fetch` cannot
352
+ * silently skip the update, and returns the fetched commit itself rather than
353
+ * the ref name: another process may advance the ref between the fetch and the
354
+ * worktree service's checkout.
355
+ * @param ctx - Host context carrying the subprocess provider.
356
+ * @param root - canonical repository root the fetch runs in.
357
+ * @param baseRef - configured base point.
358
+ * @param signal - caller cancellation; distinct from the fetch deadline.
359
+ * @returns the revision to create from and the outcome to report.
360
+ * @throws when the caller cancels; every Git failure is contained.
361
+ */
362
+ async function resolveBase(ctx, root, baseRef, signal) {
363
+ if (baseRef === "head") return LOCAL_HEAD;
364
+ let branch;
365
+ try {
366
+ branch = await defaultBranch(ctx, root, signal);
367
+ } catch {
368
+ signal?.throwIfAborted();
369
+ return LOCAL_HEAD;
370
+ }
371
+ if (branch === null) return LOCAL_HEAD;
372
+ try {
373
+ await runGit(ctx, root, [
374
+ "fetch",
375
+ "--no-tags",
376
+ "--quiet",
377
+ "origin",
378
+ `+refs/heads/${branch}:refs/remotes/origin/${branch}`
379
+ ], {
380
+ signal,
381
+ timeoutMs: FETCH_TIMEOUT_MS
382
+ });
383
+ const from = (await runGit(ctx, root, [
384
+ "rev-parse",
385
+ "--verify",
386
+ `refs/remotes/origin/${branch}^{commit}`
387
+ ], { signal })).stdout.trim();
388
+ if (from === "") throw new Error(`origin/${branch} has no commit after fetching it`);
389
+ return {
390
+ from,
391
+ base: {
392
+ kind: "remote",
393
+ branch
394
+ }
395
+ };
396
+ } catch {
397
+ signal?.throwIfAborted();
398
+ return {
399
+ from: "HEAD",
400
+ base: { kind: "fallback" }
401
+ };
402
+ }
403
+ }
283
404
  // src/host/naming.ts
284
405
  /**
285
406
  * Names for the copy a session gets: lowercase words and a short suffix, so a
@@ -567,6 +688,7 @@ function createWorktreeToggle(ctx, options) {
567
688
  repositoryRoot: current.repositoryRoot,
568
689
  workingProject
569
690
  });
691
+ const base = await resolveBase(ctx, current.repositoryRoot, options.baseRef, signal);
570
692
  let lastFailure;
571
693
  for (let attempt = 0; attempt < CREATE_ATTEMPTS; attempt += 1) {
572
694
  signal?.throwIfAborted();
@@ -574,7 +696,7 @@ function createWorktreeToggle(ctx, options) {
574
696
  try {
575
697
  const created = await ctx.worktrees.create(agent, {
576
698
  name,
577
- from: "HEAD"
699
+ from: base.from
578
700
  }, signal);
579
701
  const worktree = {
580
702
  name: created.branch,
@@ -590,7 +712,8 @@ function createWorktreeToggle(ctx, options) {
590
712
  state: "created",
591
713
  worktree,
592
714
  repositoryRoot: created.repositoryRoot,
593
- sourceDirty: current.sourceDirty
715
+ sourceDirty: current.sourceDirty,
716
+ base: base.base
594
717
  };
595
718
  } catch (error) {
596
719
  lastFailure = error;
@@ -1063,7 +1186,8 @@ const inject = [
1063
1186
  /** Schemastery schema for {@link Config}. */
1064
1187
  const Config = Schema.object({
1065
1188
  defaultEnabled: Schema.boolean().default(true).description("Start a new session in a worktree copy until the user turns the switch off for that project."),
1066
- guardSourceCheckout: Schema.boolean().default(true).description("While a session is in a copy, deny shell commands that run Git against the project checkout.")
1189
+ guardSourceCheckout: Schema.boolean().default(true).description("While a session is in a copy, deny shell commands that run Git against the project checkout."),
1190
+ baseRef: Schema.union([Schema.const("fresh"), Schema.const("head")]).default("fresh").description("Where a new copy starts: 'fresh' fetches origin's default branch first; 'head' starts at local HEAD without network access.")
1067
1191
  });
1068
1192
  /**
1069
1193
  * Mount the host half.
@@ -1074,6 +1198,7 @@ function apply(ctx, config) {
1074
1198
  const scopes = new SessionScopeRegistry();
1075
1199
  const toggle = createWorktreeToggle(ctx, {
1076
1200
  defaultEnabled: config.defaultEnabled,
1201
+ baseRef: config.baseRef,
1077
1202
  onScope: (sessionId, scope) => {
1078
1203
  if (scope === null) scopes.forget(sessionId);
1079
1204
  else scopes.remember(sessionId, scope);
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/host/paths.ts","../src/host/guard.ts","../src/host/git.ts","../src/host/naming.ts","../src/host/handlers.ts","../src/host/routes.ts","../src/host/scope.ts","../src/index.ts"],"sourcesContent":["/**\n * Path predicates the host half shares between the verbs, the scope hint, and\n * the working-directory watcher.\n * @module dsh-worktree-switch/host/paths\n */\n\nimport { isAbsolute, relative } from 'node:path'\n\n/**\n * Whether one absolute directory is the path itself or an ancestor of it.\n * @param directory - candidate ancestor.\n * @param path - absolute path to test.\n * @returns true when `path` is `directory` or lives below it.\n */\nexport function contains(directory: string, path: string): boolean {\n const inside = relative(directory, path)\n return inside === '' || (!inside.startsWith('..') && !isAbsolute(inside))\n}\n","/**\n * The source-checkout guard: while a session runs in a worktree copy, shell\n * commands that would run Git against the project checkout are refused before\n * dispatch.\n *\n * The prompt context (`worktree-switch:scope`) explains where the workspace\n * is, but it cannot stop a model that still reaches for the checkout it can\n * see — and the sandbox deliberately grants writes there. This guard is the\n * enforcement half that needs no harness change: `tools/pre-execute` can deny\n * one call, and the model reads the reason as that call's error result.\n *\n * The pattern is deliberately narrow. Only a shell call that mentions `git`\n * is considered, and only when it names the project checkout either as an\n * explicit `workdir` or as a literal absolute path in the command text.\n * `cd ..`-style relative escapes and shell variables are not resolved; the\n * guard is a net, not the sandbox boundary.\n * @module dsh-worktree-switch/host/guard\n */\n\nimport { isAbsolute, resolve } from 'node:path'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { PreToolDecision, ToolExecution } from '@deepseek-ai/dsh-tools'\nimport type { SessionScope } from '../types.ts'\nimport { contains } from './paths.ts'\nimport type { SessionScopeRegistry } from './scope.ts'\n\n/** Tool names whose `command` argument is executed by a shell. */\nconst SHELL_TOOLS = new Set(['bash'])\n\n/** The arguments the guard reads from one shell call. */\ninterface ShellArguments {\n /** Command text as the model wrote it. */\n readonly command: string\n /** Explicit working directory, when the call carried one. */\n readonly workdir?: string\n}\n\n/**\n * Read a shell call's command and explicit directory, if this is one.\n * @param exec - the pending tool call.\n * @returns the fields the guard needs, or null for every other tool.\n */\nfunction shellArguments(exec: ToolExecution): ShellArguments | null {\n if (!SHELL_TOOLS.has(exec.name)) return null\n if (exec.arguments === null || typeof exec.arguments !== 'object') return null\n const args = exec.arguments as Record<string, unknown>\n const command = args['command']\n if (typeof command !== 'string' || command.trim() === '') return null\n const workdir = args['workdir']\n const explicit = typeof workdir === 'string' && workdir.trim() !== '' ? workdir : undefined\n return explicit === undefined ? { command } : { command, workdir: explicit }\n}\n\n/**\n * The model-facing denial for one shell command.\n * @param command - shell command text as the model wrote it.\n * @param workdir - explicit working directory, when the call carried one.\n * @param cwd - the session's committed working directory.\n * @param scope - the copy the session runs in.\n * @returns the denial reason, or null when the call may run.\n */\nexport function sourceCheckoutDenial(\n command: string,\n workdir: string | undefined,\n cwd: string,\n scope: SessionScope,\n): string | null {\n // Non-Git commands are out of scope: this guard is about the checkout's Git\n // state, not about every write the sandbox already allows.\n if (!/\\bgit\\b/.test(command)) return null\n const checkout = scope.worktree.path\n const project = scope.repositoryRoot\n if (workdir !== undefined) {\n const target = isAbsolute(workdir) ? workdir : resolve(cwd, workdir)\n if (contains(project, target) && !contains(checkout, target)) return denial(scope)\n }\n // The copy lives inside the project, so mention of the copy path must not\n // count as naming the checkout; strip it before looking for the project.\n if (command.split(checkout).join('').includes(project)) return denial(scope)\n return null\n}\n\n/** The one explanation every denial carries, including the way to get main. */\nfunction denial(scope: SessionScope): string {\n return `Denied: this session runs in the worktree copy ${JSON.stringify(scope.worktree.path)}, so Git commands targeting the project checkout ${JSON.stringify(scope.repositoryRoot)} are blocked. Run Git in the current working directory instead; to bring main's latest into this copy, use \\`git fetch origin main\\` and then \\`git merge origin/main\\` (or \\`git rebase origin/main\\`).`\n}\n\n/**\n * Refuse shell calls that run Git against the project checkout while the\n * session is inside a copy.\n *\n * The registry is the same one the prompt context reads, so the guard is\n * active exactly while the model has been told it is in a copy.\n * @param ctx - host context carrying `workingDirectory` and the tool runtime.\n * @param registry - sessions' confirmed copies.\n */\nexport function installSourceCheckoutGuard(ctx: Context, registry: SessionScopeRegistry): void {\n ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {\n const agent = exec.agent\n if (agent === undefined) return next()\n const scope = registry.get(String(agent.session.id))\n if (scope === null) return next()\n const args = shellArguments(exec)\n if (args === null) return next()\n const denial = sourceCheckoutDenial(args.command, args.workdir, ctx.workingDirectory.get(agent.session), scope)\n return denial === null ? next() : { kind: 'deny', reason: denial }\n })\n}\n","/**\n * Unconfined Git calls behind the plugin's user-initiated verbs.\n *\n * Creation goes through `ctx.worktrees` (the harness service), which runs its\n * own Git under the calling session's sandbox policy. The list, status, and\n * discard verbs here belong to a person clicking in the UI rather than to a\n * model turn: they inspect and delete the copies the user can see, from a path\n * the same UI just listed. They therefore spawn Git directly, the same way the\n * installed `dsh-worktree-space` plugin does, instead of borrowing a session's\n * policy for an operation no session asked for.\n * @module dsh-worktree-switch/host/git\n */\n\nimport { realpath } from 'node:fs/promises'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-subprocess'\n\n/** Whole-command deadline for one Git call. */\nexport const GIT_TIMEOUT_MS = 20_000\n\n/** Per-stream capture cap; worktree listings and status lines are small. */\nconst MAX_OUTPUT_BYTES = 1_048_576\n\n/**\n * Clear inherited repository selectors and config so the command reads the\n * checkout named by `cwd`, never one inherited from the Host's environment.\n * One entry per key: `undefined` removes the variable for the child.\n */\nconst GIT_ENV: NodeJS.ProcessEnv = Object.fromEntries([\n 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY',\n 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT',\n 'GIT_CEILING_DIRECTORIES', 'GIT_PREFIX', 'GIT_SHALLOW_FILE', 'GIT_GRAFT_FILE',\n 'GIT_REPLACE_REF_BASE', 'GIT_ATTR_SOURCE',\n].map(key => [key, undefined]))\n\n/** One bounded Git invocation's captured result. */\nexport interface GitResult {\n /** Captured stdout. */\n readonly stdout: string\n /** Captured stderr. */\n readonly stderr: string\n /** Process exit status. */\n readonly exitCode: number\n}\n\n/** A Git invocation that exited with a status the caller did not allow. */\nexport class GitFailure extends Error {\n /**\n * @param args - arguments after the executable, for diagnostics.\n * @param result - the captured outcome.\n */\n constructor(readonly args: readonly string[], readonly result: GitResult) {\n const detail = result.stderr.trim() === '' ? result.stdout.trim() : result.stderr.trim()\n super(`git ${args.join(' ')} failed (exit ${result.exitCode})${detail === '' ? '' : `: ${detail}`}`)\n this.name = 'GitFailure'\n }\n}\n\n/** Options for {@link runGit}. */\nexport interface GitOptions {\n /** Caller cancellation, combined with the command deadline. */\n readonly signal?: AbortSignal | undefined\n /** Exit statuses that are not failures; defaults to `[0]`. */\n readonly allowedExitCodes?: readonly number[] | undefined\n /** Override for {@link GIT_TIMEOUT_MS}. */\n readonly timeoutMs?: number | undefined\n}\n\n/**\n * Run one Git command without a shell and await its termination.\n * @param ctx - Host context carrying the subprocess provider.\n * @param cwd - absolute directory the command runs in.\n * @param args - arguments after the executable.\n * @param options - cancellation, accepted exit statuses, and deadline.\n * @returns captured stdout, stderr, and exit status.\n * @throws {GitFailure} when the exit status is not allowed or the command was killed.\n */\nexport async function runGit(\n ctx: Context,\n cwd: string,\n args: readonly string[],\n options: GitOptions = {},\n): Promise<GitResult> {\n const deadline = AbortSignal.timeout(options.timeoutMs ?? GIT_TIMEOUT_MS)\n const signal = options.signal === undefined ? deadline : AbortSignal.any([options.signal, deadline])\n const allowed = options.allowedExitCodes ?? [0]\n const program = await ctx.subprocess.resolveExecutable('git', undefined, signal)\n const argv = [program, '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', ...args]\n const child = ctx.subprocess.spawn({\n argv,\n cwd,\n env: {\n ...GIT_ENV,\n GIT_TERMINAL_PROMPT: '0',\n GIT_LFS_SKIP_SMUDGE: '1',\n GIT_NO_LAZY_FETCH: '1',\n },\n signal,\n graceMs: 1_500,\n stdio: {\n stdin: 'ignore',\n stdout: { maxBytes: MAX_OUTPUT_BYTES },\n stderr: { maxBytes: MAX_OUTPUT_BYTES },\n },\n })\n try {\n const outcome = await child.done\n const stdout = child.collected.stdout?.readFrom(0).text ?? ''\n const stderr = child.collected.stderr?.readFrom(0).text ?? ''\n const result: GitResult = { stdout, stderr, exitCode: outcome.exitCode ?? -1 }\n if (outcome.exitCode === null || !allowed.includes(outcome.exitCode)) throw new GitFailure(args, result)\n return result\n } finally {\n child.terminate()\n await child.waitForExit()\n }\n}\n\n/**\n * Resolve the repository root that contains `directory`.\n * @param ctx - Host context carrying the subprocess provider.\n * @param directory - absolute directory inside (or at) the checkout.\n * @param signal - caller cancellation.\n * @returns the canonical top-level directory Git reports.\n * @throws {GitFailure} when the directory is not inside a Git working tree.\n */\nexport async function repositoryRoot(ctx: Context, directory: string, signal?: AbortSignal): Promise<string> {\n const result = await runGit(ctx, directory, ['rev-parse', '--show-toplevel'], {\n signal,\n allowedExitCodes: [0, 128],\n })\n if (result.exitCode !== 0) throw new GitFailure(['rev-parse', '--show-toplevel'], result)\n return result.stdout.replace(/\\r?\\n$/, '')\n}\n\n/**\n * Resolve symlinks in a path that exists, falling back to the path as given.\n * @param path - absolute path.\n * @returns the canonical spelling when the path exists.\n */\nexport async function canonicalPath(path: string): Promise<string> {\n try {\n return await realpath(path)\n } catch {\n return path\n }\n}\n\n/** One checkout reported by `git worktree list --porcelain`. */\nexport interface WorktreeRecord {\n /** Absolute checkout directory. */\n readonly path: string\n /** Branch the checkout has checked out, when it has one. */\n readonly branch?: string | undefined\n}\n\n/**\n * Parse `git worktree list --porcelain` output into its records.\n * @param stdout - the command's stdout.\n * @returns one record per reported checkout, in Git's order.\n */\nexport function parseWorktreeList(stdout: string): WorktreeRecord[] {\n const records: WorktreeRecord[] = []\n let path: string | undefined\n let branch: string | undefined\n const flush = (): void => {\n if (path === undefined) return\n records.push(branch === undefined ? { path } : { path, branch })\n path = undefined\n branch = undefined\n }\n for (const line of stdout.split('\\n')) {\n if (line === '') {\n flush()\n continue\n }\n if (line.startsWith('worktree ')) path = line.slice('worktree '.length)\n else if (line.startsWith('branch refs/heads/')) branch = line.slice('branch refs/heads/'.length)\n }\n flush()\n return records\n}\n\n/**\n * List the worktree checkouts of one repository.\n * @param ctx - Host context carrying the subprocess provider.\n * @param root - repository root the command runs in.\n * @param signal - caller cancellation.\n * @returns every checkout Git reports for the repository.\n */\nexport async function listWorktreeRecords(\n ctx: Context,\n root: string,\n signal?: AbortSignal,\n): Promise<WorktreeRecord[]> {\n const result = await runGit(ctx, root, ['worktree', 'list', '--porcelain'], { signal })\n return parseWorktreeList(result.stdout)\n}\n\n/**\n * Count the changed and untracked files of one checkout.\n * @param ctx - Host context carrying the subprocess provider.\n * @param directory - checkout directory to inspect.\n * @param signal - caller cancellation.\n * @returns the number of `git status --porcelain` entries.\n */\nexport async function changedFileCount(\n ctx: Context,\n directory: string,\n signal?: AbortSignal,\n): Promise<number> {\n const result = await runGit(ctx, directory, ['status', '--porcelain', '--untracked-files=normal'], {\n signal,\n })\n return result.stdout.split('\\n').filter(line => line.trim() !== '').length\n}\n","/**\n * Names for the copy a session gets: lowercase words and a short suffix, so a\n * branch, a directory, a `git branch` row and this plugin's UI all read the\n * same. No prefix: the pool path already says where it lives.\n * @module dsh-worktree-switch/host/naming\n */\n\n/** First word of a generated name. */\nconst ADJECTIVES = [\n 'amber', 'brisk', 'calm', 'clever', 'crisp', 'eager', 'faint', 'fresh',\n 'gentle', 'happy', 'hollow', 'kind', 'lively', 'mellow', 'nimble', 'polite',\n 'quiet', 'rapid', 'ready', 'silent', 'soft', 'solid', 'steady', 'sunny',\n 'swift', 'tidy', 'vivid', 'warm', 'wise', 'young',\n] as const\n\n/** Second word of a generated name. */\nconst NOUNS = [\n 'anchor', 'atlas', 'badger', 'birch', 'brook', 'cedar', 'comet', 'coral',\n 'delta', 'ember', 'fern', 'field', 'finch', 'glade', 'harbor', 'heron',\n 'island', 'lark', 'ledge', 'maple', 'meadow', 'otter', 'pebble', 'pine',\n 'quartz', 'river', 'shore', 'stone', 'trail', 'willow',\n] as const\n\n/**\n * Generate one candidate worktree name.\n * @param random - uniform source in `[0, 1)`; injectable for deterministic tests.\n * @returns a lowercase, hyphen-joined branch-safe name such as `quiet-harbor-3fa9`.\n */\nexport function worktreeName(random: () => number = Math.random): string {\n const pick = (values: readonly string[]): string => {\n const index = Math.min(values.length - 1, Math.floor(random() * values.length))\n return values[index] ?? values[0] ?? 'copy'\n }\n const suffix = Math.min(0xffff, Math.floor(random() * 0x10000)).toString(16).padStart(4, '0')\n return `${pick(ADJECTIVES)}-${pick(NOUNS)}-${suffix}`\n}\n\n/** A pool entry name is exactly one path segment, as `git worktree` names it. */\nconst NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\n/**\n * Validate a worktree name received from the browser before it reaches Git.\n * @param value - candidate name.\n * @returns true for one plain path segment that Git also accepts as a branch.\n */\nexport function isWorktreeName(value: string): boolean {\n return NAME_PATTERN.test(value) && !value.endsWith('.lock')\n}\n","/**\n * The plugin's host Remote face: the five verbs the browser half can call,\n * expressed against a live session and the checkouts on disk.\n *\n * This module is the seam the host tests drive directly. Everything below it —\n * Git, the worktree service, the sandbox policy it applies, and session\n * working-directory publication — belongs to the harness and is exercised by\n * its own tests.\n * @module dsh-worktree-switch/host/handlers\n */\n\nimport { lstat, stat } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, relative, resolve } from 'node:path'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport type { SessionId } from '@deepseek-ai/dsh-session'\nimport type {} from '@deepseek-ai/dsh-api-session-controller'\nimport type {} from '@deepseek-ai/dsh-experimental-worktree'\nimport type {} from '@deepseek-ai/dsh-working-directory'\nimport type {\n DiscardValue,\n ListValue,\n PrepareValue,\n ReleaseValue,\n SessionScope,\n StatusValue,\n WorktreeItem,\n WorktreeRef,\n} from '../types.ts'\nimport {\n canonicalPath,\n changedFileCount,\n GitFailure,\n listWorktreeRecords,\n repositoryRoot,\n runGit,\n} from './git.ts'\nimport { isWorktreeName, worktreeName } from './naming.ts'\nimport { contains } from './paths.ts'\n\n/** Attempts at a fresh name before a creation failure becomes an error. */\nconst CREATE_ATTEMPTS = 3\n\nexport type {\n DiscardValue,\n ListValue,\n PrepareValue,\n ReleaseValue,\n SessionScope,\n StatusValue,\n WorktreeItem,\n WorktreeRef,\n} from '../types.ts'\n\n/** A failed verb, carrying the stable code the browser half switches on. */\nexport class WorktreeToggleError extends Error {\n /**\n * @param code - stable failure code.\n * @param message - human-readable explanation.\n * @param details - extra machine-readable facts.\n */\n constructor(\n readonly code: string,\n message: string,\n readonly details: Readonly<Record<string, unknown>> = {},\n ) {\n super(message)\n this.name = 'WorktreeToggleError'\n }\n}\n\n/** Row config the verbs read. */\nexport interface WorktreeToggleOptions {\n /** Default for a project nothing has remembered yet. */\n readonly defaultEnabled: boolean\n /**\n * Report what each verb learned about the session's copy, so the model-facing\n * scope hint can follow it without a second Git walk.\n * @param sessionId - wire session identity.\n * @param scope - the confirmed copy, or null when the session is not in one.\n */\n readonly onScope?: (sessionId: string, scope: SessionScope | null) => void\n}\n\n/** The host face the route layer exposes over the Connection fetch bridge. */\nexport interface WorktreeToggle {\n /**\n * Report whether the session's project can be isolated, and in what.\n * @param request - the calling session.\n * @param signal - caller cancellation.\n * @returns the status payload; `supported: false` is a normal answer.\n */\n status(request: { readonly sessionId: string }, signal?: AbortSignal): Promise<StatusValue>\n /**\n * Put the session into a fresh copy, creating it when necessary.\n * @param request - the calling session.\n * @param signal - caller cancellation.\n * @returns the created or already-present copy.\n * @throws {WorktreeToggleError} when the project cannot host a copy or Git refused.\n */\n prepare(request: { readonly sessionId: string }, signal?: AbortSignal): Promise<PrepareValue>\n /**\n * Put the session back in its project directory, undoing a copy the switch\n * created for it when it never became the conversation's workspace.\n * @param request - the calling session.\n * @param signal - caller cancellation.\n * @returns the directory the session now runs in, the copy removed, and the\n * copy left on disk when deleting it was not safe.\n * @throws {WorktreeToggleError} when the project cannot be resolved or the\n * session could not be moved back.\n */\n release(request: { readonly sessionId: string }, signal?: AbortSignal): Promise<ReleaseValue>\n /**\n * List the copies under one project's pool.\n * @param request - any directory inside the project.\n * @param signal - caller cancellation.\n * @returns the pool contents, or `supported: false` for a non-repository path.\n */\n list(request: { readonly path: string }, signal?: AbortSignal): Promise<ListValue>\n /**\n * Delete one copy and its branch.\n * @param request - a directory inside the project, and the copy's name.\n * @param signal - caller cancellation.\n * @returns the removed copy's identity.\n * @throws {WorktreeToggleError} when the copy is missing, dirty, or Git refused.\n */\n discard(\n request: { readonly path: string; readonly name: string },\n signal?: AbortSignal,\n ): Promise<DiscardValue>\n}\n\n/** Normalize a browser-supplied path before any filesystem work. */\nfunction absolutePath(value: string): string {\n const trimmed = value.trim()\n if (trimmed === '') throw new WorktreeToggleError('bad-request', 'a project path is required')\n return resolve(trimmed)\n}\n\n/**\n * The copy a session already runs in.\n *\n * A linked worktree is recognised from the checkout itself — its `.git` is a\n * file pointing back at the source repository, not a directory — rather than\n * from any configured pool path. The pool belongs to the harness worktree\n * service, so this plugin never needs a second copy of that setting: moving the\n * pool in the service's row config keeps every verb working.\n * @param current - the session's committed working directory.\n * @param repositoryRoot - canonical root of the project's repository.\n * @returns the copy's identity, or null when the directory is not one.\n */\nasync function worktreeAt(current: string, repositoryRoot: string): Promise<WorktreeRef | null> {\n const path = await canonicalPath(current)\n if (path === repositoryRoot) return null\n const inside = relative(repositoryRoot, path)\n if (inside === '' || inside.startsWith('..') || isAbsolute(inside)) return null\n const name = basename(path)\n if (!isWorktreeName(name)) return null\n try {\n if (!(await lstat(`${path}/.git`)).isFile()) return null\n } catch {\n return null\n }\n return { name, path, branch: name }\n}\n\n/**\n * Resolve the canonical root of the repository that contains a directory.\n * Git reports the spelling of the path it was given; the worktree service\n * publishes canonical paths, so both halves must agree on one spelling.\n * @param ctx - host context carrying `subprocess`.\n * @param directory - absolute directory inside the project.\n * @param signal - caller cancellation.\n * @returns the canonical repository root.\n */\nasync function repositoryOf(ctx: Context, directory: string, signal?: AbortSignal): Promise<string> {\n return canonicalPath(await repositoryRoot(ctx, directory, signal))\n}\n\n/**\n * Re-derive the copy one session runs in from its committed directory.\n *\n * A copy's root is the only linked checkout whose name matches the pool\n * convention, but a session may have changed into a directory *inside* the copy,\n * so ancestors are probed from the committed directory up to the project\n * anchor.\n * @param ctx - host context carrying `workingDirectory` and `subprocess`.\n * @param agent - live session owner.\n * @param signal - caller cancellation.\n * @returns the copy and project root, or null when the session is not in one.\n */\nexport async function detectSessionScope(\n ctx: Context,\n agent: Agent,\n signal?: AbortSignal,\n): Promise<SessionScope | null> {\n const current = ctx.workingDirectory.get(agent.session)\n const anchor = agent.session.header.cwd ?? current\n if (current === anchor || !contains(anchor, current)) return null\n let root: string\n try {\n root = await repositoryOf(ctx, anchor, signal)\n } catch {\n return null\n }\n signal?.throwIfAborted()\n let probe = current\n for (;;) {\n const copy = await worktreeAt(probe, root)\n if (copy !== null) return { worktree: copy, repositoryRoot: root }\n const parent = dirname(probe)\n if (probe === root || probe === anchor || parent === probe) return null\n probe = parent\n }\n}\n\n/**\n * Build the host face.\n * @param ctx - Host context with `agents`, `worktrees`, `workingDirectory`, and `subprocess`.\n * @param options - resolved row config.\n * @returns the five verbs.\n */\nexport function createWorktreeToggle(ctx: Context, options: WorktreeToggleOptions): WorktreeToggle {\n /** One in-flight preparation per session, so a double mount cannot create twice. */\n const pending = new Map<string, Promise<PrepareValue>>()\n /**\n * Copies this host instance created for a session, by session id. Turning the\n * switch off may only delete what the switch itself just made: a copy that\n * existed before this instance started is left for the panel's explicit\n * discard, because it may carry work the switch never saw.\n */\n const createdBySession = new Map<string, WorktreeRef>()\n\n const sessionOf = async (sessionId: string, signal?: AbortSignal): Promise<Agent> => {\n signal?.throwIfAborted()\n if (sessionId === '') throw new WorktreeToggleError('bad-request', 'a session id is required')\n const controller = ctx.get('sessionController')\n if (controller !== undefined) {\n const resolved = await controller.resolveAgent(sessionId as SessionId)\n if ('error' in resolved) {\n throw new WorktreeToggleError(resolved.error.code, resolved.error.message, {\n sessionId,\n })\n }\n return resolved.agent\n }\n const agent = ctx.agents.get(sessionId as SessionId)\n if (agent === undefined) {\n throw new WorktreeToggleError('session-not-found', `no live agent for session ${sessionId}`, {\n sessionId,\n })\n }\n return agent\n }\n\n const status = async (\n request: { readonly sessionId: string },\n signal?: AbortSignal,\n ): Promise<StatusValue> => {\n const agent = await sessionOf(request.sessionId, signal)\n // The immutable creation directory is the project anchor; the committed\n // working directory may already be a copy this session entered.\n const startDirectory = agent.session.header.cwd ?? ctx.workingDirectory.get(agent.session)\n let root: string\n try {\n root = await repositoryOf(ctx, startDirectory, signal)\n } catch (error) {\n if (error instanceof GitFailure) {\n return { supported: false, reason: 'not-a-git-repository', defaultEnabled: options.defaultEnabled }\n }\n throw error\n }\n const current = ctx.workingDirectory.get(agent.session)\n signal?.throwIfAborted()\n const sourceDirty = await changedFileCount(ctx, root, signal)\n const copy = await worktreeAt(current, root)\n options.onScope?.(request.sessionId, copy === null ? null : { worktree: copy, repositoryRoot: root })\n return {\n supported: true,\n repositoryRoot: root,\n sessionWorktree: copy,\n sourceDirty,\n defaultEnabled: options.defaultEnabled,\n }\n }\n\n const prepareOnce = async (\n request: { readonly sessionId: string },\n signal?: AbortSignal,\n ): Promise<PrepareValue> => {\n const agent = await sessionOf(request.sessionId, signal)\n const current = await status(request, signal)\n if (!current.supported) {\n throw new WorktreeToggleError(\n 'not-a-git-repository',\n 'the session project is not inside a Git working tree',\n )\n }\n if (current.sessionWorktree !== null) {\n options.onScope?.(request.sessionId, {\n worktree: current.sessionWorktree,\n repositoryRoot: current.repositoryRoot,\n })\n return {\n state: 'existing',\n worktree: current.sessionWorktree,\n repositoryRoot: current.repositoryRoot,\n sourceDirty: current.sourceDirty,\n }\n }\n // Status anchors on the immutable creation directory, while the worktree\n // service creates relative to the session's CURRENT directory. Refuse to\n // create when the two name different repositories: a copy in the wrong\n // project would look like success and be worse than no copy.\n const working = ctx.workingDirectory.get(agent.session)\n const workingProject = await repositoryOf(ctx, working, signal)\n if (workingProject !== current.repositoryRoot) {\n throw new WorktreeToggleError(\n 'session-moved',\n `this session now works in ${workingProject}, not in its project ${current.repositoryRoot}`,\n { repositoryRoot: current.repositoryRoot, workingProject },\n )\n }\n let lastFailure: unknown\n for (let attempt = 0; attempt < CREATE_ATTEMPTS; attempt += 1) {\n signal?.throwIfAborted()\n const name = worktreeName()\n try {\n const created = await ctx.worktrees.create(agent, { name, from: 'HEAD' }, signal)\n const worktree: WorktreeRef = { name: created.branch, path: created.path, branch: created.branch }\n createdBySession.set(request.sessionId, worktree)\n options.onScope?.(request.sessionId, { worktree, repositoryRoot: created.repositoryRoot })\n return {\n state: 'created',\n worktree,\n repositoryRoot: created.repositoryRoot,\n sourceDirty: current.sourceDirty,\n }\n } catch (error) {\n lastFailure = error\n const message = error instanceof Error ? error.message : String(error)\n // A name collision is the one failure a fresh name can fix. Everything\n // else (no commits yet, branch or path exists, Git missing) is reported\n // as-is: the caller must not be told \"created\" after a silent retry.\n if (!/already exists|worktree branch already exists|worktree path already exists/i.test(message)) {\n throw new WorktreeToggleError('worktree-create-failed', message, { name })\n }\n }\n }\n throw new WorktreeToggleError(\n 'worktree-create-failed',\n `could not allocate a free worktree name after ${CREATE_ATTEMPTS} attempts`,\n { cause: lastFailure instanceof Error ? lastFailure.message : String(lastFailure) },\n )\n }\n\n const prepare = async (\n request: { readonly sessionId: string },\n signal?: AbortSignal,\n ): Promise<PrepareValue> => {\n const running = pending.get(request.sessionId)\n if (running !== undefined) return running\n const operation = prepareOnce(request, signal)\n pending.set(request.sessionId, operation)\n try {\n return await operation\n } finally {\n if (pending.get(request.sessionId) === operation) pending.delete(request.sessionId)\n }\n }\n\n const list = async (\n request: { readonly path: string },\n signal?: AbortSignal,\n ): Promise<ListValue> => {\n const directory = absolutePath(request.path)\n let root: string\n try {\n root = await repositoryOf(ctx, directory, signal)\n } catch (error) {\n if (error instanceof GitFailure) return { supported: false, reason: 'not-a-git-repository' }\n throw error\n }\n const records = await listWorktreeRecords(ctx, root, signal)\n const items: WorktreeItem[] = []\n for (const record of records) {\n signal?.throwIfAborted()\n const path = await canonicalPath(record.path)\n // The repository's own checkout is the source, never a copy.\n if (path === root) continue\n const name = basename(path)\n if (!isWorktreeName(name)) continue\n const branch = record.branch ?? name\n let createdAt = 0\n let prunable = true\n try {\n const info = await stat(path)\n createdAt = Math.trunc(info.birthtimeMs > 0 ? info.birthtimeMs : info.mtimeMs)\n prunable = false\n } catch {\n // The checkout directory is gone; Git still lists it until pruned.\n }\n const changedFiles = prunable ? 0 : await changedFileCount(ctx, path, signal)\n items.push({ name, path, branch, createdAt, changedFiles, prunable })\n }\n items.sort((left, right) => right.createdAt - left.createdAt || left.name.localeCompare(right.name))\n return { supported: true, repositoryRoot: root, items }\n }\n\n /**\n * Delete one clean copy and its branch. Both the panel's discard and the\n * switch's own undo go through here, so the dirty guard has one home.\n * @param root - canonical repository root.\n * @param name - copy name; already validated by the caller.\n * @param signal - caller cancellation.\n * @returns the removed copy's identity.\n */\n const removeCopy = async (root: string, name: string, signal?: AbortSignal): Promise<DiscardValue> => {\n const listed = await list({ path: root }, signal)\n if (!listed.supported) {\n throw new WorktreeToggleError('not-a-git-repository', 'the project is not inside a Git working tree')\n }\n const item = listed.items.find(entry => entry.name === name)\n if (item === undefined) {\n throw new WorktreeToggleError(\n 'worktree-not-found',\n `no worktree named ${name} in ${root}`,\n { name, repositoryRoot: root },\n )\n }\n if (item.changedFiles > 0) {\n throw new WorktreeToggleError(\n 'worktree-dirty',\n `${item.name} has ${item.changedFiles} uncommitted change(s); commit or discard them first`,\n { name: item.name, changedFiles: item.changedFiles },\n )\n }\n if (item.prunable) {\n await runGit(ctx, root, ['worktree', 'prune'], { signal })\n } else {\n const removed = await runGit(ctx, root, ['worktree', 'remove', item.path], {\n signal,\n allowedExitCodes: [0, 128],\n })\n if (removed.exitCode !== 0) {\n throw new WorktreeToggleError(\n 'worktree-remove-failed',\n new GitFailure(['worktree', 'remove', item.path], removed).message,\n { name: item.name, path: item.path },\n )\n }\n }\n const deleted = await runGit(ctx, root, ['branch', '-D', '--', item.branch], {\n signal,\n allowedExitCodes: [0, 1],\n })\n // Status 1 with \"not found\" is the branch already being gone (removed by\n // hand between the read and the click); that is not a failed discard.\n const branchGone = deleted.exitCode === 1 && /not found/i.test(deleted.stderr)\n if (deleted.exitCode !== 0 && !branchGone) {\n throw new WorktreeToggleError(\n 'worktree-remove-failed',\n new GitFailure(['branch', '-D', item.branch], deleted).message,\n { name: item.name, branch: item.branch },\n )\n }\n for (const [sessionId, copy] of createdBySession) {\n if (copy.path === item.path) createdBySession.delete(sessionId)\n }\n return { removed: true, name: item.name, branch: item.branch, path: item.path }\n }\n\n const discard = async (\n request: { readonly path: string; readonly name: string },\n signal?: AbortSignal,\n ): Promise<DiscardValue> => {\n const directory = absolutePath(request.path)\n if (!isWorktreeName(request.name)) {\n throw new WorktreeToggleError('worktree-name-invalid', `not a worktree name: ${request.name}`)\n }\n const root = await repositoryOf(ctx, directory, signal)\n return await removeCopy(root, request.name, signal)\n }\n\n const release = async (\n request: { readonly sessionId: string },\n signal?: AbortSignal,\n ): Promise<ReleaseValue> => {\n // A create may still be in flight for this session: undo after it settles,\n // so a switch turned off mid-creation cannot race the copy into existence.\n const running = pending.get(request.sessionId)\n if (running !== undefined) {\n try {\n await running\n } catch {\n // Creation failed and already moved nothing; there is nothing to undo.\n }\n }\n signal?.throwIfAborted()\n const agent = await sessionOf(request.sessionId, signal)\n const current = ctx.workingDirectory.get(agent.session)\n // The immutable creation directory anchors the project, exactly as status\n // does: the committed directory may already be a copy this session entered.\n const anchor = agent.session.header.cwd ?? current\n let root: string\n try {\n root = await repositoryOf(ctx, anchor, signal)\n } catch (error) {\n if (error instanceof GitFailure) {\n throw new WorktreeToggleError(\n 'not-a-git-repository',\n 'the session project is not inside a Git working tree',\n )\n }\n throw error\n }\n const listed = await list({ path: anchor }, signal)\n if (!listed.supported) return { directory: current, removed: null, kept: null }\n const path = await canonicalPath(current)\n const item = listed.items.find(entry => contains(entry.path, path))\n if (item === undefined) {\n options.onScope?.(request.sessionId, null)\n return { directory: current, removed: null, kept: null }\n }\n const copy: WorktreeRef = { name: item.name, path: item.path, branch: item.branch }\n signal?.throwIfAborted()\n let directory: string\n try {\n directory = await ctx.workingDirectory.set(agent, anchor, signal)\n } catch (error) {\n throw new WorktreeToggleError(\n 'release-failed',\n `could not move the session back to ${anchor}: ${error instanceof Error ? error.message : String(error)}`,\n { name: copy.name, path: copy.path },\n )\n }\n options.onScope?.(request.sessionId, null)\n const mine = createdBySession.get(request.sessionId)\n if (mine === undefined || mine.path !== copy.path) {\n // Not the switch's own copy: leave it, the panel can discard it by hand.\n return { directory, removed: null, kept: copy }\n }\n try {\n const removed = await removeCopy(root, copy.name, signal)\n return {\n directory,\n removed: { name: removed.name, path: removed.path, branch: removed.branch },\n kept: null,\n }\n } catch (error) {\n if (signal?.aborted === true) throw error\n // Dirty or refused by Git: the session is still back in the project, so\n // the switch keeps its promise; the copy stays for the panel to handle.\n return { directory, removed: null, kept: copy }\n }\n }\n\n return { status, prepare, release, list, discard }\n}\n","/**\n * The Connection fetch bridge: five exact POST routes on the shared `/api`\n * channel, one per verb, speaking the `client-request` / `server-response`\n * envelope the browser's `connection.rpc.call` already implements.\n *\n * Exact routes are the only shape an out-of-tree plugin can claim: `/api` is\n * the one logical channel the API Gateway owns, so `rpc.handle` refuses it and\n * a second `rpc.intercept` throws. Every route below answers owner peers only,\n * which is what the local Web GUI is.\n * @module dsh-worktree-switch/host/routes\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { ConnectionRpcResult } from '@deepseek-ai/dsh-client-connection'\nimport type {} from '@deepseek-ai/dsh-client-connection'\nimport type { DiscardValue, ListValue, PrepareValue, ReleaseValue, StatusValue, WorktreeToggle } from './handlers.ts'\nimport { WorktreeToggleError } from './handlers.ts'\n\n/** Absolute prefix every route below lives under. */\nexport const API_PREFIX = '/api/dsh-worktree-switch'\n\n/** Plugin id; the wire method prefix and the package name are the same string. */\nexport const PLUGIN_ID = 'dsh-worktree-switch'\n\n/** One route per verb. */\nexport const ENDPOINTS = ['status', 'prepare', 'release', 'list', 'discard'] as const\n\n/** A verb this route table serves. */\nexport type Endpoint = (typeof ENDPOINTS)[number]\n\n/** A decoded client request. */\ninterface ClientRequest {\n readonly rpcId: string\n readonly method: string\n readonly payload: Record<string, unknown>\n}\n\n/** A payload object with the named string field, or the failure to send back. */\nfunction requiredString(\n payload: Record<string, unknown>,\n field: string,\n): { readonly value: string } | { readonly failure: WorktreeToggleError } {\n const value = payload[field]\n if (typeof value !== 'string' || value.trim() === '') {\n return {\n failure: new WorktreeToggleError('bad-request', `payload.${field} must be a non-empty string`),\n }\n }\n return { value }\n}\n\n/**\n * Decode the browser's `client-request` envelope.\n * @param body - parsed JSON body.\n * @returns the request, or null when the envelope is malformed.\n */\nexport function readClientRequest(body: unknown): ClientRequest | null {\n if (body === null || typeof body !== 'object' || Array.isArray(body)) return null\n const record = body as Record<string, unknown>\n if (record.type !== 'client-request') return null\n const { rpcId, method } = record\n if (typeof rpcId !== 'string' || rpcId === '') return null\n if (typeof method !== 'string' || method === '') return null\n const payload = record.payload\n return {\n rpcId,\n method,\n payload: payload !== null && typeof payload === 'object' && !Array.isArray(payload)\n ? payload as Record<string, unknown>\n : {},\n }\n}\n\n/** A successful result. */\nfunction ok<T>(value: T): ConnectionRpcResult<T> {\n return { ok: true, value }\n}\n\n/** A failed result carrying the stable code. */\nfunction fail(code: string, message: string, details: Record<string, unknown> = {}): ConnectionRpcResult<never> {\n return { ok: false, error: { code, message, details } }\n}\n\n/**\n * Dispatch one decoded verb.\n * @param toggle - the host face.\n * @param endpoint - the verb.\n * @param payload - its decoded payload.\n * @param signal - request cancellation.\n * @returns the wire result.\n */\nexport async function dispatch(\n toggle: WorktreeToggle,\n endpoint: Endpoint,\n payload: Record<string, unknown>,\n signal: AbortSignal,\n): Promise<ConnectionRpcResult<StatusValue | PrepareValue | ReleaseValue | ListValue | DiscardValue>> {\n try {\n if (endpoint === 'status') {\n const sessionId = requiredString(payload, 'sessionId')\n if ('failure' in sessionId) throw sessionId.failure\n return ok(await toggle.status({ sessionId: sessionId.value }, signal))\n }\n if (endpoint === 'prepare') {\n const sessionId = requiredString(payload, 'sessionId')\n if ('failure' in sessionId) throw sessionId.failure\n return ok(await toggle.prepare({ sessionId: sessionId.value }, signal))\n }\n if (endpoint === 'release') {\n const sessionId = requiredString(payload, 'sessionId')\n if ('failure' in sessionId) throw sessionId.failure\n return ok(await toggle.release({ sessionId: sessionId.value }, signal))\n }\n if (endpoint === 'list') {\n const path = requiredString(payload, 'path')\n if ('failure' in path) throw path.failure\n return ok(await toggle.list({ path: path.value }, signal))\n }\n const path = requiredString(payload, 'path')\n if ('failure' in path) throw path.failure\n const name = requiredString(payload, 'name')\n if ('failure' in name) throw name.failure\n return ok(await toggle.discard({ path: path.value, name: name.value }, signal))\n } catch (error) {\n if (error instanceof WorktreeToggleError) return fail(error.code, error.message, { ...error.details })\n return fail('internal', error instanceof Error ? error.message : String(error))\n }\n}\n\n/**\n * Register one exact route per verb on the shared `/api` channel.\n * @param ctx - Host context carrying `connection`.\n * @param toggle - the host face the routes call.\n */\nexport function registerWorktreeRoutes(ctx: Context, toggle: WorktreeToggle): void {\n for (const endpoint of ENDPOINTS) {\n ctx.effect(() => ctx.connection.fetch.register({\n path: `${API_PREFIX}/${endpoint}`,\n methods: ['POST'],\n requestBody: 'buffered',\n async fetch(request) {\n const contentType = request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase()\n if (contentType !== 'application/json') {\n return new Response('content type must be application/json', { status: 415 })\n }\n let body: unknown\n try {\n body = await request.json()\n } catch {\n return new Response('body is not JSON', { status: 400 })\n }\n const message = readClientRequest(body)\n if (message === null) return new Response('invalid client-request message', { status: 400 })\n if (message.method !== `${PLUGIN_ID}/${endpoint}`) {\n return Response.json({\n type: 'server-response',\n rpcId: message.rpcId,\n result: fail('bad-request', 'RPC method does not match endpoint'),\n })\n }\n const result = await dispatch(toggle, endpoint, message.payload, request.signal)\n return Response.json({ type: 'server-response', rpcId: message.rpcId, result })\n },\n }), `${PLUGIN_ID} ${endpoint} route`)\n }\n}\n","/**\n * The copy a session is confirmed to run in, plus the one line the model reads\n * about it.\n *\n * The working-directory service already tells the model *where* it is. This\n * module answers the question that line does not: which checkout is the\n * session's workspace and which one is merely the project it was copied from.\n * The registry is fed by three sources — the switch verbs, `agent/created`\n * (resume), and `working-directory/change` (any `cd`) — so the line is never\n * stale, and it drops out entirely once the session leaves the copy.\n * @module dsh-worktree-switch/host/scope\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport type {} from '@deepseek-ai/dsh-system-prompt'\nimport type { SessionScope } from '../types.ts'\nimport { contains } from './paths.ts'\n\n/** Sessions whose confirmed copy the prompt context reads. */\nexport class SessionScopeRegistry {\n private readonly scopes = new Map<string, SessionScope>()\n\n /**\n * Read one session's confirmed scope, without any filesystem work.\n * @param sessionId - wire session identity.\n * @returns the known copy, or null.\n */\n get(sessionId: string): SessionScope | null {\n return this.scopes.get(sessionId) ?? null\n }\n\n /**\n * Record that a session now runs in a copy.\n * @param sessionId - wire session identity.\n * @param scope - the confirmed copy and its project root.\n */\n remember(sessionId: string, scope: SessionScope): void {\n this.scopes.set(sessionId, scope)\n }\n\n /**\n * Drop a session's scope; a session with no entry gets no hint.\n * @param sessionId - wire session identity.\n */\n forget(sessionId: string): void {\n this.scopes.delete(sessionId)\n }\n\n /** Drop every entry; the plugin dropping its context drops its hints with it. */\n clear(): void {\n this.scopes.clear()\n }\n}\n\n/**\n * The model-facing line describing a worktree session's workspace.\n * @param scope - the session's confirmed copy.\n * @returns one sentence pair, JSON-quoted so paths survive the prompt.\n */\nexport function scopeHint(scope: SessionScope): string {\n return `This session is a linked Git worktree checkout at ${JSON.stringify(scope.worktree.path)} of the project ${JSON.stringify(scope.repositoryRoot)}. Run Git commands and file edits from the current working directory; the project checkout is the source, not this session's workspace.`\n}\n\n/** What the installer needs from the host half that owns Git. */\nexport interface WorktreeScopeWiring {\n /** Shared registry the prompt context reads. */\n readonly registry: SessionScopeRegistry\n /**\n * Re-derive one session's copy from its committed directory.\n * @param agent - live session owner.\n * @param signal - cancellation.\n * @returns the confirmed copy, or null when the session is not in one.\n */\n detect(agent: Agent, signal?: AbortSignal): Promise<SessionScope | null>\n}\n\n/**\n * Register the worktree scope as dynamic prompt context and keep it fresh.\n *\n * The context is `required`, so it survives compositions that suppress\n * optional runtime context, and it renders from the registry synchronously —\n * the expensive Git detection happens on session creation and directory\n * changes, never at request time.\n * @param ctx - host context carrying `systemPrompt`, `agents`, and `workingDirectory`.\n * @param wiring - registry plus the Git-backed detector.\n */\nexport function installWorktreeScope(ctx: Context, wiring: WorktreeScopeWiring): void {\n const { registry, detect } = wiring\n\n ctx.inject(['systemPrompt'], (scoped: Context) => {\n scoped.systemPrompt.context({\n name: 'worktree-switch:scope',\n order: scoped.systemPrompt.getContextOrder('WORKING_DIRECTORY') + 5,\n interpolate: false,\n required: true,\n text: (assembly) => {\n const agent = assembly.agent\n if (agent === undefined) return ''\n const sessionId = String(agent.session.id)\n const current = ctx.workingDirectory.get(agent.session)\n const scope = registry.get(sessionId)\n if (scope !== null && contains(scope.worktree.path, current)) return scopeHint(scope)\n // The committed directory is the authority: a session that left the\n // copy must not keep the line.\n if (scope !== null) registry.forget(sessionId)\n const anchor = agent.session.header.cwd ?? current\n // A session still at its creation directory is in no copy; only a\n // directory change inside the project is worth a Git look, and only\n // once per distinct directory value.\n if (current === anchor || !contains(anchor, current)) return ''\n if (lastChecked.get(sessionId) === current) return ''\n void refresh(agent, current)\n return ''\n },\n })\n })\n\n const inFlight = new Set<string>()\n /** The directory value each session was last inspected at, hit or miss. */\n const lastChecked = new Map<string, string>()\n\n /** Re-derive one live agent's scope, remembering or forgetting it. */\n const refresh = async (agent: Agent, current: string = ctx.workingDirectory.get(agent.session)): Promise<void> => {\n const sessionId = String(agent.session.id)\n const anchor = agent.session.header.cwd ?? current\n // Cheap reject before any Git work: a copy is always inside the project,\n // and a session still at its creation directory is in no copy.\n if (current === anchor || !contains(anchor, current)) {\n registry.forget(sessionId)\n return\n }\n if (inFlight.has(sessionId)) return\n inFlight.add(sessionId)\n lastChecked.set(sessionId, current)\n try {\n const found = await detect(agent)\n if (found === null) registry.forget(sessionId)\n else registry.remember(sessionId, found)\n } catch {\n registry.forget(sessionId)\n } finally {\n inFlight.delete(sessionId)\n }\n }\n\n // A resumed session enters no verb, so creation is where it is recognised; an\n // ordinary new session sits at its creation directory and stops at the cheap\n // check. The hook is serial, so the first request already sees the line.\n ctx.on('agent/created', async ({ agent }) => {\n await refresh(agent)\n return undefined\n })\n}\n\n","/**\n * Host half of the Worktree switch.\n *\n * It mounts no service itself: the bundle patch inserts the harness worktree\n * service (`@deepseek-ai/dsh-experimental-worktree`, which provides\n * `ctx.worktrees`) and this plugin's own row. This plugin exposes five verbs\n * over the Connection fetch bridge and drives that service for creation; it\n * also contributes one model-facing context line while a session runs in a\n * copy, and the browser half renders the switch and the panel.\n * @module dsh-worktree-switch\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport Schema from '@deepseek-ai/schemastery'\nimport type {} from '@deepseek-ai/dsh-agent'\nimport type {} from '@deepseek-ai/dsh-experimental-worktree'\nimport type {} from '@deepseek-ai/dsh-subprocess'\nimport type {} from '@deepseek-ai/dsh-working-directory'\nimport { installSourceCheckoutGuard } from './host/guard.ts'\nimport { createWorktreeToggle, detectSessionScope } from './host/handlers.ts'\nimport { registerWorktreeRoutes } from './host/routes.ts'\nimport { installWorktreeScope, SessionScopeRegistry } from './host/scope.ts'\n\n/** Plugin id: package name, bundle row id, browser module id. */\nexport const name = 'dsh-worktree-switch'\n\n/**\n * Services this plugin cannot work without.\n *\n * `worktrees` is provided by the row this bundle's patch inserts next to its\n * own, so Cordis holds this plugin until that row has mounted.\n */\nexport const inject = ['agents', 'connection', 'subprocess', 'worktrees', 'workingDirectory']\n\n/** Row config accepted from `cordis.patch.yml`. */\nexport interface Config {\n /** Default for a project the user has never switched either way. */\n defaultEnabled: boolean\n /** Refuse shell commands that run Git against the project checkout while the session is in a copy. */\n guardSourceCheckout: boolean\n}\n\n/** Schemastery schema for {@link Config}. */\nexport const Config: Schema<Config> = Schema.object({\n defaultEnabled: Schema.boolean()\n .default(true)\n .description('Start a new session in a worktree copy until the user turns the switch off for that project.'),\n guardSourceCheckout: Schema.boolean()\n .default(true)\n .description('While a session is in a copy, deny shell commands that run Git against the project checkout.'),\n})\n\n/**\n * Mount the host half.\n * @param ctx - Host context.\n * @param config - validated row config.\n */\nexport function apply(ctx: Context, config: Config): void {\n const scopes = new SessionScopeRegistry()\n const toggle = createWorktreeToggle(ctx, {\n defaultEnabled: config.defaultEnabled,\n onScope: (sessionId, scope) => {\n if (scope === null) scopes.forget(sessionId)\n else scopes.remember(sessionId, scope)\n },\n })\n installWorktreeScope(ctx, {\n registry: scopes,\n detect: (agent, signal) => detectSessionScope(ctx, agent, signal),\n })\n if (config.guardSourceCheckout) installSourceCheckoutGuard(ctx, scopes)\n registerWorktreeRoutes(ctx, toggle)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAgB,SAAS,WAAmB,MAAuB;CACjE,MAAM,SAAS,SAAS,WAAW,IAAI;CACvC,OAAO,WAAW,MAAO,CAAC,OAAO,WAAW,IAAI,KAAK,CAAC,WAAW,MAAM;AACzE;;;;;;;;;;;;;;;;;;;;;ACUA,MAAM,8BAAc,IAAI,IAAI,CAAC,MAAM,CAAC;;;;;;AAepC,SAAS,eAAe,MAA4C;CAClE,IAAI,CAAC,YAAY,IAAI,KAAK,IAAI,GAAG,OAAO;CACxC,IAAI,KAAK,cAAc,QAAQ,OAAO,KAAK,cAAc,UAAU,OAAO;CAC1E,MAAM,OAAO,KAAK;CAClB,MAAM,UAAU,KAAK;CACrB,IAAI,OAAO,YAAY,YAAY,QAAQ,KAAK,MAAM,IAAI,OAAO;CACjE,MAAM,UAAU,KAAK;CACrB,MAAM,WAAW,OAAO,YAAY,YAAY,QAAQ,KAAK,MAAM,KAAK,UAAU,KAAA;CAClF,OAAO,aAAa,KAAA,IAAY,EAAE,QAAQ,IAAI;EAAE;EAAS,SAAS;CAAS;AAC7E;;;;;;;;;AAUA,SAAgB,qBACd,SACA,SACA,KACA,OACe;CAGf,IAAI,CAAC,UAAU,KAAK,OAAO,GAAG,O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.ts","../src/host/naming.ts","../src/host/handlers.ts","../src/host/routes.ts","../src/host/scope.ts","../src/index.ts"],"sourcesContent":["/**\n * Path predicates the host half shares between the verbs, the scope hint, and\n * the working-directory watcher.\n * @module dsh-worktree-switch/host/paths\n */\n\nimport { isAbsolute, relative } from 'node:path'\n\n/**\n * Whether one absolute directory is the path itself or an ancestor of it.\n * @param directory - candidate ancestor.\n * @param path - absolute path to test.\n * @returns true when `path` is `directory` or lives below it.\n */\nexport function contains(directory: string, path: string): boolean {\n const inside = relative(directory, path)\n return inside === '' || (!inside.startsWith('..') && !isAbsolute(inside))\n}\n","/**\n * The source-checkout guard: while a session runs in a worktree copy, shell\n * commands that would run Git against the project checkout are refused before\n * dispatch.\n *\n * The prompt context (`worktree-switch:scope`) explains where the workspace\n * is, but it cannot stop a model that still reaches for the checkout it can\n * see — and the sandbox deliberately grants writes there. This guard is the\n * enforcement half that needs no harness change: `tools/pre-execute` can deny\n * one call, and the model reads the reason as that call's error result.\n *\n * The pattern is deliberately narrow. Only a shell call that mentions `git`\n * is considered, and only when it names the project checkout either as an\n * explicit `workdir` or as a literal absolute path in the command text.\n * `cd ..`-style relative escapes and shell variables are not resolved; the\n * guard is a net, not the sandbox boundary.\n * @module dsh-worktree-switch/host/guard\n */\n\nimport { isAbsolute, resolve } from 'node:path'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { PreToolDecision, ToolExecution } from '@deepseek-ai/dsh-tools'\nimport type { SessionScope } from '../types.ts'\nimport { contains } from './paths.ts'\nimport type { SessionScopeRegistry } from './scope.ts'\n\n/** Tool names whose `command` argument is executed by a shell. */\nconst SHELL_TOOLS = new Set(['bash'])\n\n/** The arguments the guard reads from one shell call. */\ninterface ShellArguments {\n /** Command text as the model wrote it. */\n readonly command: string\n /** Explicit working directory, when the call carried one. */\n readonly workdir?: string\n}\n\n/**\n * Read a shell call's command and explicit directory, if this is one.\n * @param exec - the pending tool call.\n * @returns the fields the guard needs, or null for every other tool.\n */\nfunction shellArguments(exec: ToolExecution): ShellArguments | null {\n if (!SHELL_TOOLS.has(exec.name)) return null\n if (exec.arguments === null || typeof exec.arguments !== 'object') return null\n const args = exec.arguments as Record<string, unknown>\n const command = args['command']\n if (typeof command !== 'string' || command.trim() === '') return null\n const workdir = args['workdir']\n const explicit = typeof workdir === 'string' && workdir.trim() !== '' ? workdir : undefined\n return explicit === undefined ? { command } : { command, workdir: explicit }\n}\n\n/**\n * The model-facing denial for one shell command.\n * @param command - shell command text as the model wrote it.\n * @param workdir - explicit working directory, when the call carried one.\n * @param cwd - the session's committed working directory.\n * @param scope - the copy the session runs in.\n * @returns the denial reason, or null when the call may run.\n */\nexport function sourceCheckoutDenial(\n command: string,\n workdir: string | undefined,\n cwd: string,\n scope: SessionScope,\n): string | null {\n // Non-Git commands are out of scope: this guard is about the checkout's Git\n // state, not about every write the sandbox already allows.\n if (!/\\bgit\\b/.test(command)) return null\n const checkout = scope.worktree.path\n const project = scope.repositoryRoot\n if (workdir !== undefined) {\n const target = isAbsolute(workdir) ? workdir : resolve(cwd, workdir)\n if (contains(project, target) && !contains(checkout, target)) return denial(scope)\n }\n // The copy lives inside the project, so mention of the copy path must not\n // count as naming the checkout; strip it before looking for the project.\n if (command.split(checkout).join('').includes(project)) return denial(scope)\n return null\n}\n\n/** The one explanation every denial carries, including the way to get main. */\nfunction denial(scope: SessionScope): string {\n return `Denied: this session runs in the worktree copy ${JSON.stringify(scope.worktree.path)}, so Git commands targeting the project checkout ${JSON.stringify(scope.repositoryRoot)} are blocked. Run Git in the current working directory instead; to bring main's latest into this copy, use \\`git fetch origin main\\` and then \\`git merge origin/main\\` (or \\`git rebase origin/main\\`).`\n}\n\n/**\n * Refuse shell calls that run Git against the project checkout while the\n * session is inside a copy.\n *\n * The registry is the same one the prompt context reads, so the guard is\n * active exactly while the model has been told it is in a copy.\n * @param ctx - host context carrying `workingDirectory` and the tool runtime.\n * @param registry - sessions' confirmed copies.\n */\nexport function installSourceCheckoutGuard(ctx: Context, registry: SessionScopeRegistry): void {\n ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {\n const agent = exec.agent\n if (agent === undefined) return next()\n const scope = registry.get(String(agent.session.id))\n if (scope === null) return next()\n const args = shellArguments(exec)\n if (args === null) return next()\n const denial = sourceCheckoutDenial(args.command, args.workdir, ctx.workingDirectory.get(agent.session), scope)\n return denial === null ? next() : { kind: 'deny', reason: denial }\n })\n}\n","/**\n * Unconfined Git calls behind the plugin's user-initiated verbs.\n *\n * Creation goes through `ctx.worktrees` (the harness service), which runs its\n * own Git under the calling session's sandbox policy. The list, status, and\n * discard verbs here belong to a person clicking in the UI rather than to a\n * model turn: they inspect and delete the copies the user can see, from a path\n * the same UI just listed. They therefore spawn Git directly, the same way the\n * installed `dsh-worktree-space` plugin does, instead of borrowing a session's\n * policy for an operation no session asked for.\n * @module dsh-worktree-switch/host/git\n */\n\nimport { realpath } from 'node:fs/promises'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-subprocess'\n\n/** Whole-command deadline for one Git call. */\nexport const GIT_TIMEOUT_MS = 20_000\n\n/** Per-stream capture cap; worktree listings and status lines are small. */\nconst MAX_OUTPUT_BYTES = 1_048_576\n\n/**\n * Clear inherited repository selectors and config so the command reads the\n * checkout named by `cwd`, never one inherited from the Host's environment.\n * One entry per key: `undefined` removes the variable for the child.\n */\nconst GIT_ENV: NodeJS.ProcessEnv = Object.fromEntries([\n 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY',\n 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT',\n 'GIT_CEILING_DIRECTORIES', 'GIT_PREFIX', 'GIT_SHALLOW_FILE', 'GIT_GRAFT_FILE',\n 'GIT_REPLACE_REF_BASE', 'GIT_ATTR_SOURCE',\n].map(key => [key, undefined]))\n\n/** One bounded Git invocation's captured result. */\nexport interface GitResult {\n /** Captured stdout. */\n readonly stdout: string\n /** Captured stderr. */\n readonly stderr: string\n /** Process exit status. */\n readonly exitCode: number\n}\n\n/** A Git invocation that exited with a status the caller did not allow. */\nexport class GitFailure extends Error {\n /**\n * @param args - arguments after the executable, for diagnostics.\n * @param result - the captured outcome.\n */\n constructor(readonly args: readonly string[], readonly result: GitResult) {\n const detail = result.stderr.trim() === '' ? result.stdout.trim() : result.stderr.trim()\n super(`git ${args.join(' ')} failed (exit ${result.exitCode})${detail === '' ? '' : `: ${detail}`}`)\n this.name = 'GitFailure'\n }\n}\n\n/** Options for {@link runGit}. */\nexport interface GitOptions {\n /** Caller cancellation, combined with the command deadline. */\n readonly signal?: AbortSignal | undefined\n /** Exit statuses that are not failures; defaults to `[0]`. */\n readonly allowedExitCodes?: readonly number[] | undefined\n /** Override for {@link GIT_TIMEOUT_MS}. */\n readonly timeoutMs?: number | undefined\n}\n\n/**\n * Run one Git command without a shell and await its termination.\n * @param ctx - Host context carrying the subprocess provider.\n * @param cwd - absolute directory the command runs in.\n * @param args - arguments after the executable.\n * @param options - cancellation, accepted exit statuses, and deadline.\n * @returns captured stdout, stderr, and exit status.\n * @throws {GitFailure} when the exit status is not allowed or the command was killed.\n */\nexport async function runGit(\n ctx: Context,\n cwd: string,\n args: readonly string[],\n options: GitOptions = {},\n): Promise<GitResult> {\n const deadline = AbortSignal.timeout(options.timeoutMs ?? GIT_TIMEOUT_MS)\n const signal = options.signal === undefined ? deadline : AbortSignal.any([options.signal, deadline])\n const allowed = options.allowedExitCodes ?? [0]\n const program = await ctx.subprocess.resolveExecutable('git', undefined, signal)\n const argv = [program, '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', ...args]\n const child = ctx.subprocess.spawn({\n argv,\n cwd,\n env: {\n ...GIT_ENV,\n GIT_TERMINAL_PROMPT: '0',\n GIT_LFS_SKIP_SMUDGE: '1',\n GIT_NO_LAZY_FETCH: '1',\n },\n signal,\n graceMs: 1_500,\n stdio: {\n stdin: 'ignore',\n stdout: { maxBytes: MAX_OUTPUT_BYTES },\n stderr: { maxBytes: MAX_OUTPUT_BYTES },\n },\n })\n try {\n const outcome = await child.done\n const stdout = child.collected.stdout?.readFrom(0).text ?? ''\n const stderr = child.collected.stderr?.readFrom(0).text ?? ''\n const result: GitResult = { stdout, stderr, exitCode: outcome.exitCode ?? -1 }\n if (outcome.exitCode === null || !allowed.includes(outcome.exitCode)) throw new GitFailure(args, result)\n return result\n } finally {\n child.terminate()\n await child.waitForExit()\n }\n}\n\n/**\n * Resolve the repository root that contains `directory`.\n * @param ctx - Host context carrying the subprocess provider.\n * @param directory - absolute directory inside (or at) the checkout.\n * @param signal - caller cancellation.\n * @returns the canonical top-level directory Git reports.\n * @throws {GitFailure} when the directory is not inside a Git working tree.\n */\nexport async function repositoryRoot(ctx: Context, directory: string, signal?: AbortSignal): Promise<string> {\n const result = await runGit(ctx, directory, ['rev-parse', '--show-toplevel'], {\n signal,\n allowedExitCodes: [0, 128],\n })\n if (result.exitCode !== 0) throw new GitFailure(['rev-parse', '--show-toplevel'], result)\n return result.stdout.replace(/\\r?\\n$/, '')\n}\n\n/**\n * Resolve symlinks in a path that exists, falling back to the path as given.\n * @param path - absolute path.\n * @returns the canonical spelling when the path exists.\n */\nexport async function canonicalPath(path: string): Promise<string> {\n try {\n return await realpath(path)\n } catch {\n return path\n }\n}\n\n/** One checkout reported by `git worktree list --porcelain`. */\nexport interface WorktreeRecord {\n /** Absolute checkout directory. */\n readonly path: string\n /** Branch the checkout has checked out, when it has one. */\n readonly branch?: string | undefined\n}\n\n/**\n * Parse `git worktree list --porcelain` output into its records.\n * @param stdout - the command's stdout.\n * @returns one record per reported checkout, in Git's order.\n */\nexport function parseWorktreeList(stdout: string): WorktreeRecord[] {\n const records: WorktreeRecord[] = []\n let path: string | undefined\n let branch: string | undefined\n const flush = (): void => {\n if (path === undefined) return\n records.push(branch === undefined ? { path } : { path, branch })\n path = undefined\n branch = undefined\n }\n for (const line of stdout.split('\\n')) {\n if (line === '') {\n flush()\n continue\n }\n if (line.startsWith('worktree ')) path = line.slice('worktree '.length)\n else if (line.startsWith('branch refs/heads/')) branch = line.slice('branch refs/heads/'.length)\n }\n flush()\n return records\n}\n\n/**\n * List the worktree checkouts of one repository.\n * @param ctx - Host context carrying the subprocess provider.\n * @param root - repository root the command runs in.\n * @param signal - caller cancellation.\n * @returns every checkout Git reports for the repository.\n */\nexport async function listWorktreeRecords(\n ctx: Context,\n root: string,\n signal?: AbortSignal,\n): Promise<WorktreeRecord[]> {\n const result = await runGit(ctx, root, ['worktree', 'list', '--porcelain'], { signal })\n return parseWorktreeList(result.stdout)\n}\n\n/**\n * Count the changed and untracked files of one checkout.\n * @param ctx - Host context carrying the subprocess provider.\n * @param directory - checkout directory to inspect.\n * @param signal - caller cancellation.\n * @returns the number of `git status --porcelain` entries.\n */\nexport async function changedFileCount(\n ctx: Context,\n directory: string,\n signal?: AbortSignal,\n): Promise<number> {\n const result = await runGit(ctx, directory, ['status', '--porcelain', '--untracked-files=normal'], {\n signal,\n })\n return result.stdout.split('\\n').filter(line => line.trim() !== '').length\n}\n","/**\n * Where a new copy starts.\n *\n * Creation is the one place this plugin touches the network, and it does so as\n * a person-initiated action, not on behalf of a model turn: the browser asked\n * for a copy, so the host fetches the remote default branch itself instead of\n * borrowing a session's sandbox policy for it. This is the same class of action\n * as the panel's discard verb (see `./git.ts`).\n *\n * The fetch is deliberately best-effort. A stale remote, an unreachable host,\n * or a clone without a default branch must never turn the switch into a dead\n * end, so every failure falls back to the local HEAD — the only case the\n * browser half reports as degraded is \"there is a remote and a default branch,\n * yet fetching it failed\".\n * @module dsh-worktree-switch/host/base\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { BaseRef, PrepareBase } from '../types.ts'\nimport { runGit } from './git.ts'\n\n/** Whole-command deadline for the plugin's one network call. */\nconst FETCH_TIMEOUT_MS = 5_000\n\n/** A chosen base and how it was chosen. */\nexport interface BaseOutcome {\n /** Revision handed to the worktree service's `from` field. */\n readonly from: string\n /** Where `from` came from; only `fallback` is surfaced to the user. */\n readonly base: PrepareBase\n}\n\n/** Local HEAD, used by `head` mode and by every silent failure. */\nconst LOCAL_HEAD: BaseOutcome = { from: 'HEAD', base: { kind: 'head' } }\n\n/**\n * Resolve the default branch `origin` advertises, if it has one.\n *\n * `origin/HEAD` is the clone's own answer; clones that lost it still commonly\n * default to `main` or `master`, so those two are probed before giving up. A\n * repository with no `origin` is a normal local-only project, not a failure:\n * the caller skips fetching entirely and leaves no notice behind.\n * @param ctx - Host context carrying the subprocess provider.\n * @param root - canonical repository root to ask.\n * @param signal - caller cancellation.\n * @returns the branch name without its `origin/` prefix, or null.\n */\nasync function defaultBranch(ctx: Context, root: string, signal?: AbortSignal): Promise<string | null> {\n const remote = await runGit(ctx, root, ['remote', 'get-url', 'origin'], {\n signal,\n allowedExitCodes: [0, 1, 2],\n })\n if (remote.exitCode !== 0 || remote.stdout.trim() === '') return null\n const symbolic = await runGit(ctx, root, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], {\n signal,\n // 128 is what Git uses for \"not a symbolic ref\", which is the common case\n // for a clone whose remote-tracking HEAD was never created.\n allowedExitCodes: [0, 1, 128],\n })\n if (symbolic.exitCode === 0) {\n const name = symbolic.stdout.trim()\n if (name.startsWith('origin/') && name.length > 'origin/'.length) {\n return name.slice('origin/'.length)\n }\n }\n for (const candidate of ['main', 'master']) {\n const known = await runGit(ctx, root, ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${candidate}`], {\n signal,\n allowedExitCodes: [0, 1],\n })\n if (known.exitCode === 0 && known.stdout.trim() !== '') return candidate\n }\n return null\n}\n\n/**\n * Choose the base commit for a copy that is about to be created.\n *\n * `head` mode never touches the network. `fresh` mode fetches only the default\n * branch, with an explicit refspec so a rewritten `remote.origin.fetch` cannot\n * silently skip the update, and returns the fetched commit itself rather than\n * the ref name: another process may advance the ref between the fetch and the\n * worktree service's checkout.\n * @param ctx - Host context carrying the subprocess provider.\n * @param root - canonical repository root the fetch runs in.\n * @param baseRef - configured base point.\n * @param signal - caller cancellation; distinct from the fetch deadline.\n * @returns the revision to create from and the outcome to report.\n * @throws when the caller cancels; every Git failure is contained.\n */\nexport async function resolveBase(\n ctx: Context,\n root: string,\n baseRef: BaseRef,\n signal?: AbortSignal,\n): Promise<BaseOutcome> {\n if (baseRef === 'head') return LOCAL_HEAD\n let branch: string | null\n try {\n branch = await defaultBranch(ctx, root, signal)\n } catch {\n // Not knowing whether a remote exists is not the same as knowing one\n // failed: stay silent rather than claim a degraded fetch.\n signal?.throwIfAborted()\n return LOCAL_HEAD\n }\n if (branch === null) return LOCAL_HEAD\n try {\n await runGit(\n ctx,\n root,\n ['fetch', '--no-tags', '--quiet', 'origin', `+refs/heads/${branch}:refs/remotes/origin/${branch}`],\n { signal, timeoutMs: FETCH_TIMEOUT_MS },\n )\n const resolved = await runGit(ctx, root, ['rev-parse', '--verify', `refs/remotes/origin/${branch}^{commit}`], {\n signal,\n })\n const from = resolved.stdout.trim()\n if (from === '') throw new Error(`origin/${branch} has no commit after fetching it`)\n return { from, base: { kind: 'remote', branch } }\n } catch {\n // A cancelled request is not a degraded fetch: let the caller's abort win\n // instead of quietly creating a copy from HEAD after the user left.\n signal?.throwIfAborted()\n return { from: 'HEAD', base: { kind: 'fallback' } }\n }\n}\n","/**\n * Names for the copy a session gets: lowercase words and a short suffix, so a\n * branch, a directory, a `git branch` row and this plugin's UI all read the\n * same. No prefix: the pool path already says where it lives.\n * @module dsh-worktree-switch/host/naming\n */\n\n/** First word of a generated name. */\nconst ADJECTIVES = [\n 'amber', 'brisk', 'calm', 'clever', 'crisp', 'eager', 'faint', 'fresh',\n 'gentle', 'happy', 'hollow', 'kind', 'lively', 'mellow', 'nimble', 'polite',\n 'quiet', 'rapid', 'ready', 'silent', 'soft', 'solid', 'steady', 'sunny',\n 'swift', 'tidy', 'vivid', 'warm', 'wise', 'young',\n] as const\n\n/** Second word of a generated name. */\nconst NOUNS = [\n 'anchor', 'atlas', 'badger', 'birch', 'brook', 'cedar', 'comet', 'coral',\n 'delta', 'ember', 'fern', 'field', 'finch', 'glade', 'harbor', 'heron',\n 'island', 'lark', 'ledge', 'maple', 'meadow', 'otter', 'pebble', 'pine',\n 'quartz', 'river', 'shore', 'stone', 'trail', 'willow',\n] as const\n\n/**\n * Generate one candidate worktree name.\n * @param random - uniform source in `[0, 1)`; injectable for deterministic tests.\n * @returns a lowercase, hyphen-joined branch-safe name such as `quiet-harbor-3fa9`.\n */\nexport function worktreeName(random: () => number = Math.random): string {\n const pick = (values: readonly string[]): string => {\n const index = Math.min(values.length - 1, Math.floor(random() * values.length))\n return values[index] ?? values[0] ?? 'copy'\n }\n const suffix = Math.min(0xffff, Math.floor(random() * 0x10000)).toString(16).padStart(4, '0')\n return `${pick(ADJECTIVES)}-${pick(NOUNS)}-${suffix}`\n}\n\n/** A pool entry name is exactly one path segment, as `git worktree` names it. */\nconst NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\n/**\n * Validate a worktree name received from the browser before it reaches Git.\n * @param value - candidate name.\n * @returns true for one plain path segment that Git also accepts as a branch.\n */\nexport function isWorktreeName(value: string): boolean {\n return NAME_PATTERN.test(value) && !value.endsWith('.lock')\n}\n","/**\n * The plugin's host Remote face: the five verbs the browser half can call,\n * expressed against a live session and the checkouts on disk.\n *\n * This module is the seam the host tests drive directly. Everything below it —\n * Git, the worktree service, the sandbox policy it applies, and session\n * working-directory publication — belongs to the harness and is exercised by\n * its own tests.\n * @module dsh-worktree-switch/host/handlers\n */\n\nimport { lstat, stat } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, relative, resolve } from 'node:path'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport type { SessionId } from '@deepseek-ai/dsh-session'\nimport type {} from '@deepseek-ai/dsh-api-session-controller'\nimport type {} from '@deepseek-ai/dsh-experimental-worktree'\nimport type {} from '@deepseek-ai/dsh-working-directory'\nimport type {\n BaseRef,\n DiscardValue,\n ListValue,\n PrepareValue,\n ReleaseValue,\n SessionScope,\n StatusValue,\n WorktreeItem,\n WorktreeRef,\n} from '../types.ts'\nimport { resolveBase } from './base.ts'\nimport {\n canonicalPath,\n changedFileCount,\n GitFailure,\n listWorktreeRecords,\n repositoryRoot,\n runGit,\n} from './git.ts'\nimport { isWorktreeName, worktreeName } from './naming.ts'\nimport { contains } from './paths.ts'\n\n/** Attempts at a fresh name before a creation failure becomes an error. */\nconst CREATE_ATTEMPTS = 3\n\nexport type {\n DiscardValue,\n ListValue,\n PrepareValue,\n ReleaseValue,\n SessionScope,\n StatusValue,\n WorktreeItem,\n WorktreeRef,\n} from '../types.ts'\n\n/** A failed verb, carrying the stable code the browser half switches on. */\nexport class WorktreeToggleError extends Error {\n /**\n * @param code - stable failure code.\n * @param message - human-readable explanation.\n * @param details - extra machine-readable facts.\n */\n constructor(\n readonly code: string,\n message: string,\n readonly details: Readonly<Record<string, unknown>> = {},\n ) {\n super(message)\n this.name = 'WorktreeToggleError'\n }\n}\n\n/** Row config the verbs read. */\nexport interface WorktreeToggleOptions {\n /** Default for a project nothing has remembered yet. */\n readonly defaultEnabled: boolean\n /** Commit a new copy starts from: the fetched remote default branch, or local HEAD. */\n readonly baseRef: BaseRef\n /**\n * Report what each verb learned about the session's copy, so the model-facing\n * scope hint can follow it without a second Git walk.\n * @param sessionId - wire session identity.\n * @param scope - the confirmed copy, or null when the session is not in one.\n */\n readonly onScope?: (sessionId: string, scope: SessionScope | null) => void\n}\n\n/** The host face the route layer exposes over the Connection fetch bridge. */\nexport interface WorktreeToggle {\n /**\n * Report whether the session's project can be isolated, and in what.\n * @param request - the calling session.\n * @param signal - caller cancellation.\n * @returns the status payload; `supported: false` is a normal answer.\n */\n status(request: { readonly sessionId: string }, signal?: AbortSignal): Promise<StatusValue>\n /**\n * Put the session into a fresh copy, creating it when necessary.\n * @param request - the calling session.\n * @param signal - caller cancellation.\n * @returns the created or already-present copy.\n * @throws {WorktreeToggleError} when the project cannot host a copy or Git refused.\n */\n prepare(request: { readonly sessionId: string }, signal?: AbortSignal): Promise<PrepareValue>\n /**\n * Put the session back in its project directory, undoing a copy the switch\n * created for it when it never became the conversation's workspace.\n * @param request - the calling session.\n * @param signal - caller cancellation.\n * @returns the directory the session now runs in, the copy removed, and the\n * copy left on disk when deleting it was not safe.\n * @throws {WorktreeToggleError} when the project cannot be resolved or the\n * session could not be moved back.\n */\n release(request: { readonly sessionId: string }, signal?: AbortSignal): Promise<ReleaseValue>\n /**\n * List the copies under one project's pool.\n * @param request - any directory inside the project.\n * @param signal - caller cancellation.\n * @returns the pool contents, or `supported: false` for a non-repository path.\n */\n list(request: { readonly path: string }, signal?: AbortSignal): Promise<ListValue>\n /**\n * Delete one copy and its branch.\n * @param request - a directory inside the project, and the copy's name.\n * @param signal - caller cancellation.\n * @returns the removed copy's identity.\n * @throws {WorktreeToggleError} when the copy is missing, dirty, or Git refused.\n */\n discard(\n request: { readonly path: string; readonly name: string },\n signal?: AbortSignal,\n ): Promise<DiscardValue>\n}\n\n/** Normalize a browser-supplied path before any filesystem work. */\nfunction absolutePath(value: string): string {\n const trimmed = value.trim()\n if (trimmed === '') throw new WorktreeToggleError('bad-request', 'a project path is required')\n return resolve(trimmed)\n}\n\n/**\n * The copy a session already runs in.\n *\n * A linked worktree is recognised from the checkout itself — its `.git` is a\n * file pointing back at the source repository, not a directory — rather than\n * from any configured pool path. The pool belongs to the harness worktree\n * service, so this plugin never needs a second copy of that setting: moving the\n * pool in the service's row config keeps every verb working.\n * @param current - the session's committed working directory.\n * @param repositoryRoot - canonical root of the project's repository.\n * @returns the copy's identity, or null when the directory is not one.\n */\nasync function worktreeAt(current: string, repositoryRoot: string): Promise<WorktreeRef | null> {\n const path = await canonicalPath(current)\n if (path === repositoryRoot) return null\n const inside = relative(repositoryRoot, path)\n if (inside === '' || inside.startsWith('..') || isAbsolute(inside)) return null\n const name = basename(path)\n if (!isWorktreeName(name)) return null\n try {\n if (!(await lstat(`${path}/.git`)).isFile()) return null\n } catch {\n return null\n }\n return { name, path, branch: name }\n}\n\n/**\n * Resolve the canonical root of the repository that contains a directory.\n * Git reports the spelling of the path it was given; the worktree service\n * publishes canonical paths, so both halves must agree on one spelling.\n * @param ctx - host context carrying `subprocess`.\n * @param directory - absolute directory inside the project.\n * @param signal - caller cancellation.\n * @returns the canonical repository root.\n */\nasync function repositoryOf(ctx: Context, directory: string, signal?: AbortSignal): Promise<string> {\n return canonicalPath(await repositoryRoot(ctx, directory, signal))\n}\n\n/**\n * Re-derive the copy one session runs in from its committed directory.\n *\n * A copy's root is the only linked checkout whose name matches the pool\n * convention, but a session may have changed into a directory *inside* the copy,\n * so ancestors are probed from the committed directory up to the project\n * anchor.\n * @param ctx - host context carrying `workingDirectory` and `subprocess`.\n * @param agent - live session owner.\n * @param signal - caller cancellation.\n * @returns the copy and project root, or null when the session is not in one.\n */\nexport async function detectSessionScope(\n ctx: Context,\n agent: Agent,\n signal?: AbortSignal,\n): Promise<SessionScope | null> {\n const current = ctx.workingDirectory.get(agent.session)\n const anchor = agent.session.header.cwd ?? current\n if (current === anchor || !contains(anchor, current)) return null\n let root: string\n try {\n root = await repositoryOf(ctx, anchor, signal)\n } catch {\n return null\n }\n signal?.throwIfAborted()\n let probe = current\n for (;;) {\n const copy = await worktreeAt(probe, root)\n if (copy !== null) return { worktree: copy, repositoryRoot: root }\n const parent = dirname(probe)\n if (probe === root || probe === anchor || parent === probe) return null\n probe = parent\n }\n}\n\n/**\n * Build the host face.\n * @param ctx - Host context with `agents`, `worktrees`, `workingDirectory`, and `subprocess`.\n * @param options - resolved row config.\n * @returns the five verbs.\n */\nexport function createWorktreeToggle(ctx: Context, options: WorktreeToggleOptions): WorktreeToggle {\n /** One in-flight preparation per session, so a double mount cannot create twice. */\n const pending = new Map<string, Promise<PrepareValue>>()\n /**\n * Copies this host instance created for a session, by session id. Turning the\n * switch off may only delete what the switch itself just made: a copy that\n * existed before this instance started is left for the panel's explicit\n * discard, because it may carry work the switch never saw.\n */\n const createdBySession = new Map<string, WorktreeRef>()\n\n const sessionOf = async (sessionId: string, signal?: AbortSignal): Promise<Agent> => {\n signal?.throwIfAborted()\n if (sessionId === '') throw new WorktreeToggleError('bad-request', 'a session id is required')\n const controller = ctx.get('sessionController')\n if (controller !== undefined) {\n const resolved = await controller.resolveAgent(sessionId as SessionId)\n if ('error' in resolved) {\n throw new WorktreeToggleError(resolved.error.code, resolved.error.message, {\n sessionId,\n })\n }\n return resolved.agent\n }\n const agent = ctx.agents.get(sessionId as SessionId)\n if (agent === undefined) {\n throw new WorktreeToggleError('session-not-found', `no live agent for session ${sessionId}`, {\n sessionId,\n })\n }\n return agent\n }\n\n const status = async (\n request: { readonly sessionId: string },\n signal?: AbortSignal,\n ): Promise<StatusValue> => {\n const agent = await sessionOf(request.sessionId, signal)\n // The immutable creation directory is the project anchor; the committed\n // working directory may already be a copy this session entered.\n const startDirectory = agent.session.header.cwd ?? ctx.workingDirectory.get(agent.session)\n let root: string\n try {\n root = await repositoryOf(ctx, startDirectory, signal)\n } catch (error) {\n if (error instanceof GitFailure) {\n return { supported: false, reason: 'not-a-git-repository', defaultEnabled: options.defaultEnabled }\n }\n throw error\n }\n const current = ctx.workingDirectory.get(agent.session)\n signal?.throwIfAborted()\n const sourceDirty = await changedFileCount(ctx, root, signal)\n const copy = await worktreeAt(current, root)\n options.onScope?.(request.sessionId, copy === null ? null : { worktree: copy, repositoryRoot: root })\n return {\n supported: true,\n repositoryRoot: root,\n sessionWorktree: copy,\n sourceDirty,\n defaultEnabled: options.defaultEnabled,\n }\n }\n\n const prepareOnce = async (\n request: { readonly sessionId: string },\n signal?: AbortSignal,\n ): Promise<PrepareValue> => {\n const agent = await sessionOf(request.sessionId, signal)\n const current = await status(request, signal)\n if (!current.supported) {\n throw new WorktreeToggleError(\n 'not-a-git-repository',\n 'the session project is not inside a Git working tree',\n )\n }\n if (current.sessionWorktree !== null) {\n options.onScope?.(request.sessionId, {\n worktree: current.sessionWorktree,\n repositoryRoot: current.repositoryRoot,\n })\n return {\n state: 'existing',\n worktree: current.sessionWorktree,\n repositoryRoot: current.repositoryRoot,\n sourceDirty: current.sourceDirty,\n }\n }\n // Status anchors on the immutable creation directory, while the worktree\n // service creates relative to the session's CURRENT directory. Refuse to\n // create when the two name different repositories: a copy in the wrong\n // project would look like success and be worse than no copy.\n const working = ctx.workingDirectory.get(agent.session)\n const workingProject = await repositoryOf(ctx, working, signal)\n if (workingProject !== current.repositoryRoot) {\n throw new WorktreeToggleError(\n 'session-moved',\n `this session now works in ${workingProject}, not in its project ${current.repositoryRoot}`,\n { repositoryRoot: current.repositoryRoot, workingProject },\n )\n }\n // The base is resolved once, before any name attempt: a fetch is the one\n // costly step here, and a name collision must not repeat it.\n const base = await resolveBase(ctx, current.repositoryRoot, options.baseRef, signal)\n let lastFailure: unknown\n for (let attempt = 0; attempt < CREATE_ATTEMPTS; attempt += 1) {\n signal?.throwIfAborted()\n const name = worktreeName()\n try {\n const created = await ctx.worktrees.create(agent, { name, from: base.from }, signal)\n const worktree: WorktreeRef = { name: created.branch, path: created.path, branch: created.branch }\n createdBySession.set(request.sessionId, worktree)\n options.onScope?.(request.sessionId, { worktree, repositoryRoot: created.repositoryRoot })\n return {\n state: 'created',\n worktree,\n repositoryRoot: created.repositoryRoot,\n sourceDirty: current.sourceDirty,\n base: base.base,\n }\n } catch (error) {\n lastFailure = error\n const message = error instanceof Error ? error.message : String(error)\n // A name collision is the one failure a fresh name can fix. Everything\n // else (no commits yet, branch or path exists, Git missing) is reported\n // as-is: the caller must not be told \"created\" after a silent retry.\n if (!/already exists|worktree branch already exists|worktree path already exists/i.test(message)) {\n throw new WorktreeToggleError('worktree-create-failed', message, { name })\n }\n }\n }\n throw new WorktreeToggleError(\n 'worktree-create-failed',\n `could not allocate a free worktree name after ${CREATE_ATTEMPTS} attempts`,\n { cause: lastFailure instanceof Error ? lastFailure.message : String(lastFailure) },\n )\n }\n\n const prepare = async (\n request: { readonly sessionId: string },\n signal?: AbortSignal,\n ): Promise<PrepareValue> => {\n const running = pending.get(request.sessionId)\n if (running !== undefined) return running\n const operation = prepareOnce(request, signal)\n pending.set(request.sessionId, operation)\n try {\n return await operation\n } finally {\n if (pending.get(request.sessionId) === operation) pending.delete(request.sessionId)\n }\n }\n\n const list = async (\n request: { readonly path: string },\n signal?: AbortSignal,\n ): Promise<ListValue> => {\n const directory = absolutePath(request.path)\n let root: string\n try {\n root = await repositoryOf(ctx, directory, signal)\n } catch (error) {\n if (error instanceof GitFailure) return { supported: false, reason: 'not-a-git-repository' }\n throw error\n }\n const records = await listWorktreeRecords(ctx, root, signal)\n const items: WorktreeItem[] = []\n for (const record of records) {\n signal?.throwIfAborted()\n const path = await canonicalPath(record.path)\n // The repository's own checkout is the source, never a copy.\n if (path === root) continue\n const name = basename(path)\n if (!isWorktreeName(name)) continue\n const branch = record.branch ?? name\n let createdAt = 0\n let prunable = true\n try {\n const info = await stat(path)\n createdAt = Math.trunc(info.birthtimeMs > 0 ? info.birthtimeMs : info.mtimeMs)\n prunable = false\n } catch {\n // The checkout directory is gone; Git still lists it until pruned.\n }\n const changedFiles = prunable ? 0 : await changedFileCount(ctx, path, signal)\n items.push({ name, path, branch, createdAt, changedFiles, prunable })\n }\n items.sort((left, right) => right.createdAt - left.createdAt || left.name.localeCompare(right.name))\n return { supported: true, repositoryRoot: root, items }\n }\n\n /**\n * Delete one clean copy and its branch. Both the panel's discard and the\n * switch's own undo go through here, so the dirty guard has one home.\n * @param root - canonical repository root.\n * @param name - copy name; already validated by the caller.\n * @param signal - caller cancellation.\n * @returns the removed copy's identity.\n */\n const removeCopy = async (root: string, name: string, signal?: AbortSignal): Promise<DiscardValue> => {\n const listed = await list({ path: root }, signal)\n if (!listed.supported) {\n throw new WorktreeToggleError('not-a-git-repository', 'the project is not inside a Git working tree')\n }\n const item = listed.items.find(entry => entry.name === name)\n if (item === undefined) {\n throw new WorktreeToggleError(\n 'worktree-not-found',\n `no worktree named ${name} in ${root}`,\n { name, repositoryRoot: root },\n )\n }\n if (item.changedFiles > 0) {\n throw new WorktreeToggleError(\n 'worktree-dirty',\n `${item.name} has ${item.changedFiles} uncommitted change(s); commit or discard them first`,\n { name: item.name, changedFiles: item.changedFiles },\n )\n }\n if (item.prunable) {\n await runGit(ctx, root, ['worktree', 'prune'], { signal })\n } else {\n const removed = await runGit(ctx, root, ['worktree', 'remove', item.path], {\n signal,\n allowedExitCodes: [0, 128],\n })\n if (removed.exitCode !== 0) {\n throw new WorktreeToggleError(\n 'worktree-remove-failed',\n new GitFailure(['worktree', 'remove', item.path], removed).message,\n { name: item.name, path: item.path },\n )\n }\n }\n const deleted = await runGit(ctx, root, ['branch', '-D', '--', item.branch], {\n signal,\n allowedExitCodes: [0, 1],\n })\n // Status 1 with \"not found\" is the branch already being gone (removed by\n // hand between the read and the click); that is not a failed discard.\n const branchGone = deleted.exitCode === 1 && /not found/i.test(deleted.stderr)\n if (deleted.exitCode !== 0 && !branchGone) {\n throw new WorktreeToggleError(\n 'worktree-remove-failed',\n new GitFailure(['branch', '-D', item.branch], deleted).message,\n { name: item.name, branch: item.branch },\n )\n }\n for (const [sessionId, copy] of createdBySession) {\n if (copy.path === item.path) createdBySession.delete(sessionId)\n }\n return { removed: true, name: item.name, branch: item.branch, path: item.path }\n }\n\n const discard = async (\n request: { readonly path: string; readonly name: string },\n signal?: AbortSignal,\n ): Promise<DiscardValue> => {\n const directory = absolutePath(request.path)\n if (!isWorktreeName(request.name)) {\n throw new WorktreeToggleError('worktree-name-invalid', `not a worktree name: ${request.name}`)\n }\n const root = await repositoryOf(ctx, directory, signal)\n return await removeCopy(root, request.name, signal)\n }\n\n const release = async (\n request: { readonly sessionId: string },\n signal?: AbortSignal,\n ): Promise<ReleaseValue> => {\n // A create may still be in flight for this session: undo after it settles,\n // so a switch turned off mid-creation cannot race the copy into existence.\n const running = pending.get(request.sessionId)\n if (running !== undefined) {\n try {\n await running\n } catch {\n // Creation failed and already moved nothing; there is nothing to undo.\n }\n }\n signal?.throwIfAborted()\n const agent = await sessionOf(request.sessionId, signal)\n const current = ctx.workingDirectory.get(agent.session)\n // The immutable creation directory anchors the project, exactly as status\n // does: the committed directory may already be a copy this session entered.\n const anchor = agent.session.header.cwd ?? current\n let root: string\n try {\n root = await repositoryOf(ctx, anchor, signal)\n } catch (error) {\n if (error instanceof GitFailure) {\n throw new WorktreeToggleError(\n 'not-a-git-repository',\n 'the session project is not inside a Git working tree',\n )\n }\n throw error\n }\n const listed = await list({ path: anchor }, signal)\n if (!listed.supported) return { directory: current, removed: null, kept: null }\n const path = await canonicalPath(current)\n const item = listed.items.find(entry => contains(entry.path, path))\n if (item === undefined) {\n options.onScope?.(request.sessionId, null)\n return { directory: current, removed: null, kept: null }\n }\n const copy: WorktreeRef = { name: item.name, path: item.path, branch: item.branch }\n signal?.throwIfAborted()\n let directory: string\n try {\n directory = await ctx.workingDirectory.set(agent, anchor, signal)\n } catch (error) {\n throw new WorktreeToggleError(\n 'release-failed',\n `could not move the session back to ${anchor}: ${error instanceof Error ? error.message : String(error)}`,\n { name: copy.name, path: copy.path },\n )\n }\n options.onScope?.(request.sessionId, null)\n const mine = createdBySession.get(request.sessionId)\n if (mine === undefined || mine.path !== copy.path) {\n // Not the switch's own copy: leave it, the panel can discard it by hand.\n return { directory, removed: null, kept: copy }\n }\n try {\n const removed = await removeCopy(root, copy.name, signal)\n return {\n directory,\n removed: { name: removed.name, path: removed.path, branch: removed.branch },\n kept: null,\n }\n } catch (error) {\n if (signal?.aborted === true) throw error\n // Dirty or refused by Git: the session is still back in the project, so\n // the switch keeps its promise; the copy stays for the panel to handle.\n return { directory, removed: null, kept: copy }\n }\n }\n\n return { status, prepare, release, list, discard }\n}\n","/**\n * The Connection fetch bridge: five exact POST routes on the shared `/api`\n * channel, one per verb, speaking the `client-request` / `server-response`\n * envelope the browser's `connection.rpc.call` already implements.\n *\n * Exact routes are the only shape an out-of-tree plugin can claim: `/api` is\n * the one logical channel the API Gateway owns, so `rpc.handle` refuses it and\n * a second `rpc.intercept` throws. Every route below answers owner peers only,\n * which is what the local Web GUI is.\n * @module dsh-worktree-switch/host/routes\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { ConnectionRpcResult } from '@deepseek-ai/dsh-client-connection'\nimport type {} from '@deepseek-ai/dsh-client-connection'\nimport type { DiscardValue, ListValue, PrepareValue, ReleaseValue, StatusValue, WorktreeToggle } from './handlers.ts'\nimport { WorktreeToggleError } from './handlers.ts'\n\n/** Absolute prefix every route below lives under. */\nexport const API_PREFIX = '/api/dsh-worktree-switch'\n\n/** Plugin id; the wire method prefix and the package name are the same string. */\nexport const PLUGIN_ID = 'dsh-worktree-switch'\n\n/** One route per verb. */\nexport const ENDPOINTS = ['status', 'prepare', 'release', 'list', 'discard'] as const\n\n/** A verb this route table serves. */\nexport type Endpoint = (typeof ENDPOINTS)[number]\n\n/** A decoded client request. */\ninterface ClientRequest {\n readonly rpcId: string\n readonly method: string\n readonly payload: Record<string, unknown>\n}\n\n/** A payload object with the named string field, or the failure to send back. */\nfunction requiredString(\n payload: Record<string, unknown>,\n field: string,\n): { readonly value: string } | { readonly failure: WorktreeToggleError } {\n const value = payload[field]\n if (typeof value !== 'string' || value.trim() === '') {\n return {\n failure: new WorktreeToggleError('bad-request', `payload.${field} must be a non-empty string`),\n }\n }\n return { value }\n}\n\n/**\n * Decode the browser's `client-request` envelope.\n * @param body - parsed JSON body.\n * @returns the request, or null when the envelope is malformed.\n */\nexport function readClientRequest(body: unknown): ClientRequest | null {\n if (body === null || typeof body !== 'object' || Array.isArray(body)) return null\n const record = body as Record<string, unknown>\n if (record.type !== 'client-request') return null\n const { rpcId, method } = record\n if (typeof rpcId !== 'string' || rpcId === '') return null\n if (typeof method !== 'string' || method === '') return null\n const payload = record.payload\n return {\n rpcId,\n method,\n payload: payload !== null && typeof payload === 'object' && !Array.isArray(payload)\n ? payload as Record<string, unknown>\n : {},\n }\n}\n\n/** A successful result. */\nfunction ok<T>(value: T): ConnectionRpcResult<T> {\n return { ok: true, value }\n}\n\n/** A failed result carrying the stable code. */\nfunction fail(code: string, message: string, details: Record<string, unknown> = {}): ConnectionRpcResult<never> {\n return { ok: false, error: { code, message, details } }\n}\n\n/**\n * Dispatch one decoded verb.\n * @param toggle - the host face.\n * @param endpoint - the verb.\n * @param payload - its decoded payload.\n * @param signal - request cancellation.\n * @returns the wire result.\n */\nexport async function dispatch(\n toggle: WorktreeToggle,\n endpoint: Endpoint,\n payload: Record<string, unknown>,\n signal: AbortSignal,\n): Promise<ConnectionRpcResult<StatusValue | PrepareValue | ReleaseValue | ListValue | DiscardValue>> {\n try {\n if (endpoint === 'status') {\n const sessionId = requiredString(payload, 'sessionId')\n if ('failure' in sessionId) throw sessionId.failure\n return ok(await toggle.status({ sessionId: sessionId.value }, signal))\n }\n if (endpoint === 'prepare') {\n const sessionId = requiredString(payload, 'sessionId')\n if ('failure' in sessionId) throw sessionId.failure\n return ok(await toggle.prepare({ sessionId: sessionId.value }, signal))\n }\n if (endpoint === 'release') {\n const sessionId = requiredString(payload, 'sessionId')\n if ('failure' in sessionId) throw sessionId.failure\n return ok(await toggle.release({ sessionId: sessionId.value }, signal))\n }\n if (endpoint === 'list') {\n const path = requiredString(payload, 'path')\n if ('failure' in path) throw path.failure\n return ok(await toggle.list({ path: path.value }, signal))\n }\n const path = requiredString(payload, 'path')\n if ('failure' in path) throw path.failure\n const name = requiredString(payload, 'name')\n if ('failure' in name) throw name.failure\n return ok(await toggle.discard({ path: path.value, name: name.value }, signal))\n } catch (error) {\n if (error instanceof WorktreeToggleError) return fail(error.code, error.message, { ...error.details })\n return fail('internal', error instanceof Error ? error.message : String(error))\n }\n}\n\n/**\n * Register one exact route per verb on the shared `/api` channel.\n * @param ctx - Host context carrying `connection`.\n * @param toggle - the host face the routes call.\n */\nexport function registerWorktreeRoutes(ctx: Context, toggle: WorktreeToggle): void {\n for (const endpoint of ENDPOINTS) {\n ctx.effect(() => ctx.connection.fetch.register({\n path: `${API_PREFIX}/${endpoint}`,\n methods: ['POST'],\n requestBody: 'buffered',\n async fetch(request) {\n const contentType = request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase()\n if (contentType !== 'application/json') {\n return new Response('content type must be application/json', { status: 415 })\n }\n let body: unknown\n try {\n body = await request.json()\n } catch {\n return new Response('body is not JSON', { status: 400 })\n }\n const message = readClientRequest(body)\n if (message === null) return new Response('invalid client-request message', { status: 400 })\n if (message.method !== `${PLUGIN_ID}/${endpoint}`) {\n return Response.json({\n type: 'server-response',\n rpcId: message.rpcId,\n result: fail('bad-request', 'RPC method does not match endpoint'),\n })\n }\n const result = await dispatch(toggle, endpoint, message.payload, request.signal)\n return Response.json({ type: 'server-response', rpcId: message.rpcId, result })\n },\n }), `${PLUGIN_ID} ${endpoint} route`)\n }\n}\n","/**\n * The copy a session is confirmed to run in, plus the one line the model reads\n * about it.\n *\n * The working-directory service already tells the model *where* it is. This\n * module answers the question that line does not: which checkout is the\n * session's workspace and which one is merely the project it was copied from.\n * The registry is fed by three sources — the switch verbs, `agent/created`\n * (resume), and `working-directory/change` (any `cd`) — so the line is never\n * stale, and it drops out entirely once the session leaves the copy.\n * @module dsh-worktree-switch/host/scope\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport type {} from '@deepseek-ai/dsh-system-prompt'\nimport type { SessionScope } from '../types.ts'\nimport { contains } from './paths.ts'\n\n/** Sessions whose confirmed copy the prompt context reads. */\nexport class SessionScopeRegistry {\n private readonly scopes = new Map<string, SessionScope>()\n\n /**\n * Read one session's confirmed scope, without any filesystem work.\n * @param sessionId - wire session identity.\n * @returns the known copy, or null.\n */\n get(sessionId: string): SessionScope | null {\n return this.scopes.get(sessionId) ?? null\n }\n\n /**\n * Record that a session now runs in a copy.\n * @param sessionId - wire session identity.\n * @param scope - the confirmed copy and its project root.\n */\n remember(sessionId: string, scope: SessionScope): void {\n this.scopes.set(sessionId, scope)\n }\n\n /**\n * Drop a session's scope; a session with no entry gets no hint.\n * @param sessionId - wire session identity.\n */\n forget(sessionId: string): void {\n this.scopes.delete(sessionId)\n }\n\n /** Drop every entry; the plugin dropping its context drops its hints with it. */\n clear(): void {\n this.scopes.clear()\n }\n}\n\n/**\n * The model-facing line describing a worktree session's workspace.\n * @param scope - the session's confirmed copy.\n * @returns one sentence pair, JSON-quoted so paths survive the prompt.\n */\nexport function scopeHint(scope: SessionScope): string {\n return `This session is a linked Git worktree checkout at ${JSON.stringify(scope.worktree.path)} of the project ${JSON.stringify(scope.repositoryRoot)}. Run Git commands and file edits from the current working directory; the project checkout is the source, not this session's workspace.`\n}\n\n/** What the installer needs from the host half that owns Git. */\nexport interface WorktreeScopeWiring {\n /** Shared registry the prompt context reads. */\n readonly registry: SessionScopeRegistry\n /**\n * Re-derive one session's copy from its committed directory.\n * @param agent - live session owner.\n * @param signal - cancellation.\n * @returns the confirmed copy, or null when the session is not in one.\n */\n detect(agent: Agent, signal?: AbortSignal): Promise<SessionScope | null>\n}\n\n/**\n * Register the worktree scope as dynamic prompt context and keep it fresh.\n *\n * The context is `required`, so it survives compositions that suppress\n * optional runtime context, and it renders from the registry synchronously —\n * the expensive Git detection happens on session creation and directory\n * changes, never at request time.\n * @param ctx - host context carrying `systemPrompt`, `agents`, and `workingDirectory`.\n * @param wiring - registry plus the Git-backed detector.\n */\nexport function installWorktreeScope(ctx: Context, wiring: WorktreeScopeWiring): void {\n const { registry, detect } = wiring\n\n ctx.inject(['systemPrompt'], (scoped: Context) => {\n scoped.systemPrompt.context({\n name: 'worktree-switch:scope',\n order: scoped.systemPrompt.getContextOrder('WORKING_DIRECTORY') + 5,\n interpolate: false,\n required: true,\n text: (assembly) => {\n const agent = assembly.agent\n if (agent === undefined) return ''\n const sessionId = String(agent.session.id)\n const current = ctx.workingDirectory.get(agent.session)\n const scope = registry.get(sessionId)\n if (scope !== null && contains(scope.worktree.path, current)) return scopeHint(scope)\n // The committed directory is the authority: a session that left the\n // copy must not keep the line.\n if (scope !== null) registry.forget(sessionId)\n const anchor = agent.session.header.cwd ?? current\n // A session still at its creation directory is in no copy; only a\n // directory change inside the project is worth a Git look, and only\n // once per distinct directory value.\n if (current === anchor || !contains(anchor, current)) return ''\n if (lastChecked.get(sessionId) === current) return ''\n void refresh(agent, current)\n return ''\n },\n })\n })\n\n const inFlight = new Set<string>()\n /** The directory value each session was last inspected at, hit or miss. */\n const lastChecked = new Map<string, string>()\n\n /** Re-derive one live agent's scope, remembering or forgetting it. */\n const refresh = async (agent: Agent, current: string = ctx.workingDirectory.get(agent.session)): Promise<void> => {\n const sessionId = String(agent.session.id)\n const anchor = agent.session.header.cwd ?? current\n // Cheap reject before any Git work: a copy is always inside the project,\n // and a session still at its creation directory is in no copy.\n if (current === anchor || !contains(anchor, current)) {\n registry.forget(sessionId)\n return\n }\n if (inFlight.has(sessionId)) return\n inFlight.add(sessionId)\n lastChecked.set(sessionId, current)\n try {\n const found = await detect(agent)\n if (found === null) registry.forget(sessionId)\n else registry.remember(sessionId, found)\n } catch {\n registry.forget(sessionId)\n } finally {\n inFlight.delete(sessionId)\n }\n }\n\n // A resumed session enters no verb, so creation is where it is recognised; an\n // ordinary new session sits at its creation directory and stops at the cheap\n // check. The hook is serial, so the first request already sees the line.\n ctx.on('agent/created', async ({ agent }) => {\n await refresh(agent)\n return undefined\n })\n}\n\n","/**\n * Host half of the Worktree switch.\n *\n * It mounts no service itself: the bundle patch inserts the harness worktree\n * service (`@deepseek-ai/dsh-experimental-worktree`, which provides\n * `ctx.worktrees`) and this plugin's own row. This plugin exposes five verbs\n * over the Connection fetch bridge and drives that service for creation; it\n * also contributes one model-facing context line while a session runs in a\n * copy, and the browser half renders the switch and the panel.\n * @module dsh-worktree-switch\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport Schema from '@deepseek-ai/schemastery'\nimport type {} from '@deepseek-ai/dsh-agent'\nimport type {} from '@deepseek-ai/dsh-experimental-worktree'\nimport type {} from '@deepseek-ai/dsh-subprocess'\nimport type {} from '@deepseek-ai/dsh-working-directory'\nimport { installSourceCheckoutGuard } from './host/guard.ts'\nimport { createWorktreeToggle, detectSessionScope } from './host/handlers.ts'\nimport { registerWorktreeRoutes } from './host/routes.ts'\nimport { installWorktreeScope, SessionScopeRegistry } from './host/scope.ts'\nimport type { BaseRef } from './types.ts'\n\n/** Plugin id: package name, bundle row id, browser module id. */\nexport const name = 'dsh-worktree-switch'\n\n/**\n * Services this plugin cannot work without.\n *\n * `worktrees` is provided by the row this bundle's patch inserts next to its\n * own, so Cordis holds this plugin until that row has mounted.\n */\nexport const inject = ['agents', 'connection', 'subprocess', 'worktrees', 'workingDirectory']\n\nexport type { BaseRef } from './types.ts'\n\n/** Row config accepted from `cordis.patch.yml`. */\nexport interface Config {\n /** Default for a project the user has never switched either way. */\n defaultEnabled: boolean\n /** Refuse shell commands that run Git against the project checkout while the session is in a copy. */\n guardSourceCheckout: boolean\n /** Commit a new copy starts from: the fetched remote default branch, or local HEAD. */\n baseRef: BaseRef\n}\n\n/** Schemastery schema for {@link Config}. */\nexport const Config: Schema<Config> = Schema.object({\n defaultEnabled: Schema.boolean()\n .default(true)\n .description('Start a new session in a worktree copy until the user turns the switch off for that project.'),\n guardSourceCheckout: Schema.boolean()\n .default(true)\n .description('While a session is in a copy, deny shell commands that run Git against the project checkout.'),\n baseRef: Schema.union([Schema.const('fresh'), Schema.const('head')])\n .default('fresh')\n .description(\n \"Where a new copy starts: 'fresh' fetches origin's default branch first; 'head' starts at local HEAD without network access.\",\n ),\n})\n\n/**\n * Mount the host half.\n * @param ctx - Host context.\n * @param config - validated row config.\n */\nexport function apply(ctx: Context, config: Config): void {\n const scopes = new SessionScopeRegistry()\n const toggle = createWorktreeToggle(ctx, {\n defaultEnabled: config.defaultEnabled,\n baseRef: config.baseRef,\n onScope: (sessionId, scope) => {\n if (scope === null) scopes.forget(sessionId)\n else scopes.remember(sessionId, scope)\n },\n })\n installWorktreeScope(ctx, {\n registry: scopes,\n detect: (agent, signal) => detectSessionScope(ctx, agent, signal),\n })\n if (config.guardSourceCheckout) installSourceCheckoutGuard(ctx, scopes)\n registerWorktreeRoutes(ctx, toggle)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAgB,SAAS,WAAmB,MAAuB;CACjE,MAAM,SAAS,SAAS,WAAW,IAAI;CACvC,OAAO,WAAW,MAAO,CAAC,OAAO,WAAW,IAAI,KAAK,CAAC,WAAW,MAAM;AACzE;;;;;;;;;;;;;;;;;;;;;ACUA,MAAM,8BAAc,IAAI,IAAI,CAAC,MAAM,CAAC;;;;;;AAepC,SAAS,eAAe,MAA4C;CAClE,IAAI,CAAC,YAAY,IAAI,KAAK,IAAI,GAAG,OAAO;CACxC,IAAI,KAAK,cAAc,QAAQ,OAAO,KAAK,cAAc,UAAU,OAAO;CAC1E,MAAM,OAAO,KAAK;CAClB,MAAM,UAAU,KAAK;CACrB,IAAI,OAAO,YAAY,YAAY,QAAQ,KAAK,MAAM,IAAI,OAAO;CACjE,MAAM,UAAU,KAAK;CACrB,MAAM,WAAW,OAAO,YAAY,YAAY,QAAQ,KAAK,MAAM,KAAK,UAAU,KAAA;CAClF,OAAO,aAAa,KAAA,IAAY,EAAE,QAAQ,IAAI;EAAE;EAAS,SAAS;CAAS;AAC7E;;;;;;;;;AAUA,SAAgB,qBACd,SACA,SACA,KACA,OACe;CAGf,IAAI,CAAC,UAAU,KAAK,OAAO,GAAG,OAAO;CACrC,MAAM,WAAW,MAAM,SAAS;CAChC,MAAM,UAAU,MAAM;CACtB,IAAI,YAAY,KAAA,GAAW;EACzB,MAAM,SAAS,WAAW,OAAO,IAAI,UAAU,QAAQ,KAAK,OAAO;EACnE,IAAI,SAAS,SAAS,MAAM,KAAK,CAAC,SAAS,UAAU,MAAM,GAAG,OAAO,OAAO,KAAK;CACnF;CAGA,IAAI,QAAQ,MAAM,QAAQ,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,SAAS,OAAO,GAAG,OAAO,OA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,SAAS;QACtC,OAAO,SAAS,WAAW,KAAK;EACvC;CACF,CAAC;CACD,qBAAqB,KAAK;EACxB,UAAU;EACV,SAAS,OAAO,WAAW,mBAAmB,KAAK,OAAO,MAAM;CAClE,CAAC;CACD,IAAI,OAAO,qBAAqB,2BAA2B,KAAK,MAAM;CACtE,uBAAuB,KAAK,MAAM;AACpC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-worktree-switch",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "A New Session switch that puts the conversation into a throwaway Git worktree under the project's worktree pool (`<project>/.dsh/worktrees` by default), plus a panel to inspect and discard the copies.",
5
5
  "keywords": [
6
6
  "dsh",