> For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt.

# PowerShell Profile

## 1. Edit Profile

```pwsh
if (-not (Test-Path $PROFILE)) { New-Item -ItemType File -Force -Path $PROFILE | Out-Null }
code $PROFILE
```

:::tip\[OneDrive latency]
If `$PROFILE` resides in OneDrive (inside `Documents`), loading can be slow. Move it to a local path or ensure execution policy is set:

```pwsh
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
```

:::

## 2. Profile Configuration

```pwsh
# ===== Microsoft.PowerShell_profile.ps1 =====
if (-not [Environment]::UserInteractive) { return }

# ---------- PSReadLine: suggestion, history, completion ----------
if (Get-Module -Name PSReadLine) {
    Set-PSReadLineOption -EditMode Windows
    Set-PSReadLineOption -PredictionSource History          # Inline prediction from history
    Set-PSReadLineOption -PredictionViewStyle InlineView    # Press F2 to switch to ListView
    Set-PSReadLineOption -HistoryNoDuplicates
    Set-PSReadLineOption -HistorySearchCursorMovesToEnd
    Set-PSReadLineOption -MaximumHistoryCount 20000
    Set-PSReadLineOption -BellStyle None
    Set-PSReadLineOption -ShowToolTips
    Set-PSReadLineOption -Colors @{ InlinePrediction = $PSStyle.Foreground.BrightBlack }

    # Prefix history search with Up/Down arrows
    Set-PSReadLineKeyHandler -Key UpArrow   -Function HistorySearchBackward
    Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward
    # Tab opens selection menu instead of cycling
    Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete

    # Exclude commands containing secrets from persistent history
    Set-PSReadLineOption -AddToHistoryHandler {
        param([string]$line)
        if ($line -match 'password|passwd|secret|token|apikey|api_key|AsPlainText|SecureString') {
            return [Microsoft.PowerShell.AddToHistoryOption]::MemoryOnly
        }
        return [Microsoft.PowerShell.AddToHistoryOption]::MemoryAndFile
    }
}

# ---------- Lightweight git completion (no posh-git required) ----------
Register-ArgumentCompleter -Native -CommandName git -ScriptBlock {
    param($wordToComplete, $commandAst, $cursorPosition)

    $subcommands = 'add','am','apply','bisect','blame','branch','checkout','cherry-pick','clean',
        'clone','commit','config','describe','diff','fetch','grep','init','log','merge','mv','pull',
        'push','rebase','reflog','remote','reset','restore','revert','rm','show','stash','status',
        'submodule','switch','tag','worktree'
    $refCommands = 'checkout','switch','merge','rebase','branch','diff','log','show','cherry-pick',
        'reset','push','pull','fetch','revert'

    $tokens = @($commandAst.CommandElements | Select-Object -Skip 1 | ForEach-Object { $_.ToString() })
    if ($wordToComplete) { $tokens = @($tokens | Select-Object -SkipLast 1) }
    $sub = $tokens | Where-Object { $_ -notlike '-*' } | Select-Object -First 1

    $items = @()
    if (-not $sub) {
        $items = $subcommands
    }
    elseif ($sub -in $refCommands -and $wordToComplete -notlike '-*') {
        $items = @(git for-each-ref --format='%(refname:short)' refs/heads refs/remotes 2>$null) |
            Where-Object { $_ -notlike '*/HEAD' }
        if ($sub -in 'push','pull','fetch') { $items = @(git remote 2>$null) + $items }
    }

    $items | Where-Object { $_.StartsWith($wordToComplete, [StringComparison]::OrdinalIgnoreCase) } |
        ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
    # Fallback to filesystem completion if empty
}

# ---------- Cached Git status prompt with file counts ----------
$global:GitStatusTtlSeconds    = 5      # Refresh git status at most once every 5 seconds
$global:GitStatusShowUntracked = $true  # Set $false on massive repos (-uno) for speed
$script:GitCache = @{ Root = $null; Time = [datetime]::MinValue; Text = ''; HistId = -1 }

function Get-GitStatusText([string]$root) {
    $gitArgs = @('--no-optional-locks', '-c', 'core.quotepath=off', 'status', '--porcelain=v2', '--branch')
    $gitArgs += if ($global:GitStatusShowUntracked) { '-unormal' } else { '-uno' }
    $out = & git -C $root @gitArgs 2>$null
    if ($LASTEXITCODE -ne 0 -or -not $out) { return '' }

    $branch = ''; $oid = ''; $ahead = 0; $behind = 0
    $sA = 0; $sM = 0; $sD = 0      # staged: added / modified / deleted
    $wM = 0; $wD = 0               # working tree: modified / deleted
    $untracked = 0; $conflict = 0

    foreach ($l in $out) {
        if ($l[0] -eq '#') {
            if     ($l.StartsWith('# branch.head ')) { $branch = $l.Substring(14) }
            elseif ($l.StartsWith('# branch.oid '))  { $oid = $l.Substring(13) }
            elseif ($l.StartsWith('# branch.ab ')) {
                $p = $l.Substring(12).Split(' ')
                $ahead = [int]$p[0].TrimStart('+'); $behind = [int]$p[1].TrimStart('-')
            }
        }
        elseif ($l[0] -eq '1' -or $l[0] -eq '2') {
            $x = $l[2]; $y = $l[3]
            switch ($x) { 'A' { $sA++ } 'M' { $sM++ } 'R' { $sM++ } 'C' { $sA++ } 'T' { $sM++ } 'D' { $sD++ } }
            switch ($y) { 'M' { $wM++ } 'T' { $wM++ } 'D' { $wD++ } }
        }
        elseif ($l[0] -eq 'u') { $conflict++ }
        elseif ($l[0] -eq '?') { $untracked++ }
    }

    if ($branch -eq '(detached)') { $branch = if ($oid.Length -ge 7) { $oid.Substring(0, 7) } else { 'detached' } }

    $s = $PSStyle
    $t = "$($s.Foreground.Yellow)($branch$($s.Reset)"
    if ($ahead)  { $t += " $($s.Foreground.Cyan)↑$ahead$($s.Reset)" }
    if ($behind) { $t += " $($s.Foreground.Cyan)↓$behind$($s.Reset)" }
    if ($sA -or $sM -or $sD) {
        $t += " $($s.Foreground.Green)+$sA ~$sM -$sD$($s.Reset)"
    }
    if ($wM -or $wD) {
        $t += " $($s.Foreground.Red)~$wM -$wD$($s.Reset)"
    }
    if ($untracked) { $t += " $($s.Foreground.BrightBlack)?$untracked$($s.Reset)" }
    if ($conflict)  { $t += " $($s.Foreground.BrightRed)!$conflict$($s.Reset)" }
    $t += "$($s.Foreground.Yellow))$($s.Reset)"
    return $t
}

function global:prompt {
    $ok  = $?
    $loc = $ExecutionContext.SessionState.Path.CurrentLocation
    $cwd = $loc.Path
    if ($cwd.StartsWith($HOME, [StringComparison]::OrdinalIgnoreCase)) { $cwd = '~' + $cwd.Substring($HOME.Length) }

    $gitInfo = ''
    if ($loc.Provider.Name -eq 'FileSystem') {
        # Traverse parent directories to find repository root without invoking git.exe
        $dir = $loc.ProviderPath; $root = $null
        while ($dir) {
            $g = [IO.Path]::Combine($dir, '.git')
            if ([IO.Directory]::Exists($g) -or [IO.File]::Exists($g)) { $root = $dir; break }
            $dir = [IO.Path]::GetDirectoryName($dir)
        }

        if ($root) {
            $c = $script:GitCache
            $last = Get-History -Count 1
            $histId = if ($last) { $last.Id } else { 0 }
            # Immediately refresh status if previous command was git or a git alias
            $afterGit = $last -and $histId -ne $c.HistId -and
                        $last.CommandLine -match '^\s*(git|g(st|aa|cmsg|push|pull|fa|df|lg|undo))\b'
            $stale = $c.Root -ne $root -or
                     ([datetime]::UtcNow - $c.Time).TotalSeconds -gt $global:GitStatusTtlSeconds

            if ($stale -or $afterGit) {
                $c.Root = $root; $c.Text = Get-GitStatusText $root
                $c.Time = [datetime]::UtcNow
            }
            $c.HistId = $histId
            if ($c.Text) { $gitInfo = ' ' + $c.Text }
        }
    }

    $arrow = if ($ok) { $PSStyle.Foreground.Green } else { $PSStyle.Foreground.Red }
    "$($PSStyle.Foreground.Cyan)$cwd$($PSStyle.Reset)$gitInfo`n$arrow>$($PSStyle.Reset) "
}

