Guard against PowerShell `$home` variable footgun causing user profile mutation/deletion
Summary
PowerShell's variable names are case-insensitive, so a seemingly local variable named $home resolves to the built-in read-only $HOME variable. When a generated or agent-authored script intends to use $home as a scratch path and then runs cleanup such as Remove-Item -Recurse -Force $home, PowerShell can target the user's real profile directory instead of the intended temporary directory.
I've now seen this pattern multiple times in agent-generated PowerShell. In one case during Copilot CLI hook testing, this command shape attempted to remove content from the user profile before the process was stopped:
$home = 'C:\Users\name\.copilot\session-state\...\files\copilot-home-hooks'
if (Test-Path $home) { Remove-Item -Recurse -Force $home }
Because $HOME is read-only, assignment failed, but subsequent references still pointed at the real home directory. That creates a high-risk corrupted-profile failure mode.
Why this matters
Copilot CLI frequently generates PowerShell for Windows users. $home is a natural variable name for directories like app home, tool home, temp home, or Copilot home. In PowerShell this is a dangerous footgun because it aliases the built-in $HOME variable by case-insensitive lookup.
Suggested mitigations
- Add a Copilot CLI/system instruction for PowerShell generation: never use
$homeas a user-defined variable; use names like$userProfile,$homeDir,$copilotHomePath, or$targetRootinstead. - Add a safety rule or lint-like guard before destructive PowerShell commands when the target variable is
$home/$HOME. - Consider warning or requiring confirmation when generated PowerShell combines
$homewith destructive recursive operations such asRemove-Item -Recurse.
This is especially important for autonomous/remote sessions where a user may not see the exact command before damage occurs.
Just hit this again in a session working on a custom copilot status line and doing attempting to do verification in an isolated COPILOT_HOME folder:
The immediate PowerShell fix is to run generated compound scripts with terminating error semantics, but that is only one layer. Before any recursive Remove-Item, resolve the target to a canonical absolute path and reject HOME/USERPROFILE, drive roots, workspace roots, empty values, and unresolved variables.
The regression should preserve the exact failure order: assignment to $home fails, Test-Path still evaluates the built-in HOME, and cleanup would target the profile. Test both Windows PowerShell 5.1 and pwsh, plus case variants such as $Home and $HOME. A language-model instruction is useful, but the host-side target guard is what makes this invariant reliable.