Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(daemon): keep tracked runtime briefs out of agent commits (#10787)

leilei3167670082cffe0b
diff --git a/apps/docs/content/docs/project-resources.fr.mdx b/apps/docs/content/docs/project-resources.fr.mdx
index c4f3a26eb0..97d22b4579 100644
--- a/apps/docs/content/docs/project-resources.fr.mdx
+++ b/apps/docs/content/docs/project-resources.fr.mdx
@@ -156,6 +156,8 @@ Une exécution qui n'a pas pu enregistrer sa branche, par exemple parce qu'elle
</Accordion>
<Accordion title="Rien n'est perdu en silence" id="nothing-is-silently-lost">
+Pendant une exécution en worktree, un fichier d'instructions du runtime suivi par Git, comme `CLAUDE.md` ou `AGENTS.md`, est marqué `skip-worktree` dans l'index privé de la tâche. Le brief injecté reste ainsi hors des commits de l'agent, sans modifier votre checkout. Les modifications intentionnelles de ce fichier restent non commitées jusqu'au rétablissement du suivi lors du nettoyage, puis suivent les règles de livraison ci-dessous. Les fichiers du runtime non suivis et les répertoires de compétences doivent toujours être exclus des commits de l'agent.
+
Rien de ce que l'agent laisse non commité n'est supprimé avec le worktree, y compris lorsque l'exécution échoue en cours de route. Sa destination dépend de ce que l'agent a fait pendant l'exécution :
- **L'agent n'a fait aucun commit :** tout ce qu'il a laissé et qui n'est pas ignoré par git est commité sur la branche. Les hooks de commit de votre dépôt ne s'exécutent pas pour ce commit.
diff --git a/apps/docs/content/docs/project-resources.ja.mdx b/apps/docs/content/docs/project-resources.ja.mdx
index 4273964813..c10e32b795 100644
--- a/apps/docs/content/docs/project-resources.ja.mdx
+++ b/apps/docs/content/docs/project-resources.ja.mdx
@@ -158,6 +158,8 @@ git 管理外の通常のディレクトリはこのモードしか使えませ
</Accordion>
<Accordion title="黙って失われるものはない" id="nothing-is-silently-lost">
+ワークツリーでの実行中、追跡対象のランタイム指示ファイル(`CLAUDE.md` や `AGENTS.md` など)はタスク専用のインデックスで `skip-worktree` に設定されます。これにより、ユーザーのチェックアウトを変更せず、注入したブリーフがエージェントのコミットに含まれるのを防ぎます。このファイルへの意図的な編集は、クリーンアップで通常の追跡が復元されるまで未コミットのまま残り、以下の配信ルールに従います。未追跡のランタイムファイルやスキルディレクトリは、引き続きエージェントのコミットから除外する必要があります。
+
エージェントが未コミットのまま残した変更は、ワークツリーと一緒に削除されることはありません。実行が途中で失敗した場合も同様です。行き先は、エージェントがその実行中に自分でコミットしたかどうかで決まります。
- **エージェントがコミットしなかった場合:** gitignore されていないファイルはすべてブランチにコミットされます。このコミットではリポジトリのコミットフックは実行されません。
diff --git a/apps/docs/content/docs/project-resources.ko.mdx b/apps/docs/content/docs/project-resources.ko.mdx
index 84f8817fa5..9f2b9cb64b 100644
--- a/apps/docs/content/docs/project-resources.ko.mdx
+++ b/apps/docs/content/docs/project-resources.ko.mdx
@@ -156,6 +156,8 @@ git으로 관리되지 않는 일반 디렉터리는 이 모드만 사용할 수
</Accordion>
<Accordion title="조용히 사라지는 것은 없습니다" id="nothing-is-silently-lost">
+워크트리 실행 중에는 추적 중인 런타임 지침 파일(예: `CLAUDE.md`, `AGENTS.md`)을 작업 전용 인덱스에서 `skip-worktree`로 표시합니다. 사용자 체크아웃을 변경하지 않고 주입된 브리프가 에이전트 커밋에 포함되는 것을 막습니다. 이 파일에 대한 의도적인 수정은 정리 단계에서 일반 추적을 복원할 때까지 커밋되지 않은 상태로 남으며 아래 전달 규칙을 따릅니다. 추적되지 않는 런타임 파일과 스킬 디렉터리는 여전히 에이전트 커밋에서 제외해야 합니다.
+
에이전트가 커밋하지 않고 남긴 변경 사항은 워크트리와 함께 삭제되지 않으며, 실행이 도중에 실패한 경우에도 마찬가지입니다. 어디로 가는지는 에이전트가 그 실행 중에 직접 커밋했는지에 따라 달라집니다.
- **에이전트가 커밋하지 않은 경우:** gitignore되지 않은 파일은 모두 브랜치에 커밋됩니다. 이 커밋에서는 저장소의 커밋 훅이 실행되지 않습니다.
diff --git a/apps/docs/content/docs/project-resources.mdx b/apps/docs/content/docs/project-resources.mdx
index 8136c09e3e..0757b678c6 100644
--- a/apps/docs/content/docs/project-resources.mdx
+++ b/apps/docs/content/docs/project-resources.mdx
@@ -156,6 +156,8 @@ A run that could not record its branch — it failed before finishing, the recor
</Accordion>
<Accordion title="Nothing is silently dropped" id="nothing-is-silently-lost">
+During a worktree run, a tracked runtime instruction file such as `CLAUDE.md` or `AGENTS.md` is marked `skip-worktree` in the task's private index. This keeps the injected brief out of the agent's commits without changing your checkout. Intentional edits to that file remain uncommitted until cleanup restores normal tracking: they follow the delivery rules below. Untracked runtime files and skill directories still need to be excluded from the agent's commits.
+
Nothing the agent leaves uncommitted is deleted with the worktree, including when the run fails partway. Where it goes depends on whether the agent committed during the run:
- **The agent made no commit:** everything it left that is not gitignored is committed to the branch. Your repository's commit hooks do not run for this commit.
diff --git a/apps/docs/content/docs/project-resources.zh-Hant.mdx b/apps/docs/content/docs/project-resources.zh-Hant.mdx
index 88878adfd1..dcae27e7ce 100644
--- a/apps/docs/content/docs/project-resources.zh-Hant.mdx
+++ b/apps/docs/content/docs/project-resources.zh-Hant.mdx
@@ -157,6 +157,8 @@ AI 代理看到什麼、你拿回什麼:
</Accordion>
<Accordion title="不會靜默丟東西" id="nothing-is-silently-lost">
+在 worktree 執行期間,受追蹤的執行時指令檔(如 `CLAUDE.md` 或 `AGENTS.md`)會在任務獨立的索引中標記為 `skip-worktree`,避免注入的簡報進入代理的提交,不影響你的 checkout。對該檔案的正常修改會保持未提交狀態,直到清理階段恢復追蹤,再依下列規則交付。未追蹤的執行時檔案和技能目錄仍需從代理的提交中排除。
+
AI 代理留下的未提交改動不會隨 worktree 一起刪除,執行中途失敗時同樣如此。它們去哪裡,取決於 AI 代理這次執行有沒有自己提交:
- **AI 代理沒有提交過:** 所有沒被 gitignore 的檔案都會提交到分支上。這次提交不會執行倉庫的提交鉤子。
diff --git a/apps/docs/content/docs/project-resources.zh.mdx b/apps/docs/content/docs/project-resources.zh.mdx
index e69eb94b32..85bdf81f02 100644
--- a/apps/docs/content/docs/project-resources.zh.mdx
+++ b/apps/docs/content/docs/project-resources.zh.mdx
@@ -157,6 +157,8 @@ import { LocalDirModeDemo } from "@/components/demos/local-dir-mode-demo";
</Accordion>
<Accordion title="不会静默丢东西" id="nothing-is-silently-lost">
+在 worktree 运行期间,受跟踪的运行时指令文件(如 `CLAUDE.md` 或 `AGENTS.md`)会在任务独立的索引中标记为 `skip-worktree`,防止注入的简报进入智能体的提交,不影响你的 checkout。对该文件的正常修改会保持未提交状态,直到清理阶段恢复跟踪,再按下面的规则交付。未跟踪的运行时文件和技能目录仍需从智能体的提交中排除。
+
智能体留下的未提交改动不会随 worktree 一起删除,运行中途失败时同样如此。它们去哪里,取决于智能体这次运行有没有自己提交:
- **智能体没有提交过:** 所有没被 gitignore 的文件都会提交到分支上。这次提交不会运行仓库的提交钩子。
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 4c0a4f5e5b..e0e0a2dc1b 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -8885,6 +8885,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// in place, leave them behind in the user's tree.
if env.LocalDirectory || env.LocalWorktree != nil {
defer func() {
+ if err := env.LocalWorktree.RestoreRuntimeConfigTracking(); err != nil {
+ env.LocalWorktree.AbortWithReason(err)
+ d.logger.Warn("execenv: restore runtime config tracking failed", "error", err)
+ return
+ }
if taskResult.FailureReason == taskfailure.ReasonProcessCleanupUnconfirmed.String() {
return // Preserve files that an unconfirmed process may still use.
}
@@ -9022,6 +9027,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
if err != nil {
d.logger.Warn("execenv: inject runtime config failed (non-fatal)", "error", err)
}
+ if env.LocalWorktree != nil {
+ if err := env.LocalWorktree.ProtectRuntimeConfig(provider); err != nil {
+ return TaskResult{}, fmt.Errorf("protect worktree runtime config: %w", err)
+ }
+ }
// An exempt turn runs in the user's directory without having queued for it,
// so a sibling coding task may be writing to the same tree right now. That
// is the one thing it cannot work out from its own context — tell it.
diff --git a/server/internal/daemon/execenv/local_worktree.go b/server/internal/daemon/execenv/local_worktree.go
index 03ac609083..ea09a49329 100644
--- a/server/internal/daemon/execenv/local_worktree.go
+++ b/server/internal/daemon/execenv/local_worktree.go
@@ -162,6 +162,10 @@ type LocalWorktree struct {
// WorkDir is the agent's cwd: Path, plus the offset of LocalPath inside
// the repo when the user pointed the resource at a subdirectory.
WorkDir string
+ // RuntimeConfigSkipWorktree is the tracked instruction file hidden from
+ // agent commits in this worktree's private index. Exported so it survives
+ // environment serialization and can always be restored during teardown.
+ RuntimeConfigSkipWorktree string `json:"runtime_config_skip_worktree,omitempty"`
// Branch is the branch created for this task, in the user's repo.
Branch string
// BaseCommit is the commit the worktree started from — this turn's baseline
@@ -516,8 +520,8 @@ func PrepareLocalWorktree(params LocalWorktreeParams, logger *slog.Logger) (*Loc
// status` shows in the user's checkout, which is theirs, not ours. Instead
// the daemon runs the existing CleanupRuntimeConfig + CleanupSidecars pass
// over the worktree before Finalize, so the sidecars are simply gone by the
- // time anything is committed. That also preserves a genuine agent edit to a
- // tracked CLAUDE.md, which a blanket exclude would have swallowed.
+ // time the daemon commits. ProtectRuntimeConfig separately hides tracked
+ // instruction files from commits the agent makes while the brief is present.
if logger != nil {
logger.Info("execenv: local worktree ready",
@@ -565,6 +569,12 @@ func (w *LocalWorktree) Finalize(logger *slog.Logger) (LocalWorktreeOutcome, err
return LocalWorktreeOutcome{}, nil
}
outcome := LocalWorktreeOutcome{Branch: w.Branch}
+ if err := w.RestoreRuntimeConfigTracking(); err != nil {
+ outcome.Branch = ""
+ outcome.PreservedPath = w.Path
+ return outcome, fmt.Errorf("%w; the work is preserved in the worktree at %s (listed by `git worktree list` in %s)",
+ err, w.Path, w.GitRoot)
+ }
unlock, err := lockGitRoot(w.GitRoot, logger)
if err != nil {
@@ -774,6 +784,12 @@ func (w *LocalWorktree) Discard(logger *slog.Logger) {
if w == nil {
return
}
+ if err := w.RestoreRuntimeConfigTracking(); err != nil {
+ if logger != nil {
+ logger.Warn("execenv: could not restore runtime config tracking before discarding worktree", "error", err)
+ }
+ return
+ }
unlock, err := lockGitRoot(w.GitRoot, logger)
if err != nil {
// Best-effort by contract: every step below only logs on failure. The
diff --git a/server/internal/daemon/execenv/local_worktree_runtime.go b/server/internal/daemon/execenv/local_worktree_runtime.go
new file mode 100644
index 0000000000..2f92fda421
--- /dev/null
+++ b/server/internal/daemon/execenv/local_worktree_runtime.go
@@ -0,0 +1,64 @@
+package execenv
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// ProtectRuntimeConfig keeps an injected brief out of commits made during the
+// run. A linked worktree has its own index, so skip-worktree does not affect
+// the user's checkout or require shared git configuration changes.
+func (w *LocalWorktree) ProtectRuntimeConfig(provider string) error {
+ if w == nil || w.RuntimeConfigSkipWorktree != "" {
+ return nil
+ }
+ path := runtimeConfigPath(w.WorkDir, provider)
+ if path == "" {
+ return nil
+ }
+ // Injection follows symlinks, so protect the file that received the brief.
+ path, err := filepath.EvalSymlinks(path)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("execenv: resolve runtime config: %w", err)
+ }
+ root, err := filepath.EvalSymlinks(w.Path)
+ if err != nil {
+ return fmt.Errorf("execenv: resolve worktree %q: %w", w.Path, err)
+ }
+ rel, err := filepath.Rel(root, path)
+ if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
+ return nil // External targets do not belong to this worktree's index.
+ }
+ rel = filepath.ToSlash(rel)
+ tracked, err := runGit(w.Path, "ls-files", "-z", "--", ":(literal)"+rel)
+ if err != nil {
+ return fmt.Errorf("execenv: inspect tracked runtime config %q: %w", rel, err)
+ }
+ if tracked == "" {
+ return nil
+ }
+ if _, err := runGit(w.Path, "update-index", "--skip-worktree", "--", rel); err != nil {
+ return fmt.Errorf("execenv: protect runtime config %q from agent commits: %w", rel, err)
+ }
+ w.RuntimeConfigSkipWorktree = rel
+ return nil
+}
+
+// RestoreRuntimeConfigTracking must run before brief cleanup and finalization
+// so genuine instruction-file edits remain visible to the delivery policy.
+func (w *LocalWorktree) RestoreRuntimeConfigTracking() error {
+ if w == nil || w.RuntimeConfigSkipWorktree == "" {
+ return nil
+ }
+ if _, err := runGit(w.Path, "update-index", "--no-skip-worktree", "--", w.RuntimeConfigSkipWorktree); err != nil {
+ return fmt.Errorf("execenv: restore runtime config tracking for %q: %w", w.RuntimeConfigSkipWorktree, err)
+ }
+ w.RuntimeConfigSkipWorktree = ""
+ return nil
+}
diff --git a/server/internal/daemon/execenv/local_worktree_runtime_test.go b/server/internal/daemon/execenv/local_worktree_runtime_test.go
new file mode 100644
index 0000000000..fcbd5acc5e
--- /dev/null
+++ b/server/internal/daemon/execenv/local_worktree_runtime_test.go
@@ -0,0 +1,345 @@
+package execenv
+
+import (
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestWorktreeRuntimeBriefStaysOutOfAgentCommits(t *testing.T) {
+ for _, tc := range []struct{ provider, target string }{
+ {"claude", "CLAUDE.md"}, {"codex", "AGENTS.md"},
+ {"claude", "AGENTS.md"}, {"codex", "CLAUDE.md"},
+ } {
+ provider := tc.provider
+ for _, subdir := range []string{".", "docs [guide]"} {
+ t.Run(provider+"/"+tc.target+"/"+subdir, func(t *testing.T) {
+ repo := newTestRepo(t)
+ localDir := filepath.Join(repo, subdir)
+ if err := os.MkdirAll(localDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ path := runtimeConfigPath(localDir, provider)
+ target := filepath.Join(localDir, tc.target)
+ original := "Repository instructions.\n"
+ if err := os.WriteFile(target, []byte(original), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if path != target {
+ if err := os.Symlink(tc.target, path); err != nil {
+ t.Fatal(err)
+ }
+ }
+ gitRun(t, repo, "add", ".")
+ gitRun(t, repo, "commit", "-m", "add instructions")
+ wt := prepareForTest(t, localDir)
+ if _, err := InjectRuntimeConfig(wt.WorkDir, provider, TaskContextForEnv{}); err != nil {
+ t.Fatal(err)
+ }
+ if err := wt.ProtectRuntimeConfig(provider); err != nil {
+ t.Fatal(err)
+ }
+ if got := readFile(t, runtimeConfigPath(wt.WorkDir, provider)); !strings.Contains(got, runtimeMarkerBegin) {
+ t.Fatal("runtime brief is not readable by the agent")
+ }
+ if got := gitRun(t, wt.Path, "status", "--porcelain"); got != "" {
+ t.Fatalf("brief dirtied worktree: %s", got)
+ }
+ if got := gitRun(t, wt.Path, "diff"); got != "" {
+ t.Fatalf("brief appears in diff: %s", got)
+ }
+ gitRun(t, wt.Path, "add", "-A")
+ if got := gitRun(t, wt.Path, "diff", "--cached"); got != "" {
+ t.Fatalf("git add staged brief: %s", got)
+ }
+ if err := os.WriteFile(filepath.Join(wt.Path, "tracked.txt"), []byte("agent change\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ gitRun(t, wt.Path, "commit", "-am", "agent change")
+ rel, err := filepath.Rel(repo, target)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rel = filepath.ToSlash(rel)
+ if wt.RuntimeConfigSkipWorktree != rel {
+ t.Fatalf("protected %q, want brief target %q", wt.RuntimeConfigSkipWorktree, rel)
+ }
+ if got := gitRun(t, wt.Path, "show", "HEAD:"+rel); got != strings.TrimSpace(original) {
+ t.Fatalf("agent committed runtime brief: %s", got)
+ }
+ for _, entry := range []string{filepath.Base(path), tc.target} {
+ entry = filepath.ToSlash(filepath.Join(subdir, entry))
+ if got := gitRun(t, repo, "ls-files", "-v", "--", ":(literal)"+entry); !strings.HasPrefix(got, "H ") {
+ t.Fatalf("user's index changed: %s", got)
+ }
+ }
+ if err := wt.RestoreRuntimeConfigTracking(); err != nil {
+ t.Fatal(err)
+ }
+ if got := gitRun(t, wt.Path, "ls-files", "-v", "--", ":(literal)"+rel); !strings.HasPrefix(got, "H ") {
+ t.Fatalf("target tracking was not restored: %s", got)
+ }
+ if err := CleanupRuntimeConfig(wt.WorkDir, provider); err != nil {
+ t.Fatal(err)
+ }
+ finalizeOK(t, wt)
+ if got := readFile(t, path); got != original {
+ t.Fatalf("user's instruction file changed: %q", got)
+ }
+ })
+ }
+ }
+}
+
+func TestWorktreeRuntimeConfigEditsSurviveFinalize(t *testing.T) {
+ for _, provider := range []string{"codex", "claude"} {
+ for _, agentCommit := range []bool{false, true} {
+ t.Run(provider+"/"+map[bool]string{false: "auto commit", true: "leftover ref"}[agentCommit], func(t *testing.T) {
+ repo := newTestRepo(t)
+ if err := os.WriteFile(filepath.Join(repo, "AGENTS.md"), []byte("Original instructions.\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if provider == "claude" {
+ if err := os.Symlink("AGENTS.md", filepath.Join(repo, "CLAUDE.md")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ gitRun(t, repo, "add", ".")
+ gitRun(t, repo, "commit", "-m", "add instructions")
+ wt := prepareForTest(t, repo)
+ if _, err := InjectRuntimeConfig(wt.WorkDir, provider, TaskContextForEnv{}); err != nil {
+ t.Fatal(err)
+ }
+ if err := wt.ProtectRuntimeConfig(provider); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(wt.WorkDir, "AGENTS.md")
+ content := strings.Replace(readFile(t, path), "Original instructions.", "Updated instructions.", 1)
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if agentCommit {
+ if err := os.WriteFile(filepath.Join(wt.Path, "tracked.txt"), []byte("agent change\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ gitRun(t, wt.Path, "add", "-A")
+ gitRun(t, wt.Path, "commit", "-m", "agent change")
+ }
+ if err := wt.RestoreRuntimeConfigTracking(); err != nil {
+ t.Fatal(err)
+ }
+ if err := CleanupRuntimeConfig(wt.WorkDir, provider); err != nil {
+ t.Fatal(err)
+ }
+ outcome := finalizeOK(t, wt)
+ ref := outcome.Branch
+ if agentCommit {
+ ref = outcome.LeftoverRef
+ }
+ if ref == "" {
+ t.Fatal("instruction edit was not preserved")
+ }
+ if got := gitRun(t, repo, "show", ref+":AGENTS.md"); got != "Updated instructions." {
+ t.Fatalf("instruction edit lost or brief committed: %q", got)
+ }
+ if agentCommit {
+ if got := gitRun(t, repo, "show", outcome.Branch+":AGENTS.md"); got != "Original instructions." {
+ t.Fatalf("agent committed protected instructions: %q", got)
+ }
+ }
+ if got := readFile(t, filepath.Join(repo, "AGENTS.md")); got != "Original instructions.\n" {
+ t.Fatalf("user's instructions changed: %q", got)
+ }
+ })
+ }
+ }
+}
+
+func TestWorktreeRuntimeConfigSymlinkBoundaries(t *testing.T) {
+ for _, targetKind := range []string{"parent in worktree", "untracked", "user checkout", "directory symlink", "sibling prefix"} {
+ t.Run(targetKind, func(t *testing.T) {
+ repo := newTestRepo(t)
+ original := "User instructions.\n"
+ if err := os.WriteFile(filepath.Join(repo, "AGENTS.md"), []byte(original), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ gitRun(t, repo, "add", ".")
+ gitRun(t, repo, "commit", "-m", "add instructions")
+ userIndex := readFile(t, filepath.Join(repo, ".git", "index"))
+ wt := prepareForTest(t, repo)
+ defer wt.Discard(worktreeTestLogger())
+ target := filepath.Join(repo, "AGENTS.md")
+ linkTarget := target
+ switch targetKind {
+ case "parent in worktree":
+ wt.WorkDir = filepath.Join(wt.Path, "docs [guide]")
+ if err := os.MkdirAll(wt.WorkDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ target = filepath.Join(wt.Path, "AGENTS.md")
+ linkTarget = filepath.Join("..", "AGENTS.md")
+ case "untracked":
+ target = filepath.Join(wt.Path, "untracked.md")
+ linkTarget = "untracked.md"
+ case "directory symlink":
+ if err := os.Symlink(repo, filepath.Join(wt.Path, "shared")); err != nil {
+ t.Fatal(err)
+ }
+ linkTarget = filepath.Join("shared", "AGENTS.md")
+ case "sibling prefix":
+ outside := wt.Path + "-outside"
+ if err := os.MkdirAll(outside, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ target = filepath.Join(outside, "AGENTS.md")
+ linkTarget = target
+ }
+ if err := os.WriteFile(target, []byte(original), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ config := runtimeConfigPath(wt.WorkDir, "claude")
+ if err := os.Symlink(linkTarget, config); err != nil {
+ t.Fatal(err)
+ }
+ gitRun(t, wt.Path, "add", "--", config)
+ if err := wt.ProtectRuntimeConfig("claude"); err != nil {
+ t.Fatal(err)
+ }
+ want := ""
+ if targetKind == "parent in worktree" {
+ want = "AGENTS.md"
+ }
+ if wt.RuntimeConfigSkipWorktree != want {
+ t.Fatalf("protected %q, want %q", wt.RuntimeConfigSkipWorktree, want)
+ }
+ if got := gitRun(t, wt.Path, "ls-files", "-v", "--", config); !strings.HasPrefix(got, "H ") {
+ t.Fatalf("symlink itself was hidden: %s", got)
+ }
+ if err := wt.RestoreRuntimeConfigTracking(); err != nil {
+ t.Fatal(err)
+ }
+ if got := gitRun(t, wt.Path, "ls-files", "-v", "--", "AGENTS.md"); !strings.HasPrefix(got, "H ") {
+ t.Fatalf("target tracking was not restored: %s", got)
+ }
+ if got := readFile(t, target); got != original {
+ t.Fatalf("target changed: %q", got)
+ }
+ if got := readFile(t, filepath.Join(repo, ".git", "index")); got != userIndex {
+ t.Fatal("user's index bytes changed")
+ }
+ })
+ }
+}
+
+func TestWorktreeRuntimeConfigTrackingRestoredOnAbort(t *testing.T) {
+ repo := newTestRepo(t)
+ if err := os.WriteFile(filepath.Join(repo, "AGENTS.md"), []byte("Instructions.\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink("AGENTS.md", filepath.Join(repo, "CLAUDE.md")); err != nil {
+ t.Fatal(err)
+ }
+ gitRun(t, repo, "add", ".")
+ gitRun(t, repo, "commit", "-m", "add instructions")
+ wt := prepareForTest(t, repo)
+ if _, err := InjectRuntimeConfig(wt.WorkDir, "claude", TaskContextForEnv{}); err != nil {
+ t.Fatal(err)
+ }
+ if err := wt.ProtectRuntimeConfig("claude"); err != nil {
+ t.Fatal(err)
+ }
+ data, err := json.Marshal(wt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var restored LocalWorktree
+ if err := json.Unmarshal(data, &restored); err != nil {
+ t.Fatal(err)
+ }
+ restored.AbortWithReason(errors.New("cleanup failed"))
+ outcome, err := restored.Finalize(worktreeTestLogger())
+ if err == nil || outcome.PreservedPath != wt.Path {
+ t.Fatalf("Finalize = %+v, %v; want preserved worktree", outcome, err)
+ }
+ if got := gitRun(t, wt.Path, "ls-files", "-v", "--", "AGENTS.md"); !strings.HasPrefix(got, "H ") {
+ t.Fatalf("skip-worktree survived abort: %s", got)
+ }
+ wt.Discard(worktreeTestLogger())
+}
+
+func TestWorktreeRuntimeConfigProtectionSkipsUntrackedFiles(t *testing.T) {
+ repo := newTestRepo(t)
+ wt := prepareForTest(t, repo)
+ if _, err := InjectRuntimeConfig(wt.WorkDir, "claude", TaskContextForEnv{}); err != nil {
+ t.Fatal(err)
+ }
+ if err := wt.ProtectRuntimeConfig("claude"); err != nil {
+ t.Fatal(err)
+ }
+ if wt.RuntimeConfigSkipWorktree != "" {
+ t.Fatal("untracked instruction file recorded as protected")
+ }
+ if err := CleanupRuntimeConfig(wt.WorkDir, "claude"); err != nil {
+ t.Fatal(err)
+ }
+ finalizeOK(t, wt)
+}
+
+func TestWorktreeRuntimeConfigProtectionSkipsMissingFiles(t *testing.T) {
+ wt := prepareForTest(t, newTestRepo(t))
+ defer wt.Discard(worktreeTestLogger())
+ if err := wt.ProtectRuntimeConfig("claude"); err != nil {
+ t.Fatal(err)
+ }
+ if wt.RuntimeConfigSkipWorktree != "" {
+ t.Fatal("missing instruction file recorded as protected")
+ }
+}
+
+func TestWorktreeRuntimeConfigRestoreFailurePreservesWorktree(t *testing.T) {
+ repo := newTestRepo(t)
+ if err := os.WriteFile(filepath.Join(repo, "AGENTS.md"), []byte("Instructions.\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink("AGENTS.md", filepath.Join(repo, "CLAUDE.md")); err != nil {
+ t.Fatal(err)
+ }
+ gitRun(t, repo, "add", ".")
+ gitRun(t, repo, "commit", "-m", "add instructions")
+ wt := prepareForTest(t, repo)
+ if err := wt.ProtectRuntimeConfig("claude"); err != nil {
+ t.Fatal(err)
+ }
+ updated := "Updated instructions.\n"
+ if err := os.WriteFile(filepath.Join(wt.Path, "AGENTS.md"), []byte(updated), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ gitDir := gitRun(t, wt.Path, "rev-parse", "--absolute-git-dir")
+ lock := filepath.Join(gitDir, "index.lock")
+ if err := os.WriteFile(lock, nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ outcome, err := wt.Finalize(worktreeTestLogger())
+ if err == nil || outcome.PreservedPath != wt.Path || outcome.Branch != "" {
+ t.Fatalf("Finalize = %+v, %v; want preserved worktree without delivery", outcome, err)
+ }
+ if !strings.Contains(err.Error(), "the work is preserved in the worktree at "+wt.Path) {
+ t.Fatalf("restore failure did not report the recovery path: %v", err)
+ }
+ if got := readFile(t, filepath.Join(wt.Path, "AGENTS.md")); got != updated {
+ t.Fatalf("restore failure lost instruction edits: %q", got)
+ }
+ if wt.RuntimeConfigSkipWorktree == "" {
+ t.Fatal("failed restore discarded the path needed to retry")
+ }
+ if err := os.Remove(lock); err != nil {
+ t.Fatal(err)
+ }
+ wt.Discard(worktreeTestLogger())
+ if wt.RuntimeConfigSkipWorktree != "" {
+ t.Fatal("discard did not restore tracking after the lock was released")
+ }
+}