自分用メモ。まだ動作未確認。
背景
VS Code の Agents Window で New Worktree を使うとき、
- worktree は作りたい
- ただし最初のターンでは実装や調査を始めてほしくない
- worktree が正常に作られたかだけ確認して止まってほしい
という運用にしたいことがあります。
今回は sessionStart hook を使って、これを自動化します。
結論:ユーザーがやること
初回セットアップでは、次の4つだけです。
-
%USERPROFILE%\.copilot\hooks\を作る -
worktree-init.jsonを置く -
worktree-init.ps1を置く - VS Code を Reload する
一度設定すれば、普段は次の操作だけです。
New Worktreeを作る
↓
最初の入力にworktree名にしたい文字列を書く
↓
Agentがworktreeの状態だけ報告して止まる
↓
次のターンから本来の作業指示を出す
例えば最初の入力は、
issue-66-pca-reconstruction
のようにします。
/worktree-init のような固定 Skill を最初に入力する必要はありません。
前提
今回は以下を前提とします。
- Windows
- VS Code Agents Window
- Session Target:
Copilot - Git worktree
- PowerShell 7
初回セットアップ
1. hooksフォルダを作る
以下のディレクトリを作成します。
%USERPROFILE%\.copilot\hooks\
最終的には次の構成にします。
.copilot
└─ hooks
├─ worktree-init.json
└─ worktree-init.ps1
2. worktree-init.json を作る
%USERPROFILE%\.copilot\hooks\worktree-init.json を作成し、以下を保存します。
{
"version": 1,
"hooks": {
"sessionStart": [
{
"type": "command",
"powershell": "& (Join-Path $HOME '.copilot/hooks/worktree-init.ps1')",
"timeoutSec": 5
}
]
}
}
この設定により、新しい Copilot セッションが始まると worktree-init.ps1 が呼ばれます。
3. worktree-init.ps1 を作る
%USERPROFILE%\.copilot\hooks\worktree-init.ps1 を作成し、以下を保存します。
$raw = [Console]::In.ReadToEnd()
try {
$event = $raw | ConvertFrom-Json
}
catch {
Write-Output '{}'
exit 0
}
# 新規セッション以外では何もしない
if ($event.source -ne 'new') {
Write-Output '{}'
exit 0
}
$cwd = [string]$event.cwd
if (-not $cwd) {
Write-Output '{}'
exit 0
}
# Git repository でなければ対象外
$gitDir = [string](
& git -C $cwd rev-parse --path-format=absolute --git-dir 2>$null
)
if ($LASTEXITCODE -ne 0) {
Write-Output '{}'
exit 0
}
$commonDir = [string](
& git -C $cwd rev-parse --path-format=absolute --git-common-dir 2>$null
)
if ($LASTEXITCODE -ne 0) {
Write-Output '{}'
exit 0
}
# 通常のmain worktreeでは対象外
# linked worktree の場合だけ処理する
if ($gitDir.Trim() -eq $commonDir.Trim()) {
Write-Output '{}'
exit 0
}
$status = (
& git -C $cwd status --short --branch 2>$null
) -join "`n"
if ($LASTEXITCODE -ne 0) {
$status = "git status failed"
}
$context = @"
This is the initialization turn immediately after a new linked Git worktree was created.
The user's first submitted text is only the session/worktree label.
Do not interpret it as a task request.
The hook has already performed the minimum Git verification.
git status --short --branch:
$status
Do not call any tools.
Do not inspect source files.
Do not modify, create, delete, format, or move any files.
Do not run tests.
Do not install dependencies.
Do not fetch, pull, rebase, commit, push, or create a PR.
Do not investigate or begin implementation.
Briefly report whether the worktree appears to have been created successfully,
then stop.
"@
@{
additionalContext = $context
} | ConvertTo-Json -Compress
4. VS CodeをReloadする
設定後、一度 VS Code を Reload します。
Ctrl + Shift + P
から、
Developer: Reload Window
を実行します。
これで初回セットアップは完了です。
普段の使い方
1. New Worktreeを作る
Agents Window から通常どおり新しい worktree を作ります。
New
↓
Repositoryを選択
↓
Session Target: Copilot
↓
New Worktree
↓
base branchを選択
2. 最初の入力にはworktree名だけを書く
最初の入力には、作業内容ではなく、worktree やセッションにつけたい名前を書きます。
例えば、
issue-66-pca-reconstruction
です。
ここで、
/worktree-init
のような固定 Skill は使いません。
3. Agentが確認だけして止まる
sessionStart hook が自動で実行されます。
hook 側で、
git status --short --branch
まで確認し、その結果と、
このターンでは実装や調査を始めない
ファイルを変更しない
ツールを呼ばない
結果だけ短く報告して停止する
という指示を Agent に追加します。
期待する応答は、例えばこの程度です。
Worktree was created successfully. Working tree is clean.
ここで Agent は止まります。
4. 次のターンから本来の作業を始める
その後、普通に作業指示を出します。
Issue #66を実装して
このターンからは、先ほどの初期化制約はありません。
何が起きているか
全体の流れは次の通りです。
ユーザー
│
│ New Worktreeを作成
▼
最初の入力
│
├─ issue-66-pca-reconstruction
│
└─ worktree/session名の材料になる
│
▼
sessionStart hook
│
├─ 新規セッションか確認
├─ linked worktreeか確認
├─ git statusを取得
└─ 初回制約をadditionalContextで注入
│
▼
Agent
│
└─ 状態だけ報告して停止
ユーザー側から見ると、
New Worktree
↓
名前を書く
↓
確認結果が返る
↓
次のターンから作業開始
だけです。
なぜSkillではなくHookなのか
最初は、例えば、
/worktree-init
という Skill を作って、worktree 作成直後に毎回呼び出す方法も考えられます。
ただし、Agents Window では最初のプロンプトがセッション名や worktree 名の生成に影響します。
そのため、毎回最初に、
/worktree-init
と入力すると、生成される名前まで worktree-init に引っ張られます。
今回やりたいのは、
最初の入力
↓
worktree名を決めるために使う
初回の制約
↓
別経路でAgentに渡す
という分離です。
sessionStart hook を使えば、この2つを分けられます。
なぜAgent自身に確認させないのか
Agent に単純に、
worktreeが正常か確認して
と指示すると、モデルによっては確認範囲を広げる可能性があります。
例えば、
git status- ファイル一覧確認
- README確認
- テスト実行
- dependency確認
などです。
今回は「余計なことを何もしてほしくない」ので、確認そのものを hook 側で行います。
git status --short --branch
の結果を Agent に渡し、Agent 自身にはツールを使わせません。
つまり、
Hook
├─ Git確認
└─ 結果を渡す
Agent
└─ 結果を報告するだけ
という役割分担です。
なぜlinked worktreeだけを判定できるのか
スクリプトでは、
git rev-parse --git-dir
と、
git rev-parse --git-common-dir
を比較しています。
通常のメイン worktree では、両者は同じ Git 管理ディレクトリを指します。
一方、linked worktree では異なります。
そのため、
if ($gitDir.Trim() -eq $commonDir.Trim()) {
Write-Output '{}'
exit 0
}
として、通常のリポジトリでは hook の追加指示を出さないようにしています。
worktree のディレクトリ名に依存しない点もメリットです。
copilot-instructions.md に書かない理由
次のような永続的な instruction に、
最初は何もするな
と書く方法は適していません。
.github/copilot-instructions.md
AGENTS.md
これらは初回ターンだけでなく、その後の作業にも影響するためです。
今回必要なのは、
worktree作成直後の1ターンだけ
という制約です。
そのため、セッション開始時だけ発火する hook の方が適しています。
preToolUse まで使う必要はあるか
さらに厳密にするなら、preToolUse hook を使い、初回ターン中のツール使用自体を拒否する方法もあります。
ただし、その場合、
今が初回ターンなのか
という状態管理が必要になります。
今回の目的では、
- Git確認は hook 側で済ませる
- Agent にはツールを使わないよう指示する
- Agent は確認結果だけ報告する
という構成の方が単純です。
まずはこの構成で十分です。
まとめ
初回セットアップでやることは、
.copilot
└─ hooks
├─ worktree-init.json
└─ worktree-init.ps1
の2ファイルを置くことです。
その後の日常運用は、
New Worktree
↓
意味のある名前を入力
↓
Agentが確認だけして停止
↓
次のターンから本来の作業
だけです。
ポイントは、
worktreeの名前付けと、初回ターンのAgent制御を分離すること
です。
これにより、意味のある worktree 名を保ちつつ、worktree 作成直後に Agent が勝手に実装・調査・変更を始めるのを抑制できます。
追記:Worktree作成時にuvで仮想環境を自動生成する
Worktreeごとに独立した .venv を作成したい場合、上記の sessionStart hookに uv sync --all-groups --locked を追加する。
- 対象は 新規セッション (
source == "new") のlinked worktreeのみ。main worktreeでは実行しない。 -
.venv/Scripts/python.exeが存在しない場合だけ初期化する。既存の環境には触れない。 -
pyproject.tomlのないWorktreeではスキップする。 -
--all-groupsで全dependency groupを導入し、--lockedでlockfile変更を禁止する。 - 初期化結果を
additionalContextに含め、Agentには結果の報告だけさせる。
worktree-init.json(全体版)
ファイル:%USERPROFILE%\.copilot\hooks\worktree-init.json
uv sync の実行時間を考慮し、timeoutSec を増やす。ここでは180秒を設定する(環境やVS Codeの許容値に応じて調整)。
{
"version": 1,
"hooks": {
"sessionStart": [
{
"type": "command",
"powershell": "& (Join-Path $HOME '.copilot/hooks/worktree-init.ps1')",
"timeoutSec": 180
}
]
}
}
worktree-init.ps1(全体版)
ファイル:%USERPROFILE%\.copilot\hooks\worktree-init.ps1
$raw = [Console]::In.ReadToEnd()
try {
$event = $raw | ConvertFrom-Json
}
catch {
Write-Output '{}'
exit 0
}
# Apply only to a new session
if ($event.source -ne 'new') {
Write-Output '{}'
exit 0
}
$cwd = [string]$event.cwd
if (-not $cwd -or -not (Test-Path -LiteralPath $cwd -PathType Container)) {
Write-Output '{}'
exit 0
}
# Detect a linked worktree
$gitDir = [string](& git -C $cwd rev-parse --path-format=absolute --git-dir 2>$null)
if ($LASTEXITCODE -ne 0 -or -not $gitDir) {
Write-Output '{}'
exit 0
}
$commonDir = [string](& git -C $cwd rev-parse --path-format=absolute --git-common-dir 2>$null)
if ($LASTEXITCODE -ne 0 -or -not $commonDir) {
Write-Output '{}'
exit 0
}
if ($gitDir.Trim() -eq $commonDir.Trim()) {
Write-Output '{}'
exit 0
}
$repoRoot = [string](& git -C $cwd rev-parse --show-toplevel 2>$null)
if ($LASTEXITCODE -ne 0 -or -not $repoRoot) {
Write-Output '{}'
exit 0
}
$repoRoot = $repoRoot.Trim()
# Initialize .venv once per worktree
$venvPython = Join-Path $repoRoot '.venv\Scripts\python.exe'
$pyproject = Join-Path $repoRoot 'pyproject.toml'
$uvResult = 'Skipped: existing .venv'
if (-not (Test-Path -LiteralPath $venvPython -PathType Leaf)) {
if (-not (Test-Path -LiteralPath $pyproject -PathType Leaf)) {
$uvResult = 'Skipped: pyproject.toml not found'
}
elseif (-not (Get-Command uv -ErrorAction SilentlyContinue)) {
$uvResult = 'Failed: uv executable not found in PATH'
}
else {
Push-Location $repoRoot
try {
$uvOutput = & uv sync --all-groups --locked 2>&1
if ($LASTEXITCODE -eq 0) {
$uvResult = 'Succeeded: uv sync --all-groups --locked'
}
else {
$uvResult = 'Failed: uv sync exited with code ' + $LASTEXITCODE + '. ' + (($uvOutput | Out-String).Trim())
}
}
catch {
$uvResult = 'Failed: ' + $_.Exception.Message
}
finally {
Pop-Location
}
}
}
$status = (& git -C $repoRoot status --short --branch 2>$null) -join "`n"
if ($LASTEXITCODE -ne 0) {
$status = 'git status failed'
}
$context = @"
This is the initialization turn immediately after a new linked Git worktree session started.
The user's first submitted text is only the session/worktree label.
Do not interpret it as a task request.
The hook has already performed the Git verification and Python environment initialization.
git status --short --branch:
$status
Python environment:
$uvResult
Do not call any tools.
Do not inspect source files.
Do not modify, create, delete, format, or move any files.
Do not run tests or install dependencies yourself.
Do not fetch, pull, rebase, commit, push, or create a PR.
Do not investigate or begin implementation.
Briefly report the worktree status and Python environment initialization result,
then stop. If initialization failed, report the error without trying to fix it.
"@
@{ additionalContext = $context } | ConvertTo-Json -Compress
注意事項
-
sessionStartは厳密にはWorktree作成時ではなく新規セッション開始時に発火する。上記では.venvがあればuv syncをスキップする。 - 途中で失敗して不完全な
.venvが残った場合でも、Scripts/python.exeがなければ次回再試行される。一方、Python実行ファイルだけ存在する不完全環境までは検出できない。 -
--lockedはuv.lockの更新が必要な状態ではエラーにする。環境の初期化が失敗しても、Hookはその理由をAgentに報告して終了する。 -
uv syncはWorktreeの.venvに書き込むため、元の記事の「Hookはファイルを変更しない」という説明とは異なる。ファイルを変更しない指示はAgentに対するものであり、この追記版のHook自身には.venv作成だけを許可している。 -
timeoutSecを超える環境では初期化が中断される可能性がある。初回ダウンロードが大きい場合などは適宜調整する。
変更後は VS Code で Developer: Reload Window を実行する。