Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(dsh-tauri-worktree): 无条件继承 .agents 并加固工作树上下文注入

hairyfea996fe6fae1
diff --git a/packages/dsh-tauri-worktree/src/host/apply.ts b/packages/dsh-tauri-worktree/src/host/apply.ts
index 5a2e6198..f22056b5 100644
--- a/packages/dsh-tauri-worktree/src/host/apply.ts
+++ b/packages/dsh-tauri-worktree/src/host/apply.ts
@@ -4,6 +4,7 @@ import { clearHostRuntime, setCurrentHostInstance } from './config/runtime'
import { handleSessionEvent } from './events/session-event'
import { handleToolsExecute } from './events/tools-execute'
import { checkoutContextProvider } from './prompts/checkout-context'
+import { worktreeContextProvider } from './prompts/worktree-context'
import { worktreeSectionProvider } from './prompts/worktree-section'
import { routes } from './routes'
import { workspace } from './service/workspace'
@@ -23,6 +24,7 @@ export function apply(ctx: HostContext): void {
ctx.on('tools/execute', handleToolsExecute)
ctx.systemPrompt.section(worktreeSectionProvider)
+ ctx.systemPrompt.context(worktreeContextProvider)
ctx.systemPrompt.context(checkoutContextProvider)
ctx.effect(() => {
diff --git a/packages/dsh-tauri-worktree/src/host/prompts/worktree-context.test.ts b/packages/dsh-tauri-worktree/src/host/prompts/worktree-context.test.ts
new file mode 100644
index 00000000..d013e41e
--- /dev/null
+++ b/packages/dsh-tauri-worktree/src/host/prompts/worktree-context.test.ts
@@ -0,0 +1,74 @@
+import type { Binding } from '../types'
+import { mkdirSync, writeFileSync } from 'node:fs'
+import { join } from 'pathe'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { resetTestDshHome, testDshHome } from '../../../../.test/test-utils'
+import { checkoutContextProvider } from './checkout-context'
+import { worktreeContextProvider } from './worktree-context'
+import { worktreeSectionProvider } from './worktree-section'
+
+vi.mock('dsh-tauri', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('dsh-tauri')>()
+ const { testDshHome: home } = await import('../../../../.test/test-utils')
+ return { ...actual, DSH_HOME: home }
+})
+
+const BINDING = {
+ sessionId: 'session-a',
+ sourceSessionId: 'session-source',
+ hash: 'abc123def456',
+ dirname: 'repo',
+ worktreePath: 'C:/Users/me/.dsh/worktrees/abc123def456/repo',
+ projectPath: 'D:/projects/repo',
+ branchName: '(detached)',
+ ownsBranch: false,
+ createdAt: '2024-01-01T00:00:00.000Z',
+ log: [],
+} as Binding
+
+function bind(sessionId: string, binding: Binding = { ...BINDING, sessionId }): void {
+ mkdirSync(join(testDshHome, 'ledger'), { recursive: true })
+ writeFileSync(join(testDshHome, 'ledger', `${sessionId}.json`), `${JSON.stringify(binding, null, 2)}\n`)
+}
+
+function scope(sessionId: string): { scope: { session: { id: string } } } {
+ return { scope: { session: { id: sessionId } } }
+}
+
+beforeEach(() => {
+ resetTestDshHome()
+})
+
+describe('工作树提示词注入', () => {
+ it('常驻 section 带上工作树事实与项目路径隔离要求', () => {
+ bind('session-a')
+ const text = worktreeSectionProvider.text(scope('session-a'))
+ expect(text).toContain('is_worktree: true')
+ expect(text).toContain('Worktree key: abc123def456/repo')
+ expect(text).toContain('Worktree path: C:/Users/me/.dsh/worktrees/abc123def456/repo')
+ expect(text).toContain('Project path: D:/projects/repo')
+ expect(text).toContain('do not read from or modify it in this session')
+ })
+
+ it('动态快照与常驻 section 使用同一组事实,兜住被压缩遮蔽的常驻 section', () => {
+ bind('session-a')
+ const context = worktreeContextProvider.text(scope('session-a'))
+ expect(context).toContain('is_worktree: true')
+ expect(context).toContain('Worktree key: abc123def456/repo')
+ expect(context).toContain('Worktree path: C:/Users/me/.dsh/worktrees/abc123def456/repo')
+ expect(context).toContain('Project path: D:/projects/repo')
+ expect(worktreeSectionProvider.text(scope('session-a'))).toContain(context.split('\n\n')[0])
+ })
+
+ it('无绑定时两条通道都注入空串,不污染提示词', () => {
+ expect(worktreeSectionProvider.text(scope('session-missing'))).toBe('')
+ expect(worktreeContextProvider.text(scope('session-missing'))).toBe('')
+ expect(worktreeContextProvider.text({})).toBe('')
+ expect(worktreeSectionProvider.text({ scope: { session: { id: 42 } } })).toBe('')
+ })
+
+ it('两个 provider 的 name 互不相同,避免同一作用域重复注册', () => {
+ expect(worktreeContextProvider.name).not.toBe(worktreeSectionProvider.name)
+ expect(worktreeContextProvider.name).not.toBe(checkoutContextProvider.name)
+ })
+})
diff --git a/packages/dsh-tauri-worktree/src/host/prompts/worktree-context.ts b/packages/dsh-tauri-worktree/src/host/prompts/worktree-context.ts
new file mode 100644
index 00000000..8982e5e8
--- /dev/null
+++ b/packages/dsh-tauri-worktree/src/host/prompts/worktree-context.ts
@@ -0,0 +1,18 @@
+import { get, isString } from 'lodash-es'
+import { WORKTREE_SECTION_ORDER } from '../../shared/constants'
+import { ledger } from '../service/ledger'
+import { worktreeContextText } from '../utils/worktree-facts'
+
+export const worktreeContextProvider = {
+ name: 'plugin:dsh-tauri-worktree:worktree',
+ order: WORKTREE_SECTION_ORDER,
+ text(context: any): string {
+ const sessionId = get(context, 'scope.session.id')
+ if (!isString(sessionId))
+ return ''
+ const binding = ledger.load(sessionId)
+ if (!binding)
+ return ''
+ return worktreeContextText(binding)
+ },
+}
diff --git a/packages/dsh-tauri-worktree/src/host/prompts/worktree-section.ts b/packages/dsh-tauri-worktree/src/host/prompts/worktree-section.ts
index a225a1ca..ba59ccb4 100644
--- a/packages/dsh-tauri-worktree/src/host/prompts/worktree-section.ts
+++ b/packages/dsh-tauri-worktree/src/host/prompts/worktree-section.ts
@@ -1,6 +1,7 @@
import { get, isString } from 'lodash-es'
import { WORKTREE_SECTION_ORDER } from '../../shared/constants'
import { ledger } from '../service/ledger'
+import { worktreeSectionText } from '../utils/worktree-facts'
export const worktreeSectionProvider = {
name: 'plugin:dsh-tauri-worktree',
@@ -12,19 +13,6 @@ export const worktreeSectionProvider = {
const binding = ledger.load(sessionId)
if (!binding)
return ''
- return (
- `This session is running in an isolated worktree.\n`
- + `is_worktree: true\n`
- + `Worktree key: ${binding.hash}/${binding.dirname}\n`
- + `Worktree path: ${binding.worktreePath}\n`
- + `Project path: ${binding.projectPath}\n\n`
- + `Make code changes inside the bound worktree and use its path as the shell workdir. `
- + `Dependency directories (e.g. node_modules) are linked from the source repository so the worktree works out of the box. `
- + `Running a package manager install (e.g. \`pnpm install\`) inside the worktree first detaches that link and materializes an independent copy, `
- + `leaving the source repository untouched. `
- + `checkout_worktree is user-authorized only: call it only after a direct human user explicitly requests or approves checkout. `
- + `Task completion, a merged PR, or inferred convenience is not permission to call it. When checkout would be a natural next step, `
- + `such as after a PR is merged, you may ask the user whether they want to check out the worktree; wait for their approval before calling.`
- )
+ return worktreeSectionText(binding)
},
}
diff --git a/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts b/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts
index 27abaaf3..e69921d6 100644
--- a/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts
+++ b/packages/dsh-tauri-worktree/src/host/service/handoff.test.ts
@@ -128,5 +128,11 @@ describe('handoff.complete', () => {
},
})
expect(followup).toHaveBeenCalledTimes(1)
+ const followupMessage = followup.mock.calls[0][0]
+ const text = followupMessage.content.map((block: any) => block.text).join('')
+ expect(text).toContain('is_worktree: true')
+ expect(text).toContain('Worktree path: C:/worktrees/w1')
+ expect(text).toContain('Project path: C:/project')
+ expect(text).toContain('The task has moved to this isolated worktree session.')
})
})
diff --git a/packages/dsh-tauri-worktree/src/host/service/handoff.ts b/packages/dsh-tauri-worktree/src/host/service/handoff.ts
index 4f13edaa..a440e4a6 100644
--- a/packages/dsh-tauri-worktree/src/host/service/handoff.ts
+++ b/packages/dsh-tauri-worktree/src/host/service/handoff.ts
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto'
import { defineService } from 'dsh-tauri'
import { get } from 'lodash-es'
import { getCurrentHostInstance } from '../config/runtime'
+import { worktreeHandoffText } from '../utils/worktree-facts'
import { checkoutContext } from './checkout-context'
import { sessionContext } from './session-context'
import { worktree } from './worktree'
@@ -102,7 +103,7 @@ export const handoff = defineService({
role: 'user',
content: [{
type: 'text',
- text: 'The task has moved to an isolated worktree session. Continue the user request from the inherited context without explaining the handoff again.',
+ text: worktreeHandoffText(binding),
}],
source: { kind: 'user' },
})
diff --git a/packages/dsh-tauri-worktree/src/host/service/worktree.test.ts b/packages/dsh-tauri-worktree/src/host/service/worktree.test.ts
index 2e7ade70..e90e3e0f 100644
--- a/packages/dsh-tauri-worktree/src/host/service/worktree.test.ts
+++ b/packages/dsh-tauri-worktree/src/host/service/worktree.test.ts
@@ -1,6 +1,6 @@
import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
-import { existsSync, lstatSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, join } from 'pathe'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -398,4 +398,83 @@ describe('依赖链接', () => {
expect(existsSync(join(created.binding.worktreePath, 'node_modules'))).toBe(false)
expect(created.binding.linkedDependencies).toBeUndefined()
})
+
+ it('无条件链接 .agents,即使关闭依赖链接', async () => {
+ const repository = createRepository()
+ mkdirSync(join(repository, '.agents', 'skills', 'handle'), { recursive: true })
+ writeFileSync(join(repository, '.agents', 'skills', 'handle', 'SKILL.md'), '# handle\n')
+ const sessionId = 'skills-session'
+
+ const created = await worktree.create(repository, sessionId, { linkDependencies: false })
+ expect(created.ok).toBe(true)
+ if (!created.ok)
+ return
+
+ const link = join(created.binding.worktreePath, '.agents')
+ expect(lstatSync(link).isSymbolicLink()).toBe(true)
+ expect(readFileSync(join(link, 'skills', 'handle', 'SKILL.md'), 'utf8')).toBe('# handle\n')
+ expect(existsSync(join(created.binding.worktreePath, 'node_modules'))).toBe(false)
+
+ const removed = await worktree.remove(sessionId)
+ expect(removed.ok).toBe(true)
+ expect(existsSync(link)).toBe(false)
+ expect(readFileSync(join(repository, '.agents', 'skills', 'handle', 'SKILL.md'), 'utf8')).toBe('# handle\n')
+ })
+
+ it('源仓库没有 .agents 时创建工作树照常成功', async () => {
+ const repository = createRepository()
+ const sessionId = 'no-skills-session'
+
+ const created = await worktree.create(repository, sessionId)
+ expect(created.ok).toBe(true)
+ if (!created.ok)
+ return
+
+ expect(existsSync(join(created.binding.worktreePath, '.agents'))).toBe(false)
+ })
+
+ it('源仓库忽略 .agents 时,链接不弄脏工作树状态', async () => {
+ const repository = createRepository()
+ mkdirSync(join(repository, '.agents', 'skills', 'handle'), { recursive: true })
+ writeFileSync(join(repository, '.agents', 'skills', 'handle', 'SKILL.md'), '# handle\n')
+ writeFileSync(join(repository, '.gitignore'), '.agents/skills/\n')
+ git(repository, 'add', '.gitignore')
+ git(repository, 'commit', '-m', 'ignore skills')
+ const sessionId = 'ignored-skills-session'
+
+ const created = await worktree.create(repository, sessionId)
+ expect(created.ok).toBe(true)
+ if (!created.ok)
+ return
+
+ expect(git(created.binding.worktreePath, 'status', '--porcelain=v1')).toBe('')
+ expect(lstatSync(join(created.binding.worktreePath, '.agents')).isSymbolicLink()).toBe(true)
+ })
+
+ it('部分内容已跟踪时,补齐被忽略的 .agents/skills 子目录', async () => {
+ const repository = createRepository()
+ mkdirSync(join(repository, '.agents', 'skills', 'handle'), { recursive: true })
+ writeFileSync(join(repository, '.agents', 'config.json'), '{}\n')
+ writeFileSync(join(repository, '.agents', 'skills', 'handle', 'SKILL.md'), '# handle\n')
+ writeFileSync(join(repository, '.gitignore'), '.agents/skills/\n')
+ git(repository, 'add', '.gitignore', '.agents/config.json')
+ git(repository, 'commit', '-m', 'track agents config')
+ const sessionId = 'partial-skills-session'
+
+ const created = await worktree.create(repository, sessionId)
+ expect(created.ok).toBe(true)
+ if (!created.ok)
+ return
+
+ const skills = join(created.binding.worktreePath, '.agents', 'skills')
+ expect(lstatSync(skills).isSymbolicLink()).toBe(true)
+ expect(readFileSync(join(skills, 'handle', 'SKILL.md'), 'utf8')).toBe('# handle\n')
+ // `.agents` 本身必须是工作树里的真实目录,链接子项不能破坏被跟踪的 config.json
+ expect(lstatSync(join(created.binding.worktreePath, '.agents')).isSymbolicLink()).toBe(false)
+ expect(readFileSync(join(created.binding.worktreePath, '.agents', 'config.json'), 'utf8').trim()).toBe('{}')
+
+ const removed = await worktree.remove(sessionId)
+ expect(removed.ok).toBe(true)
+ expect(readFileSync(join(repository, '.agents', 'skills', 'handle', 'SKILL.md'), 'utf8')).toBe('# handle\n')
+ })
})
diff --git a/packages/dsh-tauri-worktree/src/host/service/worktree.ts b/packages/dsh-tauri-worktree/src/host/service/worktree.ts
index 960f7f89..ad1cc3c6 100644
--- a/packages/dsh-tauri-worktree/src/host/service/worktree.ts
+++ b/packages/dsh-tauri-worktree/src/host/service/worktree.ts
@@ -15,6 +15,7 @@ import { TRASH_DIR, WORKTREES_DIR } from '../config/constants'
import { getCurrentHostInstance } from '../config/runtime'
import {
isDependencyInstallCommand,
+ linkMissingChildren,
linkWorktreeDependencies,
normalizeLinkDirectories,
shellCommandFrom,
@@ -44,6 +45,10 @@ import { workspace } from './workspace'
const WORKTREE_BRANCH_NAME_PATTERN = /^[\w./-]+$/
+// 技能目录不进 git 索引(.agents/skills 被 gitignore),`git worktree add` 永远搬不过来;
+// 不链接它,继承会话就读不到初始会话的项目级技能,因此这条链接与依赖开关无关。
+const AGENT_SKILLS_DIRECTORY = '.agents'
+
const LINK_DEPENDENCIES = true
const SWEEP_MIN_AGE_MS = 60_000
@@ -72,8 +77,16 @@ export const worktree = defineService({
const registration = await isRegisteredWorktree(root, path, options.signal)
if (!registration.ok)
return { ok: false, error: `检查工作树残留状态失败:${registration.error}` }
- if (registration.registered)
- return { ok: true, binding: existing, existed: true, log: [] }
+ if (registration.registered) {
+ // 旧版本创建的工作树没有这条链接,重复创建时补齐,让继承会话能读到项目级技能
+ const repairedLog: string[] = []
+ await linkAgentSkills(root, path, repairedLog)
+ if (repairedLog.length === 0)
+ return { ok: true, binding: existing, existed: true, log: [] }
+ const repaired: Binding = { ...existing, log: [...existing.log, ...repairedLog] }
+ await ledger.save(sessionId, repaired)
+ return { ok: true, binding: repaired, existed: true, log: [] }
+ }
}
const mainSource = 'refs/heads/main'
@@ -142,6 +155,8 @@ export const worktree = defineService({
log.push(`HEAD is now at ${await shortHead(path)} ${await headSubject(path)}`)
log.push(`Worktree created at ${path}`)
+ await linkAgentSkills(root, path, log)
+
const linkedDependencies: string[] = []
if (linkDependencies) {
try {
@@ -466,6 +481,35 @@ async function pruneWorktreeAdmin(root: string, signal?: AbortSignal): Promise<O
return pruned.ok ? { ok: true } : { ok: false, error: pruned.error }
}
+/**
+ * 把源仓库的 `.agents` 链接进工作树:技能目录被 gitignore,`git worktree add` 不会带过来,
+ * 不补这条链接,继承会话就读不到初始会话的项目级技能。源仓库没有 `.agents` 时静默返回。
+ */
+async function linkAgentSkills(root: string, path: string, log: string[]): Promise<void> {
+ const source = join(root, AGENT_SKILLS_DIRECTORY)
+ if (!existsSync(source))
+ return
+ try {
+ const linked = await linkWorktreeDependencies(root, path, [AGENT_SKILLS_DIRECTORY])
+ if (linked.linked.length > 0) {
+ log.push(`Linked the agent skills directory from the source repository (${AGENT_SKILLS_DIRECTORY})`)
+ return
+ }
+ if (linked.skipped.includes(AGENT_SKILLS_DIRECTORY)) {
+ // `.agents` 已在工作树里(部分内容被提交进索引)时无法整体链接,
+ // 改为补齐被 gitignore 掉、worktree add 搬不过来的子目录(如 skills)。
+ const children = await linkMissingChildren(source, join(path, AGENT_SKILLS_DIRECTORY))
+ if (children.length > 0)
+ log.push(`Linked the missing agent directories from the source repository (${children.join(', ')})`)
+ return
+ }
+ log.push('Agent skills directory link skipped')
+ }
+ catch (error) {
+ log.push(`Agent skills directory link skipped: ${get(error, 'message', String(error))}`)
+ }
+}
+
function samePath(a: string, b: string): boolean {
const left = resolve(a)
const right = resolve(b)
@@ -534,8 +578,8 @@ async function removeWorktreeOnDisk(
function removalLinkDirectories(binding: Binding | null, configured?: readonly string[]): string[] {
const configuredDirectories = normalizeLinkDirectories(configured)
if (!binding || isEmpty(binding.linkedDependencies))
- return configuredDirectories
- return normalizeLinkDirectories([...binding.linkedDependencies ?? [], ...configuredDirectories])
+ return normalizeLinkDirectories([AGENT_SKILLS_DIRECTORY, ...configuredDirectories])
+ return normalizeLinkDirectories([AGENT_SKILLS_DIRECTORY, ...binding.linkedDependencies ?? [], ...configuredDirectories])
}
async function deleteOwnedBranch(root: string, branch: string, signal?: AbortSignal): Promise<OperationResult> {
diff --git a/packages/dsh-tauri-worktree/src/host/utils/dependencies.test.ts b/packages/dsh-tauri-worktree/src/host/utils/dependencies.test.ts
index 65b17dfc..34dcec3a 100644
--- a/packages/dsh-tauri-worktree/src/host/utils/dependencies.test.ts
+++ b/packages/dsh-tauri-worktree/src/host/utils/dependencies.test.ts
@@ -26,6 +26,15 @@ async function createFixture(): Promise<{ project: string, worktree: string, mar
return { project, worktree, marker }
}
+async function createSkillsFixture(): Promise<{ project: string, worktree: string, skill: string }> {
+ const project = await temporaryRoot('dsh-deps-project-')
+ const worktree = await temporaryRoot('dsh-deps-worktree-')
+ const skill = join(project, '.agents', 'skills', 'handle', 'SKILL.md')
+ await mkdir(join(project, '.agents', 'skills', 'handle'), { recursive: true })
+ await writeFile(skill, '# handle\n')
+ return { project, worktree, skill }
+}
+
afterEach(async () => {
await Promise.all(temporaryDirectories.splice(0).map(path => rm(path, { recursive: true, force: true })))
})
@@ -113,6 +122,16 @@ describe('unlinkWorktreeDependencies', () => {
expect(await readFile(marker, 'utf8')).toBe('shared-dependency\n')
})
+ it('unlinks the agent skills link without touching the source skills tree', async () => {
+ const { project, worktree, skill } = await createSkillsFixture()
+ await expect(linkWorktreeDependencies(project, worktree, ['.agents'])).resolves.toEqual({ linked: ['.agents'], skipped: [] })
+ expect(await readFile(join(worktree, '.agents', 'skills', 'handle', 'SKILL.md'), 'utf8')).toBe('# handle\n')
+
+ await expect(unlinkWorktreeDependencies(worktree, ['.agents'])).resolves.toEqual(['.agents'])
+ await expect(lstat(join(worktree, '.agents'))).rejects.toMatchObject({ code: 'ENOENT' })
+ expect(await readFile(skill, 'utf8')).toBe('# handle\n')
+ })
+
it('leaves a real (independently installed) directory untouched', async () => {
const worktree = await temporaryRoot('dsh-deps-worktree-')
const installed = join(worktree, 'node_modules', 'pkg')
diff --git a/packages/dsh-tauri-worktree/src/host/utils/dependencies.ts b/packages/dsh-tauri-worktree/src/host/utils/dependencies.ts
index d402c0c6..f8c4cbaf 100644
--- a/packages/dsh-tauri-worktree/src/host/utils/dependencies.ts
+++ b/packages/dsh-tauri-worktree/src/host/utils/dependencies.ts
@@ -3,6 +3,7 @@ import { lstat, rm, symlink } from 'node:fs/promises'
import process from 'node:process'
import { filter, find, get, isEmpty, isString, map, trimEnd, uniqBy } from 'lodash-es'
import { resolve } from 'pathe'
+import { listDirectoryNames } from './filesystem'
const DEFAULT_LINK_DIRECTORIES: readonly string[] = ['node_modules']
@@ -107,8 +108,39 @@ export async function unlinkWorktreeDependencies(
return unlinked
}
+/**
+ * 把源目录里缺失的子项逐条链接进目标目录。用于目标目录已存在(源仓库把 `.agents` 的一部分
+ * 提交进了索引)而技能等子目录被 gitignore、`git worktree add` 搬不过来的情况。
+ */
+export async function linkMissingChildren(sourceDirectory: string, targetDirectory: string): Promise<string[]> {
+ if (!existsSync(sourceDirectory) || !existsSync(targetDirectory) || await isSymbolicLink(targetDirectory))
+ return []
+ const linked: string[] = []
+ for (const name of listDirectoryNames(sourceDirectory)) {
+ const source = resolve(sourceDirectory, name)
+ const target = resolve(targetDirectory, name)
+ if (!existsSync(source) || await pathExists(target))
+ continue
+ try {
+ await symlink(source, target, process.platform === 'win32' ? 'junction' : 'dir')
+ linked.push(name)
+ }
+ catch {}
+ }
+ return linked
+}
+
// --- internal ---
+async function isSymbolicLink(path: string): Promise<boolean> {
+ try {
+ return (await lstat(path)).isSymbolicLink()
+ }
+ catch {
+ return false
+ }
+}
+
async function pathExists(path: string): Promise<boolean> {
try {
await lstat(path)
diff --git a/packages/dsh-tauri-worktree/src/host/utils/worktree-facts.ts b/packages/dsh-tauri-worktree/src/host/utils/worktree-facts.ts
new file mode 100644
index 00000000..95cb915e
--- /dev/null
+++ b/packages/dsh-tauri-worktree/src/host/utils/worktree-facts.ts
@@ -0,0 +1,48 @@
+import type { Binding } from '../types'
+
+/** 工作树事实的公共措辞:常驻 section 与动态快照共用,避免两处漂移。 */
+export function worktreeFactsText(binding: Binding): string {
+ const lines = [
+ 'This session is running in an isolated worktree.',
+ 'is_worktree: true',
+ binding.hash && binding.dirname ? `Worktree key: ${binding.hash}/${binding.dirname}` : '',
+ binding.worktreePath ? `Worktree path: ${binding.worktreePath}` : '',
+ binding.projectPath ? `Project path: ${binding.projectPath}` : '',
+ ]
+ return lines.filter(Boolean).join('\n')
+}
+
+export function worktreeSectionText(binding: Binding): string {
+ return (
+ `${worktreeFactsText(binding)}\n\n`
+ + `Resolve every path inside the worktree path. The project path is a different checkout: `
+ + `do not read from or modify it in this session, even when the inherited history refers to it. `
+ + `Dependency directories (e.g. node_modules) are linked from the source repository so the worktree works out of the box. `
+ + `Running a package manager install (e.g. \`pnpm install\`) inside the worktree first detaches that link and materializes an independent copy, `
+ + `leaving the source repository untouched. `
+ + `checkout_worktree is user-authorized only: call it only after a direct human user explicitly requests or approves checkout. `
+ + `Task completion, a merged PR, or inferred convenience is not permission to call it. When checkout would be a natural next step, `
+ + `such as after a PR is merged, you may ask the user whether they want to check out the worktree; wait for their approval before calling.`
+ )
+}
+
+/**
+ * 动态快照措辞:常驻 section 会被压缩遮蔽(`SystemPromptProjection` 在
+ * `!inHistory || startsSeries` 时清空非头节点),而运行期上下文快照是持久消息,
+ * 在同样的压缩下仍在面上,因此这条通道兜住「会话已经不知道自己在工作树里」。
+ */
+export function worktreeContextText(binding: Binding): string {
+ return (
+ `${worktreeFactsText(binding)}\n\n`
+ + `Continue this session inside the worktree path. The project path is a different checkout: `
+ + `do not read from or modify it here, even when the inherited history refers to it.`
+ )
+}
+
+export function worktreeHandoffText(binding: Binding): string {
+ return (
+ `${worktreeFactsText(binding)}\n\n`
+ + `The task has moved to this isolated worktree session. `
+ + `Continue the user request from the inherited context without explaining the handoff again.`
+ )
+}