Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(pi): 新增 Windows Git PATH 解析模块 (#2869)
nanaco33a1a8b259d9
diff --git a/apps/desktop/resources/THIRD-PARTY-NOTICES.txt b/apps/desktop/resources/THIRD-PARTY-NOTICES.txtindex 3f88ebf2ed..fdc8ae2920 100644--- a/apps/desktop/resources/THIRD-PARTY-NOTICES.txt+++ b/apps/desktop/resources/THIRD-PARTY-NOTICES.txt@@ -3431,6 +3431,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.+------------------------------------------------------------------------------+oh-my-pi Windows Git PATH helpers (adapted) 326d24bd40d9858e24e1036ae739c27c72eeb543+License: MIT+Source: https://github.com/can1357/oh-my-pi/tree/326d24bd40d9858e24e1036ae739c27c72eeb543+------------------------------------------------------------------------------+MIT License++Copyright (c) 2025 Mario Zechner+Copyright (c) 2025-2026 Can Bölük++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.+------------------------------------------------------------------------------OpenAI Codex CLI (runtime-downloaded binary) 0.145.0License: Apache-2.0diff --git a/docs/legal/notices/THIRD-PARTY-NOTICES.txt b/docs/legal/notices/THIRD-PARTY-NOTICES.txtindex 0af0c06a2a..f13883ee32 100644--- a/docs/legal/notices/THIRD-PARTY-NOTICES.txt+++ b/docs/legal/notices/THIRD-PARTY-NOTICES.txt@@ -3737,6 +3737,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.+------------------------------------------------------------------------------+oh-my-pi Windows Git PATH helpers (adapted) 326d24bd40d9858e24e1036ae739c27c72eeb543+License: MIT+Source: https://github.com/can1357/oh-my-pi/tree/326d24bd40d9858e24e1036ae739c27c72eeb543+------------------------------------------------------------------------------+MIT License++Copyright (c) 2025 Mario Zechner+Copyright (c) 2025-2026 Can Bölük++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.+------------------------------------------------------------------------------OpenAI Codex CLI (runtime-downloaded binary) 0.145.0License: Apache-2.0diff --git a/docs/legal/notices/desktop-linux.txt b/docs/legal/notices/desktop-linux.txtindex 7b7998999f..d1c254a71b 100644--- a/docs/legal/notices/desktop-linux.txt+++ b/docs/legal/notices/desktop-linux.txt@@ -285,6 +285,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.+------------------------------------------------------------------------------+oh-my-pi Windows Git PATH helpers (adapted) 326d24bd40d9858e24e1036ae739c27c72eeb543+License: MIT+Source: https://github.com/can1357/oh-my-pi/tree/326d24bd40d9858e24e1036ae739c27c72eeb543+------------------------------------------------------------------------------+MIT License++Copyright (c) 2025 Mario Zechner+Copyright (c) 2025-2026 Can Bölük++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.+------------------------------------------------------------------------------Electron (bundled runtime) 41.10.3License: MITdiff --git a/docs/legal/notices/desktop-macos.txt b/docs/legal/notices/desktop-macos.txtindex 7ca6b8bdd1..eba3730b47 100644--- a/docs/legal/notices/desktop-macos.txt+++ b/docs/legal/notices/desktop-macos.txt@@ -285,6 +285,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.+------------------------------------------------------------------------------+oh-my-pi Windows Git PATH helpers (adapted) 326d24bd40d9858e24e1036ae739c27c72eeb543+License: MIT+Source: https://github.com/can1357/oh-my-pi/tree/326d24bd40d9858e24e1036ae739c27c72eeb543+------------------------------------------------------------------------------+MIT License++Copyright (c) 2025 Mario Zechner+Copyright (c) 2025-2026 Can Bölük++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.+------------------------------------------------------------------------------Electron (bundled runtime) 41.10.3License: MITdiff --git a/docs/legal/notices/desktop-win.txt b/docs/legal/notices/desktop-win.txtindex 84a4be025d..98b07226dc 100644--- a/docs/legal/notices/desktop-win.txt+++ b/docs/legal/notices/desktop-win.txt@@ -285,6 +285,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.+------------------------------------------------------------------------------+oh-my-pi Windows Git PATH helpers (adapted) 326d24bd40d9858e24e1036ae739c27c72eeb543+License: MIT+Source: https://github.com/can1357/oh-my-pi/tree/326d24bd40d9858e24e1036ae739c27c72eeb543+------------------------------------------------------------------------------+MIT License++Copyright (c) 2025 Mario Zechner+Copyright (c) 2025-2026 Can Bölük++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.+------------------------------------------------------------------------------Electron (bundled runtime) 41.10.3License: MITdiff --git a/docs/legal/notices/sbom/desktop-linux.spdx.json b/docs/legal/notices/sbom/desktop-linux.spdx.jsonindex 6781b83925..0db95e5647 100644--- a/docs/legal/notices/sbom/desktop-linux.spdx.json+++ b/docs/legal/notices/sbom/desktop-linux.spdx.json@@ -3,9 +3,9 @@"dataLicense": "CC0-1.0","SPDXID": "SPDXRef-DOCUMENT","name": "cindy-desktop-linux",- "documentNamespace": "https://cindy.app/spdx/desktop-linux/8151ecd512d84f855fdd8838bf5948fc9b37ad5b84e05bfde10182cf77f14a3b",+ "documentNamespace": "https://cindy.app/spdx/desktop-linux/474608a0d72ac80973f3c0c12f44d0db8d19d9d87f818662dd586a576c911ca9","creationInfo": {- "created": "2026-08-02T09:08:05Z",+ "created": "2026-08-14T10:29:27Z","creators": ["Tool: scripts/generate-third-party-notices.mjs"]@@ -71,6 +71,16 @@"licenseDeclared": "MIT","copyrightText": "NOASSERTION"},+ {+ "name": "oh-my-pi Windows Git PATH helpers (adapted)",+ "SPDXID": "SPDXRef-Package-42f340d5003334bd",+ "versionInfo": "326d24bd40d9858e24e1036ae739c27c72eeb543",+ "downloadLocation": "https://github.com/can1357/oh-my-pi/tree/326d24bd40d9858e24e1036ae739c27c72eeb543",+ "filesAnalyzed": false,+ "licenseConcluded": "MIT",+ "licenseDeclared": "MIT",+ "copyrightText": "NOASSERTION"+ },{"name": "OpenAI Codex CLI (runtime-downloaded binary)","SPDXID": "SPDXRef-Package-4f22132a77577bcb",@@ -13681,6 +13691,11 @@"relationshipType": "DESCRIBES","relatedSpdxElement": "SPDXRef-Package-82458194310410e0"},+ {+ "spdxElementId": "SPDXRef-DOCUMENT",+ "relationshipType": "DESCRIBES",+ "relatedSpdxElement": "SPDXRef-Package-42f340d5003334bd"+ },{"spdxElementId": "SPDXRef-DOCUMENT","relationshipType": "DESCRIBES",diff --git a/docs/legal/notices/sbom/desktop-macos.spdx.json b/docs/legal/notices/sbom/desktop-macos.spdx.jsonindex 07f26760e2..45424fa60e 100644--- a/docs/legal/notices/sbom/desktop-macos.spdx.json+++ b/docs/legal/notices/sbom/desktop-macos.spdx.json@@ -3,9 +3,9 @@"dataLicense": "CC0-1.0","SPDXID": "SPDXRef-DOCUMENT","name": "cindy-desktop-macos",- "documentNamespace": "https://cindy.app/spdx/desktop-macos/81c6f1f9a4da87983a716bdb405a4e5adc859e32ef59b98b654af4b0a58a1a54",+ "documentNamespace": "https://cindy.app/spdx/desktop-macos/71046b3dc5cf9074da16a9c27fed04b8c046b20ddc8f62e4b43d8126c029ea09","creationInfo": {- "created": "2026-08-02T09:08:05Z",+ "created": "2026-08-14T10:29:27Z","creators": ["Tool: scripts/generate-third-party-notices.mjs"]@@ -81,6 +81,16 @@"licenseDeclared": "MIT","copyrightText": "NOASSERTION"},+ {+ "name": "oh-my-pi Windows Git PATH helpers (adapted)",+ "SPDXID": "SPDXRef-Package-42f340d5003334bd",+ "versionInfo": "326d24bd40d9858e24e1036ae739c27c72eeb543",+ "downloadLocation": "https://github.com/can1357/oh-my-pi/tree/326d24bd40d9858e24e1036ae739c27c72eeb543",+ "filesAnalyzed": false,+ "licenseConcluded": "MIT",+ "licenseDeclared": "MIT",+ "copyrightText": "NOASSERTION"+ },{"name": "OpenAI Codex CLI (runtime-downloaded binary)","SPDXID": "SPDXRef-Package-4f22132a77577bcb",@@ -13696,6 +13706,11 @@"relationshipType": "DESCRIBES","relatedSpdxElement": "SPDXRef-Package-82458194310410e0"},+ {+ "spdxElementId": "SPDXRef-DOCUMENT",+ "relationshipType": "DESCRIBES",+ "relatedSpdxElement": "SPDXRef-Package-42f340d5003334bd"+ },{"spdxElementId": "SPDXRef-DOCUMENT","relationshipType": "DESCRIBES",diff --git a/docs/legal/notices/sbom/desktop-win.spdx.json b/docs/legal/notices/sbom/desktop-win.spdx.jsonindex 81e330e6c1..f4e81b5fda 100644--- a/docs/legal/notices/sbom/desktop-win.spdx.json+++ b/docs/legal/notices/sbom/desktop-win.spdx.json@@ -3,9 +3,9 @@"dataLicense": "CC0-1.0","SPDXID": "SPDXRef-DOCUMENT","name": "cindy-desktop-win",- "documentNamespace": "https://cindy.app/spdx/desktop-win/c7127ee2d25b879a6e695800f8557d443f07d3f99c78086df0c6dea7d2a99958",+ "documentNamespace": "https://cindy.app/spdx/desktop-win/1be344db12c8580ca201f06bafbcbbe814d8770eb6125c34cc23a1742b1a628a","creationInfo": {- "created": "2026-08-02T09:08:05Z",+ "created": "2026-08-14T10:29:27Z","creators": ["Tool: scripts/generate-third-party-notices.mjs"]@@ -71,6 +71,16 @@"licenseDeclared": "MIT","copyrightText": "NOASSERTION"},+ {+ "name": "oh-my-pi Windows Git PATH helpers (adapted)",+ "SPDXID": "SPDXRef-Package-42f340d5003334bd",+ "versionInfo": "326d24bd40d9858e24e1036ae739c27c72eeb543",+ "downloadLocation": "https://github.com/can1357/oh-my-pi/tree/326d24bd40d9858e24e1036ae739c27c72eeb543",+ "filesAnalyzed": false,+ "licenseConcluded": "MIT",+ "licenseDeclared": "MIT",+ "copyrightText": "NOASSERTION"+ },{"name": "OpenAI Codex CLI (runtime-downloaded binary)","SPDXID": "SPDXRef-Package-4f22132a77577bcb",@@ -18050,6 +18060,11 @@"relationshipType": "DESCRIBES","relatedSpdxElement": "SPDXRef-Package-82458194310410e0"},+ {+ "spdxElementId": "SPDXRef-DOCUMENT",+ "relationshipType": "DESCRIBES",+ "relatedSpdxElement": "SPDXRef-Package-42f340d5003334bd"+ },{"spdxElementId": "SPDXRef-DOCUMENT","relationshipType": "DESCRIBES",diff --git a/docs/legal/notices/sbom/mobile-android.spdx.json b/docs/legal/notices/sbom/mobile-android.spdx.jsonindex 665ef17ca0..23852b367c 100644--- a/docs/legal/notices/sbom/mobile-android.spdx.json+++ b/docs/legal/notices/sbom/mobile-android.spdx.json@@ -5,7 +5,7 @@"name": "cindy-mobile-android","documentNamespace": "https://cindy.app/spdx/mobile-android/05efd357f74ac207a075699dbbd457afe65ed99fd574ee594be1d4bb651dc49a","creationInfo": {- "created": "2026-08-02T09:08:05Z",+ "created": "2026-08-14T10:29:27Z","creators": ["Tool: scripts/generate-third-party-notices.mjs"]diff --git a/docs/legal/notices/sbom/mobile-ios.spdx.json b/docs/legal/notices/sbom/mobile-ios.spdx.jsonindex 31eae9c22c..a8591c9d1d 100644--- a/docs/legal/notices/sbom/mobile-ios.spdx.json+++ b/docs/legal/notices/sbom/mobile-ios.spdx.json@@ -5,7 +5,7 @@"name": "cindy-mobile-ios","documentNamespace": "https://cindy.app/spdx/mobile-ios/9cae3d29bee1df233432e6dd0978265ea2d61b380b2e50bf92a64c3516a1cccf","creationInfo": {- "created": "2026-08-02T09:08:05Z",+ "created": "2026-08-14T10:29:27Z","creators": ["Tool: scripts/generate-third-party-notices.mjs"]diff --git a/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.ts b/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.tsnew file mode 100644index 0000000000..3e092bcb05--- /dev/null+++ b/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.ts@@ -0,0 +1,254 @@+import { execFileSync, spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { describe, expect, it, vi } from 'vitest';++import {+ buildWindowsNetworkDriveProbeScript,+ buildWindowsPathKindProbeScript,+ buildWindowsRegistryProbeScript,+ buildWindowsDescendantCleanupScript,+ countWindowsPowerShellDiagnostics,+ terminateWindowsPowerShellDescendants,+ warnWindowsGitPathProbeDiagnostics,+ warnWindowsGitPathProbeFailure,+} from './windows-git-path-powershell.js';++describe('Windows Git PATH PowerShell probes', () => {+ it('locks the registry probe command and distinguishes missing keys from real failures', () => {+ const script = buildWindowsRegistryProbeScript([+ 'Registry::HKEY_CURRENT_USER\\SOFTWARE\\GitForWindows',+ 'Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\GitForWindows',+ ]);++ expect(script).toContain("Get-ItemPropertyValue -LiteralPath $key -Name 'InstallPath' -ErrorAction Stop");+ expect(script).toContain('[Text.Encoding]::Unicode.GetBytes([string]$value)');+ expect(script).toContain('catch [System.Management.Automation.ItemNotFoundException]');+ expect(script).toContain('WriteLine("__CINDY_WINDOWS_GIT_PATH_DIAGNOSTIC__`tregistry")');+ expect(script).not.toContain('catch {}');+ });++ it('locks the mapped-drive classification probe and emits an unexpected-failure record', () => {+ const script = buildWindowsNetworkDriveProbeScript();++ expect(script).toContain('[System.IO.DriveInfo]::GetDrives()');+ expect(script).toContain('[System.IO.DriveType]::Network');+ expect(script).toContain('WriteLine("__CINDY_WINDOWS_GIT_PATH_DIAGNOSTIC__`tnetwork-drives")');+ expect(script).not.toContain('catch {}');+ });++ it('locks the single-candidate UTF-8 JSON and path metadata probe', () => {+ const script = buildWindowsPathKindProbeScript(1, 3_000);++ expect(script).toContain('[Console]::OpenStandardInput()');+ expect(script).toContain('[Text.Encoding]::UTF8.GetString($memory.ToArray())');+ expect(script).toContain('$candidate = [string]($json | ConvertFrom-Json)');+ expect(script).toContain('Get-Item -LiteralPath $candidate -Force -ErrorAction Stop');+ expect(script).toContain('"__CINDY_WINDOWS_GIT_PATH_DIAGNOSTIC__`tpath-kind"');+ expect(script).not.toContain('catch {}');+ });++ it('locks the bounded install-root process coordinator for multiple candidates', () => {+ const script = buildWindowsPathKindProbeScript(8, 3_000);++ expect(script).toContain('$allGroups = @($json | ConvertFrom-Json)');+ expect(script).toContain('$groups = @($allGroups | Select-Object -First 8)');+ expect(script).toContain('$clock = [Diagnostics.Stopwatch]::StartNew()');+ expect(script).toContain('$maxConcurrency = 4');+ expect(script).toContain('$operationTimeoutMs = 1250');+ expect(script).toContain('$operations.Count -lt $maxConcurrency');+ expect(script).toContain('$nextGroupIndex -lt $groups.Count -or $operations.Count -gt 0');+ expect(script).toContain("$startInfo.FileName = [IO.Path]::Combine($PSHOME, 'powershell.exe')");+ expect(script).toContain("$startInfo.EnvironmentVariables['CINDY_WINDOWS_GIT_PATH_CANDIDATES']");+ expect(script).toContain('[void]$process.Start()');+ expect(script).toContain('$expired = @($operations | Where-Object');+ expect(script).toContain('$operation.Process.Kill()');+ expect(script).toContain('Write-ProbeOutput $operation.Process');+ expect(script).toContain('$budgetMs = 2750');+ expect(script).toContain('if ($nextGroupIndex -lt $groups.Count -or $operations.Count -gt 0) {');+ expect(script).toContain('WriteLine("__CINDY_WINDOWS_GIT_PATH_DIAGNOSTIC__`tpath-process")');+ expect(script).not.toContain('foreach ($candidate in $paths)');+ expect(script).not.toContain('[RunspaceFactory]');+ expect(script.indexOf('$clock = [Diagnostics.Stopwatch]::StartNew()'))+ .toBeLessThan(script.indexOf('[void]$process.Start()'));+ expect(script.indexOf('$completed = @($operations | Where-Object { $_.Process.HasExited })'))+ .toBeLessThan(script.indexOf('foreach ($operation in $completed)'));+ expect(script).not.toContain('catch {}');++ const encodedProbeCommand = script.match(/\$probeCommand = '([^']+)'/)?.[1];+ expect(encodedProbeCommand).toBeTruthy();+ const probeCommand = Buffer.from(encodedProbeCommand ?? '', 'base64').toString('utf16le');+ expect(probeCommand).toContain('$env:CINDY_WINDOWS_GIT_PATH_CANDIDATES | ConvertFrom-Json');+ expect(probeCommand).toContain('foreach ($pathValue in $paths)');+ expect(probeCommand).toContain('Get-Item -LiteralPath $candidate -Force -ErrorAction Stop');+ expect(probeCommand).toContain('WriteLine($kind + "`t" + $encoded)');+ });++ it('caps queued install roots instead of shrinking PowerShell startup time', () => {+ const script = buildWindowsPathKindProbeScript(25, 3_000, 25);++ expect(script).toContain('$maxConcurrency = 4');+ expect(script).toContain('$operationTimeoutMs = 1250');+ expect(script).toContain('$groups = @($allGroups | Select-Object -First 8)');+ expect(script).toContain('__CINDY_WINDOWS_GIT_PATH_DIAGNOSTIC__`tpath-budget');+ expect(script).toContain('$nextGroupIndex += 1');+ });++ it('builds a recursive descendant cleanup script without candidate path data', () => {+ const script = buildWindowsDescendantCleanupScript(4321);++ expect(script).toContain('[void]$pending.Add(4321)');+ expect(script).toContain('Get-CimInstance Win32_Process');+ expect(script).toContain('ParentProcessId = ');+ expect(script).toContain('$descendants.Count - 1');+ expect(script).toContain('Stop-Process -Id ([int]$descendants[$index]) -Force');+ expect(script).not.toContain('C:\\');+ expect(() => buildWindowsDescendantCleanupScript(0)).toThrow(RangeError);+ });++ it.runIf(process.platform === 'win32')('executes grouped path probes in Windows PowerShell', () => {+ const systemRoot = process.env.SystemRoot ?? process.env.WINDIR;+ if (!systemRoot) throw new Error('Windows system root is unavailable');+ const tempRoot = mkdtempSync(path.join(tmpdir(), 'cindy-git-path-'));+ try {+ const staleRoot = path.join(tempRoot, 'stale-git');+ const validRoot = path.join(tempRoot, '有效 Git');+ const validCmd = path.join(validRoot, 'cmd');+ const validGit = path.join(validCmd, 'git.exe');+ mkdirSync(validCmd, { recursive: true });+ writeFileSync(validGit, '');+ const groups = [+ { paths: [path.join(staleRoot, 'cmd'), path.join(staleRoot, 'cmd', 'git.exe')] },+ { paths: [validCmd, validGit] },+ ];+ const output = execFileSync(+ path.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', buildWindowsPathKindProbeScript(4, 3_000, 2)],+ {+ encoding: 'utf8',+ input: Buffer.from(JSON.stringify(groups), 'utf8'),+ stdio: ['pipe', 'pipe', 'pipe'],+ timeout: 5_000,+ windowsHide: true,+ },+ );++ expect(output).toContain(`D\t${Buffer.from(validCmd, 'utf16le').toString('base64')}`);+ expect(output).toContain(`F\t${Buffer.from(validGit, 'utf16le').toString('base64')}`);+ } finally {+ rmSync(tempRoot, { recursive: true, force: true });+ }+ });++ it.runIf(process.platform === 'win32')('kills probe descendants after the coordinator times out', () => {+ const systemRoot = process.env.SystemRoot ?? process.env.WINDIR;+ if (!systemRoot) throw new Error('Windows system root is unavailable');+ const powershell = path.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');+ const encodedSleepCommand = Buffer.from('Start-Sleep -Seconds 30', 'utf16le').toString('base64');+ const script = [+ '$startInfo = New-Object System.Diagnostics.ProcessStartInfo',+ `$startInfo.FileName = '${powershell.replaceAll("'", "''")}'`,+ `$startInfo.Arguments = '-NoLogo -NoProfile -NonInteractive -EncodedCommand ${encodedSleepCommand}'`,+ '$startInfo.UseShellExecute = $false',+ '$startInfo.CreateNoWindow = $true',+ '$process = New-Object System.Diagnostics.Process',+ '$process.StartInfo = $startInfo',+ '[void]$process.Start()',+ '[Console]::Out.WriteLine($process.Id)',+ '[Console]::Out.Flush()',+ 'Start-Sleep -Seconds 30',+ ].join('\n');+ let childPid: number | undefined;+ let coordinatorPid: number | undefined;+ try {+ execFileSync(+ powershell,+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],+ {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ timeout: 1_500,+ windowsHide: true,+ },+ );+ throw new Error('coordinator unexpectedly completed before its timeout');+ } catch (error) {+ const failure = error as NodeJS.ErrnoException & { stdout?: string | Buffer };+ expect(failure.code).toBe('ETIMEDOUT');+ coordinatorPid = failure.pid;+ const output = Buffer.isBuffer(failure.stdout)+ ? failure.stdout.toString('utf8')+ : failure.stdout ?? '';+ childPid = Number(output.trim().split(/\r?\n/).at(-1));+ expect(Number.isInteger(childPid) && childPid > 0).toBe(true);+ }++ terminateWindowsPowerShellDescendants(powershell, coordinatorPid);++ try {+ execFileSync(+ powershell,+ [+ '-NoLogo',+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ [+ '$deadline = [DateTime]::UtcNow.AddSeconds(3)',+ `while (Get-Process -Id ${childPid} -ErrorAction SilentlyContinue) {`,+ ' if ([DateTime]::UtcNow -ge $deadline) { exit 1 }',+ ' Start-Sleep -Milliseconds 50',+ '}',+ ].join('\n'),+ ],+ { stdio: 'ignore', timeout: 5_000, windowsHide: true },+ );+ } finally {+ spawnSync('taskkill.exe', ['/PID', String(childPid), '/F'], { stdio: 'ignore', windowsHide: true });+ }+ }, 12_000);++ it('reports recoverable script failures only when a logger is supplied', () => {+ const warn = vi.fn();+ const output = [+ '__CINDY_WINDOWS_GIT_PATH_DIAGNOSTIC__\tpath-kind',+ '__CINDY_WINDOWS_GIT_PATH_DIAGNOSTIC__\tpath-runspace',+ 'F\tignored-record',+ ].join('\r\n');++ expect(countWindowsPowerShellDiagnostics(output)).toBe(2);+ warnWindowsGitPathProbeDiagnostics({ warn }, 'path-kinds', output);+ warnWindowsGitPathProbeDiagnostics(undefined, 'path-kinds', output);++ expect(warn).toHaveBeenCalledOnce();+ expect(warn).toHaveBeenCalledWith(+ 'windows git path probe completed with recoverable PowerShell errors',+ { probe: 'path-kinds', failures: 2 },+ );+ });++ it('reports bounded subprocess failures without logging candidate paths', () => {+ const warn = vi.fn();+ const error = Object.assign(new Error('command included C:\\Users\\alice\\Git'), {+ code: 'ETIMEDOUT',+ signal: 'SIGTERM',+ killed: true,+ });++ warnWindowsGitPathProbeFailure({ warn }, 'registry', error);++ expect(warn).toHaveBeenCalledWith(+ 'windows git path probe failed; continuing without unavailable metadata',+ {+ probe: 'registry',+ errorName: 'Error',+ code: 'ETIMEDOUT',+ signal: 'SIGTERM',+ killed: true,+ },+ );+ expect(JSON.stringify(warn.mock.calls)).not.toContain('alice');+ });+});diff --git a/packages/maker-core/src/agents/pi/windows-git-path-powershell.ts b/packages/maker-core/src/agents/pi/windows-git-path-powershell.tsnew file mode 100644index 0000000000..a07729f244--- /dev/null+++ b/packages/maker-core/src/agents/pi/windows-git-path-powershell.ts@@ -0,0 +1,281 @@+import { execFileSync } from 'node:child_process';++import type { Logger } from '../../interfaces/logger.js';++export type WindowsGitPathLogger = Pick<Logger, 'warn'>;++const DIAGNOSTIC_PREFIX = '__CINDY_WINDOWS_GIT_PATH_DIAGNOSTIC__';+const WINDOWS_DESCENDANT_CLEANUP_TIMEOUT_MS = 2_000;++type WindowsPowerShellProbe = 'registry' | 'network-drives' | 'path-kinds' | 'path-cleanup';++export function buildWindowsRegistryProbeScript(registryPaths: readonly string[]): string {+ const quotedPaths = registryPaths.map((registryPath) => `'${registryPath.replaceAll("'", "''")}'`).join(', ');+ return [+ `$keys = @(${quotedPaths})`,+ 'foreach ($key in $keys) {',+ ' try {',+ " $value = Get-ItemPropertyValue -LiteralPath $key -Name 'InstallPath' -ErrorAction Stop",+ ' if ($null -ne $value -and -not [string]::IsNullOrWhiteSpace([string]$value)) {',+ ' [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes([string]$value))',+ ' }',+ ' } catch [System.Management.Automation.ItemNotFoundException] {',+ ' # Git for Windows is not installed under this optional registry key.',+ ' } catch {',+ ` [Console]::Out.WriteLine("${DIAGNOSTIC_PREFIX}\`tregistry")`,+ ' }',+ '}',+ ].join('\n');+}++export function buildWindowsNetworkDriveProbeScript(): string {+ return [+ 'try {',+ ' [System.IO.DriveInfo]::GetDrives() |',+ ' Where-Object { $_.DriveType -eq [System.IO.DriveType]::Network } |',+ ' ForEach-Object { [Console]::Out.WriteLine($_.Name.Substring(0, 1)) }',+ '} catch {',+ ` [Console]::Out.WriteLine("${DIAGNOSTIC_PREFIX}\`tnetwork-drives")`,+ '}',+ ].join('\n');+}++export function buildWindowsDescendantCleanupScript(rootProcessId: number): string {+ if (!Number.isInteger(rootProcessId) || rootProcessId <= 0) {+ throw new RangeError('rootProcessId must be a positive integer');+ }+ return [+ '$pending = New-Object System.Collections.ArrayList',+ '$descendants = New-Object System.Collections.ArrayList',+ `[void]$pending.Add(${rootProcessId})`,+ 'while ($pending.Count -gt 0) {',+ ' $parentProcessId = [int]$pending[0]',+ ' $pending.RemoveAt(0)',+ ' $children = @(Get-CimInstance Win32_Process -Filter ("ParentProcessId = " + $parentProcessId) -ErrorAction Stop)',+ ' foreach ($child in $children) {',+ ' $childProcessId = [int]$child.ProcessId',+ ' [void]$descendants.Add($childProcessId)',+ ' [void]$pending.Add($childProcessId)',+ ' }',+ '}',+ 'for ($index = $descendants.Count - 1; $index -ge 0; $index -= 1) {',+ ' Stop-Process -Id ([int]$descendants[$index]) -Force -ErrorAction SilentlyContinue',+ '}',+ ].join('\n');+}++export function terminateWindowsPowerShellDescendants(+ powershell: string,+ rootProcessId: number | undefined,+ logger?: WindowsGitPathLogger,+): void {+ if (typeof rootProcessId !== 'number' || !Number.isInteger(rootProcessId) || rootProcessId <= 0) return;+ try {+ execFileSync(+ powershell,+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', buildWindowsDescendantCleanupScript(rootProcessId)],+ {+ stdio: 'ignore',+ timeout: WINDOWS_DESCENDANT_CLEANUP_TIMEOUT_MS,+ windowsHide: true,+ },+ );+ } catch (error) {+ warnWindowsGitPathProbeFailure(logger, 'path-cleanup', error);+ }+}++function windowsPathKindProbeLines(outputLine: string): string[] {+ return [+ 'try {',+ ' $item = Get-Item -LiteralPath $candidate -Force -ErrorAction Stop',+ " $kind = if ($item.PSIsContainer) { 'D' } else { 'F' }",+ ' $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($candidate))',+ outputLine,+ ' } catch [System.Management.Automation.ItemNotFoundException] {',+ ' # Missing candidate paths are expected during discovery.',+ ' } catch {',+ ` "${DIAGNOSTIC_PREFIX}\`tpath-kind"`,+ ' }',+ ];+}++export function maxWindowsPathKindProbeBatchCount(timeoutMs: number): number {+ const budgetMs = Math.max(timeoutMs - 250, 1);+ const availableOperationBudgetMs = Math.max(budgetMs - 250, 1);+ const operationTimeoutMs = Math.min(availableOperationBudgetMs, 1_250);+ const maxOperationWaves = Math.max(Math.floor(availableOperationBudgetMs / operationTimeoutMs), 1);+ return 4 * maxOperationWaves;+}++export function buildWindowsPathKindProbeScript(+ candidateCount: number,+ timeoutMs: number,+ batchCount = candidateCount,+): string {+ const inputPrelude = [+ '$stdin = [Console]::OpenStandardInput()',+ '$memory = New-Object System.IO.MemoryStream',+ '$stdin.CopyTo($memory)',+ '$json = [Text.Encoding]::UTF8.GetString($memory.ToArray())',+ ];+ if (candidateCount === 1) {+ return [+ ...inputPrelude,+ '$candidate = [string]($json | ConvertFrom-Json)',+ ...windowsPathKindProbeLines(' [Console]::Out.WriteLine($kind + "`t" + $encoded)'),+ ].join('\n');+ }+ const budgetMs = Math.max(timeoutMs - 250, 1);+ const operationCount = Math.min(Math.max(batchCount, 1), Math.max(candidateCount, 1));+ const maxConcurrency = Math.min(operationCount, 4);+ const availableOperationBudgetMs = Math.max(budgetMs - 250, 1);+ const operationTimeoutMs = Math.min(availableOperationBudgetMs, 1_250);+ const maxOperationCount = Math.min(operationCount, maxWindowsPathKindProbeBatchCount(timeoutMs));+ const encodedProbeCommand = Buffer.from([+ '$paths = @(([string]$env:CINDY_WINDOWS_GIT_PATH_CANDIDATES | ConvertFrom-Json))',+ 'foreach ($pathValue in $paths) {',+ ' $candidate = [string]$pathValue',+ ...windowsPathKindProbeLines(' [Console]::Out.WriteLine($kind + "`t" + $encoded)'),+ '}',+ ].join('\n'), 'utf16le').toString('base64');+ return [+ ...inputPrelude,+ '$allGroups = @($json | ConvertFrom-Json)',+ `$groups = @($allGroups | Select-Object -First ${maxOperationCount})`,+ 'if ($allGroups.Count -gt $groups.Count) {',+ ` [Console]::Out.WriteLine("${DIAGNOSTIC_PREFIX}\`tpath-budget")`,+ '}',+ `$probeCommand = '${encodedProbeCommand}'`,+ `$budgetMs = ${budgetMs}`,+ `$operationTimeoutMs = ${operationTimeoutMs}`,+ '$clock = [Diagnostics.Stopwatch]::StartNew()',+ `$maxConcurrency = ${maxConcurrency}`,+ '$operations = New-Object System.Collections.ArrayList',+ '$nextGroupIndex = 0',+ 'function Write-ProbeOutput([System.Diagnostics.Process]$process) {',+ ' try {',+ " foreach ($line in $process.StandardOutput.ReadToEnd() -split '\\r?\\n') {",+ ' if (-not [string]::IsNullOrWhiteSpace($line)) {',+ ' [Console]::Out.WriteLine([string]$line)',+ ' }',+ ' }',+ ' } catch {',+ ` [Console]::Out.WriteLine("${DIAGNOSTIC_PREFIX}\`tpath-process")`,+ ' }',+ '}',+ 'try {',+ ' while (($nextGroupIndex -lt $groups.Count -or $operations.Count -gt 0) -and $clock.ElapsedMilliseconds -lt $budgetMs) {',+ ' while ($nextGroupIndex -lt $groups.Count -and $operations.Count -lt $maxConcurrency -and $clock.ElapsedMilliseconds -lt $budgetMs) {',+ ' $group = $groups[$nextGroupIndex]',+ ' $nextGroupIndex += 1',+ ' $process = $null',+ ' try {',+ ' $startInfo = New-Object System.Diagnostics.ProcessStartInfo',+ " $startInfo.FileName = [IO.Path]::Combine($PSHOME, 'powershell.exe')",+ ' $startInfo.Arguments = "-NoLogo -NoProfile -NonInteractive -EncodedCommand $probeCommand"',+ ' $startInfo.UseShellExecute = $false',+ ' $startInfo.RedirectStandardOutput = $true',+ ' $startInfo.CreateNoWindow = $true',+ " $startInfo.EnvironmentVariables['CINDY_WINDOWS_GIT_PATH_CANDIDATES'] = (ConvertTo-Json -InputObject @($group.paths) -Compress)",+ ' $process = New-Object System.Diagnostics.Process',+ ' $process.StartInfo = $startInfo',+ ' [void]$process.Start()',+ ' [void]$operations.Add([PSCustomObject]@{ Process = $process; StartedAt = $clock.ElapsedMilliseconds })',+ ' } catch {',+ ` [Console]::Out.WriteLine("${DIAGNOSTIC_PREFIX}\`tpath-process")`,+ ' if ($null -ne $process) {',+ ' $process.Dispose()',+ ' }',+ ' }',+ ' }',+ ' $now = $clock.ElapsedMilliseconds',+ ' $completed = @($operations | Where-Object { $_.Process.HasExited })',+ ' $expired = @($operations | Where-Object { -not $_.Process.HasExited -and $now - $_.StartedAt -ge $operationTimeoutMs })',+ ' if ($completed.Count -eq 0 -and $expired.Count -eq 0) {',+ ' Start-Sleep -Milliseconds 10',+ ' continue',+ ' }',+ ' foreach ($operation in $completed) {',+ ' try {',+ ' Write-ProbeOutput $operation.Process',+ ' if ($operation.Process.ExitCode -ne 0) {',+ ` [Console]::Out.WriteLine("${DIAGNOSTIC_PREFIX}\`tpath-process")`,+ ' }',+ ' } catch {',+ ` [Console]::Out.WriteLine("${DIAGNOSTIC_PREFIX}\`tpath-process")`,+ ' } finally {',+ ' $operation.Process.Dispose()',+ ' [void]$operations.Remove($operation)',+ ' }',+ ' }',+ ' foreach ($operation in $expired) {',+ ` [Console]::Out.WriteLine("${DIAGNOSTIC_PREFIX}\`tpath-process")`,+ ' try {',+ ' $operation.Process.Kill()',+ ' $operation.Process.WaitForExit()',+ ' } catch {',+ ` [Console]::Out.WriteLine("${DIAGNOSTIC_PREFIX}\`tpath-process")`,+ ' } finally {',+ ' if ($operation.Process.HasExited) {',+ ' Write-ProbeOutput $operation.Process',+ ' }',+ ' $operation.Process.Dispose()',+ ' [void]$operations.Remove($operation)',+ ' }',+ ' }',+ ' }',+ ' if ($nextGroupIndex -lt $groups.Count -or $operations.Count -gt 0) {',+ ` [Console]::Out.WriteLine("${DIAGNOSTIC_PREFIX}\`tpath-process")`,+ ' }',+ '} catch {',+ ` [Console]::Out.WriteLine("${DIAGNOSTIC_PREFIX}\`tpath-process")`,+ '} finally {',+ ' foreach ($operation in @($operations)) {',+ ' try {',+ ' if (-not $operation.Process.HasExited) {',+ ' $operation.Process.Kill()',+ ' $operation.Process.WaitForExit()',+ ' }',+ ' } catch {',+ ` [Console]::Out.WriteLine("${DIAGNOSTIC_PREFIX}\`tpath-process")`,+ ' } finally {',+ ' if ($operation.Process.HasExited) {',+ ' Write-ProbeOutput $operation.Process',+ ' }',+ ' $operation.Process.Dispose()',+ ' }',+ ' }',+ '}',+ ].join('\n');+}++export function countWindowsPowerShellDiagnostics(output: string): number {+ return output.split(/\r?\n/).filter((line) => line.startsWith(`${DIAGNOSTIC_PREFIX}\t`)).length;+}++export function warnWindowsGitPathProbeDiagnostics(+ logger: WindowsGitPathLogger | undefined,+ probe: WindowsPowerShellProbe,+ output: string,+): void {+ const failures = countWindowsPowerShellDiagnostics(output);+ if (failures === 0) return;+ logger?.warn('windows git path probe completed with recoverable PowerShell errors', { probe, failures });+}++export function warnWindowsGitPathProbeFailure(+ logger: WindowsGitPathLogger | undefined,+ probe: WindowsPowerShellProbe,+ error: unknown,+): void {+ if (!logger) return;+ const failure = error as NodeJS.ErrnoException & { killed?: boolean; signal?: string };+ logger.warn('windows git path probe failed; continuing without unavailable metadata', {+ probe,+ errorName: error instanceof Error ? error.name : typeof error,+ code: failure?.code,+ signal: failure?.signal,+ killed: failure?.killed,+ });+}diff --git a/packages/maker-core/src/agents/pi/windows-git-path.test.ts b/packages/maker-core/src/agents/pi/windows-git-path.test.tsnew file mode 100644index 0000000000..4fe006f819--- /dev/null+++ b/packages/maker-core/src/agents/pi/windows-git-path.test.ts@@ -0,0 +1,661 @@+import { describe, expect, it } from 'vitest';++import {+ decodeWindowsRegistryBase64Lines,+ decodeWindowsPathKindLines,+ decodeWindowsPathKindsFromProbeError,+ findWindowsExecutablesOnPath,+ gitInstallRootFromPath,+ gitPathsForInstallRoot,+ partitionWindowsProbeCandidates,+ probePartitionedWindowsPathKinds,+ resolveWindowsGitPath,+ translateMsysPathSegment,+ WINDOWS_GIT_REGISTRY_KEYS,+ type WindowsGitPathProbes,+} from './windows-git-path.js';++function fakeFs(files: string[]): Pick<WindowsGitPathProbes, 'isDirectory' | 'isFile'> {+ const fileSet = new Set(files.map((file) => file.toLowerCase()));+ const dirs = new Set<string>();+ for (const file of fileSet) {+ let current = file;+ while (true) {+ current = current.slice(0, current.lastIndexOf('\\'));+ if (!current) break;+ dirs.add(current);+ if (/^[a-z]:$/i.test(current)) break;+ }+ }+ return {+ isFile: (candidate) => fileSet.has(candidate.replaceAll('/', '\\').toLowerCase()),+ isDirectory: (candidate) => dirs.has(candidate.replaceAll('/', '\\').replace(/[\\]+$/, '').toLowerCase()),+ };+}++describe('Windows Git/PATH helpers', () => {+ it('checks per-user Git for Windows installs before machine-wide registry keys', () => {+ expect(WINDOWS_GIT_REGISTRY_KEYS).toEqual([+ 'HKCU\\SOFTWARE\\GitForWindows',+ 'HKLM\\SOFTWARE\\GitForWindows',+ 'HKLM\\SOFTWARE\\WOW6432Node\\GitForWindows',+ ]);+ });++ it('round-trips non-ASCII registry paths through the PowerShell Base64 transport', () => {+ const installPath = 'C:\\Users\\测试用户\\Git';+ const encoded = Buffer.from(installPath, 'utf16le').toString('base64');+ expect(decodeWindowsRegistryBase64Lines(`${encoded}\r\nnot-base64\r\n`)).toEqual([installPath]);+ });++ it('isolates UNC candidates and keeps device paths local', () => {+ expect(partitionWindowsProbeCandidates([+ '\\\\offline-server\\Git\\cmd',+ 'C:\\PortableGit\\cmd',+ '\\\\?\\C:\\PortableGit\\cmd',+ '//offline-server/Git/bin',+ ], new Set())).toEqual({+ local: ['C:\\PortableGit\\cmd', '\\\\?\\C:\\PortableGit\\cmd'],+ network: ['\\\\offline-server\\Git\\cmd', '//offline-server/Git/bin'],+ });+ });++ it('isolates mapped network drives from local Git paths', () => {+ expect(partitionWindowsProbeCandidates([+ 'Z:\\Git\\cmd\\git.exe',+ 'C:\\PortableGit\\cmd',+ ], new Set(['z']))).toEqual({+ local: ['C:\\PortableGit\\cmd'],+ network: ['Z:\\Git\\cmd\\git.exe'],+ });+ });++ it('keeps a later PortableGit PATH result when an earlier UNC candidate fails', () => {+ const offlineGit = '\\\\offline-server\\Git\\cmd\\git.exe';+ const localCmd = 'C:\\PortableGit\\cmd';+ const localGit = `${localCmd}\\git.exe`;+ const phases: string[][][] = [];++ const kinds = probePartitionedWindowsPathKinds(+ [offlineGit, localCmd, localGit],+ new Set(),+ (batches) => {+ phases.push(batches.map((batch) => [...batch]));+ if (batches.some((batch) => batch.includes(offlineGit))) return new Map();+ return new Map([+ [localCmd, 'directory'],+ [localGit, 'file'],+ ]);+ },+ );++ expect(phases).toEqual([[[localCmd, localGit]], [[offlineGit]]]);+ expect(kinds).toEqual(new Map([+ [localCmd, 'directory'],+ [localGit, 'file'],+ ]));+ });++ it('isolates an unclassified mapped drive from another local drive', () => {+ const offlineMappedGit = 'Z:\\Git\\cmd\\git.exe';+ const localCmd = 'C:\\PortableGit\\cmd';+ const localGit = `${localCmd}\\git.exe`;+ const phases: string[][][] = [];++ const kinds = probePartitionedWindowsPathKinds(+ [offlineMappedGit, localCmd, localGit],+ new Set(),+ (batches) => {+ phases.push(batches.map((batch) => [...batch]));+ return new Map([+ [localCmd, 'directory'],+ [localGit, 'file'],+ ]);+ },+ );++ expect(phases).toEqual([[[offlineMappedGit], [localCmd, localGit]]]);+ expect(kinds).toEqual(new Map([+ [localCmd, 'directory'],+ [localGit, 'file'],+ ]));+ });++ it('uses one total network batch across UNC shares and mapped drives', () => {+ const localGit = 'C:\\PortableGit\\cmd\\git.exe';+ const firstUnc = '\\\\offline-one\\Git\\cmd\\git.exe';+ const secondUnc = '\\\\offline-two\\Git\\cmd\\git.exe';+ const mappedGit = 'Z:\\Git\\cmd\\git.exe';+ const phases: string[][][] = [];++ probePartitionedWindowsPathKinds(+ [firstUnc, localGit, secondUnc, mappedGit],+ new Set(['Z']),+ (batches) => {+ phases.push(batches.map((batch) => [...batch]));+ return new Map();+ },+ );++ expect(phases).toEqual([+ [[localGit]],+ [[firstUnc], [secondUnc], [mappedGit]],+ ]);+ });++ it('keeps a later network Git result when an earlier network root times out', () => {+ const offlineGit = '\\\\offline-server\\Git\\cmd\\git.exe';+ const mappedGit = 'Z:\\PortableGit\\cmd\\git.exe';+ const networkBatches: string[][][] = [];++ const kinds = probePartitionedWindowsPathKinds(+ [offlineGit, mappedGit],+ new Set(['Z']),+ (batches) => {+ networkBatches.push(batches.map((batch) => [...batch]));+ return new Map([[mappedGit, 'file']]);+ },+ );++ expect(networkBatches).toEqual([[[offlineGit], [mappedGit]]]);+ expect(kinds).toEqual(new Map([[mappedGit, 'file']]));+ });++ it('isolates candidates within the same network root under one shared budget', () => {+ const offlineGit = 'Z:\\OldGit\\cmd\\git.exe';+ const mappedGit = 'Z:\\PortableGit\\cmd\\git.exe';+ const phases: string[][][] = [];++ const kinds = probePartitionedWindowsPathKinds(+ [offlineGit, mappedGit],+ new Set(['Z']),+ (batches) => {+ phases.push(batches.map((batch) => [...batch]));+ return new Map([[mappedGit, 'file']]);+ },+ );++ expect(phases).toEqual([[[offlineGit], [mappedGit]]]);+ expect(kinds).toEqual(new Map([[mappedGit, 'file']]));+ });++ it('uses one shared local budget when mapped drives cannot be classified', () => {+ const firstOfflineGit = 'Y:\\Git\\cmd\\git.exe';+ const secondOfflineGit = 'Z:\\Git\\cmd\\git.exe';+ const localGit = 'C:\\PortableGit\\cmd\\git.exe';+ const phases: string[][][] = [];++ const kinds = probePartitionedWindowsPathKinds(+ [firstOfflineGit, secondOfflineGit, localGit],+ new Set(),+ (batches) => {+ phases.push(batches.map((batch) => [...batch]));+ return new Map([[localGit, 'file']]);+ },+ );++ expect(phases).toEqual([[[firstOfflineGit], [secondOfflineGit], [localGit]]]);+ expect(kinds).toEqual(new Map([[localGit, 'file']]));+ });++ it('keeps one stale install root from consuming every local probe slot', () => {+ const offlineRoot = 'Y:\\OldGit';+ const localRoot = 'C:\\PortableGit';+ const offlineCandidates = [+ `${offlineRoot}\\cmd\\git.exe`,+ `${offlineRoot}\\cmd`,+ `${offlineRoot}\\cmd\\git.cmd`,+ `${offlineRoot}\\cmd\\git.bat`,+ `${offlineRoot}\\bin`,+ `${offlineRoot}\\bin\\git.exe`,+ `${offlineRoot}\\bin\\git.cmd`,+ `${offlineRoot}\\bin\\git.bat`,+ `${offlineRoot}\\usr\\bin`,+ `${offlineRoot}\\usr\\bin\\git.exe`,+ `${offlineRoot}\\usr\\bin\\git.cmd`,+ `${offlineRoot}\\usr\\bin\\git.bat`,+ `${offlineRoot}\\usr\\bin\\ls.exe`,+ ];+ const localCmd = `${localRoot}\\cmd`;+ const localGit = `${localCmd}\\git.exe`;+ const phases: string[][][] = [];++ const kinds = probePartitionedWindowsPathKinds(+ [...offlineCandidates, localGit, localCmd],+ new Set(),+ (batches) => {+ phases.push(batches.map((batch) => [...batch]));+ return new Map([[localGit, 'file'], [localCmd, 'directory']]);+ },+ );++ expect(phases).toEqual([[offlineCandidates, [localGit, localCmd]]]);+ expect(kinds).toEqual(new Map([[localGit, 'file'], [localCmd, 'directory']]));+ });++ it('keeps a valid HKLM Git root after an earlier offline HKCU root', () => {+ const offlineRoot = '\\\\offline-server\\Git';+ const localRoot = 'C:\\Program Files\\Git';+ const localCmd = `${localRoot}\\cmd`;+ const localGit = `${localCmd}\\git.exe`;+ const phases: string[][][] = [];++ const result = resolveWindowsGitPath({+ platform: 'win32',+ existingPath: 'C:\\Windows',+ probes: {+ readRegistryInstallPaths: () => [offlineRoot, localRoot],+ findGitExecutablesOnPath: () => [],+ probePathKinds: (candidates) => probePartitionedWindowsPathKinds(+ candidates,+ new Set(),+ (batches) => {+ phases.push(batches.map((batch) => [...batch]));+ if (batches.some((batch) => batch.some((candidate) => candidate.startsWith(offlineRoot)))) {+ return new Map();+ }+ return new Map([+ [localCmd, 'directory'],+ [localGit, 'file'],+ ]);+ },+ ),+ },+ });++ expect(phases[0]?.flat()).toContain(localGit);+ expect(phases.at(-1)?.flat().every((candidate) => candidate.startsWith(offlineRoot))).toBe(true);+ expect(result).toBe(`C:\\Windows;${localCmd}`);+ });++ it('reserves bounded probe capacity for registry fallbacks after PATH roots are capped', () => {+ const staleRoots = Array.from({ length: 8 }, (_, index) => `C:\\StaleGit${index + 1}`);+ const staleGitExecutables = staleRoots.map((root) => `${root}\\cmd\\git.exe`);+ const registryRoot = 'D:\\Program Files\\Git';+ const registryCmd = `${registryRoot}\\cmd`;+ const registryGit = `${registryCmd}\\git.exe`;+ const phases: string[][][] = [];+ const warnings: Array<{ message: string; context: Record<string, unknown> | undefined }> = [];++ const result = resolveWindowsGitPath({+ platform: 'win32',+ existingPath: 'C:\\Windows',+ probes: {+ readRegistryInstallPaths: () => [registryRoot],+ findGitExecutablesOnPath: () => staleGitExecutables,+ probePathKinds: (candidates) => probePartitionedWindowsPathKinds(+ candidates,+ new Set(),+ (batches) => {+ phases.push(batches.map((batch) => [...batch]));+ const admitted = batches.slice(0, 8).flat();+ if (!admitted.includes(registryGit)) return new Map();+ return new Map([+ [registryCmd, 'directory'],+ [registryGit, 'file'],+ ]);+ },+ ),+ },+ logger: {+ warn: (message, context) => warnings.push({ message, context }),+ },+ });++ expect(phases).toHaveLength(1);+ expect(phases[0].slice(0, 8).some((batch) => batch.includes(registryGit))).toBe(true);+ expect(phases[0][8]).toEqual([staleGitExecutables[7]]);+ expect(warnings).toEqual([{+ message: 'windows git path PATH install-root candidates truncated',+ context: { limit: 7, omitted: 1 },+ }]);+ expect(JSON.stringify(warnings)).not.toContain(staleRoots[7]);+ expect(result).toBe(`C:\\Windows;${registryCmd}`);+ });++ it('finds git.exe in Unicode PATH segments without searching the current directory', () => {+ const gitPath = 'C:\\Users\\测试用户\\Git\\cmd\\git.exe';+ const isFile = (candidate: string) => candidate === gitPath;+ expect(findWindowsExecutablesOnPath(+ ';;tools;\\root-relative;"C:\\Users\\测试用户\\Git\\cmd";C:\\Windows',+ 'git.exe',+ isFile,+ )).toEqual([gitPath]);+ });++ it('round-trips Unicode file kinds from the bounded native path probe', () => {+ const directory = 'C:\\Users\\测试用户\\Git\\cmd';+ const file = `${directory}\\git.exe`;+ const output = [+ `D\t${Buffer.from(directory, 'utf16le').toString('base64')}`,+ `F\t${Buffer.from(file, 'utf16le').toString('base64')}`,+ 'invalid',+ ].join('\r\n');+ expect([...decodeWindowsPathKindLines(output).values()]).toEqual(['directory', 'file']);+ });++ it('uses one injected path-kind snapshot instead of direct filesystem probes', () => {+ const root = '\\\\offline-server\\Git';+ const cmd = `${root}\\cmd`;+ const git = `${cmd}\\git.exe`;+ let captured: readonly string[] = [];+ const result = resolveWindowsGitPath({+ platform: 'win32',+ existingPath: 'C:\\Windows',+ probes: {+ readRegistryInstallPaths: () => [root],+ findGitExecutablesOnPath: () => [],+ probePathKinds: (candidates) => {+ captured = candidates;+ return new Map([[cmd, 'directory'], [git, 'file']]);+ },+ },+ });+ expect(captured).toContain(git);+ expect(result).toBe(`C:\\Windows;${cmd}`);+ });++ it('validates PATH executables and install roots in one path-kind snapshot', () => {+ const staleGit = 'Z:\\OldGit\\cmd\\git.exe';+ const git = 'C:\\PortableGit\\cmd\\git.exe';+ const cmd = 'C:\\PortableGit\\cmd';+ const bin = 'C:\\PortableGit\\bin';+ const binGit = `${bin}\\git.exe`;+ const snapshots: string[][] = [];++ const result = resolveWindowsGitPath({+ platform: 'win32',+ existingPath: 'C:\\Windows',+ probes: {+ readRegistryInstallPaths: () => [],+ findGitExecutablesOnPath: () => [staleGit, git],+ probePathKinds: (candidates) => {+ snapshots.push([...candidates]);+ return new Map([+ [git, 'file'],+ [cmd, 'directory'],+ [binGit, 'file'],+ [bin, 'directory'],+ ]);+ },+ },+ });++ expect(snapshots).toHaveLength(1);+ expect(snapshots[0]).toEqual(expect.arrayContaining([staleGit, git, cmd, binGit, bin]));+ expect(result).toBe(`C:\\Windows;${cmd};${bin}`);+ });++ it('keeps path records emitted before a bounded probe timeout', () => {+ const root = 'C:\\PortableGit';+ const cmd = `${root}\\cmd`;+ const git = `${cmd}\\git.exe`;+ const partialOutput = [+ `D\t${Buffer.from(cmd, 'utf16le').toString('base64')}`,+ `F\t${Buffer.from(git, 'utf16le').toString('base64')}`,+ ].join('\r\n');+ const timeout = Object.assign(new Error('probe timed out'), { stdout: partialOutput });++ expect(decodeWindowsPathKindsFromProbeError(timeout)).toEqual(new Map([+ [cmd.toLowerCase(), 'directory'],+ [git.toLowerCase(), 'file'],+ ]));++ expect(resolveWindowsGitPath({+ platform: 'win32',+ existingPath: `\\\\offline-server\\Git;${cmd};C:\\Windows`,+ probes: {+ readRegistryInstallPaths: () => [ '\\\\offline-server\\Git' ],+ findGitExecutablesOnPath: () => [git],+ probePathKinds: () => decodeWindowsPathKindsFromProbeError(timeout),+ },+ })).toBe(`\\\\offline-server\\Git;${cmd};C:\\Windows`);+ });++ it('discovers Git install paths from registry probes', () => {+ const fs = fakeFs([+ 'C:\\Program Files\\Git\\cmd\\git.exe',+ 'C:\\Program Files\\Git\\bin\\git.exe',+ 'C:\\Program Files\\Git\\usr\\bin\\ls.exe',+ ]);+ const result = resolveWindowsGitPath({+ platform: 'win32',+ existingPath: 'C:\\Windows\\System32',+ probes: {+ readRegistryInstallPaths: () => ['C:\\Program Files\\Git'],+ findGitExecutablesOnPath: () => [],+ ...fs,+ },+ });+ expect(result.split(';')).toEqual([+ 'C:\\Windows\\System32',+ 'C:\\Program Files\\Git\\cmd',+ 'C:\\Program Files\\Git\\bin',+ 'C:\\Program Files\\Git\\usr\\bin',+ ]);+ });++ it('discovers a Git install root from a PATH executable', () => {+ const fs = fakeFs([+ 'C:\\Tools\\Git\\bin\\git.exe',+ 'C:\\Tools\\Git\\cmd\\git.exe',+ ]);+ const result = resolveWindowsGitPath({+ platform: 'win32',+ existingPath: '',+ probes: {+ readRegistryInstallPaths: () => [],+ findGitExecutablesOnPath: () => ['C:\\Tools\\Git\\bin\\git.exe'],+ ...fs,+ },+ });+ expect(result).toBe('C:\\Tools\\Git\\cmd;C:\\Tools\\Git\\bin');+ });++ it('keeps the PATH-selected Git root ahead of registry fallbacks', () => {+ const fs = fakeFs([+ 'C:\\Git\\cmd\\git.exe',+ 'C:\\Git\\bin\\git.exe',+ 'D:\\Git\\cmd\\git.exe',+ 'D:\\Git\\bin\\git.exe',+ ]);+ const result = resolveWindowsGitPath({+ platform: 'win32',+ existingPath: 'D:\\Git\\cmd;C:\\Windows',+ probes: {+ readRegistryInstallPaths: () => ['C:\\Git'],+ findGitExecutablesOnPath: () => ['D:\\Git\\cmd\\git.exe'],+ ...fs,+ },+ });++ expect(result.split(';')).toEqual([+ 'D:\\Git\\cmd',+ 'C:\\Windows',+ 'D:\\Git\\bin',+ 'C:\\Git\\cmd',+ 'C:\\Git\\bin',+ ]);+ });++ it.each([+ ['C:\\Git\\cmd\\git.exe', 'C:\\Git'],+ ['C:\\Git\\bin\\git.exe', 'C:\\Git'],+ ['C:\\Git\\usr\\bin\\git.exe', 'C:\\Git'],+ ['C:\\Git\\mingw64\\bin\\git.exe', 'C:\\Git'],+ ['C:\\Git\\mingw32\\bin\\git.exe', 'C:\\Git'],+ ])('infers install root from PATH executable %s', (gitPath, expected) => {+ expect(gitInstallRootFromPath(gitPath)).toBe(expected);+ });++ it('rejects a package-manager shim as a Git install root', () => {+ expect(gitInstallRootFromPath('C:\\Users\\alice\\scoop\\shims\\git.exe')).toBeUndefined();+ });++ it('does not let a generic bin shim prove its own Git for Windows root', () => {+ const shim = 'C:\\ProgramData\\chocolatey\\bin\\git.exe';+ const fs = fakeFs([shim]);++ expect(resolveWindowsGitPath({+ platform: 'win32',+ existingPath: 'C:\\Windows',+ probes: { readRegistryInstallPaths: () => [], findGitExecutablesOnPath: () => [shim], ...fs },+ })).toBe('C:\\Windows');+ });++ it('does not let a cmd shim prove its own Git for Windows root', () => {+ const shim = 'C:\\Tools\\cmd\\git.exe';+ const fs = fakeFs([shim]);++ expect(resolveWindowsGitPath({+ platform: 'win32',+ existingPath: 'C:\\Windows',+ probes: { readRegistryInstallPaths: () => [], findGitExecutablesOnPath: () => [shim], ...fs },+ })).toBe('C:\\Windows');+ });++ it.each([+ 'C:\\Git\\cmd\\git.exe',+ 'C:\\Git\\bin\\git.exe',+ 'C:\\Git\\usr\\bin\\git.exe',+ 'C:\\Git\\mingw64\\bin\\git.exe',+ ])('uses a PATH executable at %s to add the inferred root paths', (gitPath) => {+ const fs = fakeFs([gitPath, 'C:\\Git\\cmd\\git.exe', 'C:\\Git\\bin\\git.exe']);+ const result = resolveWindowsGitPath({+ platform: 'win32',+ existingPath: '',+ probes: { readRegistryInstallPaths: () => [], findGitExecutablesOnPath: () => [gitPath], ...fs },+ });+ expect(result).toContain('C:\\Git\\cmd');+ });++ it('ignores executable shims without running PATH candidates', () => {+ const shim = 'C:\\Users\\alice\\workspace\\tools\\git.exe';+ const standardGit = 'C:\\PortableGit\\cmd\\git.exe';+ const fs = fakeFs([shim, standardGit, 'C:\\PortableGit\\bin\\git.exe']);+ const result = resolveWindowsGitPath({+ platform: 'win32',+ existingPath: 'C:\\Windows',+ probes: {+ readRegistryInstallPaths: () => [],+ findGitExecutablesOnPath: () => [shim, standardGit],+ ...fs,+ },+ });+ expect(result).toBe('C:\\Windows;C:\\PortableGit\\cmd;C:\\PortableGit\\bin');+ });++ it('fails open when a wrapper cannot identify a valid Git for Windows root', () => {+ const original = 'C:\\Windows;C:\\Tools';+ expect(resolveWindowsGitPath({+ platform: 'win32',+ existingPath: original,+ probes: {+ readRegistryInstallPaths: () => [],+ findGitExecutablesOnPath: () => ['C:\\Tools\\git.cmd'],+ isDirectory: () => false,+ isFile: () => false,+ },+ })).toBe(original);+ });++ it('validates cmd, bin and usr/bin candidates', () => {+ const fs = fakeFs(['D:\\Git\\cmd\\git.cmd', 'D:\\Git\\usr\\bin\\ls.exe']);+ expect(gitPathsForInstallRoot('D:\\Git', fs)).toEqual(['D:\\Git\\cmd', 'D:\\Git\\usr\\bin']);+ });++ it('deduplicates Windows PATH entries case-insensitively', () => {+ const fs = fakeFs(['C:\\Git\\cmd\\git.exe']);+ const result = resolveWindowsGitPath({+ platform: 'win32',+ existingPath: 'C:\\Git\\CMD;c:\\git\\cmd;C:\\Windows',+ probes: { readRegistryInstallPaths: () => ['c:\\git'], findGitExecutablesOnPath: () => [], ...fs },+ });+ expect(result.split(';')).toEqual(['C:\\Git\\CMD', 'C:\\Windows']);+ });++ it('keeps Windows drive roots distinct from drive-relative paths', () => {+ const fs = fakeFs(['C:\\Git\\cmd\\git.exe']);+ const result = resolveWindowsGitPath({+ platform: 'win32',+ existingPath: 'C:\\;C:',+ probes: { readRegistryInstallPaths: () => ['C:\\Git'], findGitExecutablesOnPath: () => [], ...fs },+ });+ expect(result.split(';')).toEqual(['C:\\', 'C:', 'C:\\Git\\cmd']);+ });++ it('translates MSYS drive paths and anchors known MSYS roots', () => {+ expect(translateMsysPathSegment('/c/Users/alice', [], () => false)).toBe('C:\\Users\\alice');+ expect(translateMsysPathSegment('/d', [], () => false)).toBe('D:\\');+ expect(translateMsysPathSegment('/usr/bin', ['C:\\Git'], (candidate) => candidate === 'C:\\Git\\usr\\bin'))+ .toBe('C:\\Git\\usr\\bin');+ expect(translateMsysPathSegment('\\usr\\bin', ['C:\\Git'], () => true)).toBeUndefined();+ expect(translateMsysPathSegment('C:\\Windows', ['C:\\Git'], () => true)).toBeUndefined();+ });++ it('preserves native root-relative PATH entries when Git is discovered', () => {+ const rootRelative = '\\custom\\bin';+ const gitRoot = 'C:\\Git';+ const gitCmd = `${gitRoot}\\cmd`;+ const gitExecutable = `${gitCmd}\\git.exe`;+ const translatedCandidate = `${gitRoot}\\custom\\bin`;+ const captured: string[] = [];++ const result = resolveWindowsGitPath({+ platform: 'win32',+ existingPath: `${rootRelative};C:\\Windows`,+ probes: {+ readRegistryInstallPaths: () => [gitRoot],+ findGitExecutablesOnPath: () => [],+ probePathKinds: (candidates) => {+ captured.push(...candidates);+ return new Map([+ [gitCmd.toLowerCase(), 'directory'],+ [gitExecutable.toLowerCase(), 'file'],+ [translatedCandidate.toLowerCase(), 'directory'],+ ]);+ },+ },+ });++ expect(captured).not.toContain(translatedCandidate);+ expect(result).toBe(`${rootRelative};C:\\Windows;${gitCmd}`);+ });++ it('keeps the original PATH when Git is unavailable', () => {+ const original = 'C:\\Windows;C:\\Tools';+ expect(resolveWindowsGitPath({+ platform: 'win32',+ existingPath: original,+ probes: {+ readRegistryInstallPaths: () => [],+ findGitExecutablesOnPath: () => [],+ isDirectory: () => false,+ isFile: () => false,+ },+ })).toBe(original);+ });++ it('keeps the original PATH when registry discovery only finds a stale install root', () => {+ const original = 'C:\\Tools;C:\\TOOLS';+ expect(resolveWindowsGitPath({+ platform: 'win32',+ existingPath: original,+ probes: {+ readRegistryInstallPaths: () => ['C:\\Missing Git'],+ findGitExecutablesOnPath: () => [],+ isDirectory: () => false,+ isFile: () => false,+ },+ })).toBe(original);+ });++ it('does not change PATH on non-Windows platforms', () => {+ const original = '/usr/bin:/bin';+ expect(resolveWindowsGitPath({+ platform: 'linux',+ existingPath: original,+ probes: { readRegistryInstallPaths: () => { throw new Error('must not probe'); } },+ })).toBe(original);+ });+});diff --git a/packages/maker-core/src/agents/pi/windows-git-path.ts b/packages/maker-core/src/agents/pi/windows-git-path.tsnew file mode 100644index 0000000000..b0432a20a2--- /dev/null+++ b/packages/maker-core/src/agents/pi/windows-git-path.ts@@ -0,0 +1,576 @@+import { execFileSync } from 'node:child_process';+import path from 'node:path';++import {+ buildWindowsNetworkDriveProbeScript,+ buildWindowsPathKindProbeScript,+ buildWindowsRegistryProbeScript,+ maxWindowsPathKindProbeBatchCount,+ terminateWindowsPowerShellDescendants,+ type WindowsGitPathLogger,+ warnWindowsGitPathProbeDiagnostics,+ warnWindowsGitPathProbeFailure,+} from './windows-git-path-powershell.js';++export type WindowsPathKind = 'file' | 'directory';++/**+ * Windows Git/PATH helpers for the future Pi shell integration.+ *+ * Behavior is adapted from oh-my-pi's `crates/pi-shell/src/windows.rs`+ * (https://github.com/can1357/oh-my-pi, commit 326d24bd40d9858e24e1036ae739c27c72eeb543).+ * The upstream project is MIT-licensed; this small, dependency-free port is+ * compatible with Cindy's Apache-2.0 distribution. It is intentionally not+ * wired into PiAgent or any production startup path in this PR.+ */++export interface WindowsGitPathProbes {+ readRegistryInstallPaths: () => readonly string[];+ findGitExecutablesOnPath: (pathValue: string | undefined) => readonly string[];+ probePathKinds: (candidates: readonly string[]) => ReadonlyMap<string, WindowsPathKind>;+ isDirectory: (candidate: string) => boolean;+ isFile: (candidate: string) => boolean;+}++export interface ResolveWindowsGitPathOptions {+ platform?: NodeJS.Platform;+ existingPath: string | undefined;+ probes?: Partial<WindowsGitPathProbes>;+ logger?: WindowsGitPathLogger;+}++export const WINDOWS_GIT_REGISTRY_KEYS = [+ 'HKCU\\SOFTWARE\\GitForWindows',+ 'HKLM\\SOFTWARE\\GitForWindows',+ 'HKLM\\SOFTWARE\\WOW6432Node\\GitForWindows',+] as const;++const WINDOWS_GIT_EXECUTABLE = 'git.exe';+const WINDOWS_PATH_PROBE_TIMEOUT_MS = 3_000;++/**+ * PowerShell emits each registry value as UTF-16LE Base64. The transport is+ * therefore ASCII-only and cannot be corrupted by the active Windows console+ * code page before Node receives it.+ */+export function decodeWindowsRegistryBase64Lines(output: string): string[] {+ const values: string[] = [];+ for (const rawLine of output.split(/\r?\n/)) {+ const line = rawLine.trim();+ if (+ line.length === 0+ || line.length % 4 !== 0+ || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(line)+ ) {+ continue;+ }+ const bytes = Buffer.from(line, 'base64');+ if (bytes.length === 0 || bytes.length % 2 !== 0) continue;+ const value = bytes.toString('utf16le').trim();+ if (value) values.push(value);+ }+ return values;+}++function windowsPowerShellPath(): string | undefined {+ const systemRoot = process.env.SystemRoot ?? process.env.WINDIR;+ if (!systemRoot) return undefined;+ return path.win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');+}++function windowsRegistryProviderPath(key: typeof WINDOWS_GIT_REGISTRY_KEYS[number]): string {+ if (key.startsWith('HKCU\\')) {+ return `Registry::HKEY_CURRENT_USER\\${key.slice('HKCU\\'.length)}`;+ }+ return `Registry::HKEY_LOCAL_MACHINE\\${key.slice('HKLM\\'.length)}`;+}++function defaultReadRegistryInstallPaths(logger?: WindowsGitPathLogger): readonly string[] {+ if (process.platform !== 'win32') return [];+ const powershell = windowsPowerShellPath();+ if (!powershell) return [];+ const script = buildWindowsRegistryProbeScript(WINDOWS_GIT_REGISTRY_KEYS.map(windowsRegistryProviderPath));+ try {+ const output = execFileSync(powershell, ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script], {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ timeout: 3_000,+ windowsHide: true,+ });+ warnWindowsGitPathProbeDiagnostics(logger, 'registry', output);+ return decodeWindowsRegistryBase64Lines(output);+ } catch (error) {+ warnWindowsGitPathProbeFailure(logger, 'registry', error);+ return [];+ }+}++/** Decode the ASCII-only records emitted by the bounded PowerShell path probe. */+export function decodeWindowsPathKindLines(output: string): Map<string, WindowsPathKind> {+ const kinds = new Map<string, WindowsPathKind>();+ for (const rawLine of output.split(/\r?\n/)) {+ const match = rawLine.trim().match(/^([FD])\t(.+)$/);+ if (!match) continue;+ const encoded = match[2];+ if (+ encoded.length % 4 !== 0+ || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)+ ) {+ continue;+ }+ const bytes = Buffer.from(encoded, 'base64');+ if (bytes.length === 0 || bytes.length % 2 !== 0) continue;+ const candidate = bytes.toString('utf16le');+ const normalized = normalizedWindowsPath(candidate);+ if (!normalized) continue;+ kinds.set(normalized, match[1] === 'D' ? 'directory' : 'file');+ }+ return kinds;+}++/** Preserve records emitted before a bounded native probe fails or times out. */+export function decodeWindowsPathKindsFromProbeError(error: unknown): Map<string, WindowsPathKind> {+ const partialOutput = (error as { stdout?: string | Buffer } | undefined)?.stdout;+ if (typeof partialOutput === 'string') return decodeWindowsPathKindLines(partialOutput);+ if (Buffer.isBuffer(partialOutput)) return decodeWindowsPathKindLines(partialOutput.toString('utf8'));+ return new Map();+}++function isWindowsUncPath(candidate: string): boolean {+ if (!candidate.startsWith('\\\\') && !candidate.startsWith('//')) return false;+ // Device paths (`\\?\` and `\\.\`) are not network shares.+ return !/^\\\\[?.]\\/.test(candidate);+}++/**+ * Keep network candidates in a separate native probe: an offline UNC share or+ * mapped network drive must not consume the timeout for local Git paths.+ */+export function partitionWindowsProbeCandidates(+ candidates: readonly string[],+ networkDriveLetters: ReadonlySet<string>,+): { local: string[]; network: string[] } {+ const normalizedNetworkDriveLetters = new Set(+ [...networkDriveLetters].map((letter) => letter.trim().toUpperCase()),+ );+ const local: string[] = [];+ const network: string[] = [];+ for (const candidate of candidates) {+ const driveLetter = candidate.match(/^([A-Za-z]):/)?.[1]?.toUpperCase();+ (isWindowsUncPath(candidate)+ || (driveLetter !== undefined && normalizedNetworkDriveLetters.has(driveLetter))+ ? network+ : local).push(candidate);+ }+ return { local, network };+}++function windowsGitInstallRootForProbeCandidate(candidate: string): string | undefined {+ const normalized = path.win32.normalize(candidate);+ const executableRoot = gitInstallRootFromPath(normalized);+ if (executableRoot) return executableRoot;+ const name = path.win32.basename(normalized).toLowerCase();+ if (name === 'cmd') return path.win32.dirname(normalized);+ if (name !== 'bin') return undefined;+ const parent = path.win32.dirname(normalized);+ const parentName = path.win32.basename(parent).toLowerCase();+ return parentName === 'usr' || parentName.startsWith('mingw')+ ? path.win32.dirname(parent)+ : parent;+}++function windowsPathProbeBatches(candidates: readonly string[]): string[][] {+ const installRoots = uniqueWindowsPaths(candidates.flatMap((candidate) => (+ windowsGitInstallRootForProbeCandidate(candidate) ?? []+ )))+ .map(normalizedWindowsPath)+ .sort((left, right) => right.length - left.length);+ const batches = new Map<string, string[]>();+ for (const candidate of candidates) {+ const normalized = normalizedWindowsPath(candidate);+ const installRoot = installRoots.find((root) => (+ normalized === root || normalized.startsWith(`${root}\\`)+ ));+ const key = installRoot ?? normalizedWindowsPath(path.win32.parse(candidate).root) ?? normalized;+ const batch = batches.get(key);+ if (batch) batch.push(candidate);+ else batches.set(key, [candidate]);+ }+ return [...batches.values()];+}++function defaultNetworkDriveLetters(powershell: string, logger?: WindowsGitPathLogger): ReadonlySet<string> {+ const script = buildWindowsNetworkDriveProbeScript();+ try {+ const output = execFileSync(powershell, ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script], {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ timeout: WINDOWS_PATH_PROBE_TIMEOUT_MS,+ windowsHide: true,+ });+ warnWindowsGitPathProbeDiagnostics(logger, 'network-drives', output);+ return new Set(output.split(/\r?\n/)+ .map((line) => line.trim().toUpperCase())+ .filter((line) => /^[A-Z]$/.test(line)));+ } catch (error) {+ warnWindowsGitPathProbeFailure(logger, 'network-drives', error);+ return new Set();+ }+}++export function probePartitionedWindowsPathKinds(+ candidates: readonly string[],+ networkDriveLetters: ReadonlySet<string>,+ probeBatches: (+ batches: readonly (readonly string[])[],+ ) => ReadonlyMap<string, WindowsPathKind>,+): Map<string, WindowsPathKind> {+ const { local, network } = partitionWindowsProbeCandidates(candidates, networkDriveLetters);+ const kinds = new Map<string, WindowsPathKind>();+ for (const phase of [local, network]) {+ if (phase.length === 0) continue;+ for (const [candidate, kind] of probeBatches(windowsPathProbeBatches(phase))) {+ kinds.set(candidate, kind);+ }+ }+ return kinds;+}++function defaultProbeWindowsPathKindBatches(+ powershell: string,+ batches: readonly (readonly string[])[],+ logger?: WindowsGitPathLogger,+): ReadonlyMap<string, WindowsPathKind> {+ const nonEmptyBatches = batches.filter((batch) => batch.length > 0);+ if (nonEmptyBatches.length === 0) return new Map();+ const candidates = nonEmptyBatches.flat();+ const script = buildWindowsPathKindProbeScript(+ candidates.length,+ WINDOWS_PATH_PROBE_TIMEOUT_MS,+ nonEmptyBatches.length,+ );+ const input = candidates.length === 1+ ? candidates[0]+ : nonEmptyBatches.map((paths) => ({ paths }));+ try {+ const output = execFileSync(+ powershell,+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],+ {+ encoding: 'utf8',+ input: Buffer.from(JSON.stringify(input), 'utf8'),+ stdio: ['pipe', 'pipe', 'ignore'],+ timeout: WINDOWS_PATH_PROBE_TIMEOUT_MS,+ windowsHide: true,+ },+ );+ warnWindowsGitPathProbeDiagnostics(logger, 'path-kinds', output);+ return decodeWindowsPathKindLines(output);+ } catch (error) {+ terminateWindowsPowerShellDescendants(+ powershell,+ (error as { pid?: number } | undefined)?.pid,+ logger,+ );+ warnWindowsGitPathProbeFailure(logger, 'path-kinds', error);+ return decodeWindowsPathKindsFromProbeError(error);+ }+}++/**+ * Resolve local and network filesystem metadata in separate bounded native+ * subprocesses. A disconnected UNC share or mapped drive can never delay+ * local Git discovery, and can delay its own best-effort batch only up to the+ * configured timeout.+ */+function defaultProbeWindowsPathKinds(+ candidates: readonly string[],+ logger?: WindowsGitPathLogger,+): ReadonlyMap<string, WindowsPathKind> {+ if (process.platform !== 'win32') return new Map();+ const powershell = windowsPowerShellPath();+ if (!powershell) return new Map();+ const absoluteCandidates = uniqueWindowsPaths(candidates).filter(isFullyQualifiedWindowsPath);+ if (absoluteCandidates.length === 0) return new Map();+ return probePartitionedWindowsPathKinds(+ absoluteCandidates,+ defaultNetworkDriveLetters(powershell, logger),+ (batches) => defaultProbeWindowsPathKindBatches(powershell, batches, logger),+ );+}++function isFullyQualifiedWindowsPath(candidate: string): boolean {+ if (!path.win32.isAbsolute(candidate)) return false;+ const root = path.win32.parse(candidate).root;+ // `\foo` and `/foo` resolve against the process's current drive on Windows.+ // Only drive-rooted, UNC and device paths are stable discovery inputs.+ return root !== '\\' && root !== '/';+}++function windowsExecutableCandidatesOnPath(+ pathValue: string | undefined,+ executableName: string,+): string[] {+ if (!pathValue) return [];+ const candidates: string[] = [];+ for (const rawDirectory of pathValue.split(';')) {+ const directory = rawDirectory.trim().replace(/^"|"$/g, '');+ // Blank and relative PATH entries both mean the current directory on+ // Windows. Discovery must never inspect or execute workspace files.+ if (!directory || !isFullyQualifiedWindowsPath(directory)) continue;+ candidates.push(path.win32.join(directory, executableName));+ }+ return uniqueWindowsPaths(candidates);+}++export function findWindowsExecutablesOnPath(+ pathValue: string | undefined,+ executableName: string,+ isFile: (candidate: string) => boolean,+): string[] {+ return windowsExecutableCandidatesOnPath(pathValue, executableName).filter(isFile);+}++function defaultFindGitExecutablesOnPath(pathValue: string | undefined): readonly string[] {+ if (process.platform !== 'win32') return [];+ return windowsExecutableCandidatesOnPath(pathValue, WINDOWS_GIT_EXECUTABLE);+}++function normalizedWindowsPath(value: string): string {+ const trimmed = value.trim().replace(/^"|"$/g, '');+ if (!trimmed) return '';+ const normalized = path.win32.normalize(trimmed.replaceAll('/', '\\'));+ const root = path.win32.parse(normalized).root;+ const withoutTrailingSeparators = normalized.length > root.length+ ? normalized.replace(/[\\]+$/, '')+ : normalized;+ return withoutTrailingSeparators.toLowerCase();+}++function uniqueWindowsPaths(values: readonly string[]): string[] {+ const seen = new Set<string>();+ const result: string[] = [];+ for (const value of values) {+ const normalized = normalizedWindowsPath(value);+ if (!normalized || seen.has(normalized)) continue;+ seen.add(normalized);+ result.push(value);+ }+ return result;+}++export function gitInstallRootFromPath(gitPath: string): string | undefined {+ const normalized = path.win32.normalize(gitPath.replaceAll('/', '\\'));+ const parent = path.win32.dirname(normalized);+ const parentName = path.win32.basename(parent);+ if (parentName.toLowerCase() === 'cmd') {+ return path.win32.dirname(parent);+ }+ if (parentName.toLowerCase() === 'bin') {+ const grandparent = path.win32.dirname(parent);+ const grandparentName = path.win32.basename(grandparent).toLowerCase();+ if (grandparentName === 'usr' || grandparentName.startsWith('mingw')) {+ return path.win32.dirname(grandparent);+ }+ return grandparent;+ }+ return undefined;+}++type WindowsGitFileProbes = Pick<WindowsGitPathProbes, 'isDirectory' | 'isFile'>;++function hasGitCommand(directory: string, probes: WindowsGitFileProbes): boolean {+ if (!probes.isDirectory(directory)) return false;+ return ['git.exe', 'git.cmd', 'git.bat'].some((name) => probes.isFile(path.win32.join(directory, name)));+}++function pathExecutableValidatesInstallRoot(+ gitPath: string,+ installRoot: string,+ probes: WindowsGitFileProbes,+): boolean {+ const normalized = path.win32.normalize(gitPath);+ const parent = path.win32.dirname(normalized);+ const parentName = path.win32.basename(parent).toLowerCase();+ const root = path.win32.normalize(installRoot);+ if (parentName === 'cmd') {+ const bin = path.win32.join(root, 'bin');+ const usrBin = path.win32.join(root, 'usr', 'bin');+ return hasGitCommand(bin, probes)+ || hasGitCommand(usrBin, probes)+ || probes.isFile(path.win32.join(usrBin, 'ls.exe'));+ }+ if (parentName !== 'bin') return true;+ const grandparentName = path.win32.basename(path.win32.dirname(parent)).toLowerCase();+ if (grandparentName === 'usr' || grandparentName.startsWith('mingw')) return true;+ const cmd = path.win32.join(root, 'cmd');+ const usrBin = path.win32.join(root, 'usr', 'bin');+ return hasGitCommand(cmd, probes)+ || hasGitCommand(usrBin, probes)+ || probes.isFile(path.win32.join(usrBin, 'ls.exe'));+}++export function gitPathsForInstallRoot(+ installRoot: string,+ probes: Pick<WindowsGitPathProbes, 'isDirectory' | 'isFile'>,+): string[] {+ const root = path.win32.normalize(installRoot);+ const candidates: string[] = [];+ const cmd = path.win32.join(root, 'cmd');+ if (hasGitCommand(cmd, probes)) candidates.push(cmd);+ const bin = path.win32.join(root, 'bin');+ if (hasGitCommand(bin, probes)) candidates.push(bin);+ const usrBin = path.win32.join(root, 'usr', 'bin');+ if (hasGitCommand(usrBin, probes) || probes.isFile(path.win32.join(usrBin, 'ls.exe'))) candidates.push(usrBin);+ return uniqueWindowsPaths(candidates);+}++function installRootProbeCandidates(installRoot: string): string[] {+ const root = path.win32.normalize(installRoot);+ const candidates: string[] = [];+ for (const directory of [+ path.win32.join(root, 'cmd'),+ path.win32.join(root, 'bin'),+ path.win32.join(root, 'usr', 'bin'),+ ]) {+ candidates.push(directory);+ for (const executable of ['git.exe', 'git.cmd', 'git.bat']) {+ candidates.push(path.win32.join(directory, executable));+ }+ }+ candidates.push(path.win32.join(root, 'usr', 'bin', 'ls.exe'));+ return candidates;+}++function msysRootProbeCandidates(segments: readonly string[], installRoots: readonly string[]): string[] {+ const candidates: string[] = [];+ for (const segment of segments) {+ const trimmed = segment.trim().replace(/^"|"$/g, '');+ if (!trimmed || /^[A-Za-z]:[\\/]/.test(trimmed) || trimmed.startsWith('\\')) continue;+ const forward = trimmed.replaceAll('\\', '/');+ if (!forward.startsWith('/')) continue;+ const rest = forward.slice(1);+ const slash = rest.indexOf('/');+ const head = slash >= 0 ? rest.slice(0, slash) : rest;+ if (/^[A-Za-z]$/.test(head)) continue;+ const relative = rest.replaceAll('/', '\\');+ for (const root of installRoots) candidates.push(path.win32.join(root, relative));+ }+ return candidates;+}++function fileProbesFromPathKinds(kinds: ReadonlyMap<string, WindowsPathKind>): WindowsGitFileProbes {+ const normalizedKinds = new Map<string, WindowsPathKind>();+ for (const [candidate, kind] of kinds) {+ const normalized = normalizedWindowsPath(candidate);+ if (normalized) normalizedKinds.set(normalized, kind);+ }+ return {+ isDirectory: (candidate) => normalizedKinds.get(normalizedWindowsPath(candidate)) === 'directory',+ isFile: (candidate) => normalizedKinds.get(normalizedWindowsPath(candidate)) === 'file',+ };+}++export function translateMsysPathSegment(segment: string, installRoots: readonly string[], isDirectory: (candidate: string) => boolean): string | undefined {+ const trimmed = segment.trim().replace(/^"|"$/g, '');+ if (!trimmed || /^[A-Za-z]:[\\/]/.test(trimmed) || trimmed.startsWith('\\')) return undefined;+ const forward = trimmed.replaceAll('\\', '/');+ if (!forward.startsWith('/')) return undefined;+ const rest = forward.slice(1);+ const slash = rest.indexOf('/');+ const head = slash >= 0 ? rest.slice(0, slash) : rest;+ const tail = slash >= 0 ? rest.slice(slash + 1) : '';+ if (/^[A-Za-z]$/.test(head)) return `${head.toUpperCase()}:\\${tail.replaceAll('/', '\\')}`;+ const relative = rest.replaceAll('/', '\\');+ for (const root of installRoots) {+ const candidate = path.win32.join(root, relative);+ if (isDirectory(candidate)) return candidate;+ }+ return undefined;+}++export function resolveWindowsGitPath({+ platform = process.platform,+ existingPath,+ probes: overrides,+ logger,+}: ResolveWindowsGitPathOptions): string {+ if (platform !== 'win32') return existingPath ?? '';+ const probes: WindowsGitPathProbes = {+ readRegistryInstallPaths: () => defaultReadRegistryInstallPaths(logger),+ findGitExecutablesOnPath: defaultFindGitExecutablesOnPath,+ probePathKinds: (candidates) => defaultProbeWindowsPathKinds(candidates, logger),+ // The production resolver replaces these placeholders with one batched+ // snapshot. They remain injectable for cross-platform pure-function tests.+ isDirectory: () => false,+ isFile: () => false,+ ...overrides,+ };+ const original = existingPath ?? '';+ const segments = original.split(';').filter((segment) => segment.trim() !== '');+ const registryRoots = uniqueWindowsPaths(probes.readRegistryInstallPaths());+ const gitExecutableCandidates = probes.findGitExecutablesOnPath(existingPath);+ const allInferredRoots = uniqueWindowsPaths(+ gitExecutableCandidates.flatMap((gitPath) => gitInstallRootFromPath(gitPath) ?? []),+ );+ const inferredRootLimit = Math.max(+ maxWindowsPathKindProbeBatchCount(WINDOWS_PATH_PROBE_TIMEOUT_MS) - registryRoots.length,+ 0,+ );+ const inferredRoots = allInferredRoots.slice(0, inferredRootLimit);+ if (allInferredRoots.length > inferredRoots.length) {+ logger?.warn('windows git path PATH install-root candidates truncated', {+ limit: inferredRootLimit,+ omitted: allInferredRoots.length - inferredRoots.length,+ });+ }+ const potentialRoots = uniqueWindowsPaths([...inferredRoots, ...registryRoots]);+ const potentialRootKeys = new Set(potentialRoots.map(normalizedWindowsPath));+ const prioritizedGitExecutableCandidates = gitExecutableCandidates.filter((gitPath) => {+ const installRoot = gitInstallRootFromPath(gitPath);+ return installRoot !== undefined && potentialRootKeys.has(normalizedWindowsPath(installRoot));+ });+ const deferredGitExecutableCandidates = gitExecutableCandidates.filter(+ (gitPath) => !prioritizedGitExecutableCandidates.includes(gitPath),+ );+ const injectedFileProbes = overrides?.isDirectory !== undefined || overrides?.isFile !== undefined;+ const fileProbes: WindowsGitFileProbes = injectedFileProbes+ ? { isDirectory: probes.isDirectory, isFile: probes.isFile }+ : fileProbesFromPathKinds(probes.probePathKinds([+ ...prioritizedGitExecutableCandidates,+ ...potentialRoots.flatMap(installRootProbeCandidates),+ ...msysRootProbeCandidates(segments, potentialRoots),+ ...deferredGitExecutableCandidates,+ ]));+ const rootCandidates = uniqueWindowsPaths([+ ...gitExecutableCandidates+ .filter(fileProbes.isFile)+ .flatMap((gitPath) => {+ const installRoot = gitInstallRootFromPath(gitPath);+ return installRoot && pathExecutableValidatesInstallRoot(gitPath, installRoot, fileProbes)+ ? [installRoot]+ : [];+ }),+ ...registryRoots,+ ]);+ const roots = rootCandidates.filter((root) => gitPathsForInstallRoot(root, fileProbes).length > 0);+ const added = roots.flatMap((root) => gitPathsForInstallRoot(root, fileProbes));+ if (added.length === 0) return original;++ const seen = new Set<string>();+ const result: string[] = [];+ for (const segment of segments) {+ const translated = translateMsysPathSegment(segment, roots, fileProbes.isDirectory) ?? segment;+ const normalized = normalizedWindowsPath(translated);+ if (!normalized || seen.has(normalized)) continue;+ seen.add(normalized);+ result.push(translated);+ }+ for (const candidate of added) {+ const normalized = normalizedWindowsPath(candidate);+ if (!normalized || seen.has(normalized) || !fileProbes.isDirectory(candidate)) continue;+ seen.add(normalized);+ result.push(candidate);+ }+ return result.join(';');+}diff --git a/scripts/__tests__/third-party-notices.test.mjs b/scripts/__tests__/third-party-notices.test.mjsindex 2f5d1ecdcd..2677c47c5d 100644--- a/scripts/__tests__/third-party-notices.test.mjs+++ b/scripts/__tests__/third-party-notices.test.mjs@@ -220,6 +220,10 @@ test("desktop resources include both open-source and restricted disclosures", ()read("apps/desktop/resources/THIRD-PARTY-NOTICES.txt"),/LiteLLM mascot SVG path \(adapted\).*Copyright \(c\) 2026 Berri AI/s,);+ assert.match(+ read("apps/desktop/resources/THIRD-PARTY-NOTICES.txt"),+ /oh-my-pi Windows Git PATH helpers \(adapted\).*Copyright \(c\) 2025 Mario Zechner.*Copyright \(c\) 2025-2026 Can Bölük/s,+ );assert.doesNotMatch(read("apps/desktop/resources/THIRD-PARTY-NOTICES.txt"),/LiteLLM mascot SVG path \(adapted\) adapted/,diff --git a/scripts/generate-third-party-notices.mjs b/scripts/generate-third-party-notices.mjsindex f2c43b8276..29cda124cc 100644--- a/scripts/generate-third-party-notices.mjs+++ b/scripts/generate-third-party-notices.mjs@@ -665,6 +665,18 @@ function buildDesktopCommonEntries(apacheText, sharpPackageNames) {}),);+ entries.push(+ bundledComponent({+ name: "oh-my-pi Windows Git PATH helpers (adapted)",+ version: "326d24bd40d9858e24e1036ae739c27c72eeb543",+ license: "MIT",+ url: "https://github.com/can1357/oh-my-pi/tree/326d24bd40d9858e24e1036ae739c27c72eeb543",+ licenseText: MIT_TEXT(+ "MIT License\n\nCopyright (c) 2025 Mario Zechner\nCopyright (c) 2025-2026 Can Bölük",+ ),+ }),+ );+// Electron(devDependency 但二进制随包分发)let electronVersion = "bundled";let electronLicense = null;