Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Keep Windows OS diagnostics independent of query speed (#5576)
Nick Gomez12671bbda8ad
diff --git a/knip.config.ts b/knip.config.tsindex 65f0e8807..d3638888e 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -147,11 +147,15 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: ['@types/shell-quote'],+ ignoreDependencies: [+ '@types/shell-quote',+ ],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],- ignoreDependencies: ['yjs'],+ ignoreDependencies: [+ 'yjs',+ ],},'packages/desktop': {entry: [diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.tsindex 8a60e5826..a28cc2b18 100644--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts@@ -1,3 +1,4 @@+import { readFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.tsindex 6fcdc23f2..4fc2c11f9 100644--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts@@ -1,3 +1,4 @@+import { setTimeout as wait } from 'node:timers/promises';import { normalizeBridge } from '@inkeep/open-knowledge-core';import { updateYFragment } from '@tiptap/y-tiptap';diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.tsindex 40b5cdfd6..9f2f6feb6 100644--- a/packages/app/tests/integration/interior-edit-freshness.test.ts+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts@@ -1,3 +1,4 @@+import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.tsindex 93666af70..2a085742b 100644--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts@@ -1,3 +1,4 @@+import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.tsindex 867598d34..878d5196b 100644--- a/packages/app/tests/integration/producer-guard-wiring.test.ts+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts@@ -1,3 +1,4 @@+import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.tsindex 0970ac12f..4ada3cf26 100644--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts@@ -1,3 +1,4 @@+import { randomUUID } from 'node:crypto';import { afterEach, describe, expect, test } from 'vitest';import { agentWriteMd, createTestServer, type TestServer } from './test-harness';diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.tsindex b632185e1..cbe2b705f 100644--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts@@ -1,3 +1,4 @@+import { execFileSync } from 'node:child_process';import { randomUUID } from 'node:crypto';import { join } from 'node:path';diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.tsindex c530ce4ba..89bc9b4d9 100644--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts@@ -1,3 +1,4 @@+import { randomUUID } from 'node:crypto';import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';import type * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.tsindex d3767adc9..a78aeb0e4 100644--- a/packages/app/tests/integration/undo-after-rollback.test.ts+++ b/packages/app/tests/integration/undo-after-rollback.test.ts@@ -1,3 +1,4 @@+import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';import { afterAll, beforeAll, describe, expect, test } from 'vitest';import * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.tsindex b076f955c..e7cc69c3f 100644--- a/packages/app/tests/integration/undo-recycle-reset.test.ts+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts@@ -1,3 +1,4 @@+import { writeFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.tsindex 7935e35f8..9ddcd0730 100644--- a/packages/app/tests/integration/undo-rederive-survival.test.ts+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts@@ -1,3 +1,4 @@+import { prependFrontmatter } from '@inkeep/open-knowledge-core';import { Plugin, PluginKey } from '@tiptap/pm/state';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex f4cc8a286..2a597ec3d 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,3 +1,4 @@+import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 8fb428b90..01ef76a9f 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,3 +1,4 @@+import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex fc267cbea..fb0ba5a7c 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex bfd7e3109..fa3cfcd86 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 4d3250d3a..8be632ba4 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,3 +1,4 @@+export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/desktop/src/utility/pty-host.ts b/packages/desktop/src/utility/pty-host.tsindex be0b8f390..f4786010d 100644--- a/packages/desktop/src/utility/pty-host.ts+++ b/packages/desktop/src/utility/pty-host.ts@@ -201,18 +201,129 @@ export type PtyStartupSnapshotReason =| 'before-shutdown'| 'exit';+export type PtyOsUnavailableReason =+ | 'deadline'+ | 'no-budget'+ | 'unsupported-platform'+ | 'query-start-failed'+ | 'query-exited'+ | 'invalid-json'+ | 'invalid-shape'+ | 'output-limit'+ | 'owner-loss'+ | 'process-absent'+ | 'access-unavailable'+ | 'identity-changed'+ | 'worker-request-deadline'+ | 'worker-unavailable'+ | 'console-identity-unavailable';++export type PtyOsSection<T> =+ | { status: 'captured'; value: T }+ | { status: 'unavailable'; reason: PtyOsUnavailableReason };++export interface PtyOsThreadSample {+ id: number;+ state:+ | 'initialized'+ | 'ready'+ | 'running'+ | 'standby'+ | 'terminated'+ | 'wait'+ | 'transition'+ | 'unknown';+ waitReason:+ | 'executive'+ | 'free-page'+ | 'page-in'+ | 'pool-allocation'+ | 'execution-delay'+ | 'suspended'+ | 'user-request'+ | 'event-pair-high'+ | 'event-pair-low'+ | 'lpc-receive'+ | 'lpc-reply'+ | 'virtual-memory'+ | 'page-out'+ | 'unknown'+ | 'not-applicable';+}++export interface PtyOsProcessSample {+ pid: number;+ parentPid: number | null;+ createdAtMs: number;+ first: { userMs: number; kernelMs: number; threadCount: number };+ second: { userMs: number; kernelMs: number; threadCount: number };+ threads: PtyOsThreadSample[];+ omittedThreads: number;+}++export interface PtyOsMachineSample {+ atMs: number;+ logicalCpus: number;+ userMs: number;+ systemMs: number;+ idleMs: number;+ irqMs: number;+ niceMs: number;+}++export interface PtyOsObservation {+ version: 1;+ status: 'captured' | 'partial' | 'unavailable';+ reason: PtyOsUnavailableReason | null;+ requestedPid: number | null;+ targets: Array<{ requestedPid: number; shell: PtyOsSection<PtyOsProcessSample> }>;+ startedAtMs: number | null;+ completedAtMs: number | null;+ shell: PtyOsSection<PtyOsProcessSample>;+ machine: PtyOsSection<{ first: PtyOsMachineSample; second: PtyOsMachineSample }>;+ console: PtyOsSection<{+ association: 'candidate-parent-relation';+ candidateCount: number;+ candidates: PtyOsProcessSample[];+ unavailableCandidates: Array<{+ reason: 'process-absent' | 'access-unavailable' | 'identity-changed';+ count: number;+ }>;+ omittedCandidates: number;+ }>;+ worker: PtyOsSection<{+ nodeThreadId: number;+ requestedAtMs: number;+ repliedAtMs: number;+ userMs: number;+ systemMs: number;+ }>;+ helper: {+ requested: boolean;+ reason: 'deadline' | 'output-limit' | 'owner-loss' | null;+ delivery: 'not-attempted' | 'no-pid' | 'already-exited' | 'accepted' | 'rejected' | 'threw';+ exit:+ | 'not-observed'+ | 'observed-before-request'+ | 'observed-after-request'+ | 'cooperative-deadline'+ | 'cooperative-owner-loss';+ exitCode: number | null;+ };+}+export interface PtyStartupNativeSnapshot {shell: {pid: number | null;nativeExitObserved: boolean;exitCode: number | null;- osState: 'unobserved';+ osState: 'unobserved' | PtyOsObservation['shell'];};console: {backend: PtyStartupBackend;connection: 'pending' | 'entered' | 'returned' | 'failed';outputConnectionDisposed: boolean;- osState: 'unobserved';+ osState: 'unobserved' | PtyOsObservation['console'];};worker: {threadId: number;@@ -221,7 +332,7 @@ export interface PtyStartupNativeSnapshot {errorObserved: boolean;writerError: boolean;exitCode: number | null;- osState: 'unobserved';+ osState: 'unobserved' | PtyOsObservation['worker'];};transport: {capture: 'installed' | 'missing';@@ -248,7 +359,12 @@ export type PtyStartupObservation =| { stage: 'native-connect-failed' }| { stage: 'native-shell-exit'; shellPid: number | null; exitCode: number }| { stage: 'worker-exit'; exitCode: number }- | { stage: 'observer-unavailable'; reason: 'unsupported-node-pty-shape' };+ | { stage: 'observer-unavailable'; reason: 'unsupported-node-pty-shape' }+ | {+ stage: 'os-snapshot';+ observation: PtyOsObservation;+ transport: PtyStartupNativeSnapshot['transport'] | null;+ };type PtyStartupHostObservation =| PtyStartupObservationdiff --git a/packages/desktop/tests/support/pty-readiness.test-helper.ts b/packages/desktop/tests/support/pty-readiness.test-helper.tsindex c76e53a40..051a886a7 100644--- a/packages/desktop/tests/support/pty-readiness.test-helper.ts+++ b/packages/desktop/tests/support/pty-readiness.test-helper.ts@@ -9,8 +9,12 @@ import {type SpawnPty,setupPtyHost,} from '../../src/utility/pty-host.ts';-import { windowsPtyStartupTrace } from './pty-startup-trace.test-helper.ts';+import { createWindowsPtyStartupCoordinator } from './pty-startup-trace.test-helper.ts';import { harnessScenarioTitles } from './real-io-harness-roster.test-helper.ts';+import {+ WINDOWS_OS_MAX_BUDGET_MS,+ type WindowsOsStateOptions,+} from './windows-os-state.test-helper.ts';export interface PtyStream {read(): string;@@ -24,6 +28,8 @@ export interface PtyHostProbe {exitOf(ptyId: string): { exitCode: number | undefined; signal: number | null } | null;errorOf(ptyId: string): string | null;snapshotStartup(): void;+ captureFailure(): Promise<void>;+ cancelCapture(): void;killActive(): void;}@@ -36,6 +42,8 @@ export interface PtyHostProbeOptions {startupTrace?:| (NonNullable<SetupPtyHostDeps['startupTrace']> & { native?: never })| { native: boolean; aroundSpawn?: never };+ osCaptureDeadlineAt?: () => number;+ spawnQuery?: WindowsOsStateOptions['spawnQuery'];}export function createPtyHostProbe(options: PtyHostProbeOptions): PtyHostProbe {@@ -43,6 +51,14 @@ export function createPtyHostProbe(options: PtyHostProbeOptions): PtyHostProbe {const data = new Map<string, string>();const exits = new Map<string, { exitCode: number | undefined; signal: number | null }>();const errors = new Map<string, string>();+ const coordinator = options.startupTrace?.native+ ? createWindowsPtyStartupCoordinator({+ platform: options.platform ?? process.platform,+ deadlineAt:+ options.osCaptureDeadlineAt ?? (() => performance.now() + WINDOWS_OS_MAX_BUDGET_MS),+ ...(options.spawnQuery === undefined ? {} : { spawnQuery: options.spawnQuery }),+ })+ : null;const handle = setupPtyHost({parentPort: {on(_event, h) {@@ -62,7 +78,7 @@ export function createPtyHostProbe(options: PtyHostProbeOptions): PtyHostProbe {},},spawn: options.spawn,- startupTrace: options.startupTrace?.native ? windowsPtyStartupTrace : options.startupTrace,+ startupTrace: coordinator?.trace ?? options.startupTrace,env: options.env,...(options.platform === undefined ? {} : { platform: options.platform }),shellExists: options.shellExists,@@ -78,6 +94,10 @@ export function createPtyHostProbe(options: PtyHostProbeOptions): PtyHostProbe {exitOf,errorOf,snapshotStartup: () => handle.snapshotStartup?.(),+ captureFailure: async () => {+ await coordinator?.captureFailure();+ },+ cancelCapture: () => coordinator?.cancelCapture(),killActive: () => handle.killActive(),streamOf: (ptyId) => ({read: () => dataOf(ptyId),diff --git a/packages/desktop/tests/support/pty-startup-trace.test-helper.ts b/packages/desktop/tests/support/pty-startup-trace.test-helper.tsindex 41e0b2183..89b194fba 100644--- a/packages/desktop/tests/support/pty-startup-trace.test-helper.ts+++ b/packages/desktop/tests/support/pty-startup-trace.test-helper.ts@@ -1,9 +1,15 @@import { getEnvironmentData, setEnvironmentData, type Worker } from 'node:worker_threads';import type {+ PtyOsObservation,PtyStartupNativeSnapshot,PtyStartupSpawnContext,PtyStartupTraceOptions,} from '../../src/utility/pty-host.ts';+import {+ startWindowsOsState,+ type WindowsOsCollection,+ type WindowsOsStateOptions,+} from './windows-os-state.test-helper.ts';export const PTY_STARTUP_WORKER_CONTEXT = 'ok-pty-startup-worker-trace-v1';@@ -303,8 +309,110 @@ export const windowsPtyStartupTrace: PtyStartupTraceOptions = {},};+export function createWindowsPtyStartupCoordinator(options: {+ platform: NodeJS.Platform;+ deadlineAt: () => number;+ spawnQuery?: WindowsOsStateOptions['spawnQuery'];+}) {+ const attempts: Array<{+ context: PtyStartupSpawnContext;+ pty: ReturnType<NonNullable<PtyStartupTraceOptions['aroundSpawn']>>['pty'];+ observation: PtyOsObservation | null;+ collection: WindowsOsCollection | null;+ disposed: boolean;+ readTransport: () => PtyStartupNativeSnapshot['transport'] | null;+ detectedTransport: PtyStartupNativeSnapshot['transport'] | null;+ }> = [];+ const trace: PtyStartupTraceOptions = {+ aroundSpawn(next, context) {+ const observed = windowsPtyStartupTrace.aroundSpawn?.(next, context) ?? { pty: next() };+ const snapshot = observed.snapshot;+ const attempt: (typeof attempts)[number] = {+ context,+ pty: observed.pty,+ observation: null,+ collection: null,+ disposed: false,+ readTransport: () => snapshot?.().transport ?? null,+ detectedTransport: null,+ };+ attempts.push(attempt);+ return {+ pty: observed.pty,+ ...(snapshot === undefined+ ? {}+ : {+ snapshot() {+ const native = snapshot();+ if (attempt.observation === null) return native;+ return {+ ...native,+ shell: { ...native.shell, osState: attempt.observation.shell },+ console: { ...native.console, osState: attempt.observation.console },+ worker: { ...native.worker, osState: attempt.observation.worker },+ };+ },+ }),+ dispose() {+ attempt.disposed = true;+ attempt.collection?.cancel('owner-loss');+ observed.dispose?.();+ },+ };+ },+ };+ return {+ trace,+ async captureFailure(): Promise<void> {+ const pending = attempts.filter(+ (attempt) =>+ !attempt.disposed &&+ attempt.observation === null &&+ attempt.collection === null &&+ attempt.pty.pid > 0,+ );+ for (const attempt of pending) attempt.detectedTransport = attempt.readTransport();+ for (const attempt of pending) {+ if (attempt.disposed || attempt.observation !== null) continue;+ const terminal = inspectTerminal(attempt.pty);+ attempt.collection = startWindowsOsState({+ pid: attempt.pty.pid,+ parentPid: process.pid,+ deadlineAt: options.deadlineAt(),+ platform: options.platform,+ ...(terminal === null ? {} : { worker: terminal._agent._conoutSocketWorker._worker }),+ ...(options.spawnQuery === undefined ? {} : { spawnQuery: options.spawnQuery }),+ });+ const observation = await attempt.collection.result;+ if (attempt.disposed || attempt.observation !== null) continue;+ attempt.observation = observation;+ attempt.context.emit({+ stage: 'os-snapshot',+ observation,+ transport: attempt.detectedTransport,+ });+ }+ },+ cancelCapture(): void {+ for (const attempt of attempts) {+ if (attempt.disposed || attempt.observation !== null) continue;+ const observation = attempt.collection?.cancel('deadline');+ if (observation === undefined || observation === null) continue;+ attempt.observation = observation;+ attempt.context.emit({+ stage: 'os-snapshot',+ observation,+ transport: attempt.detectedTransport,+ });+ }+ },+ };+}+interface HarnessScenarioHost {snapshot(): void;+ captureFailure?(): Promise<void>;+ cancelCapture?(): void;release(): void;}@@ -352,8 +460,11 @@ export function createHarnessScenarioRunner(options: HarnessScenarioRunnerOptionresults.push({ name, outcome: 'passed' });options.print(`PASS ${name}`);} catch (err) {- for (const host of owned) host.snapshot();const outcome = options.isRefusal(err) ? 'refused' : 'failed';+ if (outcome === 'failed') {+ for (const host of owned) await host.captureFailure?.();+ }+ for (const host of owned) host.snapshot();results.push({ name, outcome, detail: (err as Error).message });options.print(`${outcome === 'refused' ? 'REFUSED' : 'FAIL'} ${name} :: ${(err as Error).message}`,@@ -365,6 +476,7 @@ export function createHarnessScenarioRunner(options: HarnessScenarioRunnerOption},verdictLine,hardTimeoutVerdict(): string {+ for (const host of owned) host.cancelCapture?.();for (const host of owned) host.snapshot();return verdictLine(` :: hard timeout during ${inFlight ?? 'startup'}`);},diff --git a/packages/desktop/tests/support/windows-os-query.test-helper.ps1 b/packages/desktop/tests/support/windows-os-query.test-helper.ps1new file mode 100644index 000000000..8eb8d313e--- /dev/null+++ b/packages/desktop/tests/support/windows-os-query.test-helper.ps1@@ -0,0 +1,192 @@+param(+ [Parameter(Mandatory = $true)][string]$PidValues,+ [Parameter(Mandatory = $true)][int]$ParentPidValue,+ [Parameter(Mandatory = $true)][long]$DeadlineEpochMs,+ [Parameter(Mandatory = $true)][int]$DurationCapMs+)++$ErrorActionPreference = 'Stop'+$elapsed = [System.Diagnostics.Stopwatch]::StartNew()+$startGate = [System.Threading.ManualResetEventSlim]::new($false)+$ownerScript = {+ param($gate)+ $stream = [Console]::OpenStandardInput()+ $first = $stream.ReadByte()+ if ($first -lt 0) { return }+ $gate.Set()+ while ($stream.ReadByte() -ge 0) {}+}+$queryScript = {+ param($pidValues, $parentPidValue, $gate)+ $gate.Wait()++ function Convert-ThreadState($state) {+ switch ([string]$state) {+ 'Initialized' { return 'initialized' }+ 'Ready' { return 'ready' }+ 'Running' { return 'running' }+ 'Standby' { return 'standby' }+ 'Terminated' { return 'terminated' }+ 'Wait' { return 'wait' }+ 'Transition' { return 'transition' }+ default { return 'unknown' }+ }+ }++ function Convert-WaitReason($reason) {+ switch ([string]$reason) {+ 'Executive' { return 'executive' }+ 'FreePage' { return 'free-page' }+ 'PageIn' { return 'page-in' }+ 'SystemAllocation' { return 'pool-allocation' }+ 'ExecutionDelay' { return 'execution-delay' }+ 'Suspended' { return 'suspended' }+ 'UserRequest' { return 'user-request' }+ 'EventPairHigh' { return 'event-pair-high' }+ 'EventPairLow' { return 'event-pair-low' }+ 'LpcReceive' { return 'lpc-receive' }+ 'LpcReply' { return 'lpc-reply' }+ 'VirtualMemory' { return 'virtual-memory' }+ 'PageOut' { return 'page-out' }+ default { return 'unknown' }+ }+ }++ function Read-ProcessSample([int]$targetPid, $knownParentPid) {+ try {+ $process = [System.Diagnostics.Process]::GetProcessById($targetPid)+ } catch [System.ArgumentException] {+ return @{ status = 'unavailable'; reason = 'process-absent' }+ } catch {+ return @{ status = 'unavailable'; reason = 'access-unavailable' }+ }+ try {+ $createdAtMs = [long]([DateTimeOffset]$process.StartTime).ToUnixTimeMilliseconds()+ $first = @{+ userMs = [double]$process.UserProcessorTime.TotalMilliseconds+ kernelMs = [double]$process.PrivilegedProcessorTime.TotalMilliseconds+ threadCount = [int]$process.Threads.Count+ }+ $threads = @()+ $count = 0+ foreach ($thread in $process.Threads) {+ if ($count -ge 16) { break }+ $state = Convert-ThreadState $thread.ThreadState+ $waitReason = if ($state -eq 'wait') { Convert-WaitReason $thread.WaitReason } else { 'not-applicable' }+ $threads += @{+ id = [int]$thread.Id+ state = $state+ waitReason = $waitReason+ }+ $count += 1+ }+ $process.Refresh()+ $secondCreatedAtMs = [long]([DateTimeOffset]$process.StartTime).ToUnixTimeMilliseconds()+ if ($createdAtMs -ne $secondCreatedAtMs) {+ return @{ status = 'unavailable'; reason = 'identity-changed' }+ }+ $second = @{+ userMs = [double]$process.UserProcessorTime.TotalMilliseconds+ kernelMs = [double]$process.PrivilegedProcessorTime.TotalMilliseconds+ threadCount = [int]$process.Threads.Count+ }+ return @{+ status = 'captured'+ pid = [int]$process.Id+ parentPid = $knownParentPid+ createdAtMs = $createdAtMs+ secondCreatedAtMs = $secondCreatedAtMs+ first = $first+ second = $second+ threads = @($threads)+ omittedThreads = [Math]::Max(0, $first.threadCount - $count)+ }+ } catch [System.ArgumentException], [System.InvalidOperationException] {+ return @{ status = 'unavailable'; reason = 'process-absent' }+ } catch {+ return @{ status = 'unavailable'; reason = 'access-unavailable' }+ } finally {+ $process.Dispose()+ }+ }++ $shells = @()+ foreach ($targetPid in $pidValues) {+ $shells += (Read-ProcessSample $targetPid $null)+ }+ [Console]::Out.WriteLine('SHELL ' + (ConvertTo-Json -InputObject @{ version = 1; shells = @($shells) } -Depth 12 -Compress))+ [Console]::Out.Flush()+ $pidValue = $pidValues[0]+ try {+ $identity = Get-CimInstance -ClassName Win32_Process -Filter "ProcessId=$pidValue" -Property ProcessId, ParentProcessId -ErrorAction Stop+ if ($null -ne $identity -and $shells[0].status -eq 'captured') { $shells[0].parentPid = [int]$identity.ParentProcessId }+ } catch {}+ $console = @{ status = 'unavailable'; reason = 'console-identity-unavailable' }+ if ($parentPidValue -gt 0) {+ try {+ $rows = @(Get-CimInstance -ClassName Win32_Process -Filter "(Name='conhost.exe' OR Name='OpenConsole.exe') AND ParentProcessId=$parentPidValue" -Property ProcessId, ParentProcessId -ErrorAction Stop)+ $candidates = @()+ $unavailableCandidates = @()+ foreach ($row in ($rows | Select-Object -First 4)) {+ $sample = Read-ProcessSample ([int]$row.ProcessId) ([int]$row.ParentProcessId)+ if ($sample.status -eq 'captured') {+ $candidates += $sample+ } else {+ $unavailableCandidates += @{ reason = $sample.reason; count = 1 }+ }+ }+ $console = @{+ status = 'captured'+ candidateCount = [int]$rows.Count+ candidates = @($candidates)+ unavailableCandidates = @($unavailableCandidates)+ omittedCandidates = [Math]::Max(0, $rows.Count - 4)+ }+ } catch {+ $console = @{ status = 'unavailable'; reason = 'access-unavailable' }+ }+ }+ return @{ version = 1; shells = @($shells); console = $console }+}++try {+ $pids = @($PidValues.Split(',') | ForEach-Object { [int]::Parse($_) })+ if ($pids.Count -lt 1 -or $pids.Count -gt 8 -or @($pids | Where-Object { $_ -le 0 }).Count -gt 0) {+ [Environment]::Exit(88)+ }+ $ownerRunspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace()+ $queryRunspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace()+ $ownerRunspace.Open()+ $queryRunspace.Open()+ $owner = [System.Management.Automation.PowerShell]::Create()+ $query = [System.Management.Automation.PowerShell]::Create()+ $owner.Runspace = $ownerRunspace+ $query.Runspace = $queryRunspace+ [void]$owner.AddScript($ownerScript.ToString()).AddArgument($startGate)+ [void]$query.AddScript($queryScript.ToString()).AddArgument($pids).AddArgument($ParentPidValue).AddArgument($startGate)+ $ownerTask = $owner.BeginInvoke()+ $queryTask = $query.BeginInvoke()+ [Console]::Out.WriteLine('READY')+ [Console]::Out.Flush()+ $handles = [System.Threading.WaitHandle[]]@($ownerTask.AsyncWaitHandle, $queryTask.AsyncWaitHandle)+ while ($true) {+ $remaining = [Math]::Min(+ $DeadlineEpochMs - [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds(),+ $DurationCapMs - $elapsed.ElapsedMilliseconds+ )+ if ($remaining -le 0) { [Environment]::Exit(87) }+ $winner = [System.Threading.WaitHandle]::WaitAny($handles, [int][Math]::Min($remaining, 2147483647))+ if ($winner -eq 0) { [Environment]::Exit(86) }+ if ($winner -eq 1) {+ $records = $query.EndInvoke($queryTask)+ if ($records.Count -ne 1) { [Environment]::Exit(88) }+ $json = ConvertTo-Json -InputObject $records[0].psobject.BaseObject -Depth 12 -Compress+ [Console]::Out.WriteLine('RESULT ' + $json)+ [Console]::Out.Flush()+ [Environment]::Exit(0)+ }+ [Environment]::Exit(87)+ }+} catch {+ [Environment]::Exit(88)+}diff --git a/packages/desktop/tests/support/windows-os-state-cli.test-helper.ts b/packages/desktop/tests/support/windows-os-state-cli.test-helper.tsnew file mode 100644index 000000000..6ac2ad77a--- /dev/null+++ b/packages/desktop/tests/support/windows-os-state-cli.test-helper.ts@@ -0,0 +1,84 @@+import {+ collectWindowsOsState,+ WINDOWS_OS_MAX_BUDGET_MS,+ WINDOWS_OS_MAX_RESULT_BYTES,+ WINDOWS_OS_MAX_TARGETS,+} from './windows-os-state.test-helper.ts';++function positive(value: string | undefined): number | null {+ if (value === undefined || !/^[1-9][0-9]*$/u.test(value)) return null;+ const number = Number(value);+ return Number.isSafeInteger(number) && number > 0 ? number : null;+}++function boundedBudget(value: string | undefined): number | null {+ const number = positive(value);+ return number !== null && number <= WINDOWS_OS_MAX_BUDGET_MS ? number : null;+}++function emit(value: unknown, status: number): void {+ const serialized = JSON.stringify(value);+ const tooLarge = Buffer.byteLength(serialized) > WINDOWS_OS_MAX_RESULT_BYTES;+ const output = tooLarge+ ? JSON.stringify({ version: 1, status: 'unavailable', reason: 'output-limit' })+ : serialized;+ process.stdout.write(`${output}\n`);+ process.exitCode = tooLarge ? 1 : status;+}++const args = process.argv.slice(2);+const pids: number[] = [];+let parentPid: number | undefined;+let budgetMs = WINDOWS_OS_MAX_BUDGET_MS;+let valid = true;+for (let index = 0; index < args.length; index += 2) {+ const flag = args[index];+ const value = args[index + 1];+ if (flag === '--pid') {+ const pid = positive(value);+ if (pid === null || pids.length >= WINDOWS_OS_MAX_TARGETS) {+ valid = false;+ break;+ }+ pids.push(pid);+ } else if (flag === '--parent-pid' && parentPid === undefined) {+ const pid = positive(value);+ if (pid === null) {+ valid = false;+ break;+ }+ parentPid = pid;+ } else if (flag === '--budget-ms') {+ const budget = boundedBudget(value);+ if (budget === null) {+ valid = false;+ break;+ }+ budgetMs = budget;+ } else {+ valid = false;+ break;+ }+}++if (!valid || pids.length === 0 || args.length % 2 !== 0) {+ emit({ version: 1, status: 'unavailable', reason: 'invalid-shape' }, 2);+} else {+ const deadlineAt = performance.now() + budgetMs;+ const firstPid = pids[0];+ if (firstPid === undefined) {+ emit({ version: 1, status: 'unavailable', reason: 'invalid-shape' }, 2);+ } else {+ const observation = await collectWindowsOsState({+ pid: firstPid,+ additionalPids: pids.slice(1),+ parentPid,+ deadlineAt,+ });+ const success =+ observation.machine.status === 'captured' &&+ observation.targets.length === pids.length &&+ observation.targets.every((target) => target.shell.status === 'captured');+ emit(observation, success ? 0 : 1);+ }+}diff --git a/packages/desktop/tests/support/windows-os-state-contract.test-helper.ts b/packages/desktop/tests/support/windows-os-state-contract.test-helper.tsnew file mode 100644index 000000000..88082b7d2--- /dev/null+++ b/packages/desktop/tests/support/windows-os-state-contract.test-helper.ts@@ -0,0 +1,288 @@+import assert from 'node:assert/strict';+import type { PtyOsObservation } from '../../src/utility/pty-host.ts';+import {+ WINDOWS_OS_MAX_CANDIDATES,+ WINDOWS_OS_MAX_RESULT_BYTES,+ WINDOWS_OS_MAX_TARGETS,+ WINDOWS_OS_MAX_THREADS,+} from './windows-os-state.test-helper.ts';++const unavailableReasons = new Set([+ 'deadline',+ 'no-budget',+ 'unsupported-platform',+ 'query-start-failed',+ 'query-exited',+ 'invalid-json',+ 'invalid-shape',+ 'output-limit',+ 'owner-loss',+ 'process-absent',+ 'access-unavailable',+ 'identity-changed',+ 'worker-request-deadline',+ 'worker-unavailable',+ 'console-identity-unavailable',+]);+const threadStates = new Set([+ 'initialized',+ 'ready',+ 'running',+ 'standby',+ 'terminated',+ 'wait',+ 'transition',+ 'unknown',+]);+const waitReasons = new Set([+ 'executive',+ 'free-page',+ 'page-in',+ 'pool-allocation',+ 'execution-delay',+ 'suspended',+ 'user-request',+ 'event-pair-high',+ 'event-pair-low',+ 'lpc-receive',+ 'lpc-reply',+ 'virtual-memory',+ 'page-out',+ 'unknown',+ 'not-applicable',+]);+const candidateFailureReasons = new Set([+ 'process-absent',+ 'access-unavailable',+ 'identity-changed',+]);++function assertRecord(value: unknown, keys: string[]): asserts value is Record<string, unknown> {+ assert.ok(value !== null && typeof value === 'object' && !Array.isArray(value));+ assert.deepEqual(Object.keys(value).sort(), keys.sort());+}++function assertEnum(value: unknown, values: Set<string>): void {+ assert.ok(typeof value === 'string' && values.has(value));+}++function assertNonnegativeNumber(value: unknown): void {+ assert.ok(+ typeof value === 'number' &&+ Number.isFinite(value) &&+ value >= 0 &&+ value <= Number.MAX_SAFE_INTEGER,+ );+}++function assertNonnegativeInteger(value: unknown): void {+ assert.ok(typeof value === 'number' && Number.isSafeInteger(value) && value >= 0);+}++function assertPositiveInteger(value: unknown): void {+ assert.ok(typeof value === 'number' && Number.isSafeInteger(value) && value > 0);+}++function assertProcess(value: unknown): void {+ assertRecord(value, [+ 'pid',+ 'parentPid',+ 'createdAtMs',+ 'first',+ 'second',+ 'threads',+ 'omittedThreads',+ ]);+ assertPositiveInteger(value.pid);+ if (value.parentPid !== null) assertNonnegativeInteger(value.parentPid);+ assertNonnegativeNumber(value.createdAtMs);+ for (const sample of [value.first, value.second]) {+ assertRecord(sample, ['userMs', 'kernelMs', 'threadCount']);+ assertNonnegativeNumber(sample.userMs);+ assertNonnegativeNumber(sample.kernelMs);+ assertNonnegativeInteger(sample.threadCount);+ }+ assert.ok(Array.isArray(value.threads) && value.threads.length <= WINDOWS_OS_MAX_THREADS);+ for (const thread of value.threads) {+ assertRecord(thread, ['id', 'state', 'waitReason']);+ assertPositiveInteger(thread.id);+ assertEnum(thread.state, threadStates);+ assertEnum(thread.waitReason, waitReasons);+ assert.equal(thread.state === 'wait', thread.waitReason !== 'not-applicable');+ }+ assertNonnegativeInteger(value.omittedThreads);+}++function assertMachineSample(value: unknown): void {+ assertRecord(value, ['atMs', 'logicalCpus', 'userMs', 'systemMs', 'idleMs', 'irqMs', 'niceMs']);+ assertNonnegativeNumber(value.atMs);+ assertPositiveInteger(value.logicalCpus);+ for (const field of ['userMs', 'systemMs', 'idleMs', 'irqMs', 'niceMs']) {+ assertNonnegativeNumber(value[field]);+ }+}++function assertConsole(value: unknown): void {+ assertRecord(value, [+ 'association',+ 'candidateCount',+ 'candidates',+ 'unavailableCandidates',+ 'omittedCandidates',+ ]);+ assert.equal(value.association, 'candidate-parent-relation');+ assertNonnegativeInteger(value.candidateCount);+ assert.ok(+ Array.isArray(value.candidates) && value.candidates.length <= WINDOWS_OS_MAX_CANDIDATES,+ );+ for (const candidate of value.candidates) assertProcess(candidate);+ assert.ok(+ Array.isArray(value.unavailableCandidates) &&+ value.unavailableCandidates.length <= WINDOWS_OS_MAX_CANDIDATES,+ );+ let unavailableCount = 0;+ for (const candidate of value.unavailableCandidates) {+ assertRecord(candidate, ['reason', 'count']);+ assertEnum(candidate.reason, candidateFailureReasons);+ assertPositiveInteger(candidate.count);+ unavailableCount += candidate.count as number;+ }+ assertNonnegativeInteger(value.omittedCandidates);+ assert.equal(+ value.candidateCount,+ value.candidates.length + unavailableCount + (value.omittedCandidates as number),+ );+}++function assertWorker(value: unknown): void {+ assertRecord(value, ['nodeThreadId', 'requestedAtMs', 'repliedAtMs', 'userMs', 'systemMs']);+ assertPositiveInteger(value.nodeThreadId);+ assertNonnegativeNumber(value.requestedAtMs);+ assertNonnegativeNumber(value.repliedAtMs);+ assert.ok((value.repliedAtMs as number) >= (value.requestedAtMs as number));+ assertNonnegativeNumber(value.userMs);+ assertNonnegativeNumber(value.systemMs);+}++function assertSection(value: unknown, assertCaptured: (captured: unknown) => void): void {+ assert.ok(value !== null && typeof value === 'object' && !Array.isArray(value));+ const section = value as Record<string, unknown>;+ if (section.status === 'unavailable') {+ assertRecord(section, ['status', 'reason']);+ assertEnum(section.reason, unavailableReasons);+ return;+ }+ assertRecord(section, ['status', 'value']);+ assert.equal(section.status, 'captured');+ assertCaptured(section.value);+}++export function assertBoundedWindowsOsState(+ value: unknown,+ expectedPid: number,+): asserts value is PtyOsObservation {+ assertRecord(value, [+ 'version',+ 'status',+ 'reason',+ 'requestedPid',+ 'targets',+ 'startedAtMs',+ 'completedAtMs',+ 'shell',+ 'machine',+ 'console',+ 'worker',+ 'helper',+ ]);+ assert.ok(Buffer.byteLength(JSON.stringify(value)) <= WINDOWS_OS_MAX_RESULT_BYTES);+ assert.equal(value.version, 1);+ assert.equal(value.requestedPid, expectedPid);+ assertPositiveInteger(value.requestedPid);+ assert.ok(['captured', 'partial', 'unavailable'].includes(value.status as string));+ if (value.reason !== null) assertEnum(value.reason, unavailableReasons);+ if (value.startedAtMs !== null) assertNonnegativeNumber(value.startedAtMs);+ if (value.completedAtMs !== null) assertNonnegativeNumber(value.completedAtMs);+ assert.ok(Array.isArray(value.targets) && value.targets.length <= WINDOWS_OS_MAX_TARGETS);+ for (const target of value.targets) {+ assertRecord(target, ['requestedPid', 'shell']);+ assertPositiveInteger(target.requestedPid);+ assertSection(target.shell, assertProcess);+ if ((target.shell as PtyOsObservation['shell']).status === 'captured') {+ assert.equal(+ (target.shell as Extract<PtyOsObservation['shell'], { status: 'captured' }>).value.pid,+ target.requestedPid,+ );+ }+ }+ if (value.targets.length > 0) {+ assert.equal(value.targets[0]?.requestedPid, expectedPid);+ assert.deepEqual(value.targets[0]?.shell, value.shell);+ } else {+ assert.equal(value.reason, 'output-limit');+ }+ assertSection(value.shell, assertProcess);+ if ((value.shell as PtyOsObservation['shell']).status === 'captured') {+ assert.equal(+ (value.shell as Extract<PtyOsObservation['shell'], { status: 'captured' }>).value.pid,+ expectedPid,+ );+ }+ assertSection(value.machine, (captured) => {+ assertRecord(captured, ['first', 'second']);+ assertMachineSample(captured.first);+ assertMachineSample(captured.second);+ assert.ok(+ (captured.second as { atMs: number }).atMs >= (captured.first as { atMs: number }).atMs,+ );+ });+ assertSection(value.console, assertConsole);+ assertSection(value.worker, assertWorker);+ assertRecord(value.helper, ['requested', 'reason', 'delivery', 'exit', 'exitCode']);+ assert.equal(typeof value.helper.requested, 'boolean');+ if (value.helper.reason !== null) {+ assertEnum(value.helper.reason, new Set(['deadline', 'output-limit', 'owner-loss']));+ }+ assert.equal(value.helper.requested, value.helper.reason !== null);+ assertEnum(+ value.helper.delivery,+ new Set(['not-attempted', 'no-pid', 'already-exited', 'accepted', 'rejected', 'threw']),+ );+ assertEnum(+ value.helper.exit,+ new Set([+ 'not-observed',+ 'observed-before-request',+ 'observed-after-request',+ 'cooperative-deadline',+ 'cooperative-owner-loss',+ ]),+ );+ if (value.helper.exitCode !== null) assertNonnegativeInteger(value.helper.exitCode);+ if (value.status === 'captured') {+ assert.equal(value.reason, null);+ assert.equal((value.shell as PtyOsObservation['shell']).status, 'captured');+ assert.equal((value.machine as PtyOsObservation['machine']).status, 'captured');+ assert.equal((value.console as PtyOsObservation['console']).status, 'captured');+ assert.equal((value.worker as PtyOsObservation['worker']).status, 'captured');+ assert.equal(+ (value.console as Extract<PtyOsObservation['console'], { status: 'captured' }>).value+ .unavailableCandidates.length,+ 0,+ );+ } else {+ assert.notEqual(value.reason, null);+ if (value.status === 'partial') {+ assert.equal((value.shell as PtyOsObservation['shell']).status, 'captured');+ assert.ok(+ (value.machine as PtyOsObservation['machine']).status !== 'captured' ||+ (value.console as PtyOsObservation['console']).status !== 'captured' ||+ (value.worker as PtyOsObservation['worker']).status !== 'captured' ||+ (value.console as Extract<PtyOsObservation['console'], { status: 'captured' }>).value+ .unavailableCandidates.length > 0,+ );+ } else {+ assert.equal((value.shell as PtyOsObservation['shell']).status, 'unavailable');+ }+ }+}diff --git a/packages/desktop/tests/support/windows-os-state-proof.test-helper.ts b/packages/desktop/tests/support/windows-os-state-proof.test-helper.tsnew file mode 100644index 000000000..4a88b5e60--- /dev/null+++ b/packages/desktop/tests/support/windows-os-state-proof.test-helper.ts@@ -0,0 +1,171 @@+import assert from 'node:assert/strict';+import { type ChildProcess, spawn } from 'node:child_process';+import { Worker } from 'node:worker_threads';+import type { PtyOsObservation, PtyOsUnavailableReason } from '../../src/utility/pty-host.ts';+import {+ collectWindowsOsState,+ WINDOWS_OS_MAX_BUDGET_MS,+ WINDOWS_OS_MAX_RESULT_BYTES,+} from './windows-os-state.test-helper.ts';+import { assertBoundedWindowsOsState } from './windows-os-state-contract.test-helper.ts';++const helperExitFailed = {+ 'not-observed': false,+ 'observed-before-request': true,+ 'observed-after-request': false,+ 'cooperative-deadline': false,+ 'cooperative-owner-loss': true,+} as const satisfies Record<PtyOsObservation['helper']['exit'], boolean>;++const reasonShowsHelperFailure = {+ deadline: () => false,+ 'no-budget': () => false,+ 'unsupported-platform': () => true,+ 'query-start-failed': (result) => result.helper.reason !== 'deadline',+ 'query-exited': (result) => helperExitFailed[result.helper.exit],+ 'invalid-json': () => true,+ 'invalid-shape': (result) => result.status === 'unavailable',+ 'output-limit': () => true,+ 'owner-loss': () => false,+ 'process-absent': () => false,+ 'access-unavailable': () => false,+ 'identity-changed': () => false,+ 'worker-request-deadline': () => false,+ 'worker-unavailable': () => false,+ 'console-identity-unavailable': () => false,+} satisfies Record<PtyOsUnavailableReason, (result: PtyOsObservation) => boolean>;++function assertHelperDidNotFail(result: PtyOsObservation): void {+ assert.ok(result.reason === null || !reasonShowsHelperFailure[result.reason](result));+}++function bounded<T>(promise: Promise<T>, ms: number): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error('owned proof process did not settle')), ms);+ promise.then(+ (value) => {+ clearTimeout(timer);+ resolve(value);+ },+ () => {+ clearTimeout(timer);+ reject(new Error('owned proof process failed'));+ },+ );+ });+}++function watchClose(child: ChildProcess): Promise<number | null> {+ child.on('error', () => undefined);+ return new Promise((resolve) => {+ child.once('close', (code) => resolve(code));+ });+}++export async function runWindowsOsStateProof(): Promise<void> {+ const child = spawn(+ process.execPath,+ [+ '-e',+ `process.send('ready'); process.on('message', value => { if (value === 'release') process.exit(0) }); process.on('disconnect', () => process.exit(0)); setTimeout(() => process.exit(0), 30000)`,+ ],+ { stdio: ['ignore', 'pipe', 'pipe', 'ipc'], windowsHide: true, shell: false },+ );+ const childExit = watchClose(child);+ const childReady = new Promise<unknown>((resolve) => {+ child.once('message', (value) => resolve(value));+ child.once('error', () => resolve(null));+ child.once('close', () => resolve(null));+ });+ const pid = child.pid;+ let childStdoutBytes = 0;+ let childStderrBytes = 0;+ child.stdout?.on('data', (chunk: Buffer) => {+ childStdoutBytes = Math.min(32 * 1024 + 1, childStdoutBytes + chunk.byteLength);+ });+ child.stderr?.on('data', (chunk: Buffer) => {+ childStderrBytes = Math.min(32 * 1024 + 1, childStderrBytes + chunk.byteLength);+ });+ let worker: Worker | null = null;+ let workerExit: Promise<number> | null = null;+ let proofFailed = false;+ let proofError: unknown;+ let cleanupFailure: 'subject' | 'worker' | null = null;+ try {+ assert.ok(pid && pid > 0);+ worker = new Worker(+ `const { parentPort } = require('node:worker_threads'); const timer = setTimeout(() => process.exit(0), 30000); parentPort.postMessage('ready'); parentPort.on('message', value => { if (value === 'release') { clearTimeout(timer); parentPort.close() } })`,+ { eval: true },+ );+ const ownedWorker = worker;+ workerExit = new Promise<number>((resolve) => {+ ownedWorker.on('error', () => undefined);+ ownedWorker.once('exit', (code) => resolve(code));+ });+ const workerReady = new Promise<unknown>((resolve) => {+ ownedWorker.once('message', (value) => resolve(value));+ ownedWorker.once('error', () => resolve(null));+ ownedWorker.once('exit', () => resolve(null));+ });+ const readyMessage = await bounded(childReady, 8_000);+ assert.equal(readyMessage, 'ready');+ const workerReadyMessage = await bounded(workerReady, 8_000);+ assert.equal(workerReadyMessage, 'ready');+ const result = await collectWindowsOsState({+ pid,+ parentPid: process.pid,+ worker,+ budgetMs: WINDOWS_OS_MAX_BUDGET_MS,+ });+ const serialized = JSON.stringify(result);+ const serializedBytes = Buffer.byteLength(serialized);+ if (serializedBytes <= WINDOWS_OS_MAX_RESULT_BYTES) {+ console.log(`WINDOWS_OS_PROOF ${serialized}`);+ } else {+ console.log(`WINDOWS_OS_PROOF_OVERSIZE bytes=${serializedBytes}`);+ }+ assertBoundedWindowsOsState(result, pid);+ assertHelperDidNotFail(result);+ assert.equal(childStdoutBytes, 0);+ assert.equal(childStderrBytes, 0);+ } catch (error) {+ proofFailed = true;+ proofError = error;+ } finally {+ if (child.connected) {+ try {+ child.send('release');+ } catch {}+ }+ if (worker !== null && worker.threadId > 0) {+ try {+ worker.postMessage('release');+ } catch {}+ }+ const childOutcome = await bounded(childExit, 35_000).then(+ (code) => ({ status: 'closed' as const, code }),+ () => ({ status: 'deadline' as const, code: null }),+ );+ if (childOutcome.status === 'deadline') {+ console.log(`WINDOWS_OS_SUBJECT_PENDING pid=${pid ?? 'none'} command=node`);+ cleanupFailure = 'subject';+ } else if (childOutcome.code !== 0) {+ console.log(+ `WINDOWS_OS_SUBJECT_EXIT pid=${pid ?? 'none'} code=${childOutcome.code ?? 'null'} command=node`,+ );+ cleanupFailure = 'subject';+ }+ if (workerExit !== null) {+ const workerCode = await bounded(workerExit, 35_000).catch(() => null);+ if (workerCode === null) {+ console.log('WINDOWS_OS_WORKER_PENDING command=node-worker');+ cleanupFailure = 'worker';+ } else if (workerCode !== 0) {+ console.log(`WINDOWS_OS_WORKER_EXIT code=${workerCode} command=node-worker`);+ cleanupFailure = 'worker';+ }+ }+ }+ if (proofFailed) throw proofError;+ if (cleanupFailure !== null) throw new Error(`owned ${cleanupFailure} did not exit cleanly`);+}diff --git a/packages/desktop/tests/support/windows-os-state.md b/packages/desktop/tests/support/windows-os-state.mdnew file mode 100644index 000000000..7db0197ee--- /dev/null+++ b/packages/desktop/tests/support/windows-os-state.md@@ -0,0 +1,29 @@+# Windows PTY OS observation++Run the standalone collector with Node 24 from the Open Knowledge workspace:++```sh+node packages/desktop/tests/support/windows-os-state-cli.test-helper.ts --pid 12345 --parent-pid 6789 --budget-ms 5000+```++`--pid` accepts one to eight positive process IDs; repeat the flag for more than one target. One collection starts one PowerShell helper for all requested IDs. The top-level `requestedPid` and `shell` describe the first `--pid` only; read each ID's row in `targets`. `--parent-pid` is optional and only selects the console query: the helper lists `conhost.exe` and `OpenConsole.exe` processes whose parent is that ID. Without it no console query runs, and `console` is `unavailable` with reason `console-identity-unavailable`. `--budget-ms` must be positive and no greater than 5000. Invalid arguments return exit 2 and the fixed `{"version":1,"status":"unavailable","reason":"invalid-shape"}` record; the rejected value is not echoed. The collector queries only on Windows; elsewhere it returns reason `unsupported-platform` and exit 1. The entire stdout record is capped at 32 KiB.++The exit code and the top-level `status` answer different questions. Exit 0 means the `machine` section and every requested target's `shell` were captured; exit 1 means at least one of them was not. `status` is `captured` only when `shell`, `machine` and `console` are captured, no console candidate failed and `worker` is captured. The CLI owns no Worker, so its best possible record is exit 0 with `"status":"partial"`; that is the expected good standalone result. The top-level `reason` names a single cause: the collection-level reason when collection failed or ended early, otherwise the first unavailable section in the order `shell`, `machine`, `console`, failed console candidates, `worker`. Check each section's own `status` rather than reading the top-level `reason` as the only degraded section.++The test harness invokes this collector only after a scenario fails. A passing scenario, ordinary cleanup or budget refusal does no query. The collector's deadline is the earlier of its 5000 ms ceiling and the existing report allowance. It accepts no more than 64 KiB of raw helper stdout and stderr together. The result contains at most four console candidates and sixteen thread rows per process, with omitted counts. It validates each field and constructs a fresh record; raw output and errors are discarded.++Use `requestedPid`, `targets`, trace ID, attempt, and collection interval to correlate a record with a failure. A PID row describes collection time. Matching creation times across the two process samples support continuity during that short interval; they do not prove that the sampled process is the one that existed when the earlier silence began. The machine timestamps use the Node owner's monotonic clock. Process creation uses wall time, so subtract neither from the other.++The `shell` section gives creation time, two user/kernel CPU samples, thread count and bounded thread states. Its `parentPid` is the sampled process's own parent from a best-effort CIM lookup, unrelated to the `--parent-pid` input; only the first target gets one, and it is `null` when that lookup fails or has not finished. The two process samples are taken back to back, so their CPU difference is normally zero under every hypothesis and is not evidence for either; they support identity continuity only. Read the cumulative user/kernel CPU since creation together with the sampled thread states instead. Windows advances process CPU time in ticks of about 15.6 ms, so a small cumulative value is a count of ticks: `31.25` is two. A waiting thread's reason applies only to that sampled wait; other thread states have `not-applicable`. The `machine` section gives two aggregate CPU-time samples and logical CPU count, taken at the start and end of the whole collection. Compute its busy fraction as `(ΔuserMs + ΔsystemMs) / (ΔuserMs + ΔsystemMs + ΔidleMs)`, and only when that denominator is positive. Keep `irqMs` separate rather than adding it to that total: the pinned [Node 24.21.0 Windows implementation](https://github.com/nodejs/node/blob/v24.21.0/deps/uv/src/win/util.c#L585-L590) derives system time from kernel time minus idle time. Machine activity includes the query helper's own work; it is not a baseline measurement with the collector absent. Low cumulative shell CPU together with sampled `wait` threads can support investigation of a startup wait. High machine activity with shell threads in `ready` or `running` can support investigation of scheduling contention in the sampled interval. Neither pattern establishes what happened during the earlier silence or names a competing process.++`console` lists candidates under `candidate-parent-relation`; no candidate is claimed as the precise ConPTY host. `candidateCount: 0` is an observed empty query result. When `candidateCount` is positive, `unavailableCandidates` retains fixed reasons and counts for candidates that could not be sampled, while `omittedCandidates` counts rows beyond the cap. An empty `candidates` list alone does not mean the query was empty. `worker` contains `nodeThreadId` and opportunistic `Worker.cpuUsage()` counters when that owned Worker object exists, has a positive `threadId` and replies with finite counters before collection ends. `nodeThreadId` is a Node worker ID, not a Windows thread ID. Missing worker response is not zero CPU. The standalone CLI has no owned Worker object.++Read existing native byte and forwarding counters beside the OS record. Each `os-snapshot` record carries `transport`, that attempt's counters read when the failure was detected and before collection started, or `null` when the attempt has no native snapshot; the `failure` snapshot is taken after collection, so a difference between the two shows bytes that arrived while the OS state was collected. Advancing counts locate progress at their named transport boundaries. CPU activity without advancing native reads is compatible with several behaviors, including computation without output. This collector does not hold a pipe read handle and cannot establish that bytes waited unread in the kernel.++Each section uses `captured` or an explicit `unavailable` reason. The reasons are `deadline`, `no-budget`, `unsupported-platform`, `query-start-failed`, `query-exited`, `invalid-json`, `invalid-shape`, `output-limit`, `owner-loss`, `process-absent`, `access-unavailable`, `identity-changed`, `worker-request-deadline`, `worker-unavailable` and `console-identity-unavailable`. `console-identity-unavailable` means no parent process ID was supplied, so no console query ran. For `worker`, `worker-unavailable` means there was no owned Worker object, its `threadId` was not positive so no request was sent (Node sets an exited Worker's `threadId` to -1), or the `cpuUsage()` request failed; `worker-request-deadline` means the request was sent but no reply arrived before collection ended, and `invalid-shape` means the reply carried counters that are not finite. `process-absent` means no process with that ID was running when its sample began, or the process exited while it was being sampled; it applies to `targets` rows and to failed console candidates alike. Every other reason is a failed observation. In the harness the top-level `partial` result preserves available sections and is not healthy state. The original harness failure remains the verdict when collection fails.++The helper writes three line frames on stdout: `READY` once its guard is armed, `SHELL` with the process samples taken before any CIM query, then `RESULT` with the full record including the CIM-derived `parentPid` and `console`. When collection ends at its deadline, on owner loss, or because the helper exited with a nonzero code after a valid `SHELL` frame, the record keeps those process samples with the ending reason, an unavailable `console` and a `null` `parentPid`; it reads `partial` when the first target was captured. A malformed or mismatched `SHELL` frame, or any unexpected line, discards them.++The collector directly owns one disposable PowerShell helper. Only deadline, output limit or owner loss can request termination through that original handle. The helper starts with a process-scoped `-ExecutionPolicy Bypass`; no persistent policy changes. `helper.delivery=accepted` records a request accepted by Node, not proof of exit. `helper.exit` records independently observed exit: `observed-before-request` and `observed-after-request` place an exit relative to a termination request, `cooperative-owner-loss` (exit 86) and `cooperative-deadline` (exit 87) are the helper ending itself on lost ownership or its own deadline without a request, and `not-observed` leaves it unknown. Missing helper PID or an observed exit prevents another termination call. The helper uses in-process runspaces and an ownership pipe. Once its guard is armed, EOF or its own deadline can end it without a descendant process. Uncatchable owner death before guard initialization has no proven cleanup guarantee.++The Windows spent-budget case owns a silent process and Worker and collects one OS observation. It prints the record as `WINDOWS_OS_PROOF ` followed by its JSON, or, when that JSON exceeds 32 KiB, only `WINDOWS_OS_PROOF_OVERSIZE bytes=` with the byte count, and then validates the bounded record. It accepts every record not listed below, including the timing outcomes: reason `deadline`, reason `query-start-failed` with `helper.reason` `deadline`, and reason `query-exited` with `helper.exit` `cooperative-deadline`. It rejects a record of any status whose reason shows that the helper or its invocation failed: reason `invalid-json`, `output-limit` or `unsupported-platform`; reason `query-start-failed` when `helper.reason` is not `deadline`; reason `query-exited` when `helper.exit` is `observed-before-request` or `cooperative-owner-loss`; and, on an `unavailable` record, reason `invalid-shape`. A deadline record passes, so a green run does not show that the CIM query completed. The standalone CLI remains available through the command above. Local recording tests cover record acceptance and lifecycle behavior. No Windows case requires the helper's own exits 86 and 87 to occur: recorded tests cover how the collector classifies them, and a Windows record shows `cooperative-owner-loss` or `cooperative-deadline` only when the helper ends itself that way, unrequested, before collection settles.diff --git a/packages/desktop/tests/support/windows-os-state.test-helper.ts b/packages/desktop/tests/support/windows-os-state.test-helper.tsnew file mode 100644index 000000000..fd5cc62a1--- /dev/null+++ b/packages/desktop/tests/support/windows-os-state.test-helper.ts@@ -0,0 +1,715 @@+import { spawn } from 'node:child_process';+import { cpus } from 'node:os';+import { win32 } from 'node:path';+import { fileURLToPath } from 'node:url';+import type { Worker } from 'node:worker_threads';+import { getWindowsEnvValue } from '../../src/shared/windows-env.ts';+import type {+ PtyOsMachineSample,+ PtyOsObservation,+ PtyOsProcessSample,+ PtyOsSection,+ PtyOsThreadSample,+ PtyOsUnavailableReason,+} from '../../src/utility/pty-host.ts';++export const WINDOWS_OS_MAX_BUDGET_MS = 5_000;+export const WINDOWS_OS_MAX_TARGETS = 8;+export const WINDOWS_OS_MAX_CANDIDATES = 4;+export const WINDOWS_OS_MAX_THREADS = 16;+export const WINDOWS_OS_MAX_RAW_BYTES = 64 * 1024;+export const WINDOWS_OS_MAX_RESULT_BYTES = 32 * 1024;+export const WINDOWS_OS_HELPER_EXIT = { ownerLoss: 86, deadline: 87 } as const;++export function windowsPowerShellPath(+ env: Record<string, string | undefined> = process.env,+): string {+ return win32.join(+ getWindowsEnvValue(env, 'SystemRoot') ?? 'C:\\Windows',+ 'System32',+ 'WindowsPowerShell',+ 'v1.0',+ 'powershell.exe',+ );+}++type TerminationReason = 'deadline' | 'output-limit' | 'owner-loss';+type StreamLike = {+ on(event: 'data', listener: (chunk: Buffer | string) => void): unknown;+ on(event: 'error', listener: () => void): unknown;+ destroy?(): unknown;+};+type InputLike = {+ write(chunk: string): unknown;+ end(): unknown;+ on?(event: 'error', listener: () => void): unknown;+ destroy?(): unknown;+};+export interface WindowsQueryHelper {+ pid?: number;+ stdout: StreamLike | null;+ stderr: StreamLike | null;+ stdin: InputLike | null;+ on(event: 'error', listener: () => void): unknown;+ on(+ event: 'exit',+ listener: (code: number | null, signal: NodeJS.Signals | null) => void,+ ): unknown;+ on(+ event: 'close',+ listener: (code: number | null, signal: NodeJS.Signals | null) => void,+ ): unknown;+ kill(): boolean;+ unref?(): void;+}++export interface WindowsOsStateOptions {+ pid: number;+ additionalPids?: number[];+ parentPid?: number;+ budgetMs?: number;+ deadlineAt?: number;+ platform?: NodeJS.Platform;+ worker?: Pick<Worker, 'threadId' | 'cpuUsage'>;+ spawnQuery?: (file: string, args: string[]) => WindowsQueryHelper;+}++export interface WindowsOsCollection {+ result: Promise<PtyOsObservation>;+ cancel(reason: 'deadline' | 'owner-loss'): PtyOsObservation | null;+}++const queryFile = fileURLToPath(new URL('./windows-os-query.test-helper.ps1', import.meta.url));+const threadStates = [+ 'initialized',+ 'ready',+ 'running',+ 'standby',+ 'terminated',+ 'wait',+ 'transition',+ 'unknown',+] as const;+const waitReasons = [+ 'executive',+ 'free-page',+ 'page-in',+ 'pool-allocation',+ 'execution-delay',+ 'suspended',+ 'user-request',+ 'event-pair-high',+ 'event-pair-low',+ 'lpc-receive',+ 'lpc-reply',+ 'virtual-memory',+ 'page-out',+ 'unknown',+ 'not-applicable',+] as const;+const unavailableReasons = [+ 'process-absent',+ 'access-unavailable',+ 'identity-changed',+ 'console-identity-unavailable',+] as const;+const shellRetainingReasons = ['deadline', 'owner-loss', 'query-exited'] as const;+const candidateFailureReasons = [+ 'process-absent',+ 'access-unavailable',+ 'identity-changed',+] as const;++function record(value: unknown): Record<string, unknown> | null {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+}++function finite(value: unknown): value is number {+ return (+ typeof value === 'number' &&+ Number.isFinite(value) &&+ value >= 0 &&+ value <= Number.MAX_SAFE_INTEGER+ );+}++function positivePid(value: unknown): value is number {+ return finite(value) && Number.isSafeInteger(value) && value > 0;+}++function nonnegativeInteger(value: unknown): value is number {+ return finite(value) && Number.isSafeInteger(value);+}++function member<const T extends readonly string[]>(value: unknown, values: T): value is T[number] {+ return typeof value === 'string' && values.some((item) => item === value);+}++function unavailable<T>(reason: PtyOsUnavailableReason): PtyOsSection<T> {+ return { status: 'unavailable', reason };+}++function parseCpu(value: unknown): PtyOsProcessSample['first'] | null {+ const item = record(value);+ if (+ item === null ||+ !finite(item.userMs) ||+ !finite(item.kernelMs) ||+ !nonnegativeInteger(item.threadCount)+ )+ return null;+ return {+ userMs: item.userMs,+ kernelMs: item.kernelMs,+ threadCount: item.threadCount,+ };+}++function parseThread(value: unknown): PtyOsThreadSample | null {+ const item = record(value);+ if (+ item === null ||+ !positivePid(item.id) ||+ !member(item.state, threadStates) ||+ !member(item.waitReason, waitReasons) ||+ (item.state !== 'wait' && item.waitReason !== 'not-applicable') ||+ (item.state === 'wait' && item.waitReason === 'not-applicable')+ )+ return null;+ return { id: item.id, state: item.state, waitReason: item.waitReason };+}++function parseProcess(value: unknown): PtyOsSection<PtyOsProcessSample> | null {+ const item = record(value);+ if (item === null) return null;+ if (item.status === 'unavailable') {+ return member(item.reason, unavailableReasons) ? unavailable(item.reason) : null;+ }+ if (item.status !== 'captured') return null;+ const first = parseCpu(item.first);+ const second = parseCpu(item.second);+ if (+ !positivePid(item.pid) ||+ !(item.parentPid === null || nonnegativeInteger(item.parentPid)) ||+ !finite(item.createdAtMs) ||+ !finite(item.secondCreatedAtMs) ||+ first === null ||+ second === null ||+ !Array.isArray(item.threads) ||+ !nonnegativeInteger(item.omittedThreads)+ )+ return null;+ if (item.createdAtMs !== item.secondCreatedAtMs) return unavailable('identity-changed');+ const threads: PtyOsThreadSample[] = [];+ for (const raw of item.threads.slice(0, WINDOWS_OS_MAX_THREADS)) {+ const thread = parseThread(raw);+ if (thread === null) return null;+ threads.push(thread);+ }+ const omittedThreads =+ item.omittedThreads + Math.max(0, item.threads.length - WINDOWS_OS_MAX_THREADS);+ if (!nonnegativeInteger(omittedThreads)) return null;+ return {+ status: 'captured',+ value: {+ pid: item.pid,+ parentPid: item.parentPid,+ createdAtMs: item.createdAtMs,+ first,+ second,+ threads,+ omittedThreads,+ },+ };+}++function parseShells(+ value: unknown,+ requestedPids: number[],+): {+ shell: PtyOsSection<PtyOsProcessSample>;+ targets: PtyOsObservation['targets'];+} | null {+ const item = record(value);+ if (+ item === null ||+ item.version !== 1 ||+ !Array.isArray(item.shells) ||+ item.shells.length !== requestedPids.length+ )+ return null;+ const targets: PtyOsObservation['targets'] = [];+ for (let index = 0; index < requestedPids.length; index++) {+ const requestedPid = requestedPids[index];+ if (requestedPid === undefined) return null;+ const shell = parseProcess(item.shells[index]);+ if (shell === null || (shell.status === 'captured' && shell.value.pid !== requestedPid))+ return null;+ targets.push({ requestedPid, shell });+ }+ const shell = targets[0]?.shell ?? null;+ return shell === null ? null : { shell, targets };+}++function parseQuery(+ value: unknown,+ requestedPids: number[],+): {+ shell: PtyOsSection<PtyOsProcessSample>;+ targets: PtyOsObservation['targets'];+ console: PtyOsObservation['console'];+} | null {+ const shells = parseShells(value, requestedPids);+ const console = record(record(value)?.console);+ if (shells === null || console === null) return null;+ const { shell, targets } = shells;+ let candidates: PtyOsObservation['console'];+ if (console.status === 'unavailable') {+ if (!member(console.reason, unavailableReasons)) return null;+ candidates = unavailable(console.reason);+ } else {+ if (+ console.status !== 'captured' ||+ !nonnegativeInteger(console.candidateCount) ||+ !Array.isArray(console.candidates) ||+ !Array.isArray(console.unavailableCandidates) ||+ console.unavailableCandidates.length > WINDOWS_OS_MAX_CANDIDATES ||+ !nonnegativeInteger(console.omittedCandidates)+ )+ return null;+ const parsed: PtyOsProcessSample[] = [];+ for (const raw of console.candidates.slice(0, WINDOWS_OS_MAX_CANDIDATES)) {+ const process = parseProcess(raw);+ if (process === null || process.status !== 'captured') return null;+ parsed.push(process.value);+ }+ const unavailableCandidates: Array<{+ reason: (typeof candidateFailureReasons)[number];+ count: number;+ }> = [];+ let failedCount = 0;+ for (const raw of console.unavailableCandidates) {+ const failure = record(raw);+ if (+ failure === null ||+ !member(failure.reason, candidateFailureReasons) ||+ !nonnegativeInteger(failure.count) ||+ failure.count === 0+ )+ return null;+ failedCount += failure.count;+ unavailableCandidates.push({ reason: failure.reason, count: failure.count });+ }+ const countedCandidates = console.candidates.length + failedCount + console.omittedCandidates;+ if (+ !nonnegativeInteger(failedCount) ||+ !nonnegativeInteger(countedCandidates) ||+ countedCandidates !== console.candidateCount+ )+ return null;+ const omittedCandidates =+ console.omittedCandidates ++ Math.max(0, console.candidates.length - WINDOWS_OS_MAX_CANDIDATES);+ if (!nonnegativeInteger(omittedCandidates)) return null;+ candidates = {+ status: 'captured',+ value: {+ association: 'candidate-parent-relation',+ candidateCount: console.candidateCount,+ candidates: parsed,+ unavailableCandidates,+ omittedCandidates,+ },+ };+ }+ return { shell, targets, console: candidates };+}++function sampleMachine(): PtyOsMachineSample | null {+ try {+ const values = cpus();+ const totals = { userMs: 0, systemMs: 0, idleMs: 0, irqMs: 0, niceMs: 0 };+ for (const cpu of values) {+ totals.userMs += cpu.times.user;+ totals.systemMs += cpu.times.sys;+ totals.idleMs += cpu.times.idle;+ totals.irqMs += cpu.times.irq;+ totals.niceMs += cpu.times.nice;+ }+ return { atMs: performance.now(), logicalCpus: values.length, ...totals };+ } catch {+ return null;+ }+}++function boundedMachine(+ first: PtyOsMachineSample | null,+ second: PtyOsMachineSample | null,+): PtyOsObservation['machine'] {+ if (first === null || second === null) return unavailable('access-unavailable');+ const numbers = [+ first.atMs,+ first.logicalCpus,+ first.userMs,+ first.systemMs,+ first.idleMs,+ first.irqMs,+ first.niceMs,+ second.atMs,+ second.logicalCpus,+ second.userMs,+ second.systemMs,+ second.idleMs,+ second.irqMs,+ second.niceMs,+ ];+ return numbers.every(finite) && first.logicalCpus > 0 && second.logicalCpus > 0+ ? { status: 'captured', value: { first, second } }+ : unavailable('invalid-shape');+}++function defaultSpawnQuery(file: string, args: string[]): WindowsQueryHelper {+ return spawn(file, args, { stdio: 'pipe', windowsHide: true, shell: false });+}++export function startWindowsOsState(options: WindowsOsStateOptions): WindowsOsCollection {+ const startedAtMs = performance.now();+ const requestedPid = options.pid;+ const requestedPids = [options.pid, ...(options.additionalPids ?? [])];+ const firstMachine = sampleMachine();+ const parentPid = options.parentPid;+ const allowedBudget = Math.min(+ WINDOWS_OS_MAX_BUDGET_MS,+ options.budgetMs ?? WINDOWS_OS_MAX_BUDGET_MS,+ options.deadlineAt === undefined ? WINDOWS_OS_MAX_BUDGET_MS : options.deadlineAt - startedAtMs,+ );+ let child: WindowsQueryHelper | null = null;+ let closed = false;+ let exited = false;+ let exitCode: number | null = null;+ let terminationReason: TerminationReason | null = null;+ let delivery: PtyOsObservation['helper']['delivery'] = 'not-attempted';+ let exit: PtyOsObservation['helper']['exit'] = 'not-observed';+ let timer: ReturnType<typeof setTimeout> | undefined;+ let settled = false;+ let rawBytes = 0;+ let stdout = '';+ let ready = false;+ let resultSeen = false;+ let protocolInvalid = false;+ let shellFrame: ReturnType<typeof parseShells> | null = null;+ let shellSeen = false;+ let query: ReturnType<typeof parseQuery> | null = null;+ let queryReason: PtyOsUnavailableReason | null = null;+ let finalObservation: PtyOsObservation | null = null;+ let workerValue: PtyOsObservation['worker'] = unavailable('worker-unavailable');+ const worker = options.worker;+ if (worker !== undefined && worker.threadId > 0) {+ const nodeThreadId = worker.threadId;+ const requestedAtMs = performance.now();+ void Promise.resolve()+ .then(() => worker.cpuUsage())+ .then((cpu) => {+ const repliedAtMs = performance.now();+ if (settled) return;+ if (!finite(cpu.user) || !finite(cpu.system) || !finite(repliedAtMs)) {+ workerValue = unavailable('invalid-shape');+ return;+ }+ workerValue = {+ status: 'captured',+ value: {+ nodeThreadId,+ requestedAtMs,+ repliedAtMs,+ userMs: cpu.user / 1_000,+ systemMs: cpu.system / 1_000,+ },+ };+ })+ .catch(() => {+ if (!settled) workerValue = unavailable('worker-unavailable');+ });+ workerValue = unavailable('worker-request-deadline');+ }+ let resolveResult: (result: PtyOsObservation) => void = () => undefined;+ const result = new Promise<PtyOsObservation>((resolve) => {+ resolveResult = resolve;+ });+ const requestTermination = (reason: TerminationReason): void => {+ if (terminationReason !== null) return;+ terminationReason = reason;+ if (child === null || !positivePid(child.pid)) {+ delivery = 'no-pid';+ return;+ }+ if (exited || closed) {+ delivery = 'already-exited';+ exit = 'observed-before-request';+ return;+ }+ try {+ delivery = child.kill() ? 'accepted' : 'rejected';+ } catch {+ delivery = 'threw';+ }+ };+ const settle = (reason: PtyOsUnavailableReason | null): PtyOsObservation | null => {+ if (settled) return finalObservation;+ settled = true;+ if (timer !== undefined) clearTimeout(timer);+ if (reason !== null && child !== null && !closed) {+ try {+ child.stdin?.end();+ } catch {}+ try {+ child.stdout?.destroy?.();+ } catch {}+ try {+ child.stderr?.destroy?.();+ } catch {}+ try {+ child.unref?.();+ } catch {}+ }+ const sampled =+ reason === null+ ? query+ : !protocolInvalid && member(reason, shellRetainingReasons)+ ? shellFrame+ : null;+ const shell = sampled?.shell ?? unavailable<PtyOsProcessSample>(reason ?? 'invalid-shape');+ const targets: PtyOsObservation['targets'] =+ sampled?.targets ??+ requestedPids+ .slice(0, WINDOWS_OS_MAX_TARGETS)+ .filter(positivePid)+ .map((pid) => ({ requestedPid: pid, shell: unavailable(reason ?? 'invalid-shape') }));+ const console: PtyOsObservation['console'] =+ reason === null && query !== null ? query.console : unavailable(reason ?? 'invalid-shape');+ const machine = boundedMachine(firstMachine, sampleMachine());+ const completedAtMs = performance.now();+ const status: PtyOsObservation['status'] =+ shell.status === 'captured' &&+ machine.status === 'captured' &&+ console.status === 'captured' &&+ console.value.unavailableCandidates.length === 0 &&+ workerValue.status === 'captured'+ ? 'captured'+ : shell.status === 'captured'+ ? 'partial'+ : 'unavailable';+ const outcomeReason =+ reason ??+ (shell.status === 'unavailable'+ ? shell.reason+ : machine.status === 'unavailable'+ ? machine.reason+ : console.status === 'unavailable'+ ? console.reason+ : console.value.unavailableCandidates[0] !== undefined+ ? console.value.unavailableCandidates[0].reason+ : workerValue.status === 'unavailable'+ ? workerValue.reason+ : null);+ const observation: PtyOsObservation = {+ version: 1,+ status,+ reason: outcomeReason,+ requestedPid: positivePid(requestedPid) ? requestedPid : null,+ targets,+ startedAtMs: finite(startedAtMs) ? startedAtMs : null,+ completedAtMs: finite(completedAtMs) ? completedAtMs : null,+ shell,+ machine,+ console,+ worker: workerValue,+ helper: {+ requested: terminationReason !== null,+ reason: terminationReason,+ delivery,+ exit,+ exitCode,+ },+ };+ if (Buffer.byteLength(JSON.stringify(observation)) > WINDOWS_OS_MAX_RESULT_BYTES) {+ finalObservation = {+ ...observation,+ status: 'unavailable',+ reason: 'output-limit',+ targets: [],+ shell: unavailable('output-limit'),+ console: unavailable('output-limit'),+ worker: unavailable('output-limit'),+ };+ resolveResult(finalObservation);+ return finalObservation;+ }+ finalObservation = observation;+ resolveResult(observation);+ return observation;+ };+ if (+ requestedPids.length > WINDOWS_OS_MAX_TARGETS ||+ requestedPids.some((pid) => !positivePid(pid)) ||+ (parentPid !== undefined && !positivePid(parentPid))+ ) {+ settle('invalid-shape');+ return { result, cancel: () => finalObservation };+ }+ if ((options.platform ?? process.platform) !== 'win32') {+ settle('unsupported-platform');+ return { result, cancel: () => finalObservation };+ }+ if (!finite(allowedBudget) || allowedBudget < 1) {+ settle('no-budget');+ return { result, cancel: () => finalObservation };+ }+ const executable = windowsPowerShellPath();+ const deadlineEpochMs = Date.now() + allowedBudget;+ try {+ child = (options.spawnQuery ?? defaultSpawnQuery)(executable, [+ '-NoLogo',+ '-NoProfile',+ '-NonInteractive',+ '-ExecutionPolicy',+ 'Bypass',+ '-File',+ queryFile,+ '-PidValues',+ requestedPids.join(','),+ '-ParentPidValue',+ String(parentPid ?? 0),+ '-DeadlineEpochMs',+ String(Math.floor(deadlineEpochMs)),+ '-DurationCapMs',+ String(Math.floor(allowedBudget)),+ ]);+ } catch {+ settle('query-start-failed');+ return { result, cancel: () => finalObservation };+ }+ const active = child;+ active.on('error', () => {+ if (!settled) settle('query-start-failed');+ });+ const observeExit = (code: number | null): void => {+ exited = true;+ exitCode = nonnegativeInteger(code) ? code : null;+ exit =+ terminationReason === null+ ? code === WINDOWS_OS_HELPER_EXIT.ownerLoss+ ? 'cooperative-owner-loss'+ : code === WINDOWS_OS_HELPER_EXIT.deadline+ ? 'cooperative-deadline'+ : 'observed-before-request'+ : 'observed-after-request';+ };+ active.on('exit', observeExit);+ active.on('close', (code) => {+ closed = true;+ if (!exited) observeExit(code);+ if (!settled) {+ if (stdout.length > 0) queryReason = 'invalid-json';+ settle(+ code === 0+ ? protocolInvalid+ ? 'invalid-shape'+ : (queryReason ?? (query === null ? 'invalid-json' : null))+ : 'query-exited',+ );+ }+ });+ if (!positivePid(active.pid)) {+ settle('query-start-failed');+ return { result, cancel: () => finalObservation };+ }+ const remainingBudget = Math.max(0, allowedBudget - (performance.now() - startedAtMs));+ timer = setTimeout(() => {+ requestTermination('deadline');+ settle('deadline');+ }, remainingBudget);+ const ingest = (chunk: Buffer | string, isStdout: boolean): void => {+ if (settled) return;+ rawBytes += Buffer.byteLength(chunk);+ if (rawBytes > WINDOWS_OS_MAX_RAW_BYTES) {+ requestTermination('output-limit');+ settle('output-limit');+ return;+ }+ if (!isStdout) return;+ stdout += chunk.toString();+ for (;;) {+ const end = stdout.indexOf('\n');+ if (end < 0) break;+ const line = stdout.slice(0, end).replace(/\r$/u, '');+ stdout = stdout.slice(end + 1);+ if (!ready) {+ if (line !== 'READY') {+ protocolInvalid = true;+ queryReason = 'invalid-shape';+ continue;+ }+ ready = true;+ try {+ active.stdin?.write('S\n');+ } catch {+ settle('query-exited');+ }+ continue;+ }+ if (line.startsWith('SHELL ') && !shellSeen && !resultSeen) {+ shellSeen = true;+ try {+ shellFrame = parseShells(JSON.parse(line.slice(6)) as unknown, requestedPids);+ } catch {+ shellFrame = null;+ }+ if (shellFrame === null) {+ protocolInvalid = true;+ queryReason = 'invalid-shape';+ }+ continue;+ }+ if (!line.startsWith('RESULT ') || resultSeen) {+ protocolInvalid = true;+ queryReason = 'invalid-shape';+ continue;+ }+ resultSeen = true;+ try {+ query = parseQuery(JSON.parse(line.slice(7)) as unknown, requestedPids);+ queryReason = query === null || protocolInvalid ? 'invalid-shape' : null;+ } catch {+ queryReason = 'invalid-json';+ }+ }+ };+ active.stdout?.on('data', (chunk) => ingest(chunk, true));+ active.stderr?.on('data', (chunk) => ingest(chunk, false));+ active.stdout?.on('error', () => {+ if (!settled) settle('query-exited');+ });+ active.stderr?.on('error', () => {+ if (!settled) settle('query-exited');+ });+ active.stdin?.on?.('error', () => {+ if (!settled) settle('query-exited');+ });+ return {+ result,+ cancel(reason) {+ if (settled) return finalObservation;+ requestTermination(reason);+ return settle(reason);+ },+ };+}++export async function collectWindowsOsState(+ options: WindowsOsStateOptions,+): Promise<PtyOsObservation> {+ return startWindowsOsState(options).result;+}diff --git a/packages/desktop/tests/utility/pty-harness-environment.test-helper.ts b/packages/desktop/tests/utility/pty-harness-environment.test-helper.tsindex 904a687f0..f76ad7624 100644--- a/packages/desktop/tests/utility/pty-harness-environment.test-helper.ts+++ b/packages/desktop/tests/utility/pty-harness-environment.test-helper.ts@@ -1,5 +1,7 @@+import { EventEmitter } from 'node:events';import { readFileSync, rmSync } from 'node:fs';import { basename, join } from 'node:path';+import { PassThrough } from 'node:stream';import { vi } from 'vitest';import type { PtyProcessLike, SpawnPty } from '../../src/utility/pty-host.ts';@@ -33,18 +35,27 @@ export interface ControlledHarnessOptions {| 'posix-unstable-quiet';launchReadiness?: 'advancing' | 'stuck' | 'dead';budgetOverride?: string;+ silentAt?: 'initial-input' | 'environment-input' | 'launch-token' | 'command-output';+ queryMode?: 'delayed-invalid';}export interface ControlledHarnessResult {exitCode: Parameters<typeof process.exit>[0];lines: string[];- events: Array<{ shell: number; event: string; at: number }>;+ events: Array<{ shell: number; event: string; at: number; trace?: Record<string, unknown> }>;+ traceEvents: Record<string, unknown>[];+ delayedQuery?: { traceBeforeDelivery: string; linesBeforeDelivery: string };}export async function runControlledHarness(options: ControlledHarnessOptions,): Promise<ControlledHarnessResult> {- const result: ControlledHarnessResult = { exitCode: undefined, lines: [], events: [] };+ const result: ControlledHarnessResult = {+ exitCode: undefined,+ lines: [],+ events: [],+ traceEvents: [],+ };const dirs: string[] = [];const timers = new Set<ReturnType<typeof setTimeout>>();const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');@@ -55,8 +66,14 @@ export async function runControlledHarness(options.lifecycle ??(options.phase === 'delayed-exit' ? { launchAtMs: 44_000, exitAfterKillMs: 1_800 } : undefined);let shellCount = 0;- const record = (shell: number, event: string): void => {- result.events.push({ shell, event, at: performance.now() });+ const delayedQuery = { release: undefined as (() => void) | undefined };+ const record = (shell: number, event: string, trace?: Record<string, unknown>): void => {+ result.events.push({+ shell,+ event,+ at: performance.now(),+ ...(trace === undefined ? {} : { trace }),+ });};const spawn: SpawnPty = (file, args, spawnOptions): PtyProcessLike => {if (file.includes('no-such-shell-xyz')) throw new Error('file not found');@@ -128,7 +145,10 @@ export async function runControlledHarness(progressingUntil(84_000, 500, '\u001b[?1004h');} else {for (const when of [1_000, 8_000, 15_000, 22_000]) {- later(when, () => emit('PowerShell startup\r\n'));+ later(when, () => {+ record(shell, 'launch-startup-output');+ emit('PowerShell startup\r\n');+ });}if (options.phase === 'launch-after-grant') {for (const when of [24_000, 25_000]) at(when, () => emit('PowerShell startup\r\n'));@@ -139,10 +159,12 @@ export async function runControlledHarness(}}const launchAt = lifecycle?.launchAtMs ?? 23_000;- at(options.phase === 'launch-after-grant' ? 26_000 : launchAt, () => {- record(shell, 'launch-token');- emit(`${spawnOptions.env.OK_HARNESS_LAUNCH_TOKEN}\r\nPS C:\\project> `);- });+ if (options.silentAt !== 'launch-token') {+ at(options.phase === 'launch-after-grant' ? 26_000 : launchAt, () => {+ record(shell, 'launch-token');+ emit(`${spawnOptions.env.OK_HARNESS_LAUNCH_TOKEN}\r\nPS C:\\project> `);+ });+ }}} else {if (platform === 'linux' && shell === 1 && options.phase === 'posix-late-quiet') {@@ -174,6 +196,17 @@ export async function runControlledHarness(: /^echo (.*)_\$\(\((\d+)\*(\d+)\)\)_(.*)$/u.exec(command);if (arithmetic !== null) {const output = `${arithmetic[1]}_${Number(arithmetic[2]) * Number(arithmetic[3])}_${arithmetic[4]}\r\n`;+ if (+ (shell === 1 && options.silentAt === 'initial-input') ||+ (shell === 2 && options.silentAt === 'environment-input')+ ) {+ record(shell, 'unanswered-readiness-input');+ return;+ }+ if (shell === 1 && arithmetic[1] === 'HARNESS') {+ record(shell, 'command-input');+ if (options.silentAt === 'command-output') return;+ }if (launch && arithmetic[1]?.startsWith('OK_INPUT_READY_')) {const readiness = options.launchReadiness ?? 'advancing';if (readiness === 'dead') {@@ -337,7 +370,29 @@ export async function runControlledHarness(return 'C:\\Program Files\\PowerShell\\7\\pwsh.exe\r\n';},spawn: () => {- throw new Error('controlled harness cannot spawn a native subprocess');+ record(0, 'query-start');+ if (options.queryMode !== 'delayed-invalid') {+ throw new Error('controlled harness cannot spawn a native subprocess');+ }+ const stdout = new PassThrough();+ const stderr = new PassThrough();+ const child = Object.assign(new EventEmitter(), {+ pid: 93_421,+ stdout,+ stderr,+ stdin: new PassThrough(),+ kill() {+ record(0, 'query-termination-request');+ return true;+ },+ });+ delayedQuery.release = () => {+ record(0, 'late-query-output');+ stdout.end('{"extra":"private shell text"');+ stderr.end('private fixture stderr');+ child.emit('close', 1, null);+ };+ return child;},};});@@ -364,6 +419,14 @@ export async function runControlledHarness(});const log = vi.spyOn(console, 'log').mockImplementation((line: string) => {result.lines.push(line);+ if (line.startsWith('PTY_HOST ')) {+ const start = line.indexOf('{');+ if (start >= 0) {+ const trace = JSON.parse(line.slice(start)) as Record<string, unknown>;+ result.traceEvents.push(trace);+ record(0, `trace:${String(trace.stage)}`, trace);+ }+ }});const exit = vi.spyOn(process, 'exit').mockImplementation((code) => {result.exitCode = code;@@ -377,6 +440,13 @@ export async function runControlledHarness(Object.defineProperty(process, 'platform', { ...platformDescriptor, value: platform });await import('./pty-host.real-io-harness.ts');await vi.runAllTimersAsync();+ if (options.queryMode === 'delayed-invalid' && delayedQuery.release !== undefined) {+ const traceBeforeDelivery = JSON.stringify(result.traceEvents);+ const linesBeforeDelivery = JSON.stringify(result.lines);+ delayedQuery.release();+ await vi.runAllTimersAsync();+ result.delayedQuery = { traceBeforeDelivery, linesBeforeDelivery };+ }return result;} finally {Object.defineProperty(process, 'platform', platformDescriptor);diff --git a/packages/desktop/tests/utility/pty-harness-os-observation.test.ts b/packages/desktop/tests/utility/pty-harness-os-observation.test.tsnew file mode 100644index 000000000..82ecb9f91--- /dev/null+++ b/packages/desktop/tests/utility/pty-harness-os-observation.test.ts@@ -0,0 +1,393 @@+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';+import { expect, test, vi } from 'vitest';+import type { PtyOsObservation, PtyProcessLike } from '../../src/utility/pty-host.ts';+import {+ createHarnessReadinessAfterCompletion,+ createHarnessReadinessObserver,+ createPtyHostProbe,+ HARNESS_WINDOWS_LAUNCH_STALL_MS,+} from '../support/pty-readiness.test-helper.ts';+import { createHarnessScenarioRunner } from '../support/pty-startup-trace.test-helper.ts';+import type { WindowsOsStateOptions } from '../support/windows-os-state.test-helper.ts';++const PROLOGUE = '\u001b[1t\u001b[c\u001b[?1004h\u001b[?9001h';+const SHELL_TEXT = 'shell output with private content';+const PTY_ID = 'observed-shell';+const SHELL_PID = 424_242;+const CONSOLE_PID = 5_150;+const LATE_OUTPUT = 'late collection bytes';++function processRecord(pid: number) {+ return {+ status: 'captured',+ pid,+ parentPid: process.pid,+ createdAtMs: 1_700_000_000_000,+ secondCreatedAtMs: 1_700_000_000_000,+ first: { userMs: 5, kernelMs: 1, threadCount: 1 },+ second: { userMs: 5, kernelMs: 1, threadCount: 1 },+ threads: [{ id: 3, state: 'wait', waitReason: 'user-request' }],+ omittedThreads: 0,+ };+}++const QUERY_RESULT = {+ version: 1,+ shells: [processRecord(SHELL_PID)],+ console: {+ status: 'captured',+ candidateCount: 1,+ candidates: [processRecord(CONSOLE_PID)],+ unavailableCandidates: [],+ omittedCandidates: 0,+ },+};++const EXPECTED_SECTIONS = {+ shell: { status: 'captured', value: expect.objectContaining({ pid: SHELL_PID }) },+ console: {+ status: 'captured',+ value: expect.objectContaining({ candidates: [expect.objectContaining({ pid: CONSOLE_PID })] }),+ },+ worker: {+ status: 'captured',+ value: expect.objectContaining({ nodeThreadId: 41, userMs: 7, systemMs: 3 }),+ },+};++function answeringQuery() {+ const stdout = new PassThrough();+ const query = Object.assign(new EventEmitter(), {+ pid: 93_422,+ stdout,+ stderr: new PassThrough(),+ stdin: new PassThrough(),+ kill: vi.fn(() => true),+ });+ const hooks = { started: () => {} };+ const spawnQuery: WindowsOsStateOptions['spawnQuery'] = () => {+ setImmediate(() => stdout.write('READY\n'));+ query.stdin.once('data', () => {+ hooks.started();+ stdout.write(`RESULT ${JSON.stringify(QUERY_RESULT)}\n`);+ queueMicrotask(() => query.emit('close', 0, null));+ });+ return query;+ };+ return { spawnQuery, hooks };+}++function createScenario(+ title: string,+ grantMs = 0,+ spawnQuery?: WindowsOsStateOptions['spawnQuery'],+) {+ const events: Record<string, unknown>[] = [];+ const sequence: Array<{ kind: string; value?: unknown }> = [];+ const worker = Object.assign(new EventEmitter(), {+ threadId: 41,+ cpuUsage: async () => ({ user: 7_000, system: 3_000 }),+ });+ const socket = () =>+ Object.assign(new EventEmitter(), {+ destroyed: false,+ connecting: false,+ bytesRead: 0,+ readableLength: 0,+ writableLength: 0,+ });+ const output = socket();+ const input = socket();+ let receive = (_data: string) => {};+ const agent = {+ _conoutSocketWorker: { _worker: worker, _isDisposed: false },+ _outSocket: output,+ _inSocket: input,+ _pendingPtyInfo: {},+ innerPid: 0,+ exitCode: undefined,+ _completePtyConnection() {+ this.innerPid = 424242;+ this._pendingPtyInfo = undefined;+ },+ _$onProcessExit() {},+ };+ const terminal: PtyProcessLike & { _agent: typeof agent } = {+ _agent: agent,+ get pid() {+ return agent.innerPid;+ },+ onData(callback) {+ receive = callback;+ },+ onExit() {},+ write: vi.fn(),+ resize() {},+ kill: vi.fn(() => sequence.push({ kind: 'release' })),+ pause() {},+ resume() {},+ };+ const host = createPtyHostProbe({+ platform: 'win32',+ env: {},+ shellExists: () => true,+ startupTrace: { native: true },+ spawnQuery:+ spawnQuery ??+ (() => {+ throw new Error('recording query is unavailable');+ }),+ spawn: () => terminal,+ logger: {+ info(entry) {+ events.push(entry);+ sequence.push({ kind: 'trace', value: entry });+ },+ warn(entry) {+ events.push(entry);+ sequence.push({ kind: 'trace', value: entry });+ },+ },+ });+ const lines: string[] = [];+ const runner = createHarnessScenarioRunner({+ titles: [title],+ grantMs: () => grantMs,+ isRefusal: () => false,+ print(line) {+ lines.push(line);+ sequence.push({ kind: 'verdict', value: line });+ },+ });+ runner.own({+ snapshot: () => host.snapshotStartup(),+ captureFailure: () => host.captureFailure(),+ cancelCapture: () => host.cancelCapture(),+ release: () => host.killActive(),+ });+ host.send({+ type: 'create',+ ptyId: PTY_ID,+ cwd: process.cwd(),+ cols: 80,+ rows: 24,+ shell: 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',+ });+ worker.emit('online');+ worker.emit('message', 1);+ agent._completePtyConnection();+ output.emit('connect');+ return {+ host,+ runner,+ events,+ lines,+ sequence,+ terminal,+ output(data: string) {+ output.bytesRead += Buffer.byteLength(data);+ receive(data);+ },+ };+}++const SILENCE_ROUTES = [+ { title: 'initial interactive readiness', output: PROLOGUE, wait: 'input' },+ { title: 'env-stripped interactive readiness', output: PROLOGUE, wait: 'input' },+ { title: 'structured launch marker', output: PROLOGUE, wait: 'condition' },+ {+ title: 'post-launch input readiness',+ output: `${PROLOGUE}${SHELL_TEXT}`,+ wait: 'input',+ },+ { title: 'post-output command marker', output: `${PROLOGUE}${SHELL_TEXT}`, wait: 'condition' },+ { title: 'silent respawn readiness', output: PROLOGUE, wait: 'respawn' },+] as const;++test.each(SILENCE_ROUTES)('$title has pre-cleanup OS state', async ({ title, output, wait }) => {+ const query = answeringQuery();+ const scenario = createScenario(title, 0, query.spawnQuery);+ query.hooks.started = () => scenario.sequence.push({ kind: 'query-start' });+ await scenario.runner.run(title, async (deadlineAt) => {+ scenario.output(output);+ const stream = scenario.host.streamOf(PTY_ID);+ const readiness =+ wait === 'respawn'+ ? createHarnessReadinessAfterCompletion(stream, {+ after: { observedAt: deadlineAt },+ initialDeadlineAt: deadlineAt,+ reportDeadlineAt: deadlineAt,+ })+ : createHarnessReadinessObserver(stream, deadlineAt, deadlineAt);+ if (wait === 'input') {+ await readiness.waitForEvaluatedInput(+ (data) => scenario.host.send({ type: 'input', ptyId: PTY_ID, data }),+ { input: 'readiness-probe\r', marker: 'readiness-answer' },+ title,+ );+ } else {+ await readiness.waitForCondition(() => stream.read().includes('missing-answer'), title);+ }+ });++ const snapshots = scenario.events.filter((entry) => entry.stage === 'snapshot');+ expect(snapshots.map((entry) => entry.reason)).toEqual(['failure', 'before-cleanup']);+ expect(snapshots[0]?.traceId).toBe(snapshots[1]?.traceId);+ expect(scenario.sequence.findIndex((entry) => entry.kind === 'release')).toBeGreaterThan(+ scenario.sequence.findIndex(+ (entry) =>+ entry.kind === 'trace' &&+ (entry.value as Record<string, unknown>).stage === 'snapshot' &&+ (entry.value as Record<string, unknown>).reason === 'failure',+ ),+ );+ expect(scenario.lines).toEqual([expect.stringMatching(`^FAIL ${title} ::`)]);+ expect(scenario.runner.verdictLine('')).toBe('HARNESS_RESULT ok=0 fail=1 refused=0');+ expect(JSON.stringify(scenario.events)).not.toContain(SHELL_TEXT);+ expect(JSON.stringify(scenario.events)).not.toContain('readiness-probe');+ const osSnapshot = scenario.events.find((entry) => entry.stage === 'os-snapshot');+ expect(osSnapshot).toEqual(+ expect.objectContaining({+ traceId: snapshots[0]?.traceId,+ attempt: snapshots[0]?.attempt,+ observation: expect.objectContaining(EXPECTED_SECTIONS),+ }),+ );+ const observation = osSnapshot?.observation as PtyOsObservation;+ for (const snapshot of snapshots) {+ expect(snapshot.native).toEqual(+ expect.objectContaining({+ shell: expect.objectContaining({ osState: observation.shell }),+ console: expect.objectContaining({ osState: observation.console }),+ worker: expect.objectContaining({ osState: observation.worker }),+ }),+ );+ }+ const release = scenario.sequence.findIndex((entry) => entry.kind === 'release');+ expect(scenario.sequence.findIndex((entry) => entry.kind === 'query-start')).toBeGreaterThan(-1);+ expect(scenario.sequence.findIndex((entry) => entry.kind === 'query-start')).toBeLessThan(+ release,+ );+});++test('the OS record keeps transport counters from failure detection apart from the failure snapshot', async () => {+ const query = answeringQuery();+ const scenario = createScenario('bytes during collection', 0, query.spawnQuery);+ query.hooks.started = () => scenario.output(LATE_OUTPUT);+ await scenario.runner.run('bytes during collection', async () => {+ scenario.output(PROLOGUE);+ throw new Error('shell did not answer');+ });+ const detected = Buffer.byteLength(PROLOGUE);+ const osSnapshot = scenario.events.find((entry) => entry.stage === 'os-snapshot');+ const failure = scenario.events.find(+ (entry) => entry.stage === 'snapshot' && entry.reason === 'failure',+ );+ expect(osSnapshot?.transport).toEqual(expect.objectContaining({ mainBytes: detected }));+ expect(failure?.native).toEqual(+ expect.objectContaining({+ transport: expect.objectContaining({+ mainBytes: detected + Buffer.byteLength(LATE_OUTPUT),+ }),+ }),+ );+});++test('a passing scenario leaves OS observation unused', async () => {+ const scenario = createScenario('shell answers');+ await scenario.runner.run('shell answers', async () => {+ scenario.output(`${PROLOGUE}${SHELL_TEXT}`);+ });+ const snapshots = scenario.events.filter((entry) => entry.stage === 'snapshot');+ expect(snapshots.map((entry) => entry.reason)).toEqual(['before-cleanup']);+ expect(snapshots[0]?.native).toEqual(+ expect.objectContaining({+ shell: expect.objectContaining({ osState: 'unobserved' }),+ console: expect.objectContaining({ osState: 'unobserved' }),+ worker: expect.objectContaining({ osState: 'unobserved' }),+ }),+ );+ expect(scenario.terminal.kill).toHaveBeenCalledOnce();+ expect(scenario.lines).toEqual(['PASS shell answers']);+ expect(scenario.runner.verdictLine('')).toBe('HARNESS_RESULT ok=1 fail=0 refused=0');+});++test('a sent readiness probe without a reply retains OS state before release', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });+ try {+ const scenario = createScenario('sent probe reply stalls', HARNESS_WINDOWS_LAUNCH_STALL_MS);+ const running = scenario.runner.run('sent probe reply stalls', async (deadlineAt) => {+ scenario.output(`${PROLOGUE}${SHELL_TEXT}`);+ const readiness = createHarnessReadinessObserver(+ scenario.host.streamOf(PTY_ID),+ deadlineAt,+ deadlineAt,+ );+ await readiness.waitForEvaluatedInput(+ (data) => scenario.host.send({ type: 'input', ptyId: PTY_ID, data }),+ { input: 'readiness-probe\r', marker: 'readiness-answer' },+ 'sent probe reply stalls',+ );+ });+ await vi.advanceTimersToNextTimerAsync();+ expect(scenario.terminal.write).toHaveBeenCalledWith('readiness-probe\r');+ await vi.runAllTimersAsync();+ await running;+ const failure = scenario.events.find(+ (entry) => entry.stage === 'snapshot' && entry.reason === 'failure',+ );+ expect(scenario.lines).toEqual([expect.stringMatching(/^FAIL sent probe reply stalls ::/u)]);+ expect(scenario.runner.verdictLine('')).toBe('HARNESS_RESULT ok=0 fail=1 refused=0');+ const native = failure?.native as { shell: { osState: unknown } };+ expect(native.shell.osState).toBeDefined();+ expect(native.shell.osState).not.toBe('unobserved');+ expect(scenario.sequence.findIndex((entry) => entry.kind === 'release')).toBeGreaterThan(+ scenario.sequence.findIndex((entry) => entry.kind === 'trace' && entry.value === failure),+ );+ } finally {+ vi.useRealTimers();+ }+});++test('a hard timeout synchronously retains an in-flight collection deadline and its detection-time transport before release', async () => {+ const query = Object.assign(new EventEmitter(), {+ pid: 93_421,+ stdout: new PassThrough(),+ stderr: new PassThrough(),+ stdin: new PassThrough(),+ kill: vi.fn(() => true),+ });+ let starts = 0;+ const scenario = createScenario('hard-timeout collection', 10_000, () => {+ starts += 1;+ return query;+ });+ const running = scenario.runner.run('hard-timeout collection', async () => {+ scenario.output(PROLOGUE);+ throw new Error('shell did not answer');+ });+ await vi.waitFor(() => expect(starts).toBe(1));+ scenario.output(LATE_OUTPUT);+ const verdict = scenario.runner.hardTimeoutVerdict();+ const observation = scenario.events.find((entry) => entry.stage === 'os-snapshot');+ const hardSnapshot = scenario.events.find(+ (entry) => entry.stage === 'snapshot' && entry.reason === 'failure',+ );+ expect(verdict).toContain('hard timeout during hard-timeout collection');+ expect(observation?.observation).toEqual(expect.objectContaining({ reason: 'deadline' }));+ const detected = Buffer.byteLength(PROLOGUE);+ expect(observation?.transport).toEqual(expect.objectContaining({ mainBytes: detected }));+ expect(hardSnapshot?.native).toEqual(+ expect.objectContaining({+ shell: expect.objectContaining({ osState: expect.objectContaining({ reason: 'deadline' }) }),+ transport: expect.objectContaining({ mainBytes: detected + Buffer.byteLength(LATE_OUTPUT) }),+ }),+ );+ expect(query.kill).toHaveBeenCalledOnce();+ await running;+ expect(scenario.events.filter((entry) => entry.stage === 'os-snapshot')).toHaveLength(1);+ expect(scenario.sequence.findIndex((entry) => entry.kind === 'release')).toBeGreaterThan(+ scenario.sequence.findIndex((entry) => entry.value === hardSnapshot),+ );+});diff --git a/packages/desktop/tests/utility/pty-host-real-io.test.ts b/packages/desktop/tests/utility/pty-host-real-io.test.tsindex 1ae3f1a30..466534366 100644--- a/packages/desktop/tests/utility/pty-host-real-io.test.ts+++ b/packages/desktop/tests/utility/pty-host-real-io.test.ts@@ -6,6 +6,7 @@ import { isTerminalPlatform } from '../../src/shared/terminal-platform.ts';import { harnessTimeouts, runHarness } from '../support/pty-readiness.test-helper.ts';import { harnessScenarioTitles } from '../support/real-io-harness-roster.test-helper.ts';import { removeTempDirBestEffort } from '../support/temp-dir-cleanup.test-helper.ts';+import { runWindowsOsStateProof } from '../support/windows-os-state-proof.test-helper.ts';const HARNESS_TIMEOUTS = harnessTimeouts(process.platform);@@ -45,6 +46,7 @@ describe('PTY host — real shell I/O (Node runtime)', () => {expect(failure).toContain('the 1ms harness budget was spent before this scenario started');expect(failure).toContain(`HARNESS_RESULT ok=0 fail=0 refused=${SCENARIO_COUNT}`);expect(failure).not.toContain('hard timeout');+ if (process.platform === 'win32') await runWindowsOsStateProof();} finally {removeTempDirBestEffort(outputDir);}diff --git a/packages/desktop/tests/utility/pty-host.real-io-harness.ts b/packages/desktop/tests/utility/pty-host.real-io-harness.tsindex 9644ba39d..3c57298ce 100644--- a/packages/desktop/tests/utility/pty-host.real-io-harness.ts+++ b/packages/desktop/tests/utility/pty-host.real-io-harness.ts@@ -25,6 +25,10 @@ import {} from '../support/pty-readiness.test-helper.ts';import { createHarnessScenarioRunner } from '../support/pty-startup-trace.test-helper.ts';import { harnessScenarioTitles } from '../support/real-io-harness-roster.test-helper.ts';+import {+ WINDOWS_OS_MAX_BUDGET_MS,+ windowsPowerShellPath,+} from '../support/windows-os-state.test-helper.ts';const require = createRequire(import.meta.url);@@ -57,8 +61,18 @@ const createHost = (shellExists,logger: hostLogger,startupTrace: { native: process.platform === 'win32' },+ osCaptureDeadlineAt: () =>+ Math.min(+ performance.now() + WINDOWS_OS_MAX_BUDGET_MS,+ harnessBudget.reportDeadlineAt + HARNESS_REPORT_RESERVE_MS / 2,+ ),+ });+ runner.own({+ snapshot: () => host.snapshotStartup(),+ captureFailure: () => host.captureFailure(),+ cancelCapture: () => host.cancelCapture(),+ release: () => host.killActive(),});- runner.own({ snapshot: () => host.snapshotStartup(), release: () => host.killActive() });return host;};@@ -183,13 +197,7 @@ async function main(): Promise<void> {if (process.platform === 'win32') {await runner.run('PowerShell executes a structured launch command', async (deadlineAt) => {- const powershell = join(- process.env.SystemRoot ?? 'C:\\Windows',- 'System32',- 'WindowsPowerShell',- 'v1.0',- 'powershell.exe',- );+ const powershell = windowsPowerShellPath();if (!existsSync(powershell)) throw new Error(`Windows PowerShell is missing: ${powershell}`);const launchToken = randomUUID();diff --git a/packages/desktop/tests/utility/pty-readiness.test.ts b/packages/desktop/tests/utility/pty-readiness.test.tsindex 12882b759..c012a344e 100644--- a/packages/desktop/tests/utility/pty-readiness.test.ts+++ b/packages/desktop/tests/utility/pty-readiness.test.ts@@ -29,6 +29,7 @@ import {waitForShellReady,} from '../support/pty-readiness.test-helper.ts';import {+ type ControlledHarnessOptions,type ControlledHarnessResult,runControlledHarness,} from './pty-harness-environment.test-helper.ts';@@ -124,6 +125,176 @@ afterEach(() => {});describe('real harness readiness across sequential scenarios', () => {+ test.each([+ {+ name: 'initial interactive readiness',+ options: { firstScenario: 'fast', silentAt: 'initial-input' },+ shell: 1,+ predecessor: 'unanswered-readiness-input',+ scenario: 'real command round-trip at project root',+ },+ {+ name: 'env-stripped interactive readiness',+ options: { firstScenario: 'fast', silentAt: 'environment-input' },+ shell: 2,+ predecessor: 'unanswered-readiness-input',+ scenario: 'strips desktop env markers from the shell',+ },+ {+ name: 'structured launch token',+ options: { firstScenario: 'fast', silentAt: 'launch-token' },+ shell: 3,+ predecessor: 'launch-startup-output',+ scenario: 'PowerShell executes a structured launch command',+ },+ {+ name: 'post-launch evaluated reply',+ options: { firstScenario: 'slow', launchReadiness: 'stuck' },+ shell: 3,+ predecessor: 'input',+ scenario: 'PowerShell executes a structured launch command',+ },+ {+ name: 'post-output command marker',+ options: { firstScenario: 'fast', silentAt: 'command-output' },+ shell: 1,+ predecessor: 'command-input',+ scenario: 'real command round-trip at project root',+ },+ {+ name: 'silent replacement output',+ options: {+ firstScenario: 'fast',+ lifecycle: {+ launchAtMs: 26_000,+ exitAfterKillMs: 1_200,+ replacementOutputAfterCreateMs: null,+ },+ },+ shell: 5,+ predecessor: 'spawn',+ scenario: 'host survives a PTY death and respawns',+ },+ ] as const)(+ '$name retains an OS observation in the real harness before release',+ async ({ options, shell, predecessor, scenario }) => {+ const result = await runControlledHarness(options as ControlledHarnessOptions);+ const reached = lifecycleEventIndex(result, shell, predecessor);+ expect(reached).toBeGreaterThan(-1);+ if (shell === 5) {+ expect(reached).toBeGreaterThan(lifecycleEventIndex(result, 4, 'exit:1'));+ }+ expect(scenarioVerdicts(result)).toContain(`FAIL ${scenario}`);+ expect(result.lines.join('\n')).not.toContain('hard timeout during');+ const failure = result.traceEvents.find(+ (entry) => entry.stage === 'snapshot' && entry.reason === 'failure',+ );+ expect(failure).toEqual(expect.objectContaining({ publicPid: 4_000 + shell }));+ expect(result.traceEvents).toContainEqual(+ expect.objectContaining({+ event: 'pty-host-startup',+ stage: 'observer-unavailable',+ traceId: failure?.traceId,+ attempt: failure?.attempt,+ }),+ );+ const observation = result.traceEvents.find(+ (entry) =>+ entry.event === 'pty-host-startup' &&+ entry.stage === 'os-snapshot' &&+ entry.traceId === failure?.traceId &&+ entry.attempt === failure?.attempt,+ );+ expect(observation?.observation).toEqual(+ expect.objectContaining({+ status: 'unavailable',+ reason: 'query-start-failed',+ shell: { status: 'unavailable', reason: 'query-start-failed' },+ console: { status: 'unavailable', reason: 'query-start-failed' },+ worker: { status: 'unavailable', reason: 'worker-unavailable' },+ }),+ );+ const observed = result.events.findIndex((entry) => entry.trace === observation);+ expect(observed).toBeGreaterThan(reached);+ expect(+ result.events.findIndex(+ (entry, index) =>+ index > reached &&+ index < observed &&+ entry.shell === 0 &&+ entry.event === 'query-start',+ ),+ ).toBeGreaterThan(-1);+ expect(lifecycleEventIndex(result, shell, 'kill-request')).toBeGreaterThan(observed);+ if (shell === 1 && predecessor === 'unanswered-readiness-input') {+ const queryStart = lifecycleEventIndex(result, 0, 'query-start');+ expect(queryStart).toBeGreaterThan(reached);+ expect(lifecycleEventIndex(result, shell, 'kill-request')).toBeGreaterThan(queryStart);+ }+ if (shell === 5) {+ expect(+ result.events.filter((entry) => entry.shell === 0 && entry.event === 'query-start'),+ ).toHaveLength(1);+ }+ expect(JSON.stringify(observation)).not.toContain('PowerShell startup');+ expect(JSON.stringify(observation)).not.toContain(+ 'controlled harness cannot spawn a native subprocess',+ );+ },+ );++ test('a delayed OS query cannot rewrite a released failure attempt', async () => {+ const result = await runControlledHarness({+ firstScenario: 'fast',+ silentAt: 'initial-input',+ queryMode: 'delayed-invalid',+ });+ const sent = lifecycleEventIndex(result, 1, 'unanswered-readiness-input');+ expect(sent).toBeGreaterThan(-1);+ expect(scenarioVerdicts(result)).toContain('FAIL real command round-trip at project root');+ const failure = result.traceEvents.find(+ (entry) => entry.stage === 'snapshot' && entry.reason === 'failure',+ );+ expect(failure).toEqual(expect.objectContaining({ publicPid: 4_001 }));+ const release = lifecycleEventIndex(result, 1, 'kill-request');+ expect(release).toBeGreaterThan(sent);+ const observation = result.traceEvents.find(+ (entry) =>+ entry.event === 'pty-host-startup' &&+ entry.stage === 'os-snapshot' &&+ entry.traceId === failure?.traceId &&+ entry.attempt === failure?.attempt,+ );+ expect(observation).toEqual(expect.objectContaining({ observation: expect.any(Object) }));+ expect(lifecycleEventIndex(result, 0, 'query-start')).toBeGreaterThan(sent);+ expect(lifecycleEventIndex(result, 0, 'late-query-output')).toBeGreaterThan(release);+ expect(result.delayedQuery).toEqual(+ expect.objectContaining({+ traceBeforeDelivery: expect.any(String),+ linesBeforeDelivery: expect.any(String),+ }),+ );+ expect(result.events.findIndex((entry) => entry.trace === observation)).toBeLessThan(release);+ expect(JSON.stringify(result.traceEvents)).toBe(result.delayedQuery?.traceBeforeDelivery);+ expect(JSON.stringify(result.lines)).toBe(result.delayedQuery?.linesBeforeDelivery);+ expect(scenarioVerdicts(result)).toContain('FAIL real command round-trip at project root');+ expect(JSON.stringify(result.traceEvents)).not.toContain('private shell text');+ expect(JSON.stringify(result.traceEvents)).not.toContain('private fixture stderr');+ });++ test('passing cleanup and spent-budget refusal issue no OS query', async () => {+ const passing = await runControlledHarness({ firstScenario: 'fast' });+ expect(passing.lines).toContain('HARNESS_RESULT ok=5 fail=0 refused=0');+ expect(passing.exitCode).toBe(0);+ expect(lifecycleEventIndex(passing, 1, 'kill-request')).toBeGreaterThan(-1);+ expect(passing.events.filter((entry) => entry.event === 'query-start')).toEqual([]);++ const refused = await runControlledHarness({ firstScenario: 'fast', budgetOverride: '1' });+ expect(refused.lines.filter((line) => line.startsWith('REFUSED '))).toHaveLength(5);+ expect(refused.lines).toContain('HARNESS_RESULT ok=0 fail=0 refused=5');+ expect(refused.events.filter((entry) => entry.event === 'query-start')).toEqual([]);+ });+test('keeps an advancing later shell eligible after an earlier scenario passes slowly', async () => {const fast = await runControlledHarness({ firstScenario: 'fast' });expect(fast.lines.join('\n')).toContain('HARNESS_RESULT ok=5 fail=0 refused=0');@@ -597,6 +768,24 @@ describe('real harness readiness across sequential scenarios', () => {);expect(launchFailure).toContain(REPORT_DEADLINE_BOUND);expect(launchFailure).toContain(SHELL_PROGRESS_ADVANCED);+ const launchToken = lifecycleEventIndex(result, 3, 'launch-token');+ const queryStart = lifecycleEventIndex(result, 0, 'query-start');+ const release = lifecycleEventIndex(result, 3, 'kill-request');+ const failure = result.traceEvents.find(+ (entry) => entry.stage === 'snapshot' && entry.reason === 'failure',+ );+ const observation = result.traceEvents.find(+ (entry) =>+ entry.event === 'pty-host-startup' &&+ entry.stage === 'os-snapshot' &&+ entry.traceId === failure?.traceId &&+ entry.attempt === failure?.attempt,+ );+ const observed = result.events.findIndex((entry) => entry.trace === observation);+ expect(queryStart).toBeGreaterThan(launchToken);+ expect(observation).toEqual(expect.objectContaining({ observation: expect.any(Object) }));+ expect(observed).toBeGreaterThan(queryStart);+ expect(release).toBeGreaterThan(observed);});test('refuses every scenario when the run has no admissible grant', async () => {diff --git a/packages/desktop/tests/utility/windows-os-state-cli.test.ts b/packages/desktop/tests/utility/windows-os-state-cli.test.tsnew file mode 100644index 000000000..fa6ccfb32--- /dev/null+++ b/packages/desktop/tests/utility/windows-os-state-cli.test.ts@@ -0,0 +1,60 @@+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { expect, test } from 'vitest';++const cliFile = fileURLToPath(+ new URL('../support/windows-os-state-cli.test-helper.ts', import.meta.url),+);+const INVALID_RECORD = '{"version":1,"status":"unavailable","reason":"invalid-shape"}\n';+const OFF_WINDOWS = [+ '--import',+ 'data:text/javascript,Object.defineProperty(process,"platform",{value:"linux"})',+];++function runCli(args: string[], nodeArgs: string[] = []): { code: number | null; stdout: string } {+ const run = spawnSync(process.execPath, [...nodeArgs, cliFile, ...args], { encoding: 'utf8' });+ return { code: run.status, stdout: run.stdout };+}++const pidFlags = (count: number, first = 4_100): string[] =>+ Array.from({ length: count }, (_, index) => ['--pid', String(first + index)]).flat();++test.each([+ { caseName: 'nine targets', args: pidFlags(9, 731_000), rejected: '731008' },+ {+ caseName: 'a budget above the ceiling',+ args: ['--pid', '42', '--budget-ms', '5001'],+ rejected: '5001',+ },+ { caseName: 'a zero budget', args: ['--pid', '42', '--budget-ms', '0'], rejected: '"0"' },+ { caseName: 'a zero PID', args: ['--pid', '0', '--pid', '731111'], rejected: '731111' },+ { caseName: 'a zero-padded PID', args: ['--pid', '0731222'], rejected: '731222' },+ { caseName: 'a fractional PID', args: ['--pid', '7313.5'], rejected: '7313' },+ {+ caseName: 'a repeated parent PID',+ args: ['--pid', '42', '--parent-pid', '731444', '--parent-pid', '731445'],+ rejected: '73144',+ },+ {+ caseName: 'an unknown flag',+ args: ['--pid', '42', '--private-flag-731', '1'],+ rejected: 'private-flag',+ },+ { caseName: 'a flag without a value', args: ['--pid', '42', '--budget-ms'], rejected: 'budget' },+ { caseName: 'no target', args: ['--parent-pid', '731555'], rejected: '731555' },+])('$caseName exits 2 with the fixed record and no echo', ({ args, rejected }) => {+ const result = runCli(args);+ expect(result.code).toBe(2);+ expect(result.stdout).toBe(INVALID_RECORD);+ expect(result.stdout).not.toContain(rejected);+});++test('eight targets at the budget ceiling are accepted and exit 1 off Windows', () => {+ const result = runCli([...pidFlags(8), '--budget-ms', '5000'], OFF_WINDOWS);+ expect(result.code).toBe(1);+ const record = JSON.parse(result.stdout) as Record<string, unknown>;+ expect(record).toEqual(+ expect.objectContaining({ version: 1, status: 'unavailable', reason: 'unsupported-platform' }),+ );+ expect(record.targets).toHaveLength(8);+});diff --git a/packages/desktop/tests/utility/windows-os-state-proof-acceptance.test.ts b/packages/desktop/tests/utility/windows-os-state-proof-acceptance.test.tsnew file mode 100644index 000000000..aa7702726--- /dev/null+++ b/packages/desktop/tests/utility/windows-os-state-proof-acceptance.test.ts@@ -0,0 +1,625 @@+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';+import { afterEach, expect, test, vi } from 'vitest';+import type { PtyOsObservation } from '../../src/utility/pty-host.ts';+import {+ WINDOWS_OS_MAX_BUDGET_MS,+ WINDOWS_OS_MAX_RAW_BYTES,+ WINDOWS_OS_MAX_RESULT_BYTES,+ type WindowsOsStateOptions,+} from '../support/windows-os-state.test-helper.ts';+import { runWindowsOsStateProof } from '../support/windows-os-state-proof.test-helper.ts';++type QueryMode =+ | 'before-ready'+ | 'after-shell'+ | 'captured'+ | 'exit-after-shell'+ | 'exit-before-ready'+ | 'protocol-break'+ | 'ready-without-result'+ | 'no-pid'+ | 'raw-overflow'+ | 'stream-error';++type MachineSample = 'sampled' | 'empty';+type WorkerReply = 'finite' | 'pending' | 'non-finite';++interface ScenarioOptions {+ directCli?: boolean;+ platform?: NodeJS.Platform;+ exitCode?: number;+ killFails?: boolean;+ machine?: MachineSample;+ workerReply?: WorkerReply;+ replaceRecord?: (observed: PtyOsObservation) => unknown;+}++interface Scenario {+ queryMode: QueryMode;+ directCli: boolean;+ exitCode: number | null;+ killFails: boolean;+ machine: MachineSample;+ workerReply: WorkerReply;+ replaceRecord: ((observed: PtyOsObservation) => unknown) | null;+ suppliedRecord: unknown;+ spawnCount: number;+ querySpawned: Promise<void>;+ resolveQuerySpawned: () => void;+ logs: string[];+}++let scenario: Scenario | null = null;+const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');+const originalLog = console.log.bind(console);++const processSample = {+ status: 'captured',+ pid: 4_242,+ parentPid: 12,+ createdAtMs: 1_700_000_000_000,+ secondCreatedAtMs: 1_700_000_000_000,+ first: { userMs: 11, kernelMs: 2, threadCount: 1 },+ second: { userMs: 13, kernelMs: 3, threadCount: 1 },+ threads: [{ id: 8, state: 'wait', waitReason: 'user-request' }],+ omittedThreads: 0,+};++const emptyConsole = {+ status: 'captured',+ candidateCount: 0,+ candidates: [],+ unavailableCandidates: [],+ omittedCandidates: 0,+};++function close(child: EventEmitter, code: number): void {+ child.emit('exit', code, null);+ child.emit('close', code, null);+}++function recordingProcess(pid: number | undefined, killFails = false) {+ const child = Object.assign(new EventEmitter(), {+ pid,+ stdin: new PassThrough(),+ stdout: new PassThrough(),+ stderr: new PassThrough(),+ connected: true,+ send(value: string) {+ if (value === 'release') {+ child.connected = false;+ queueMicrotask(() => close(child, 0));+ }+ },+ kill() {+ if (killFails) {+ child.emit('error', new Error('helper kill failed'));+ return false;+ }+ queueMicrotask(() => close(child, 1));+ return true;+ },+ unref() {},+ });+ return child;+}++function writeQuery(child: ReturnType<typeof recordingProcess>, active: Scenario): void {+ const mode = active.queryMode;+ if (mode === 'before-ready' || mode === 'no-pid') return;+ if (mode === 'exit-before-ready') {+ if (active.exitCode === null) throw new Error('helper exit code is missing');+ close(child, active.exitCode);+ return;+ }+ if (mode === 'raw-overflow') {+ child.stderr.write('x'.repeat(WINDOWS_OS_MAX_RAW_BYTES + 1));+ return;+ }+ if (mode === 'protocol-break') {+ child.stdout.write('BANNER\n');+ setImmediate(() => close(child, 0));+ return;+ }+ child.stdout.write('READY\n');+ if (mode === 'ready-without-result') {+ setImmediate(() => close(child, 0));+ return;+ }+ if (mode === 'stream-error') {+ setImmediate(() => child.stdout.emit('error', new Error('helper stream failed')));+ return;+ }+ if (mode === 'after-shell' || mode === 'exit-after-shell') {+ child.stdout.write(+ `SHELL ${JSON.stringify({ version: 1, shells: [{ ...processSample, parentPid: null }] })}\n`,+ );+ if (mode === 'exit-after-shell') {+ const exitCode = active.exitCode;+ if (exitCode === null) throw new Error('helper exit code is missing');+ setImmediate(() => close(child, exitCode));+ }+ return;+ }+ child.stdout.write(+ `RESULT ${JSON.stringify({ version: 1, shells: [processSample], console: emptyConsole })}\n`,+ );+ setImmediate(() => close(child, 0));+}++function fakeSpawn() {+ const active = scenario;+ if (active === null) throw new Error('proof scenario is missing');+ const index = active.spawnCount++;+ if (active.directCli) {+ if (index !== 0) throw new Error('the CLI launched an unexpected process');+ const query = recordingProcess(93_421);+ active.resolveQuerySpawned();+ queueMicrotask(() => writeQuery(query, active));+ return query;+ }+ if (index === 0) {+ const subject = recordingProcess(4_242);+ queueMicrotask(() => subject.emit('message', 'ready'));+ return subject;+ }+ if (index === 1) {+ const query = recordingProcess(+ active.queryMode === 'no-pid' ? undefined : 93_421,+ active.killFails,+ );+ active.resolveQuerySpawned();+ queueMicrotask(() => writeQuery(query, active));+ return query;+ }+ throw new Error('the proof launched an unexpected process');+}++function workerCpuUsage(): Promise<{ user: number; system: number }> {+ const reply = scenario?.workerReply ?? 'finite';+ if (reply === 'pending') return new Promise(() => undefined);+ return Promise.resolve({ user: reply === 'non-finite' ? Number.NaN : 1_000, system: 2_000 });+}++vi.mock('node:child_process', async (importOriginal) => ({+ ...(await importOriginal<typeof import('node:child_process')>()),+ spawn: fakeSpawn,+}));++vi.mock('node:os', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:os')>();+ return { ...actual, cpus: () => (scenario?.machine === 'empty' ? [] : actual.cpus()) };+});++vi.mock('node:worker_threads', async (importOriginal) => {+ const { EventEmitter: BaseEventEmitter } = await import('node:events');+ return {+ ...(await importOriginal<typeof import('node:worker_threads')>()),+ Worker: class extends BaseEventEmitter {+ threadId = 91;++ constructor() {+ super();+ queueMicrotask(() => this.emit('message', 'ready'));+ }++ cpuUsage() {+ return workerCpuUsage();+ }++ postMessage(value: string) {+ if (value === 'release') queueMicrotask(() => this.emit('exit', 0));+ }+ },+ };+});++vi.mock('../support/windows-os-state.test-helper.ts', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('../support/windows-os-state.test-helper.ts')>();+ return {+ ...actual,+ async collectWindowsOsState(options: WindowsOsStateOptions): Promise<PtyOsObservation> {+ const observed = await actual.collectWindowsOsState(options);+ const active = scenario;+ if (active === null || active.replaceRecord === null) return observed;+ active.suppliedRecord = active.replaceRecord(observed);+ return active.suppliedRecord as PtyOsObservation;+ },+ };+});++function createScenario(queryMode: QueryMode, options: ScenarioOptions = {}) {+ let resolveQuerySpawned: () => void = () => undefined;+ const querySpawned = new Promise<void>((resolve) => {+ resolveQuerySpawned = resolve;+ });+ scenario = {+ queryMode,+ directCli: options.directCli ?? false,+ exitCode: options.exitCode ?? null,+ killFails: options.killFails ?? false,+ machine: options.machine ?? 'sampled',+ workerReply: options.workerReply ?? 'finite',+ replaceRecord: options.replaceRecord ?? null,+ suppliedRecord: undefined,+ spawnCount: 0,+ querySpawned,+ resolveQuerySpawned,+ logs: [],+ };+ vi.spyOn(console, 'log').mockImplementation((...values: unknown[]) => {+ scenario?.logs.push(values.map(String).join(' '));+ originalLog(...values);+ });+ Object.defineProperty(process, 'platform', {+ configurable: true,+ value: options.platform ?? 'win32',+ });+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });+ return scenario;+}++function proofOutcome() {+ return runWindowsOsStateProof().then(+ () => ({ ok: true as const }),+ (error: unknown) => ({ ok: false as const, error }),+ );+}++async function requireAccepted(outcome: Awaited<ReturnType<typeof proofOutcome>>): Promise<void> {+ if (!outcome.ok) throw outcome.error;+ expect(outcome.ok).toBe(true);+}++function expectRejected(outcome: Awaited<ReturnType<typeof proofOutcome>>): void {+ expect(outcome.ok).toBe(false);+}++async function proofAfterDeadline(active: Scenario) {+ const proof = proofOutcome();+ const reached = await Promise.race([+ active.querySpawned.then(() => true),+ proof.then(() => false),+ ]);+ if (reached) await vi.advanceTimersByTimeAsync(WINDOWS_OS_MAX_BUDGET_MS);+ return proof;+}++function proofLines(active: Scenario, prefix: string): string[] {+ return active.logs.filter((line) => line.startsWith(prefix));+}++function expectProofSnapshot(active: Scenario, expected: Record<string, unknown>): void {+ const prefix = 'WINDOWS_OS_PROOF ';+ const lines = active.logs.filter((line) => line.startsWith(prefix));+ expect(lines).toHaveLength(1);+ const record = JSON.parse(lines[0]?.slice(prefix.length) ?? 'null') as Record<string, unknown>;+ expect(record).toMatchObject({ version: 1, requestedPid: 4_242, ...expected });+}++async function runDirectCli(queryMode: QueryMode) {+ const active = createScenario(queryMode, { directCli: true });+ const originalArgv = process.argv;+ const originalExitCode = process.exitCode;+ const output: string[] = [];+ const write = vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {+ output.push(String(chunk));+ return true;+ });+ try {+ process.argv = [process.execPath, 'windows-os-state-cli.test-helper.ts', '--pid', '4242'];+ vi.resetModules();+ const loaded = import('../support/windows-os-state-cli.test-helper.ts').then(+ () => ({ ok: true as const }),+ (error: unknown) => ({ ok: false as const, error }),+ );+ const reached = await Promise.race([+ active.querySpawned.then(() => true),+ loaded.then(() => false),+ ]);+ if (reached) await vi.advanceTimersByTimeAsync(WINDOWS_OS_MAX_BUDGET_MS);+ const outcome = await loaded;+ if (!outcome.ok) throw outcome.error;+ const serialized = output.join('');+ return {+ code: process.exitCode,+ bytes: Buffer.byteLength(serialized),+ record: JSON.parse(serialized) as Record<string, unknown>,+ };+ } finally {+ process.argv = originalArgv;+ process.exitCode = originalExitCode;+ write.mockRestore();+ }+}++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ if (platformDescriptor !== undefined)+ Object.defineProperty(process, 'platform', platformDescriptor);+ scenario = null;+});++test('required proof accepts a bounded observation when the query never becomes ready', async () => {+ const active = createScenario('before-ready');+ const proof = proofOutcome();+ const reached = await Promise.race([+ active.querySpawned.then(() => true),+ proof.then(() => false),+ ]);+ if (reached) await vi.advanceTimersByTimeAsync(WINDOWS_OS_MAX_BUDGET_MS);+ await requireAccepted(await proof);+ expectProofSnapshot(active, {+ status: 'unavailable',+ shell: { status: 'unavailable', reason: 'deadline' },+ });+});++test('required proof accepts a partial observation when the query stalls after the shell frame', async () => {+ const active = createScenario('after-shell');+ const proof = proofOutcome();+ const reached = await Promise.race([+ active.querySpawned.then(() => true),+ proof.then(() => false),+ ]);+ if (reached) await vi.advanceTimersByTimeAsync(WINDOWS_OS_MAX_BUDGET_MS);+ await requireAccepted(await proof);+ expectProofSnapshot(active, {+ status: 'partial',+ shell: { status: 'captured' },+ console: { status: 'unavailable', reason: 'deadline' },+ });+});++test('required proof logs a bounded OS snapshot for its owned subject', async () => {+ const active = createScenario('captured');+ const proof = proofOutcome();+ await requireAccepted(await proof);+ expectProofSnapshot(active, {+ status: 'captured',+ shell: { status: 'captured' },+ console: { status: 'captured' },+ });+});++test('standalone CLI emits a bounded partial record when query stalls after shell', async () => {+ const result = await runDirectCli('after-shell');+ expect(result.code).toBe(0);+ expect(result.bytes).toBeLessThanOrEqual(WINDOWS_OS_MAX_RESULT_BYTES + 1);+ expect(result.record).toMatchObject({+ version: 1,+ status: 'partial',+ console: { status: 'unavailable', reason: 'deadline' },+ });+});++test('standalone CLI emits an unavailable record when query stalls before ready', async () => {+ const result = await runDirectCli('before-ready');+ expect(result.code).toBe(1);+ expect(result.bytes).toBeLessThanOrEqual(WINDOWS_OS_MAX_RESULT_BYTES + 1);+ expect(result.record).toMatchObject({+ version: 1,+ status: 'unavailable',+ shell: { status: 'unavailable', reason: 'deadline' },+ });+});++const rejectedCollections: Array<{+ caseName: string;+ queryMode: QueryMode;+ options: ScenarioOptions;+ expected: Record<string, unknown>;+}> = [+ {+ caseName: 'the helper fails before it is ready',+ queryMode: 'exit-before-ready',+ options: { exitCode: 1 },+ expected: { reason: 'query-exited', helper: { exit: 'observed-before-request' } },+ },+ {+ caseName: 'the helper reports owner loss early',+ queryMode: 'exit-before-ready',+ options: { exitCode: 86 },+ expected: { reason: 'query-exited', helper: { exit: 'cooperative-owner-loss' } },+ },+ {+ caseName: 'the helper fails after its shell frame',+ queryMode: 'exit-after-shell',+ options: { exitCode: 88 },+ expected: {+ status: 'partial',+ reason: 'query-exited',+ shell: { status: 'captured' },+ console: { status: 'unavailable', reason: 'query-exited' },+ helper: { requested: false, exit: 'observed-before-request', exitCode: 88 },+ },+ },+ {+ caseName: 'the helper reports owner loss after its shell frame',+ queryMode: 'exit-after-shell',+ options: { exitCode: 86 },+ expected: {+ status: 'partial',+ reason: 'query-exited',+ shell: { status: 'captured' },+ console: { status: 'unavailable', reason: 'query-exited' },+ helper: { requested: false, exit: 'cooperative-owner-loss', exitCode: 86 },+ },+ },+ {+ caseName: 'an unexpected line precedes ready',+ queryMode: 'protocol-break',+ options: {},+ expected: { reason: 'invalid-shape', helper: { reason: null } },+ },+ {+ caseName: 'the helper exits without a result',+ queryMode: 'ready-without-result',+ options: {},+ expected: { reason: 'invalid-json', helper: { reason: null } },+ },+ {+ caseName: 'the helper starts without a process id',+ queryMode: 'no-pid',+ options: {},+ expected: { reason: 'query-start-failed', helper: { requested: false, reason: null } },+ },+ {+ caseName: 'the helper exceeds the raw output limit',+ queryMode: 'raw-overflow',+ options: {},+ expected: { reason: 'output-limit', helper: { requested: true, reason: 'output-limit' } },+ },+ {+ caseName: 'ending an over-limit helper errors',+ queryMode: 'raw-overflow',+ options: { killFails: true },+ expected: {+ reason: 'query-start-failed',+ helper: { requested: true, reason: 'output-limit' },+ },+ },+ {+ caseName: 'the platform is not Windows',+ queryMode: 'before-ready',+ options: { platform: 'linux' },+ expected: { reason: 'unsupported-platform', helper: { requested: false, reason: null } },+ },+];++test.each(rejectedCollections)(+ 'required proof rejects and prints the record when $caseName',+ async ({ queryMode, options, expected }) => {+ const active = createScenario(queryMode, options);+ const outcome = await proofOutcome();+ expectProofSnapshot(active, { status: 'unavailable', ...expected });+ expectRejected(outcome);+ },+);++test.each([+ {+ caseName: 'the helper reports its deadline early',+ queryMode: 'exit-before-ready' as const,+ options: { exitCode: 87 },+ expected: { reason: 'query-exited', helper: { exit: 'cooperative-deadline' } },+ },+ {+ caseName: 'the helper reports its deadline after its shell frame',+ queryMode: 'exit-after-shell' as const,+ options: { exitCode: 87 },+ expected: {+ status: 'partial',+ reason: 'query-exited',+ shell: { status: 'captured' },+ console: { status: 'unavailable', reason: 'query-exited' },+ helper: { requested: false, exit: 'cooperative-deadline', exitCode: 87 },+ },+ },+ {+ caseName: 'a helper stream fails before exit',+ queryMode: 'stream-error' as const,+ options: {},+ expected: { reason: 'query-exited', helper: { exit: 'not-observed', reason: null } },+ },+])(+ 'required proof accepts a bounded observation when $caseName',+ async ({ queryMode, options, expected }) => {+ const active = createScenario(queryMode, options);+ await requireAccepted(await proofOutcome());+ expectProofSnapshot(active, { status: 'unavailable', ...expected });+ },+);++const acceptedPartialCollections: Array<{+ caseName: string;+ options: ScenarioOptions;+ expected: Record<string, unknown>;+}> = [+ {+ caseName: 'the Worker reply is still pending',+ options: { workerReply: 'pending' },+ expected: {+ reason: 'worker-request-deadline',+ machine: { status: 'captured' },+ worker: { status: 'unavailable', reason: 'worker-request-deadline' },+ },+ },+ {+ caseName: 'the Worker reply is not finite',+ options: { workerReply: 'non-finite' },+ expected: {+ reason: 'invalid-shape',+ machine: { status: 'captured' },+ worker: { status: 'unavailable', reason: 'invalid-shape' },+ },+ },+ {+ caseName: 'the machine sample lists no CPUs',+ options: { machine: 'empty' },+ expected: {+ reason: 'invalid-shape',+ machine: { status: 'unavailable', reason: 'invalid-shape' },+ worker: { status: 'captured' },+ },+ },+];++test.each(acceptedPartialCollections)(+ 'required proof accepts a partial observation when $caseName',+ async ({ options, expected }) => {+ const active = createScenario('captured', options);+ const outcome = await proofOutcome();+ expectProofSnapshot(active, {+ status: 'partial',+ shell: { status: 'captured' },+ console: { status: 'captured' },+ ...expected,+ });+ await requireAccepted(outcome);+ },+);++test('required proof accepts a bounded observation when ending the helper at the deadline reports an error', async () => {+ const active = createScenario('before-ready', { killFails: true });+ await requireAccepted(await proofAfterDeadline(active));+ expectProofSnapshot(active, {+ status: 'unavailable',+ reason: 'query-start-failed',+ helper: { requested: true, reason: 'deadline' },+ });+});++test('required proof prints a malformed record before rejecting it', async () => {+ const active = createScenario('captured', {+ replaceRecord: (observed) => ({ ...observed, version: 2 }),+ });+ const outcome = await proofOutcome();+ expectRejected(outcome);+ expect(active.suppliedRecord).toMatchObject({ version: 2, requestedPid: 4_242 });+ const lines = proofLines(active, 'WINDOWS_OS_PROOF ');+ expect(lines).toHaveLength(1);+ expect(JSON.parse(lines[0]?.slice('WINDOWS_OS_PROOF '.length) ?? 'null')).toEqual(+ active.suppliedRecord,+ );+});++test('required proof reports only the size of an oversized record and rejects it', async () => {+ const active = createScenario('captured', {+ replaceRecord: (observed) => ({+ ...observed,+ padding: 'x'.repeat(WINDOWS_OS_MAX_RESULT_BYTES),+ }),+ });+ const outcome = await proofOutcome();+ expectRejected(outcome);+ const bytes = Buffer.byteLength(JSON.stringify(active.suppliedRecord));+ expect(bytes).toBeGreaterThan(WINDOWS_OS_MAX_RESULT_BYTES);+ expect(proofLines(active, 'WINDOWS_OS_PROOF ')).toEqual([]);+ expect(proofLines(active, 'WINDOWS_OS_PROOF_OVERSIZE')).toEqual([+ `WINDOWS_OS_PROOF_OVERSIZE bytes=${bytes}`,+ ]);+});diff --git a/packages/desktop/tests/utility/windows-os-state.test.ts b/packages/desktop/tests/utility/windows-os-state.test.tsnew file mode 100644index 000000000..857f71f97--- /dev/null+++ b/packages/desktop/tests/utility/windows-os-state.test.ts@@ -0,0 +1,1011 @@+import { EventEmitter } from 'node:events';+import { cpus } from 'node:os';+import { PassThrough } from 'node:stream';+import { afterEach, expect, test, vi } from 'vitest';++vi.mock('node:os', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:os')>();+ return { ...actual, cpus: vi.fn(actual.cpus) };+});++import type { PtyOsObservation } from '../../src/utility/pty-host.ts';+import {+ collectWindowsOsState,+ startWindowsOsState,+ WINDOWS_OS_MAX_RAW_BYTES,+ type WindowsOsCollection,+ type WindowsOsStateOptions,+ type WindowsQueryHelper,+ windowsPowerShellPath,+} from '../support/windows-os-state.test-helper.ts';+import { assertBoundedWindowsOsState } from '../support/windows-os-state-contract.test-helper.ts';++const processSample = {+ status: 'captured',+ pid: 4_242,+ parentPid: 12,+ createdAtMs: 1_700_000_000_000,+ secondCreatedAtMs: 1_700_000_000_000,+ first: { userMs: 11, kernelMs: 2, threadCount: 1 },+ second: { userMs: 13, kernelMs: 3, threadCount: 1 },+ threads: [{ id: 8, state: 'wait', waitReason: 'user-request' }],+ omittedThreads: 0,+ privateContent: 'secret title',+};+const emptyConsole = {+ status: 'captured',+ candidateCount: 0,+ candidates: [],+ unavailableCandidates: [],+ omittedCandidates: 0,+};++function recordingQuery(+ raw: string | null,+ options?: {+ pid?: number | undefined;+ ready?: boolean;+ code?: number;+ killResult?: boolean;+ killThrows?: boolean;+ },+) {+ const sends: string[] = [];+ const unrefs: string[] = [];+ const stdout = new PassThrough();+ const stderr = new PassThrough();+ const stdin = new PassThrough();+ const child = Object.assign(new EventEmitter(), {+ pid: options !== undefined && Object.hasOwn(options, 'pid') ? options.pid : 99_999,+ stdout,+ stderr,+ stdin,+ kill() {+ sends.push('helper-kill-request');+ if (options?.killThrows) throw new Error('private helper command');+ return options?.killResult ?? true;+ },+ unref() {+ unrefs.push('helper-unref');+ },+ });+ const spawnQuery = (_file: string, _args: string[]): WindowsQueryHelper => {+ if (options?.ready !== false) {+ queueMicrotask(() => stdout.write('READY\n'));+ stdin.once('data', () => {+ if (raw !== null) {+ stdout.write(`RESULT ${raw}\n`);+ queueMicrotask(() => child.emit('close', options?.code ?? 0, null));+ }+ });+ }+ return child;+ };+ return { spawnQuery, sends, unrefs, child, stdout, stderr, stdin };+}++afterEach(() => {+ vi.useRealTimers();+ vi.mocked(cpus).mockReset();+});++test('a projected raw result retains typed shell and machine samples without arbitrary content', async () => {+ const raw = JSON.stringify({+ version: 1,+ shells: [processSample],+ console: emptyConsole,+ privateContent: 'secret environment',+ });+ const query = recordingQuery(raw);+ const result = await collectWindowsOsState({+ pid: 4_242,+ parentPid: 12,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ assertBoundedWindowsOsState(result, 4_242);+ expect(() => assertBoundedWindowsOsState({ ...result, version: 2 }, 4_242)).toThrow();+ expect(() =>+ assertBoundedWindowsOsState({ ...result, console: { status: 'unavailable' } }, 4_242),+ ).toThrow();+ expect(() =>+ assertBoundedWindowsOsState(+ { ...result, console: { status: 'unavailable', reason: 'captured' } },+ 4_242,+ ),+ ).toThrow();+ if (result.shell.status === 'captured') {+ const invalidShell = {+ ...result.shell,+ value: { ...result.shell.value, first: { ...result.shell.value.first, userMs: -1 } },+ };+ expect(() =>+ assertBoundedWindowsOsState(+ { ...result, shell: invalidShell, targets: [{ requestedPid: 4_242, shell: invalidShell }] },+ 4_242,+ ),+ ).toThrow();+ }+ expect(() =>+ assertBoundedWindowsOsState({ ...result, privateContent: 'secret' }, 4_242),+ ).toThrow();+ expect(result.shell).toEqual(+ expect.objectContaining({+ status: 'captured',+ value: expect.objectContaining({+ pid: 4_242,+ createdAtMs: processSample.createdAtMs,+ threads: [{ id: 8, state: 'wait', waitReason: 'user-request' }],+ }),+ }),+ );+ expect(result.machine).toEqual(expect.objectContaining({ status: 'captured' }));+ expect(result.console).toEqual(expect.objectContaining({ status: 'captured' }));+ expect(result.helper).toEqual(+ expect.objectContaining({+ requested: false,+ delivery: 'not-attempted',+ exit: 'observed-before-request',+ }),+ );+ expect(JSON.stringify(result)).not.toContain('secret');+ expect(query.sends).toEqual([]);+});++const capturedWorker = {+ status: 'captured',+ value: { nodeThreadId: 91, requestedAtMs: 0, repliedAtMs: 0, userMs: 1, systemMs: 2 },+} as const;++test.each([+ {+ caseName: 'a helper reason without a request',+ reshape: (result: PtyOsObservation) => ({+ ...result,+ helper: { ...result.helper, reason: 'deadline' },+ }),+ },+ {+ caseName: 'a helper request without a reason',+ reshape: (result: PtyOsObservation) => ({+ ...result,+ helper: { ...result.helper, requested: true },+ }),+ },+ {+ caseName: 'a partial record with nothing missing',+ reshape: (result: PtyOsObservation) => ({ ...result, worker: capturedWorker }),+ },+])('the bounded contract rejects $caseName', async ({ reshape }) => {+ const query = recordingQuery(+ JSON.stringify({ version: 1, shells: [processSample], console: emptyConsole }),+ );+ const result = await collectWindowsOsState({+ pid: 4_242,+ parentPid: 12,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ expect(result).toMatchObject({+ status: 'partial',+ shell: { status: 'captured' },+ machine: { status: 'captured' },+ console: { status: 'captured', value: { unavailableCandidates: [] } },+ worker: { status: 'unavailable' },+ helper: { requested: false, reason: null },+ });+ assertBoundedWindowsOsState(result, 4_242);+ expect(() => assertBoundedWindowsOsState(reshape(result), 4_242)).toThrow();+});++test.each([+ { caseName: 'malformed JSON', raw: '{private', reason: 'invalid-json' },+ { caseName: 'empty JSON', raw: '', reason: 'invalid-json' },+ { caseName: 'truncated JSON', raw: '{"version":', reason: 'invalid-json' },+ { caseName: 'array root', raw: '[]', reason: 'invalid-shape' },+ {+ caseName: 'nonnumeric CPU time',+ raw: JSON.stringify({+ version: 1,+ shells: [{ ...processSample, first: { userMs: '11', kernelMs: 2, threadCount: 1 } }],+ console: emptyConsole,+ }),+ reason: 'invalid-shape',+ },+ {+ caseName: 'changed creation identity',+ raw: JSON.stringify({+ version: 1,+ shells: [{ ...processSample, secondCreatedAtMs: processSample.createdAtMs + 1 }],+ console: emptyConsole,+ }),+ reason: 'identity-changed',+ },+ {+ caseName: 'unknown thread wait reason',+ raw: JSON.stringify({+ version: 1,+ shells: [+ {+ ...processSample,+ threads: [{ id: 8, state: 'wait', waitReason: 'private reason' }],+ },+ ],+ console: emptyConsole,+ }),+ reason: 'invalid-shape',+ },+ {+ caseName: 'overflowed omitted thread count',+ raw: JSON.stringify({+ version: 1,+ shells: [+ {+ ...processSample,+ threads: Array.from({ length: 17 }, (_, index) => ({+ id: index + 1,+ state: 'running',+ waitReason: 'not-applicable',+ })),+ omittedThreads: Number.MAX_SAFE_INTEGER,+ },+ ],+ console: emptyConsole,+ }),+ reason: 'invalid-shape',+ },+ {+ caseName: 'shell sample for another PID',+ raw: JSON.stringify({+ version: 1,+ shells: [{ ...processSample, pid: 4_243 }],+ console: emptyConsole,+ }),+ reason: 'invalid-shape',+ },+ {+ caseName: 'console candidate count without candidates',+ raw: JSON.stringify({+ version: 1,+ shells: [processSample],+ console: { ...emptyConsole, candidateCount: 1 },+ }),+ reason: 'invalid-shape',+ },+ {+ caseName: 'unknown record version',+ raw: JSON.stringify({ version: 2, shells: [processSample], console: emptyConsole }),+ reason: 'invalid-shape',+ },+ {+ caseName: 'more shells than requested PIDs',+ raw: JSON.stringify({+ version: 1,+ shells: [processSample, processSample],+ console: emptyConsole,+ }),+ reason: 'invalid-shape',+ },+ {+ caseName: 'waiting thread without a wait reason',+ raw: JSON.stringify({+ version: 1,+ shells: [+ { ...processSample, threads: [{ id: 8, state: 'wait', waitReason: 'not-applicable' }] },+ ],+ console: emptyConsole,+ }),+ reason: 'invalid-shape',+ },+ {+ caseName: 'running thread with a wait reason',+ raw: JSON.stringify({+ version: 1,+ shells: [+ { ...processSample, threads: [{ id: 8, state: 'running', waitReason: 'user-request' }] },+ ],+ console: emptyConsole,+ }),+ reason: 'invalid-shape',+ },+ {+ caseName: 'duplicate result frame',+ raw: `${JSON.stringify({ version: 1, shells: [processSample], console: emptyConsole })}\nRESULT {}`,+ reason: 'invalid-shape',+ },+])('$caseName produces $reason without leaking content', async ({ raw, reason }) => {+ const query = recordingQuery(raw);+ const result = await collectWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ expect(result.shell).toEqual(expect.objectContaining({ status: 'unavailable', reason }));+ expect(JSON.stringify(result)).not.toContain('private');+});++test('a missing process remains distinct from denied access and a valid non-wait thread has no wait reason', async () => {+ const results = await Promise.all(+ ['process-absent', 'access-unavailable'].map(async (reason) => {+ const query = recordingQuery(+ JSON.stringify({+ version: 1,+ shells: [{ status: 'unavailable', reason }],+ console: { status: 'unavailable', reason: 'console-identity-unavailable' },+ }),+ );+ return collectWindowsOsState({ pid: 4_242, platform: 'win32', spawnQuery: query.spawnQuery });+ }),+ );+ expect(results.map((item) => item.shell)).toEqual([+ { status: 'unavailable', reason: 'process-absent' },+ { status: 'unavailable', reason: 'access-unavailable' },+ ]);+ const query = recordingQuery(+ JSON.stringify({+ version: 1,+ shells: [+ {+ ...processSample,+ threads: [{ id: 9, state: 'running', waitReason: 'not-applicable' }],+ },+ ],+ console: emptyConsole,+ }),+ );+ const result = await collectWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ expect(result.shell.status === 'captured' && result.shell.value.threads[0]?.waitReason).toBe(+ 'not-applicable',+ );+});++test('a UTF-8 byte overflow records a helper request without asserting that the helper exited', async () => {+ const query = recordingQuery(null, { ready: false });+ const running = startWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ query.stderr.write('é'.repeat(WINDOWS_OS_MAX_RAW_BYTES / 2 + 1));+ const result = await running.result;+ expect(result.reason).toBe('output-limit');+ expect(result.helper).toEqual(+ expect.objectContaining({+ requested: true,+ reason: 'output-limit',+ delivery: 'accepted',+ exit: 'not-observed',+ }),+ );+ expect(query.sends).toEqual(['helper-kill-request']);+ expect(JSON.stringify(result)).not.toContain('é');+});++test('a bounded multi-target request uses one helper and retains each requested process identity', async () => {+ const query = recordingQuery(+ JSON.stringify({+ version: 1,+ shells: [processSample, { ...processSample, pid: 4_243 }],+ console: emptyConsole,+ }),+ );+ let launches = 0;+ const result = await collectWindowsOsState({+ pid: 4_242,+ additionalPids: [4_243],+ platform: 'win32',+ spawnQuery: (file, args) => {+ launches += 1;+ return query.spawnQuery(file, args);+ },+ });+ expect(result.targets.map((target) => target.requestedPid)).toEqual([4_242, 4_243]);+ expect(result.targets.every((target) => target.shell.status === 'captured')).toBe(true);+ expect(launches).toBe(1);+});++test('thread and console candidate limits keep omitted counts without retaining extra rows', async () => {+ const oversizedProcess = {+ ...processSample,+ first: { ...processSample.first, threadCount: 20 },+ second: { ...processSample.second, threadCount: 20 },+ threads: Array.from({ length: 20 }, (_, index) => ({+ id: index + 1,+ state: 'running',+ waitReason: 'not-applicable',+ })),+ };+ const query = recordingQuery(+ JSON.stringify({+ version: 1,+ shells: [oversizedProcess],+ console: {+ status: 'captured',+ candidateCount: 6,+ candidates: Array.from({ length: 6 }, (_, index) => ({+ ...processSample,+ pid: 5_000 + index,+ })),+ unavailableCandidates: [],+ omittedCandidates: 0,+ },+ }),+ );+ const result = await collectWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ expect(result.shell.status === 'captured' && result.shell.value.threads).toHaveLength(16);+ expect(result.shell.status === 'captured' && result.shell.value.omittedThreads).toBe(4);+ expect(result.console.status === 'captured' && result.console.value.candidates).toHaveLength(4);+ expect(result.console.status === 'captured' && result.console.value.omittedCandidates).toBe(2);+});++test('a candidate that exits after enumeration remains distinct from an empty candidate query', async () => {+ const query = recordingQuery(+ JSON.stringify({+ version: 1,+ shells: [processSample],+ console: {+ status: 'captured',+ candidateCount: 2,+ candidates: [{ ...processSample, pid: 5_000 }],+ unavailableCandidates: [{ reason: 'process-absent', count: 1 }],+ omittedCandidates: 0,+ },+ }),+ );+ const result = await collectWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ expect(result.status).toBe('partial');+ expect(result.console).toEqual(+ expect.objectContaining({+ status: 'captured',+ value: expect.objectContaining({+ candidateCount: 2,+ candidates: [expect.objectContaining({ pid: 5_000 })],+ unavailableCandidates: [{ reason: 'process-absent', count: 1 }],+ omittedCandidates: 0,+ }),+ }),+ );+ expect(JSON.stringify(result)).not.toContain('private');+});++test('the bounded contract accepts a partial record whose only gap is a failed console candidate', async () => {+ const query = recordingQuery(+ JSON.stringify({+ version: 1,+ shells: [processSample],+ console: {+ status: 'captured',+ candidateCount: 2,+ candidates: [{ ...processSample, pid: 5_000 }],+ unavailableCandidates: [{ reason: 'process-absent', count: 1 }],+ omittedCandidates: 0,+ },+ }),+ );+ const result = await collectWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ expect(result.status).toBe('partial');+ expect(() => assertBoundedWindowsOsState(result, 4_242)).not.toThrow();+ expect(() =>+ assertBoundedWindowsOsState({ ...result, worker: capturedWorker }, 4_242),+ ).not.toThrow();+});++test('a captured shell retains a partial result when console enumeration is unavailable', async () => {+ const query = recordingQuery(+ JSON.stringify({+ version: 1,+ shells: [processSample],+ console: { status: 'unavailable', reason: 'access-unavailable' },+ }),+ );+ const result = await collectWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ expect(result.status).toBe('partial');+ expect(result.shell.status).toBe('captured');+ expect(result.console).toEqual({ status: 'unavailable', reason: 'access-unavailable' });+});++test('an unavailable machine section alone names its reason on a partial record', async () => {+ vi.mocked(cpus).mockReturnValue([]);+ const query = recordingQuery(null, { ready: false });+ const running = startWindowsOsState({+ pid: 4_242,+ parentPid: 12,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ worker: { threadId: 91, cpuUsage: async () => ({ user: 1_000, system: 2_000 }) },+ });+ await new Promise<void>(setImmediate);+ query.stdout.write(+ `READY\nRESULT ${JSON.stringify({ version: 1, shells: [processSample], console: emptyConsole })}\n`,+ );+ await new Promise<void>(setImmediate);+ query.child.emit('close', 0, null);+ const result = await running.result;+ expect(result.shell.status).toBe('captured');+ expect(result.console.status).toBe('captured');+ expect(result.worker.status).toBe('captured');+ expect(result.machine).toEqual({ status: 'unavailable', reason: 'invalid-shape' });+ expect(result.status).toBe('partial');+ expect(result.reason).toBe('invalid-shape');+ assertBoundedWindowsOsState(result, 4_242);+});++test('a captured query with a pending worker sample remains a bounded observation', async () => {+ const query = recordingQuery(+ JSON.stringify({ version: 1, shells: [processSample], console: emptyConsole }),+ );+ const result = await collectWindowsOsState({+ pid: 4_242,+ parentPid: 12,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ worker: {+ threadId: 91,+ cpuUsage: () => new Promise<{ user: number; system: number }>(() => undefined),+ },+ });+ expect(result.shell.status).toBe('captured');+ expect(result.machine.status).toBe('captured');+ expect(result.console.status).toBe('captured');+ expect(result.worker).toEqual({ status: 'unavailable', reason: 'worker-request-deadline' });+ expect(result.status).toBe('partial');+ expect(query.sends).toEqual([]);+ assertBoundedWindowsOsState(result, 4_242);+});++test('the query helper starts with an execution policy scoped to its own process', async () => {+ const query = recordingQuery(null, { ready: false });+ const launches: string[][] = [];+ const running = startWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: (file, args) => {+ launches.push(args);+ return query.spawnQuery(file, args);+ },+ });+ running.cancel('owner-loss');+ await running.result;+ expect(launches).toHaveLength(1);+ const args = launches[0] ?? [];+ const policy = args.indexOf('-ExecutionPolicy');+ expect(policy).toBeGreaterThanOrEqual(0);+ expect(args[policy + 1]).toBe('Bypass');+ expect(policy).toBeLessThan(args.indexOf('-File'));+});++const shellFrame = JSON.stringify({ version: 1, shells: [{ ...processSample, parentPid: null }] });++test('a deadline after the process frame keeps the sampled shell on a partial record', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });+ const query = recordingQuery(null, { ready: false });+ const running = startWindowsOsState({+ pid: 4_242,+ parentPid: 12,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ query.stdout.write(`READY\nSHELL ${shellFrame}\n`);+ await new Promise<void>(setImmediate);+ await vi.runAllTimersAsync();+ const result = await running.result;+ expect(result.reason).toBe('deadline');+ expect(result.status).toBe('partial');+ expect(result.shell).toEqual({+ status: 'captured',+ value: expect.objectContaining({ pid: 4_242, parentPid: null, threads: processSample.threads }),+ });+ expect(result.targets).toEqual([{ requestedPid: 4_242, shell: result.shell }]);+ expect(result.console).toEqual({ status: 'unavailable', reason: 'deadline' });+ expect(query.sends).toEqual(['helper-kill-request']);+ expect(JSON.stringify(result)).not.toContain('secret');+ assertBoundedWindowsOsState(result, 4_242);+});++test('a helper deadline exit after the process frame keeps the sampled shell', async () => {+ const query = recordingQuery(null, { ready: false });+ const running = startWindowsOsState({+ pid: 4_242,+ parentPid: 12,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ query.stdout.write(`READY\nSHELL ${shellFrame}\n`);+ await new Promise<void>(setImmediate);+ query.child.emit('exit', 87, null);+ query.child.emit('close', 87, null);+ const result = await running.result;+ expect(result.reason).toBe('query-exited');+ expect(result.status).toBe('partial');+ expect(result.shell.status).toBe('captured');+ expect(result.console).toEqual({ status: 'unavailable', reason: 'query-exited' });+ expect(result.helper).toEqual(expect.objectContaining({ exit: 'cooperative-deadline' }));+});++test('a result frame after the process frame supplies the parent PID and console', async () => {+ const query = recordingQuery(null, { ready: false });+ const running = startWindowsOsState({+ pid: 4_242,+ parentPid: 12,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ query.stdout.write(+ `READY\nSHELL ${shellFrame}\nRESULT ${JSON.stringify({ version: 1, shells: [processSample], console: emptyConsole })}\n`,+ );+ await new Promise<void>(setImmediate);+ query.child.emit('close', 0, null);+ const result = await running.result;+ expect(result.reason).toBe('worker-unavailable');+ expect(result.shell).toEqual(+ expect.objectContaining({+ status: 'captured',+ value: expect.objectContaining({ parentPid: 12 }),+ }),+ );+ expect(result.console.status).toBe('captured');+});++test('a process frame for another PID is not kept at the deadline', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });+ const query = recordingQuery(null, { ready: false });+ const running = startWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ query.stdout.write(+ `READY\nSHELL ${JSON.stringify({ version: 1, shells: [{ ...processSample, pid: 4_243 }] })}\n`,+ );+ await new Promise<void>(setImmediate);+ await vi.runAllTimersAsync();+ const result = await running.result;+ expect(result.shell).toEqual({ status: 'unavailable', reason: 'deadline' });+ expect(result.status).toBe('unavailable');+});++const shellRetentionCases: Array<{+ caseName: string;+ frames: string;+ finish: (running: WindowsOsCollection, query: ReturnType<typeof recordingQuery>) => unknown;+ reason: string;+ status: string;+ shell: unknown;+}> = [+ {+ caseName: 'owner-loss after a valid process frame',+ frames: `SHELL ${shellFrame}\n`,+ finish: (running) => running.cancel('owner-loss'),+ reason: 'owner-loss',+ status: 'partial',+ shell: {+ status: 'captured',+ value: expect.objectContaining({+ pid: 4_242,+ parentPid: null,+ threads: processSample.threads,+ }),+ },+ },+ {+ caseName: 'a stray line after a valid process frame',+ frames: `SHELL ${shellFrame}\nunexpected\n`,+ finish: (running) => running.cancel('deadline'),+ reason: 'deadline',+ status: 'unavailable',+ shell: { status: 'unavailable', reason: 'deadline' },+ },+ {+ caseName: 'a duplicate valid process frame',+ frames: `SHELL ${shellFrame}\nSHELL ${shellFrame}\n`,+ finish: (running) => running.cancel('deadline'),+ reason: 'deadline',+ status: 'unavailable',+ shell: { status: 'unavailable', reason: 'deadline' },+ },+ {+ caseName: 'output overflow after a process frame',+ frames: `SHELL ${shellFrame}\n`,+ finish: (_running, query) => query.stderr.write('x'.repeat(WINDOWS_OS_MAX_RAW_BYTES + 1)),+ reason: 'output-limit',+ status: 'unavailable',+ shell: { status: 'unavailable', reason: 'output-limit' },+ },+ {+ caseName: 'a process frame after the result frame',+ frames: `RESULT ${JSON.stringify({ version: 1, shells: [processSample], console: emptyConsole })}\nSHELL ${shellFrame}\n`,+ finish: (_running, query) => query.child.emit('close', 0, null),+ reason: 'invalid-shape',+ status: 'unavailable',+ shell: { status: 'unavailable', reason: 'invalid-shape' },+ },+];++test.each(shellRetentionCases)(+ '$caseName settles with $reason and shell $shell.status',+ async ({ frames, finish, reason, status, shell }) => {+ const query = recordingQuery(null, { ready: false });+ const running = startWindowsOsState({+ pid: 4_242,+ parentPid: 12,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ query.stdout.write(`READY\n${frames}`);+ await new Promise<void>(setImmediate);+ finish(running, query);+ const result = await running.result;+ expect(result.requestedPid).toBe(4_242);+ expect(result.targets).toEqual([{ requestedPid: 4_242, shell }]);+ expect(result.reason).toBe(reason);+ expect(result.status).toBe(status);+ expect(result.shell).toEqual(shell);+ expect(result.console).toEqual({ status: 'unavailable', reason });+ },+);++test('more than eight requested targets never reaches the query boundary', async () => {+ const query = recordingQuery(null, { ready: false });+ let starts = 0;+ const result = await collectWindowsOsState({+ pid: 4_242,+ additionalPids: Array.from({ length: 8 }, (_, index) => 5_000 + index),+ platform: 'win32',+ spawnQuery: (file, args) => {+ starts += 1;+ return query.spawnQuery(file, args);+ },+ });+ expect(result.reason).toBe('invalid-shape');+ expect(result.targets.length).toBeLessThanOrEqual(8);+ expect(starts).toBe(0);+});++test('an owned helper with no PID receives no termination call at a deadline', async () => {+ const query = recordingQuery(null, { pid: undefined, ready: false });+ const result = await collectWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ expect(result.reason).toBe('query-start-failed');+ expect(query.child.pid).toBeUndefined();+ expect(result.helper.delivery).toBe('not-attempted');+ expect(query.sends).toEqual([]);+ expect(() => query.child.emit('error', new Error('private spawn command'))).not.toThrow();+});++test('a zero helper PID is rejected without a termination call', async () => {+ const query = recordingQuery(null, { pid: 0, ready: false });+ const result = await collectWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ expect(query.child.pid).toBe(0);+ expect(result.reason).toBe('query-start-failed');+ expect(result.helper.delivery).toBe('not-attempted');+ expect(query.sends).toEqual([]);+});++test('a helper that exits before a result frame reports query-exited', async () => {+ const query = recordingQuery(null, { ready: false });+ const running = startWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ query.child.emit('close', 88, null);+ const result = await running.result;+ expect(result.reason).toBe('query-exited');+ expect(result.helper.exit).toBe('observed-before-request');+});++test.each([+ { code: 86, exit: 'cooperative-owner-loss' },+ { code: 87, exit: 'cooperative-deadline' },+] as const)(+ 'an unrequested helper exit code $code is recorded as $exit',+ async ({ code, exit }) => {+ const query = recordingQuery(null, { ready: false });+ const running = startWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ query.child.emit('exit', code, null);+ query.child.emit('close', code, null);+ const result = await running.result;+ expect(result.reason).toBe('query-exited');+ expect(result.helper).toEqual(+ expect.objectContaining({ requested: false, exit, exitCode: code }),+ );+ expect(query.sends).toEqual([]);+ },+);++test('observed helper exit prevents a later deadline from sending a termination request', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });+ const query = recordingQuery(null, { ready: false });+ const running = startWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ query.child.emit('exit', 0, null);+ await vi.runAllTimersAsync();+ const result = await running.result;+ expect(result.helper).toEqual(+ expect.objectContaining({+ requested: true,+ delivery: 'already-exited',+ exit: 'observed-before-request',+ }),+ );+ expect(query.sends).toEqual([]);+});++test('owner disposal requests only its recording helper and seals late output', async () => {+ const query = recordingQuery(null, { ready: false });+ const running = startWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ const cancelled = running.cancel('owner-loss');+ const result = await running.result;+ expect(cancelled).toBe(result);+ expect(result.helper).toEqual(+ expect.objectContaining({+ requested: true,+ reason: 'owner-loss',+ delivery: 'accepted',+ exit: 'not-observed',+ }),+ );+ expect(query.sends).toEqual(['helper-kill-request']);+ query.child.emit('exit', 86, null);+ expect(result.helper.exit).toBe('not-observed');+});++test('worker response and rejection have distinct typed outcomes before collection settles', async () => {+ const acceptedQuery = recordingQuery(null, { ready: false });+ const accepted = startWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: acceptedQuery.spawnQuery,+ worker: { threadId: 91, cpuUsage: async () => ({ user: 1_000, system: 2_000 }) },+ });+ await new Promise<void>(setImmediate);+ const acceptedResult = accepted.cancel('owner-loss');+ expect(acceptedResult?.worker).toEqual(+ expect.objectContaining({+ status: 'captured',+ value: expect.objectContaining({ nodeThreadId: 91, userMs: 1, systemMs: 2 }),+ }),+ );++ const rejectedQuery = recordingQuery(null, { ready: false });+ const rejected = startWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: rejectedQuery.spawnQuery,+ worker: {+ threadId: 92,+ cpuUsage: async () => {+ throw new Error('private worker response');+ },+ },+ });+ await new Promise<void>(setImmediate);+ const rejectedResult = rejected.cancel('owner-loss');+ expect(rejectedResult?.worker).toEqual({ status: 'unavailable', reason: 'worker-unavailable' });+});++test.each([+ { killResult: false, killThrows: false, delivery: 'rejected' },+ { killResult: true, killThrows: true, delivery: 'threw' },+])(+ 'a termination delivery of $delivery still releases owned pipes after the deadline',+ async ({ killResult, killThrows, delivery }) => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });+ const query = recordingQuery(null, { ready: false, killResult, killThrows });+ const running = startWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ await vi.runAllTimersAsync();+ const result = await running.result;+ expect(result.helper.delivery).toBe(delivery);+ expect(query.sends).toEqual(['helper-kill-request']);+ expect(query.stdin.writableEnded).toBe(true);+ expect(query.stdout.destroyed).toBe(true);+ expect(query.stderr.destroyed).toBe(true);+ expect(query.unrefs).toEqual(['helper-unref']);+ },+);++test('a never-settling helper is cancelled through its recording handle at the collection deadline', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });+ const query = recordingQuery(null, { ready: false });+ const running = startWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ spawnQuery: query.spawnQuery,+ });+ await vi.runAllTimersAsync();+ const result = await running.result;+ expect(result.reason).toBe('deadline');+ expect(result.helper).toEqual(+ expect.objectContaining({+ requested: true,+ reason: 'deadline',+ delivery: 'accepted',+ exit: 'not-observed',+ }),+ );+ expect(query.sends).toEqual(['helper-kill-request']);+ query.child.emit('close', 1, null);+ expect(result.helper.exit).toBe('not-observed');+});++test('an unsupported platform or spent budget does not start the helper', async () => {+ const query = recordingQuery(null, { ready: false });+ let starts = 0;+ const spawnQuery: WindowsOsStateOptions['spawnQuery'] = (file, args) => {+ starts += 1;+ return query.spawnQuery(file, args);+ };+ const unsupported = await collectWindowsOsState({+ pid: 4_242,+ platform: 'darwin',+ spawnQuery,+ });+ const spent = await collectWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ budgetMs: 0,+ spawnQuery,+ });+ const lessThanOneMs = await collectWindowsOsState({+ pid: 4_242,+ platform: 'win32',+ budgetMs: 0.5,+ spawnQuery,+ });+ expect(unsupported.reason).toBe('unsupported-platform');+ expect(spent.reason).toBe('no-budget');+ expect(lessThanOneMs.reason).toBe('no-budget');+ expect(starts).toBe(0);+ expect(query.sends).toEqual([]);+});++test('the Windows PowerShell path reads SystemRoot case-insensitively with Windows separators', () => {+ expect(windowsPowerShellPath({ systemroot: 'D:\\Win' })).toBe(+ 'D:\\Win\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',+ );+ expect(windowsPowerShellPath({})).toBe(+ 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',+ );+});