# ---------- Git aliases ----------
function gst    { git status -sb @args }
function gaa    { git add -A @args }
function gcmsg  { git commit -m @args }
function gpush  { git push @args }
function gpull  { git pull @args }
function gfa    { git fetch --all --prune @args }
function gdf    { git diff @args }
function glg    { git log --oneline --graph --decorate -n 20 @args }
function gundo  { git reset --soft HEAD~1 }
```

### Prompt Format

```text
~\dev\repo (main ↑1 ↓0 +2 ~1 -0 ~3 -1 ?4)
```

| Indicator                             | Meaning                                           |
| ------------------------------------- | ------------------------------------------------- |
| `↑ahead ↓behind`                      | Commits ahead / behind upstream (hidden when `0`) |
| `+added ~modified -deleted` _(Green)_ | Staged changes                                    |
| `~modified -deleted` _(Red)_          | Unstaged working tree changes                     |
| `?count` _(Bright black)_             | Untracked files                                   |
| `!count` _(Bright red)_               | Merge conflicts                                   |

### Key Design Choices

- **Non-locking git query (`--no-optional-locks`)**: Prevents `git status` from refreshing the index file, eliminating lock contention (`index.lock`) with VS Code.
- **Adaptive caching**: Caches status for 5 seconds by default during navigation/empty enters, but invalidates immediately when a git command or alias (`gaa`, `gcmsg`, `gpull`, etc.) runs.
- **Safe alias naming**: Avoids collisions with built-in PowerShell aliases (`gc`, `gp`, `gl`, `gcm`, `gps` already map to `Get-Content`, `Get-ItemProperty`, etc.).
- **Alias completion limitation**: Custom PowerShell alias functions are not intercepted by the git argument completer. Use full commands (`git switch <Tab>`, `git checkout <Tab>`) for branch completion.

## 3. Useful Shortcuts

| Key         | Description                          |
| ----------- | ------------------------------------ |
| `→` / `End` | Accept full inline suggestion        |
| `Ctrl+→`    | Accept suggestion word-by-word       |
| `F2`        | Toggle InlineView / ListView         |
| `↑` / `↓`   | Search history matching typed prefix |
| `Ctrl+R`    | Reverse interactive history search   |
| `Tab`       | Open menu completion                 |
| `F4`        | Show filtered history menu           |

## 4. Startup Optimization

Disable update checks and telemetry via user environment variables (evaluated before the profile loads):

```pwsh
[Environment]::SetEnvironmentVariable('POWERSHELL_UPDATECHECK', 'Off', 'User')
[Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', '1', 'User')
```

In Windows Terminal, set the command line to:

```text
pwsh.exe -NoLogo
```

Benchmark profile load overhead:

```pwsh
Measure-Command { pwsh -NoLogo -Command exit }               # with profile
Measure-Command { pwsh -NoLogo -NoProfile -Command exit }    # without profile
```

The difference is the profile load cost (typically tens of milliseconds).

## 5. Git Optimization for Large Monorepos

Speed up `git status` and filesystem operations:

```pwsh
git config --global core.fsmonitor true
git config --global core.untrackedCache true
git config --global feature.manyFiles true
git config --global core.preloadindex true
git config --global fetch.prune true
```

:::note\[FSMonitor daemon]
`core.fsmonitor` uses the built-in Git for Windows daemon (`git fsmonitor--daemon`, requires Git 2.37+).
:::
