From 399e7d10f2716e1de796417f30acf97df4aa8cd8 Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:01:24 +0900 Subject: [PATCH 1/3] fix(windows): query the named task within the stop probe deadline --- src/service/windows-checked-stop-live.ts | 28 ++++++- structure/ops/windows-checked-stop.md | 4 + .../windows/windows-checked-stop-live.test.ts | 78 +++++++++++++++++++ 3 files changed, 106 insertions(+), 4 deletions(-) diff --git a/src/service/windows-checked-stop-live.ts b/src/service/windows-checked-stop-live.ts index e367e4ca808..ec3ea07ff9f 100644 --- a/src/service/windows-checked-stop-live.ts +++ b/src/service/windows-checked-stop-live.ts @@ -42,6 +42,21 @@ import type { WindowsListenerIdentity, WindowsPortSample, WindowsStopConfirmDeps import { windowsSchedulerCsvIncludesTask } from "./windows-scheduler"; import { WINDOWS_TASK_INSTANCE_STOP_SCRIPT, verifyWindowsTaskStopProof } from "./windows-task-instance-stop"; +// Only a missing task after connecting to the local root folder establishes absence. +const TASK_REGISTRATION_SCRIPT = String.raw` +$ErrorActionPreference = 'Stop' +try { + $service = [Activator]::CreateInstance([type]::GetTypeFromProgID('Schedule.Service', $true)) + $service.Connect() + $folder = $service.GetFolder('\') +} catch { 'unknown'; return } +try { + $task = $folder.GetTask('${TASK}') + if ($null -ne $task) { 'present' } else { 'unknown' } +} catch { + if ($_.Exception.GetBaseException().HResult -eq -2147024894) { 'absent' } else { 'unknown' } +}`; + export interface WindowsStopCommandResult { status: number | null; stdout: string; @@ -267,12 +282,17 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption canonicalPaths: windowsStopCanonicalPaths(), childPid: windowsStopChildPid(), async probeScheduler(timeoutMs) { - const started = Date.now(); + const deadline = performance.now() + timeoutMs; + const unknown = { status: "unknown", detail: "the Task Scheduler query did not answer" } as const; const direct = await run("schtasks", ["/query", "/tn", TASK], timeoutMs); + if (direct.timedOut || performance.now() >= deadline) return unknown; if (direct.status === 0 && direct.stdout.includes(TASK)) return { status: "present" }; - const listing = await run("schtasks", ["/query", "/fo", "CSV"], Math.max(1, timeoutMs - (Date.now() - started))); - if (listing.status !== 0 || listing.timedOut) return { status: "unknown", detail: "the Task Scheduler query did not answer" }; - return windowsSchedulerCsvIncludesTask(listing.stdout, TASK) ? { status: "present" } : { status: "absent" }; + const remaining = wholeTimeoutMs(deadline - performance.now()); + if (remaining === null) return unknown; + const probe = await run("powershell", ["-NoProfile", "-NonInteractive", "-Command", TASK_REGISTRATION_SCRIPT], remaining); + if (probe.timedOut || probe.status !== 0 || performance.now() >= deadline) return unknown; + const status = probe.stdout.trim(); + return status === "present" || status === "absent" ? { status } : unknown; }, async probeWinsw(timeoutMs) { // One cap covers both reads: the ownership query gets only what the state query left. diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index 8ce82db99e5..6eefafd00c0 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -122,6 +122,10 @@ asynchronous `schtasks` and `sc.exe` calls through `execFile` (a deadline-derive floored to whole milliseconds and one that floors to 0 spawns nothing, because `execFile` reads 0 as no timeout), the evidence snapshot `windowsProcessSnapshot` for every bind, the checked terminate, the exit watch, the Part B port sampler and the listener identity. +For Scheduler registration, Part A queries the named task. If `schtasks /query /tn` cannot +confirm it, the local Task Scheduler COM API reads that exact task in the root folder within +the remaining 2 s budget. Only `GetTask` returning `ERROR_FILE_NOT_FOUND` proves absence. +An inaccessible folder, denied task, or late answer leaves registration unknown. `src/service/windows-task-instance-stop.ts` keeps the root registration and its running instances in one Task Scheduler COM session. It passes the registered XML and the helper's current account as base64 UTF-8 to preserve Unicode through the console. The live adapter checks the recognized task diff --git a/tests/windows/windows-checked-stop-live.test.ts b/tests/windows/windows-checked-stop-live.test.ts index fd50849f3f5..1b2ee501936 100644 --- a/tests/windows/windows-checked-stop-live.test.ts +++ b/tests/windows/windows-checked-stop-live.test.ts @@ -254,6 +254,84 @@ describe("capped command answers", () => { const portablePowerShell = Bun.which("pwsh"); +describe("the bounded Scheduler registration query", () => { + test("a direct hit avoids PowerShell; only a completed, exact fallback answer is accepted", async () => { + const directHit = result(0, "opencodex-proxy"); + const missing = result(1, "", "지정된 파일을 찾을 수 없습니다."); + for (const [direct, fallback, expected] of [ + [directHit, null, "present"], + [result(1, "", "", true), null, "unknown"], + [missing, result(0, "absent\r\n"), "absent"], + [missing, result(0, "present"), "present"], + [missing, result(0, "unknown"), "unknown"], + [missing, result(0, "noise\nabsent"), "unknown"], + [missing, result(1, "absent"), "unknown"], + [missing, result(null, "absent", "", true), "unknown"], + ] as const) { + const calls: string[] = []; + const deps = windowsCheckedStopLiveDeps({ run: async (program, args, timeout) => { + calls.push(program); + if (program === "schtasks") { + expect(args).toEqual(["/query", "/tn", "opencodex-proxy"]); + return direct; + } + expect(timeout).toBeGreaterThan(0); + expect(timeout).toBeLessThanOrEqual(2_000); + return fallback!; + } }); + expect((await deps.probeScheduler(2_000)).status).toBe(expected); + expect(calls).toEqual(fallback ? ["schtasks", "powershell"] : ["schtasks"]); + } + }); + + test("the fallback uses only the remaining time and a late answer is unknown", async () => { + let now = 100; + const clock = spyOn(performance, "now").mockImplementation(() => now); + try { + const deps = windowsCheckedStopLiveDeps({ run: async (program, _args, timeout) => { + if (program === "schtasks") { now += 750; return result(1); } + expect(timeout).toBe(1_250); + now += timeout; + return result(0, "absent"); + } }); + expect((await deps.probeScheduler(2_000)).status).toBe("unknown"); + } finally { clock.mockRestore(); } + }); + + test.skipIf(process.platform !== "win32" && !portablePowerShell)("only a missing task in an accessible root is absent", async () => { + let script = ""; + await windowsCheckedStopLiveDeps({ run: async (program, args) => { + if (program === "schtasks") return result(1); + script = args.at(-1)!; + return result(0, "unknown"); + } }).probeScheduler(2_000); + const activation = "[Activator]::CreateInstance([type]::GetTypeFromProgID('Schedule.Service', $true))"; + expect(script).toContain(activation); + const fixture = String.raw` +class SchedulerFixture { + [void] Connect() { if ($global:scenario -eq 'connect') { throw [IO.FileNotFoundException]::new() } } + [object] GetFolder([string] $path) { + if ($path -cne '\' -or $global:scenario -eq 'folder') { throw [IO.FileNotFoundException]::new() } + return $this + } + [object] GetTask([string] $name) { + if ($name -cne 'opencodex-proxy') { throw 'wrong name' } + if ($global:scenario -eq 'missing') { throw [Runtime.InteropServices.COMException]::new('missing', -2147024894) } + if ($global:scenario -eq 'denied') { throw [UnauthorizedAccessException]::new() } + if ($global:scenario -eq 'empty') { return $null } + return $this + } +}`; + const command = fixture + "\nforeach ($global:scenario in 'found','missing','denied','connect','folder','empty') { & {\n" + + script.replace(activation, "[SchedulerFixture]::new()") + "\n} }"; + const powershell = process.platform === "win32" ? resolveTrustedWindowsPowerShellExe() : portablePowerShell!; + const child = Bun.spawn([powershell, "-NoProfile", "-NonInteractive", "-EncodedCommand", + Buffer.from(command, "utf16le").toString("base64")], { stdout: "pipe", stderr: "pipe", windowsHide: true, timeout: SPAWN_BUDGET_MS }); + const [out, err, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); + expect({ code, err, lines: out.trim().split(/\r?\n/) }).toEqual({ code: 0, err: "", lines: ["present", "absent", "unknown", "unknown", "unknown", "unknown"] }); + }, SPAWN_BUDGET_MS + 1_000); +}); + test.skipIf(process.platform !== "win32" && !portablePowerShell)("the PowerShell helper stops captured instances only after every proof succeeds", async () => { const powershell = process.platform === "win32" ? resolveTrustedWindowsPowerShellExe() : portablePowerShell!; const fixture = String.raw` From 94500b4366723cdd26fb84c4719de40c222e1f20 Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:28:03 +0900 Subject: [PATCH 2/3] fix(windows): preserve the native Scheduler query HRESULT --- src/service/windows-checked-stop-live.ts | 17 +++++++++++-- src/service/windows-process-native.ts | 15 +++++++++++ structure/ops/windows-checked-stop.md | 10 +++++--- .../windows/windows-checked-stop-live.test.ts | 25 ++++++++++++++++--- 4 files changed, 58 insertions(+), 9 deletions(-) diff --git a/src/service/windows-checked-stop-live.ts b/src/service/windows-checked-stop-live.ts index ec3ea07ff9f..a353bf5bc48 100644 --- a/src/service/windows-checked-stop-live.ts +++ b/src/service/windows-checked-stop-live.ts @@ -59,6 +59,8 @@ try { export interface WindowsStopCommandResult { status: number | null; + /** Captured from the spawned process handle. Bun's child exit status can contain only the low byte. */ + windowsExitCode?: number; stdout: string; stderr: string; timedOut: boolean; @@ -104,18 +106,23 @@ export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program, resolve({ status: null, stdout: "", stderr: error instanceof Error ? error.message : String(error), timedOut: false }); return; } + const native = program === "schtasks" && args.includes("/hresult") ? windowsProcessNative() : null; + let readExitCode: (() => number | null) | null = null; const helper = execFile(file, args, { encoding: "buffer", timeout, windowsHide: true, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => { const text = (value: Buffer | string | undefined): string => value === undefined ? "" : typeof value === "string" ? value : decodeWindowsTextBytes(value); const failure = error as (NodeJS.ErrnoException & { killed?: boolean; signal?: string | null; code?: number | string }) | null; + const windowsExitCode = readExitCode?.(); resolve({ status: failure ? (typeof failure.code === "number" ? failure.code : null) : 0, + ...(windowsExitCode == null || failure?.killed ? {} : { windowsExitCode }), stdout: text(stdout), stderr: text(stderr), timedOut: !!failure?.killed && failure.signal !== null, }); }); + if (helper.pid !== undefined) readExitCode = native?.captureChildExitCode?.(helper.pid) ?? null; if (authorizeProof) { let pending = ""; const onProof = async (chunk: Buffer): Promise => { @@ -284,9 +291,15 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption async probeScheduler(timeoutMs) { const deadline = performance.now() + timeoutMs; const unknown = { status: "unknown", detail: "the Task Scheduler query did not answer" } as const; - const direct = await run("schtasks", ["/query", "/tn", TASK], timeoutMs); + const direct = await run("schtasks", ["/query", "/tn", `\\${TASK}`, "/fo", "CSV", "/nh", "/hresult"], timeoutMs); if (direct.timedOut || performance.now() >= deadline) return unknown; - if (direct.status === 0 && direct.stdout.includes(TASK)) return { status: "present" }; + if (direct.status === 0 && (direct.windowsExitCode ?? 0) === 0 + && direct.stdout.trimStart().toLowerCase().startsWith(`"\\${TASK}",`)) return { status: "present" }; + if (direct.windowsExitCode !== undefined) { + const missing = 0x80070002; // HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) + const statusAgrees = direct.status === 2 || (direct.status !== null && (direct.status >>> 0) === missing); + return direct.windowsExitCode === missing && statusAgrees ? { status: "absent" } : unknown; + } const remaining = wholeTimeoutMs(deadline - performance.now()); if (remaining === null) return unknown; const probe = await run("powershell", ["-NoProfile", "-NonInteractive", "-Command", TASK_REGISTRATION_SCRIPT], remaining); diff --git a/src/service/windows-process-native.ts b/src/service/windows-process-native.ts index 16123c19aff..301edf24a11 100644 --- a/src/service/windows-process-native.ts +++ b/src/service/windows-process-native.ts @@ -64,6 +64,8 @@ export type WindowsProcessWatch = | { status: "gone" | "reused" | "denied" | "unavailable" }; export interface WindowsProcessNativeApi { + /** Pin a just-spawned child until its completion callback reads its full Windows exit code. */ + captureChildExitCode?(pid: number): (() => number | null) | null; /** Creation time in epoch ms (FILETIME truncated to ms), or null when unreadable. */ creationTime(pid: number): number | null; /** Creation in .NET ticks at CIM precision from a live process with the same token user. */ @@ -139,6 +141,7 @@ function loadNativeApi(): WindowsProcessNativeApi | null { kernel32 = ffi.dlopen(join(systemDirectory, "kernel32.dll"), { OpenProcess: { args: ["u32", "i32", "u32"], returns: "u64" }, CloseHandle: { args: ["u64"], returns: "i32" }, + GetExitCodeProcess: { args: ["u64", "ptr"], returns: "i32" }, GetProcessTimes: { args: ["u64", "ptr", "ptr", "ptr", "ptr"], returns: "i32" }, TerminateProcess: { args: ["u64", "u32"], returns: "i32" }, WaitForSingleObject: { args: ["u64", "u32"], returns: "u32" }, @@ -199,6 +202,18 @@ function loadNativeApi(): WindowsProcessNativeApi | null { }; nativeApi = { + captureChildExitCode(pid) { + const handle = k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid); + if (!handle) return null; + return () => { + try { + const code = new Uint32Array(1); + return handleExited(handle) === true && k.GetExitCodeProcess(handle, ptr(code)) ? code[0]! : null; + } finally { + k.CloseHandle(handle); + } + }; + }, creationTime(pid) { const handle = k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); if (!handle) return null; diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index 6eefafd00c0..b97b96f9b3d 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -122,10 +122,12 @@ asynchronous `schtasks` and `sc.exe` calls through `execFile` (a deadline-derive floored to whole milliseconds and one that floors to 0 spawns nothing, because `execFile` reads 0 as no timeout), the evidence snapshot `windowsProcessSnapshot` for every bind, the checked terminate, the exit watch, the Part B port sampler and the listener identity. -For Scheduler registration, Part A queries the named task. If `schtasks /query /tn` cannot -confirm it, the local Task Scheduler COM API reads that exact task in the root folder within -the remaining 2 s budget. Only `GetTask` returning `ERROR_FILE_NOT_FOUND` proves absence. -An inaccessible folder, denied task, or late answer leaves registration unknown. +For Scheduler registration, Part A queries the exact root task with `schtasks /query /tn` and +`/hresult`. On Windows x64 it reads the full exit code from the spawned process handle. Only +`0x80070002` establishes absence. Bun's truncated process status cannot prove that result. +Where a full exit code is unavailable, the local Scheduler COM API can still confirm the task +or report `ERROR_FILE_NOT_FOUND` from `GetTask` within the remainder of the same 2 s budget. +Denied access, incomplete evidence, and late answers keep the registration unknown. `src/service/windows-task-instance-stop.ts` keeps the root registration and its running instances in one Task Scheduler COM session. It passes the registered XML and the helper's current account as base64 UTF-8 to preserve Unicode through the console. The live adapter checks the recognized task diff --git a/tests/windows/windows-checked-stop-live.test.ts b/tests/windows/windows-checked-stop-live.test.ts index 1b2ee501936..2e2438c162d 100644 --- a/tests/windows/windows-checked-stop-live.test.ts +++ b/tests/windows/windows-checked-stop-live.test.ts @@ -23,7 +23,7 @@ import { winswStatusFromScState, windowsCheckedStopLiveDeps, } from "../../src/service/windows-checked-stop-live"; -import type { WindowsProcessNativeApi } from "../../src/service/windows-process-native"; +import { windowsProcessNative, type WindowsProcessNativeApi } from "../../src/service/windows-process-native"; import { windowsLauncherVbsPath } from "../../src/service/state"; import { WINDOWS_TASK_INSTANCE_STOP_SCRIPT } from "../../src/service/windows-task-instance-stop"; import { buildWindowsTaskXml, windowsTaskRegistrationHealthy } from "../../src/service/windows-taskxml"; @@ -256,10 +256,17 @@ const portablePowerShell = Bun.which("pwsh"); describe("the bounded Scheduler registration query", () => { test("a direct hit avoids PowerShell; only a completed, exact fallback answer is accepted", async () => { - const directHit = result(0, "opencodex-proxy"); + const directHit = result(0, '"\\opencodex-proxy","N/A","Disabled"'); const missing = result(1, "", "지정된 파일을 찾을 수 없습니다."); for (const [direct, fallback, expected] of [ [directHit, null, "present"], + [{ ...result(2), windowsExitCode: 0x80070002 }, null, "absent"], + [{ ...result(-2147024894), windowsExitCode: 0x80070002 }, null, "absent"], + [{ ...result(1), windowsExitCode: 0x80070002 }, null, "unknown"], + [{ ...result(2), windowsExitCode: 0x80041302 }, null, "unknown"], + [{ ...result(5), windowsExitCode: 0x80070005 }, null, "unknown"], + [{ ...result(null), windowsExitCode: 0x80070002 }, null, "unknown"], + [result(2), result(0, "unknown"), "unknown"], [result(1, "", "", true), null, "unknown"], [missing, result(0, "absent\r\n"), "absent"], [missing, result(0, "present"), "present"], @@ -272,7 +279,7 @@ describe("the bounded Scheduler registration query", () => { const deps = windowsCheckedStopLiveDeps({ run: async (program, args, timeout) => { calls.push(program); if (program === "schtasks") { - expect(args).toEqual(["/query", "/tn", "opencodex-proxy"]); + expect(args).toEqual(["/query", "/tn", "\\opencodex-proxy", "/fo", "CSV", "/nh", "/hresult"]); return direct; } expect(timeout).toBeGreaterThan(0); @@ -284,6 +291,18 @@ describe("the bounded Scheduler registration query", () => { } }); + test.skipIf(process.platform !== "win32" || process.arch !== "x64")("the child handle preserves distinct HRESULTs with the same low byte", async () => { + const native = windowsProcessNative(); + expect(native?.captureChildExitCode).toBeFunction(); + for (const code of [0x80070002, 0x80041302]) { + const child = Bun.spawn([resolveTrustedWindowsPowerShellExe(), "-NoProfile", "-NonInteractive", "-Command", + `[Environment]::Exit(${code | 0})`], { stdout: "ignore", stderr: "ignore", windowsHide: true, timeout: SPAWN_BUDGET_MS }); + const readExitCode = native!.captureChildExitCode!(child.pid); + await child.exited; + expect(readExitCode?.()).toBe(code); + } + }, 2 * SPAWN_BUDGET_MS + 1_000); + test("the fallback uses only the remaining time and a late answer is unknown", async () => { let now = 100; const clock = spyOn(performance, "now").mockImplementation(() => now); From e632b73ccb8dabb79a9a8e45951ed86310057846 Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:57:15 +0900 Subject: [PATCH 3/3] refactor(windows): prepare Scheduler exit evidence before helper dispatch --- src/service/windows-checked-stop-live.ts | 5 +++-- structure/ops/windows-checked-stop.md | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/service/windows-checked-stop-live.ts b/src/service/windows-checked-stop-live.ts index a353bf5bc48..2d09a1bfd6b 100644 --- a/src/service/windows-checked-stop-live.ts +++ b/src/service/windows-checked-stop-live.ts @@ -100,14 +100,15 @@ export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program, return; } let file: string; + let native: WindowsProcessNativeApi | null; + let readExitCode: (() => number | null) | null = null; try { file = programPath(program); + native = program === "schtasks" && args.includes("/hresult") ? windowsProcessNative() : null; } catch (error) { resolve({ status: null, stdout: "", stderr: error instanceof Error ? error.message : String(error), timedOut: false }); return; } - const native = program === "schtasks" && args.includes("/hresult") ? windowsProcessNative() : null; - let readExitCode: (() => number | null) | null = null; const helper = execFile(file, args, { encoding: "buffer", timeout, windowsHide: true, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => { const text = (value: Buffer | string | undefined): string => diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index b97b96f9b3d..ddd7dd78683 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -123,7 +123,8 @@ floored to whole milliseconds and one that floors to 0 spawns nothing, because ` as no timeout), the evidence snapshot `windowsProcessSnapshot` for every bind, the checked terminate, the exit watch, the Part B port sampler and the listener identity. For Scheduler registration, Part A queries the exact root task with `schtasks /query /tn` and -`/hresult`. On Windows x64 it reads the full exit code from the spawned process handle. Only +`/hresult`. On Windows x64 it prepares native exit-code capture during executable lookup, +then reads the full exit code from the spawned process handle. Only `0x80070002` establishes absence. Bun's truncated process status cannot prove that result. Where a full exit code is unavailable, the local Scheduler COM API can still confirm the task or report `ERROR_FILE_NOT_FOUND` from `GetTask` within the remainder of the same 2 s budget.