跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

提交记录

保留 Windows 启动故障证据并完善云签名重试与可验证构建缓存

作者
Lee-xeo
时间
2026/11/09 18:54
提交
a7fb3dc
上一个
b10516c
这个版本的全部文件
修改.github/workflows/windows-build.yml+49 −3看文件
@@ -81,7 +81,10 @@ jobs:
8181 uses: actions/upload-artifact@v4
8282 with:
8383 name: ${{ inputs.artifact_name }}-${{ matrix.os }}-reports
84删除: path: ${{ runner.temp }}/cage-smoke-*.json
84新增: path: |
85新增: ${{ runner.temp }}/cage-smoke-*.json
86新增: ${{ runner.temp }}/cage-build-ui-*/smoke.json
87新增: ${{ runner.temp }}/cage-build-ui-*/*.png
8588 if-no-files-found: ignore
8689 overwrite: true
8790 retention-days: 14
@@ -125,10 +128,42 @@ jobs:
125128 mingw-w64-ucrt-x86_64-ninja
126129 mingw-w64-ucrt-x86_64-python
127130 mingw-w64-ucrt-x86_64-pkgconf
128删除: - uses: actions/cache@v4
131新增: - uses: actions/cache/restore@v4
132新增: id: qemu_cache
129133 with:
130134 path: _output/windows-deps
131删除: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json', 'patches/qemu/**', 'scripts/build-qemu-windows.*') }}
135新增: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json', 'patches/qemu/**', 'scripts/build-qemu-windows.*', 'scripts/bundle-qemu-sources.sh') }}
136新增: - name: Build and verify QEMU runtime and package identity
137新增: id: qemu_build
138新增: env:
139新增: CAGE_MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }}
140新增: run: |
141新增: ./scripts/build-qemu-windows.ps1
142新增: $identity = Get-Content '_output/windows-deps/qemu-cage/cage-build.json' -Raw | ConvertFrom-Json
143新增: "fingerprint=$($identity.fingerprint)" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8
144新增: $collectorHash = (Get-FileHash 'scripts/bundle-qemu-sources.sh' -Algorithm SHA256).Hash + (Get-FileHash 'scripts/prepare-qemu-release.ps1' -Algorithm SHA256).Hash
145新增: "collector=$collectorHash" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8
146新增: - name: Preserve only the completed verified runtime cache
147新增: if: steps.qemu_cache.outputs.cache-hit != 'true'
148新增: uses: actions/cache/save@v4
149新增: with:
150新增: path: _output/windows-deps
151新增: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json', 'patches/qemu/**', 'scripts/build-qemu-windows.*', 'scripts/bundle-qemu-sources.sh') }}
152新增: - uses: actions/cache/restore@v4
153新增: id: qemu_sources
154新增: with:
155新增: path: _output/windows-qemu-sources
156新增: key: cage-qemu-sources-${{ steps.qemu_build.outputs.fingerprint }}-${{ steps.qemu_build.outputs.collector }}
157新增: - name: Collect and verify corresponding sources before signing
158新增: env:
159新增: CAGE_MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }}
160新增: run: ./scripts/prepare-qemu-release.ps1
161新增: - name: Preserve only the completed verified source cache
162新增: if: steps.qemu_sources.outputs.cache-hit != 'true'
163新增: uses: actions/cache/save@v4
164新增: with:
165新增: path: _output/windows-qemu-sources
166新增: key: cage-qemu-sources-${{ steps.qemu_build.outputs.fingerprint }}-${{ steps.qemu_build.outputs.collector }}
132167 - uses: actions/setup-java@v4
133168 with:
134169 distribution: temurin
@@ -159,4 +194,15 @@ jobs:
159194 if-no-files-found: error
160195 overwrite: true
161196 retention-days: 14
197新增: - name: Preserve public release acceptance reports
198新增: if: always()
199新增: uses: actions/upload-artifact@v4
200新增: with:
201新增: name: ${{ inputs.artifact_name }}-reports
202新增: path: |
203新增: ${{ runner.temp }}/cage-smoke-*.json
204新增: ${{ runner.temp }}/cage-build-ui-*/smoke.json
205新增: ${{ runner.temp }}/cage-build-ui-*/*.png
206新增: if-no-files-found: ignore
207新增: retention-days: 14
162208 # The caller owns publication. This workflow has no repository write access.
修改desktop/windows/MainWindow.cs+71 −6看文件
@@ -17,6 +17,8 @@ internal sealed class MainWindow : Form
1717 private readonly AppUpdater updater;
1818 private int expectedPort;
1919 private bool controllerNeedsUpdate, allowQuit, bootstrapping, webFailed;
20新增: private bool completingSmoke;
21新增: private string smokePhase = "starting";
2022 private readonly CancellationTokenSource lifetime = new();
2123 private readonly Dictionary<string, (string[] Paths, DateTime Expires)> fileSelections = new();
2224
@@ -154,6 +156,7 @@ internal sealed class MainWindow : Form
154156
155157 private async Task Initialize(bool recreate = false)
156158 {
159新增: smokePhase = "initializing_webview";
157160 retry.Enabled = false;
158161 try
159162 {
@@ -165,6 +168,7 @@ internal sealed class MainWindow : Form
165168 }
166169 var environment = await CoreWebView2Environment.CreateAsync(null, Path.Combine(Backend.Root, "webview2"));
167170 await web.EnsureCoreWebView2Async(environment);
171新增: smokePhase = "webview_initialized";
168172 var core = web.CoreWebView2;
169173 core.Settings.AreDevToolsEnabled = false; core.Settings.AreDefaultContextMenusEnabled = false;
170174 core.Settings.IsStatusBarEnabled = false; core.Settings.IsZoomControlEnabled = false;
@@ -189,6 +193,7 @@ internal sealed class MainWindow : Form
189193 status.Hide(); web.Show(); web.Focus(); PublishVisibility();
190194 };
191195 await core.AddScriptToExecuteOnDocumentCreatedAsync(BridgeScript);
196新增: if (Program.SmokeOutput != null) await core.AddScriptToExecuteOnDocumentCreatedAsync(SmokeDiagnosticsScript);
192197 webFailed = false;
193198 await Bootstrap();
194199 }
@@ -203,20 +208,41 @@ internal sealed class MainWindow : Form
203208
204209 private async Task SmokeDeadline()
205210 {
206删除: try { await Task.Delay(TimeSpan.FromSeconds(120), lifetime.Token); allowQuit = true; Close(); }
211新增: try { await Task.Delay(TimeSpan.FromSeconds(120), lifetime.Token); await CompleteSmoke(false, "工作台未在自检期限内确认就绪"); }
207212 catch (OperationCanceledException) { }
208213 }
209214
210删除: private async Task CompleteSmoke()
215新增: private async Task CompleteSmoke(bool nativeBridgeReady = true, string? failure = null)
211216 {
212删除: if (Program.SmokeOutput == null) return;
217新增: if (Program.SmokeOutput == null || completingSmoke) return;
218新增: completingSmoke = true;
219新增: JsonElement? page = null;
220新增: var errors = new List<string>();
221新增: if (failure != null) errors.Add(failure);
213222 try
214223 {
215删除: var (exit, data) = await Backend.Json(["prepare-update", "--json"], lifetime.Token);
224新增: if (!nativeBridgeReady && web.CoreWebView2 != null)
225新增: {
226新增: try
227新增: {
228新增: var snapshot = await web.CoreWebView2.ExecuteScriptAsync("({title:document.title,ready:document.readyState,text:(document.body?.innerText||'').slice(0,4096),errors:window.__cageSmokeErrors||[]})");
229新增: page = JsonDocument.Parse(snapshot).RootElement.Clone();
230新增: await using var capture = File.Create(Path.ChangeExtension(Program.SmokeOutput, ".png"));
231新增: await web.CoreWebView2.CapturePreviewAsync(CoreWebView2CapturePreviewImageFormat.Png, capture);
232新增: }
233新增: catch (Exception error) { errors.Add("无法保存工作台画面:" + error.Message); }
234新增: }
235新增: var (exit, data) = await Backend.Json(["prepare-update", "--json"], lifetime.Token, TimeSpan.FromSeconds(20));
216236 if (exit != 0 || data.Text("status") != "prepared") throw new IOException("自检结束时无法确认后台已停止");
237新增: }
238新增: catch (Exception error) { errors.Add(error.Message); }
239新增: try
240新增: {
217241 File.WriteAllText(Program.SmokeOutput, JsonSerializer.Serialize(new {
218删除: success = true, nativeBridgeReady = true, version = AppUpdater.Version,
219删除: webviewVersion = web.CoreWebView2.Environment.BrowserVersionString,
242新增: success = nativeBridgeReady && errors.Count == 0, nativeBridgeReady, version = AppUpdater.Version,
243新增: phase = smokePhase, nativeStatus = message.Text, errors, page,
244新增: pageURL = web.Source?.GetLeftPart(UriPartial.Path),
245新增: webviewVersion = web.CoreWebView2?.Environment.BrowserVersionString,
220246 windowBounds = Bounds, workingArea = Screen.FromHandle(Handle).WorkingArea, deviceDpi = DeviceDpi,
221247 nativeMenuBar = MainMenuStrip != null,
222248 }));
@@ -233,7 +259,9 @@ internal sealed class MainWindow : Form
233259 retry.Hide(); existing.Hide(); complete.Hide();
234260 try
235261 {
262新增: smokePhase = "starting_backend";
236263 var (exit, data) = await Backend.Json(["desktop", "--json", ..options], lifetime.Token);
264新增: smokePhase = "backend_returned";
237265 if (exit != 0) throw new IOException(data.Text("message") is { Length: > 0 } detail ? detail : "工作台未能启动");
238266 controllerNeedsUpdate = data.Text("status") != "ready";
239267 if (data.Text("status") == "upgrade_pending")
@@ -241,6 +269,7 @@ internal sealed class MainWindow : Form
241269 message.Text = data.Text("message"); existing.Show(); complete.Show(); return;
242270 }
243271 var entry = UpdatePolicy.Entry(data.Text("url")); expectedPort = entry.Port;
272新增: smokePhase = "loading_workbench";
244273 Text = controllerNeedsUpdate ? "Cage(更新待完成)" : "Cage";
245274 web.CoreWebView2.Navigate(entry.AbsoluteUri);
246275 }
@@ -460,6 +489,42 @@ internal sealed class MainWindow : Form
460489 }
461490 }
462491
492新增: private const string SmokeDiagnosticsScript = """
493新增: (() => {
494新增: if (window !== window.top || location.protocol !== 'http:' || location.hostname !== 'localhost') return;
495新增: const errors = [];
496新增: Object.defineProperty(window, '__cageSmokeErrors', { value: errors });
497新增: const ownPath = value => {
498新增: try { const url = new URL(value, location.href); return url.origin === location.origin ? url.pathname : ''; }
499新增: catch { return ''; }
500新增: };
501新增: const scrub = value => {
502新增: let text = String(value || '');
503新增: for (const input of document.querySelectorAll('input,textarea'))
504新增: if (input.value) text = text.split(input.value).join('[form-value]');
505新增: return text.replace(/https?:\/\/[^\s"'<>`]+/g, value => ownPath(value) || '[external]')
506新增: .replace(/[?#][^\s"'<>)]*/g, '[redacted]').slice(0, 768);
507新增: };
508新增: const stack = error => String(error?.stack || '').split('\n').slice(1)
509新增: .filter(line => line.includes(location.origin + '/')).slice(0, 6).map(scrub);
510新增: const record = value => { if (errors.length < 8) errors.push(value); };
511新增: addEventListener('error', event => {
512新增: if (event.target instanceof HTMLScriptElement || event.target instanceof HTMLLinkElement) {
513新增: const source = ownPath(event.target.src || event.target.href);
514新增: if (source) record({ type: 'module-load', source });
515新增: return;
516新增: }
517新增: const source = ownPath(event.filename || location.href);
518新增: if (source) record({ type: 'error', source, message: scrub(event.message), stack: stack(event.error) });
519新增: }, true);
520新增: addEventListener('unhandledrejection', event => {
521新增: const frames = stack(event.reason);
522新增: // Primitive/cross-origin rejections are counted without exporting arbitrary values.
523新增: record({ type: 'unhandledrejection', message: frames.length ? scrub(event.reason?.message) : 'Unhandled rejection', stack: frames });
524新增: });
525新增: })();
526新增: """;
527新增:
463528 private const string BridgeScript = """
464529 (() => {
465530 if (window !== window.top || location.protocol !== 'http:' || location.hostname !== 'localhost') return;
修改desktop/windows/Program.cs+8 −1看文件
@@ -2,6 +2,7 @@ using System.IO.Pipes;
22using System.Security.Cryptography;
33using System.Security.Principal;
44using System.Text;
5新增:using System.Text.Json;
56using System.Runtime.InteropServices;
67
78namespace Cage.Windows;
@@ -67,6 +68,12 @@ internal static class Program
6768 }
6869 });
6970 Application.Run(form); cancellation.Cancel();
70删除: return SmokeOutput == null || File.Exists(SmokeOutput) ? 0 : 1;
71新增: if (SmokeOutput == null) return 0;
72新增: try
73新增: {
74新增: using var report = JsonDocument.Parse(File.ReadAllText(SmokeOutput));
75新增: return report.RootElement.TryGetProperty("success", out var success) && success.ValueKind == JsonValueKind.True ? 0 : 1;
76新增: }
77新增: catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException) { return 1; }
7178 }
7279}
修改scripts/agent-cli-smoke.mjs+1 −1看文件
@@ -34,7 +34,7 @@ try {
3434 call(['service.start']);
3535 assert.equal(JSON.parse(await readFile(join(profile, 'profile', 'control.json'), 'utf8')).pid, controllerPID);
3636 assert.equal(call(['call', 'settings.get'], undefined, 3).error.code, 'account_locked');
37删除: call(['call', 'account.create', '--input', '-'], { username: 'Agent acceptance', password: 'Ephemeral-Test-Password-123!', confirm_password: 'Ephemeral-Test-Password-123!' });
37新增: call(['call', 'account.create', '--input', '-'], { username: 'agent_acceptance', password: 'Ephemeral-Test-Password-123!', confirm_password: 'Ephemeral-Test-Password-123!' });
3838 const before = call(['call', 'settings.get']).data;
3939 const patch = { balanced_display: !before.balanced_display };
4040 call(['call', 'settings.patch', '--input', '-'], { patch, dry_run: true });
修改scripts/build-windows.ps1+4 −1看文件
@@ -197,5 +197,8 @@ try {
197197} finally {
198198 Pop-Location
199199 $env:GOOS = $savedGoOS; $env:GOARCH = $savedGoArch; $env:CGO_ENABLED = $savedCGO
200删除: if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force }
200新增: if (Test-Path -LiteralPath $stage) {
201新增: try { Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction Stop }
202新增: catch { Write-Warning "Temporary build files remain at $stage. Cleanup did not complete: $($_.Exception.Message)" }
203新增: }
201204}
修改scripts/ci-windows-build.ps1+4 −10看文件
@@ -51,17 +51,11 @@ try {
5151 Invoke-BuildTool 'node' @('--test', 'internal/cage/browser-clipboard.test.mjs', 'scripts/windows-native-bridge.test.mjs')
5252 $windowsPowerShell = Join-Path ([Environment]::SystemDirectory) 'WindowsPowerShell/v1.0/powershell.exe'
5353 & (Join-Path $PSScriptRoot 'test-windows-installation-files.ps1') -HelperShell $windowsPowerShell
54删除: & (Join-Path $PSScriptRoot 'build-windows.ps1') -Release:$Release
5554 if ($Release) {
56删除: $qemuSource = Join-Path $env:RUNNER_TEMP 'qemu-windows-full-source.tar.gz'
57删除: $savedMsystem, $savedChere = $env:MSYSTEM, $env:CHERE_INVOKING
58删除: try {
59删除: $env:MSYSTEM = 'UCRT64'; $env:CHERE_INVOKING = '1'
60删除: Invoke-BuildTool (Join-Path $env:CAGE_MSYS2_ROOT 'usr/bin/bash.exe') @('-l',
61删除: (Join-Path $PSScriptRoot 'bundle-qemu-sources.sh'), $repository,
62删除: (Join-Path $repository '_output/windows-deps/qemu-cage'), $qemuSource)
63删除: } finally { $env:MSYSTEM = $savedMsystem; $env:CHERE_INVOKING = $savedChere }
55新增: & (Join-Path $PSScriptRoot 'prepare-qemu-release.ps1')
56新增: $qemuSource = Join-Path $repository '_output/windows-qemu-sources/full-source.tar.gz'
6457 }
58新增: & (Join-Path $PSScriptRoot 'build-windows.ps1') -Release:$Release
6559 if (-not $Release) {
6660 $windowsPowerShell = Join-Path ([Environment]::SystemDirectory) 'WindowsPowerShell/v1.0/powershell.exe'
6761 foreach ($test in @('install-guest-powershell.tests.ps1', 'windows-evaluation.tests.ps1')) {
@@ -101,7 +95,7 @@ try {
10195 Remove-Item "Cert:\CurrentUser\My\$($imported.Thumbprint)" -Force -ErrorAction SilentlyContinue
10296 }
10397 }
104删除: if ($qemuSource) { Remove-Item -LiteralPath $qemuSource -Force -ErrorAction SilentlyContinue }
98新增: # Verified QEMU sources remain in the build cache; packaging copies them separately.
10599 $env:PATH = $savedPath
106100 $env:CAGE_WINDOWS_CERT_SHA1 = $savedCertificate
107101 Remove-Item Env:CAGE_ESIGNER_PASSWORD, Env:CAGE_ESIGNER_TOTP_SECRET -ErrorAction SilentlyContinue
修改scripts/esigner.mjs+19 −1看文件
@@ -168,6 +168,23 @@ async function credentials() {
168168 return { username, password, credential, totp: process.env.CAGE_ESIGNER_TOTP_SECRET };
169169}
170170
171新增:// A provider-declared server error is a definite failure. Timeouts, OTP and
172新增:// authentication errors are not retried. Any output proceeds to the caller's
173新增:// existing Authenticode verification; it must never trigger another signature.
174新增:export async function invokeSigning({ invoke, outputPath, pause = ms => new Promise(done => setTimeout(done, ms)) }) {
175新增: for (let attempt = 0; attempt < 3; attempt++) {
176新增: try { return await invoke(); }
177新增: catch (error) {
178新增: try { await access(outputPath); return ''; }
179新增: catch (outputError) { if (outputError.code !== 'ENOENT') throw error; }
180新增: const uncertainOrRejected = /timeout|timed out|abort|cancel|invalid_grant|invalid_client|access_denied|unauthorized|(?:otp|totp|authentication|authorization|credential|password)[^\n]*(?:invalid|expired|failed|rejected)/i.test(error.message);
181新增: if (attempt === 2 || uncertainOrRejected || !/^CodeSignTool failed \(exit 11\)/.test(error.message) || !/"error"\s*:\s*"server_error"/.test(error.message)) throw error;
182新增: console.error(`Signing service returned server_error; retrying in ${(attempt + 1) * 15} seconds.`);
183新增: await pause((attempt + 1) * 15000);
184新增: }
185新增: }
186新增:}
187新增:
171188async function main(argv) {
172189 const [command, input, flag, destination] = argv;
173190 if (command === 'install' && argv.length === 1) { console.log(`Verified CodeSignTool ${pin.version}: ${await installTool()}`); return; }
@@ -193,8 +210,9 @@ async function main(argv) {
193210 args.push(`-input_file_path=${vendor.path}`, `-output_dir_path=${vendor.output}`);
194211 if (auth.totp) args.push(`-totp_secret=${auth.totp}`);
195212 }
196删除: const result = await invokeJava({ jar: join(directory, pin.jar), config: join(directory, configPath), arguments: args,
213新增: const invoke = () => invokeJava({ jar: join(directory, pin.jar), config: join(directory, configPath), arguments: args,
197214 otp: signal => prompt('Current six-digit authenticator code', true, signal), secrets: [auth.password, auth.totp] });
215新增: const result = command === 'sign' ? await invokeSigning({ invoke, outputPath: join(vendor.output, basename(vendor.path)) }) : await invoke();
198216 if (command === 'sign') {
199217 const signed = join(vendor.output, basename(vendor.path));
200218 const bytes = await readFile(signed);
修改scripts/esigner.test.mjs+23 −1看文件
@@ -5,13 +5,35 @@ import { join } from 'node:path';
55import { tmpdir } from 'node:os';
66import { fileURLToPath } from 'node:url';
77import { test } from 'node:test';
8删除:import { assertWindowsExecutable, invokeJava, javaArgument, prepareVendorInput, redact, verifyTool } from './esigner.mjs';
8新增:import { assertWindowsExecutable, invokeJava, invokeSigning, javaArgument, prepareVendorInput, redact, verifyTool } from './esigner.mjs';
99
1010test('Java arguments reject line injection and redact overlapping secrets', () => {
1111 for (const value of ['line\nbreak', 'line\rbreak', 'a\0b']) assert.throws(() => javaArgument(value));
1212 assert.equal(redact('secret-long and secret', ['secret', 'secret-long']), '[redacted] and [redacted]');
1313});
1414
15新增:test('signing retries only declared server errors without output and remains bounded', async t => {
16新增: const root = await mkdtemp(join(tmpdir(), 'cage-sign-retry-'));
17新增: t.after(() => rm(root, { recursive: true, force: true }));
18新增: const outputPath = join(root, 'signed.exe'), delays = [];
19新增: const failure = () => new Error('CodeSignTool failed (exit 11). Error: {"error":"server_error"}');
20新增: let count = 0;
21新增: assert.equal(await invokeSigning({ outputPath, pause: async ms => delays.push(ms), invoke: async () => { if (++count < 3) throw failure(); return 'signed'; } }), 'signed');
22新增: assert.deepEqual(delays, [15000, 30000]);
23新增: count = 0;
24新增: await assert.rejects(invokeSigning({ outputPath, pause: async () => {}, invoke: async () => { count++; throw failure(); } }), /server_error/);
25新增: assert.equal(count, 3);
26新增: for (const message of ['OTP rejected', 'authentication failed', 'timeout', 'CodeSignTool failed (exit 1). server_error', `${failure().message}\nOTP rejected`, `${failure().message}\ntimeout`]) {
27新增: count = 0;
28新增: await assert.rejects(invokeSigning({ outputPath, pause: async () => assert.fail('must not wait'), invoke: async () => { count++; throw new Error(message); } }));
29新增: assert.equal(count, 1);
30新增: }
31新增: count = 0;
32新增: await invokeSigning({ outputPath, pause: async () => assert.fail('output requires trust verification, never another signature'), invoke: async () => { count++; await writeFile(outputPath, 'candidate output'); throw failure(); } });
33新增: assert.equal(count, 1);
34新增: assert.equal(await readFile(outputPath, 'utf8'), 'candidate output');
35新增:});
36新增:
1537test('a real JVM receives quoted Unicode arguments, no secrets in process arguments, and OTP through stdin', async t => {
1638 const temp = await mkdtemp(join(tmpdir(), 'cage-esigner-test-'));
1739 t.after(() => rm(temp, { recursive: true, force: true }));
新增scripts/prepare-qemu-release.ps1+36 −0看文件
@@ -0,0 +1,36 @@
1新增:#requires -Version 7.0
2新增:[CmdletBinding()]
3新增:param([string]$MsysDirectory = $env:CAGE_MSYS2_ROOT)
4新增:. (Join-Path $PSScriptRoot 'windows-common.ps1')
5新增:if (-not $IsWindows) { throw 'Prepare the corresponding runtime sources on Windows.' }
6新增:$repository = Split-Path $PSScriptRoot -Parent
7新增:if (-not $MsysDirectory) {
8新增: $MsysDirectory = @('C:\msys64', 'D:\msys64') | Where-Object { Test-Path (Join-Path $_ 'ucrt64/bin/pkg-config.exe') } | Select-Object -First 1
9新增:}
10新增:if (-not $MsysDirectory) { throw 'Set CAGE_MSYS2_ROOT to the MSYS2 UCRT64 build environment.' }
11新增:$runtime = Join-Path $repository '_output/windows-deps/qemu-cage'
12新增:& (Join-Path $PSScriptRoot 'build-qemu-windows.ps1') -OutputDirectory $runtime -MsysDirectory $MsysDirectory
13新增:$runtimeIdentity = Get-Content (Join-Path $runtime 'cage-build.json') -Raw | ConvertFrom-Json
14新增:$collectorHash = (Get-FileHash -LiteralPath (Join-Path $PSScriptRoot 'bundle-qemu-sources.sh') -Algorithm SHA256).Hash + (Get-FileHash -LiteralPath $PSCommandPath -Algorithm SHA256).Hash
15新增:$directory = Join-Path $repository '_output/windows-qemu-sources'
16新增:$archive = Join-Path $directory 'full-source.tar.gz'
17新增:$record = Join-Path $directory 'source-identity.json'
18新增:if ((Test-Path -LiteralPath $record) -and (Test-Path -LiteralPath $archive)) {
19新增: $identity = Get-Content -LiteralPath $record -Raw | ConvertFrom-Json
20新增: if ($identity.schema -ne 1 -or $identity.fingerprint -ne $runtimeIdentity.fingerprint -or $identity.collectorHash -ne $collectorHash -or $identity.sha256 -ne (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash) {
21新增: throw 'Cached QEMU sources differ from their verified runtime identity.'
22新增: }
23新增: Write-Host 'Verified cached QEMU corresponding sources.'
24新增: return
25新增:}
26新增:New-Item -ItemType Directory -Path $directory -Force | Out-Null
27新增:$savedMsystem, $savedChere = $env:MSYSTEM, $env:CHERE_INVOKING
28新增:try {
29新增: $env:MSYSTEM = 'UCRT64'; $env:CHERE_INVOKING = '1'
30新增: Invoke-BuildTool (Join-Path $MsysDirectory 'usr/bin/bash.exe') @('-l',
31新增: (Join-Path $PSScriptRoot 'bundle-qemu-sources.sh'), $repository, $runtime, $archive)
32新增:} finally { $env:MSYSTEM = $savedMsystem; $env:CHERE_INVOKING = $savedChere }
33新增:$identity = @{ schema = 1; fingerprint = $runtimeIdentity.fingerprint; collectorHash = $collectorHash; sha256 = (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash }
34新增:$identity | ConvertTo-Json | Set-Content -LiteralPath "$record.partial" -Encoding utf8
35新增:Move-Item -LiteralPath "$record.partial" -Destination $record -Force
36新增:Write-Host 'Collected and verified QEMU corresponding sources before application signing.'
修改scripts/windows-common.ps1+24 −1看文件
@@ -27,11 +27,34 @@ function Assert-WindowsWorkbench {
2727 if (-not $window.WaitForExit(180000)) { throw "Cage workbench acceptance timed out. Diagnostics retained at $testRoot" }
2828 if ($window.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $report)) { throw "Cage workbench acceptance failed. Diagnostics retained at $testRoot" }
2929 $result = Get-Content -LiteralPath $report -Raw | ConvertFrom-Json
30删除: if ($result.success -ne $true -or $result.nativeBridgeReady -ne $true) { throw "Cage workbench/bridge acceptance failed. Diagnostics retained at $testRoot" }
30新增: if ($result.success -ne $true -or $result.nativeBridgeReady -ne $true) {
31新增: $detail = if ($result.PSObject.Properties.Name -contains 'nativeStatus') { $result.nativeStatus } else { 'No native status was recorded.' }
32新增: throw "Cage workbench/bridge acceptance failed: $detail Diagnostics retained at $testRoot"
33新增: }
3134 $passed = $true
3235 } finally {
3336 if (-not $window.HasExited) { $window.Kill($true); $window.WaitForExit() }
3437 $window.Dispose()
38新增: if (-not $passed) {
39新增: # Close only this test's authenticated controller. Killing every
40新增: # cage.exe could terminate another installed application or VM.
41新增: try {
42新增: $cleanup = [Diagnostics.ProcessStartInfo]::new((Join-Path $AppDirectory 'resources/cage.exe'))
43新增: $cleanup.UseShellExecute = $false
44新增: $cleanup.CreateNoWindow = $true
45新增: $cleanup.RedirectStandardOutput = $true
46新增: $cleanup.RedirectStandardError = $true
47新增: $cleanup.Environment['CLAUDE_CAGE_CONFIG'] = Join-Path $testRoot 'profile/config.json'
48新增: $cleanup.ArgumentList.Add('prepare-update'); $cleanup.ArgumentList.Add('--json')
49新增: $controller = [Diagnostics.Process]::Start($cleanup)
50新增: try {
51新增: $stdout = $controller.StandardOutput.ReadToEndAsync()
52新增: $stderr = $controller.StandardError.ReadToEndAsync()
53新增: if (-not $controller.WaitForExit(20000)) { $controller.Kill($true); $controller.WaitForExit() }
54新增: if ($controller.ExitCode -ne 0) { Write-Warning 'The isolated smoke controller did not confirm shutdown; its profile is retained.' }
55新增: } finally { $controller.Dispose() }
56新增: } catch { Write-Warning "Isolated smoke cleanup failed: $($_.Exception.Message)" }
57新增: }
3558 # A successful smoke report is written only after the isolated backend
3659 # confirms shutdown. Failed profiles remain available for diagnosis.
3760 if ($passed) { Remove-Item -LiteralPath $testRoot -Recurse -Force -ErrorAction SilentlyContinue }