Skip to content

Commit d8a39cf

Browse files
committed
refactor(infra): isolate Windows process identity
1 parent 266b047 commit d8a39cf

8 files changed

Lines changed: 131 additions & 99 deletions

‎scripts/ci-changed-scope.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ const WINDOWS_SQLITE_SCOPE_RE = /^src\/(?:state\/|.*sqlite.*\.ts$)/;
7070
// to any of them that skipped the lane would merge a Windows regression unseen.
7171
// Not gated on isTestOnly: the proof itself is a test file and must route here.
7272
const WINDOWS_PROCESS_IDENTITY_SCOPE_RE =
73-
/^(?:src\/(?:shared\/pid-alive(?:\.[a-z-]+)?(?:\.test)?\.ts|infra\/(?:windows-port-pids|gateway-lock)(?:\.test)?\.ts|node-host\/node-worker-process-identity(?:\.test)?\.ts|cron\/store\/run-receipt-store(?:\.test)?\.ts)|test\/e2e\/windows-cron-process-identity\.e2e\.test\.ts)$/;
73+
/^(?:src\/(?:shared\/pid-alive(?:\.[a-z-]+)?(?:\.test)?\.ts|infra\/(?:windows-process-start|gateway-lock)(?:\.test)?\.ts|node-host\/node-worker-process-identity(?:\.test)?\.ts|cron\/store\/run-receipt-store(?:\.test)?\.ts)|test\/e2e\/windows-cron-process-identity\.e2e\.test\.ts)$/;
7474
const WINDOWS_FILE_URL_SCOPE_RE =
7575
/^(?:src\/agents\/tools\/(?:media-tool-file-url\.windows\.test|media-tool-shared(?:\.test)?|pdf-tool(?:\.test)?)|src\/auto-reply\/(?:reply\/stage-sandbox-media|reply\.triggers\.trigger-handling\.stages-inbound-media-into-sandbox-workspace\.test)|src\/media\/(?:local-media-path(?:\.windows\.test)?|local-roots(?:\.test)?|web-media(?:\.file-url\.windows\.test)?)|src\/channels\/inbound-event\/media(?:\.test)?|src\/gateway\/managed-image-attachments(?:\.test)?|extensions\/msteams\/src\/(?:media-helpers|messenger)(?:\.test)?)\.ts$/;
7676
const WINDOWS_SCOPE_RE =

‎src/infra/gateway-lock.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,8 @@ import {
2424
} from "./gateway-process-argv.js";
2525
import { tryAcquireExclusiveSqliteCoordinator } from "./node-sqlite.js";
2626
import { acquireGatewayLifecycleCoordinator } from "./state-database-coordinator.js";
27-
import {
28-
readWindowsProcessArgsSync,
29-
readWindowsProcessStartTimeSync,
30-
} from "./windows-port-pids.js";
27+
import { readWindowsProcessArgsSync } from "./windows-port-pids.js";
28+
import { readWindowsProcessStartTimeSync } from "./windows-process-start.js";
3129

3230
const DEFAULT_TIMEOUT_MS = 5000;
3331
const DEFAULT_POLL_INTERVAL_MS = 100;

‎src/infra/windows-port-pids.ts‎

Lines changed: 1 addition & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ import {
1010
getWindowsSystem32ExePath,
1111
getWindowsWmicExePath,
1212
} from "./windows-install-roots.js";
13+
import { decodeWindowsProcessOutput } from "./windows-process-start.js";
1314

1415
const DEFAULT_TIMEOUT_MS = 5_000;
15-
const DEFAULT_PROCESS_START_TIMEOUT_MS = 10_000;
1616

1717
export type WindowsListeningPidsResult =
1818
| { ok: true; pids: number[] }
@@ -85,15 +85,6 @@ export function readWindowsListeningPidsResultSync(
8585
// Windows process identity reading (PowerShell → WMIC fallback)
8686
// ---------------------------------------------------------------------------
8787

88-
function decodeWindowsProcessOutput(output: Buffer | string): string {
89-
if (!Buffer.isBuffer(output)) {
90-
return output;
91-
}
92-
return output.length >= 2 && output[0] === 0xff && output[1] === 0xfe
93-
? output.toString("utf16le")
94-
: output.toString("utf8");
95-
}
96-
9788
function extractWindowsCommandLine(raw: Buffer | string): string | null {
9889
const lines = normalizeStringEntries(decodeWindowsProcessOutput(raw).split(/\r?\n/));
9990
for (const line of lines) {
@@ -106,85 +97,6 @@ function extractWindowsCommandLine(raw: Buffer | string): string | null {
10697
return lines.find((line) => normalizeLowercaseStringOrEmpty(line) !== "commandline") ?? null;
10798
}
10899

109-
function parseWindowsProcessStartTime(raw: Buffer | string): number | null {
110-
const lines = normalizeStringEntries(decodeWindowsProcessOutput(raw).split(/\r?\n/));
111-
const value =
112-
lines
113-
.find((line) => normalizeLowercaseStringOrEmpty(line).startsWith("creationdate="))
114-
?.slice("creationdate=".length)
115-
.trim() ??
116-
lines.find((line) => normalizeLowercaseStringOrEmpty(line) !== "creationdate") ??
117-
"";
118-
const parsedIso = Date.parse(value);
119-
if (Number.isFinite(parsedIso)) {
120-
return parsedIso;
121-
}
122-
const dmtf = value.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-])(\d{3})$/);
123-
if (!dmtf) {
124-
return null;
125-
}
126-
const [, year, month, day, hour, minute, second, microseconds, offsetSign, offset] = dmtf;
127-
const localTimeMs = Date.UTC(
128-
Number(year),
129-
Number(month) - 1,
130-
Number(day),
131-
Number(hour),
132-
Number(minute),
133-
Number(second),
134-
Math.floor(Number(microseconds) / 1000),
135-
);
136-
const offsetMs = Number(offset) * 60_000 * (offsetSign === "+" ? 1 : -1);
137-
return localTimeMs - offsetMs;
138-
}
139-
140-
/** Read a stable Windows process creation time for lock-owner identity checks. */
141-
export function readWindowsProcessStartTimeSync(
142-
pid: number,
143-
timeoutMs = DEFAULT_PROCESS_START_TIMEOUT_MS,
144-
): number | null {
145-
if (!Number.isInteger(pid) || pid <= 0) {
146-
return null;
147-
}
148-
// Keep the former default availability: PowerShell and WMIC each had 5s.
149-
// Explicit callers still get one end-to-end budget, while the default 10s
150-
// deadline preserves enough time for WMIC after a stalled primary probe.
151-
const deadline = Date.now() + timeoutMs;
152-
const powershell = spawnSync(
153-
getWindowsPowerShellExePath(),
154-
[
155-
"-NoProfile",
156-
"-NonInteractive",
157-
"-Command",
158-
`$process = Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}" -ErrorAction Stop; [Console]::Out.Write($process.CreationDate.ToUniversalTime().ToString("o"))`,
159-
],
160-
{
161-
encoding: "utf8",
162-
timeout: Math.min(timeoutMs, DEFAULT_TIMEOUT_MS),
163-
windowsHide: true,
164-
},
165-
);
166-
if (!powershell.error && powershell.status === 0) {
167-
const startTime = parseWindowsProcessStartTime(powershell.stdout);
168-
if (startTime !== null) {
169-
return startTime;
170-
}
171-
}
172-
const remainingMs = deadline - Date.now();
173-
if (remainingMs <= 0) {
174-
return null;
175-
}
176-
const wmic = spawnSync(
177-
getWindowsWmicExePath(),
178-
["process", "where", `ProcessId=${pid}`, "get", "CreationDate", "/value"],
179-
{
180-
timeout: remainingMs,
181-
windowsHide: true,
182-
stdio: ["ignore", "pipe", "ignore"],
183-
},
184-
);
185-
return !wmic.error && wmic.status === 0 ? parseWindowsProcessStartTime(wmic.stdout) : null;
186-
}
187-
188100
export function readWindowsProcessArgsSync(
189101
pid: number,
190102
timeoutMs = DEFAULT_TIMEOUT_MS,
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
22
import { getWindowsPowerShellExePath, getWindowsWmicExePath } from "./windows-install-roots.js";
3-
import { readWindowsProcessStartTimeSync } from "./windows-port-pids.js";
3+
import { readWindowsProcessStartTimeSync } from "./windows-process-start.js";
44

55
const spawnSyncMock = vi.hoisted(() => vi.fn());
66

‎src/infra/windows-process-start.ts‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
// Reads PID-reuse-safe Windows process start identities without workspace imports.
2+
import { spawnSync } from "node:child_process";
3+
import path from "node:path";
4+
5+
const DEFAULT_TIMEOUT_MS = 5_000;
6+
const DEFAULT_PROCESS_START_TIMEOUT_MS = 10_000;
7+
const DEFAULT_WINDOWS_SYSTEM_ROOT = "C:\\Windows";
8+
9+
function windowsSystemRoot(): string {
10+
const configured = process.env.SystemRoot ?? process.env.WINDIR;
11+
if (!configured) {
12+
return DEFAULT_WINDOWS_SYSTEM_ROOT;
13+
}
14+
const normalized = path.win32.normalize(configured);
15+
return /^[A-Za-z]:\\/.test(normalized) && !normalized.startsWith("\\\\")
16+
? normalized
17+
: DEFAULT_WINDOWS_SYSTEM_ROOT;
18+
}
19+
20+
function windowsPowerShellPath(): string {
21+
return path.win32.join(
22+
windowsSystemRoot(),
23+
"System32",
24+
"WindowsPowerShell",
25+
"v1.0",
26+
"powershell.exe",
27+
);
28+
}
29+
30+
function windowsWmicPath(): string {
31+
return path.win32.join(windowsSystemRoot(), "System32", "wbem", "wmic.exe");
32+
}
33+
34+
export function decodeWindowsProcessOutput(output: Buffer | string): string {
35+
if (!Buffer.isBuffer(output)) {
36+
return output;
37+
}
38+
return output.length >= 2 && output[0] === 0xff && output[1] === 0xfe
39+
? output.toString("utf16le")
40+
: output.toString("utf8");
41+
}
42+
43+
function parseWindowsProcessStartTime(raw: Buffer | string): number | null {
44+
const lines = decodeWindowsProcessOutput(raw)
45+
.split(/\r?\n/)
46+
.map((line) => line.trim())
47+
.filter(Boolean);
48+
const value =
49+
lines
50+
.find((line) => line.toLowerCase().startsWith("creationdate="))
51+
?.slice("creationdate=".length)
52+
.trim() ??
53+
lines.find((line) => line.toLowerCase() !== "creationdate") ??
54+
"";
55+
const parsedIso = Date.parse(value);
56+
if (Number.isFinite(parsedIso)) {
57+
return parsedIso;
58+
}
59+
const dmtf = value.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-])(\d{3})$/);
60+
if (!dmtf) {
61+
return null;
62+
}
63+
const [, year, month, day, hour, minute, second, microseconds, offsetSign, offset] = dmtf;
64+
const localTimeMs = Date.UTC(
65+
Number(year),
66+
Number(month) - 1,
67+
Number(day),
68+
Number(hour),
69+
Number(minute),
70+
Number(second),
71+
Math.floor(Number(microseconds) / 1000),
72+
);
73+
const offsetMs = Number(offset) * 60_000 * (offsetSign === "+" ? 1 : -1);
74+
return localTimeMs - offsetMs;
75+
}
76+
77+
/** Read a stable Windows process creation time for lock-owner identity checks. */
78+
export function readWindowsProcessStartTimeSync(
79+
pid: number,
80+
timeoutMs = DEFAULT_PROCESS_START_TIMEOUT_MS,
81+
): number | null {
82+
if (!Number.isInteger(pid) || pid <= 0) {
83+
return null;
84+
}
85+
// Preserve both former 5s attempts inside one deadline. Explicit callers
86+
// still keep their smaller end-to-end budget.
87+
const deadline = Date.now() + timeoutMs;
88+
const powershell = spawnSync(
89+
windowsPowerShellPath(),
90+
[
91+
"-NoProfile",
92+
"-NonInteractive",
93+
"-Command",
94+
`$process = Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}" -ErrorAction Stop; [Console]::Out.Write($process.CreationDate.ToUniversalTime().ToString("o"))`,
95+
],
96+
{
97+
encoding: "utf8",
98+
timeout: Math.min(timeoutMs, DEFAULT_TIMEOUT_MS),
99+
windowsHide: true,
100+
},
101+
);
102+
if (!powershell.error && powershell.status === 0) {
103+
const startTime = parseWindowsProcessStartTime(powershell.stdout);
104+
if (startTime !== null) {
105+
return startTime;
106+
}
107+
}
108+
const remainingMs = deadline - Date.now();
109+
if (remainingMs <= 0) {
110+
return null;
111+
}
112+
const wmic = spawnSync(
113+
windowsWmicPath(),
114+
["process", "where", `ProcessId=${pid}`, "get", "CreationDate", "/value"],
115+
{
116+
timeout: remainingMs,
117+
windowsHide: true,
118+
stdio: ["ignore", "pipe", "ignore"],
119+
},
120+
);
121+
return !wmic.error && wmic.status === 0 ? parseWindowsProcessStartTime(wmic.stdout) : null;
122+
}

‎src/scripts/ci-changed-scope.windows.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ describe("detectChangedScope Windows routing", () => {
9898
for (const identityPath of [
9999
"src/shared/pid-alive.ts",
100100
"test/e2e/windows-cron-process-identity.e2e.test.ts",
101-
"src/infra/windows-port-pids.ts",
101+
"src/infra/windows-process-start.ts",
102102
"src/infra/gateway-lock.ts",
103103
"src/node-host/node-worker-process-identity.ts",
104104
"src/cron/store/run-receipt-store.ts",

‎src/shared/pid-alive.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ const readWindowsProcessStartTimeSyncMock = vi.hoisted(() =>
1414
vi.fn<(pid: number) => number | null>(() => null),
1515
);
1616

17-
vi.mock("../infra/windows-port-pids.js", async (importOriginal) => ({
18-
...(await importOriginal<typeof import("../infra/windows-port-pids.js")>()),
17+
vi.mock("../infra/windows-process-start.js", async (importOriginal) => ({
18+
...(await importOriginal<typeof import("../infra/windows-process-start.js")>()),
1919
readWindowsProcessStartTimeSync: readWindowsProcessStartTimeSyncMock,
2020
}));
2121

‎src/shared/pid-alive.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// PID liveness helpers check whether process ids still refer to active processes.
22
import childProcess from "node:child_process";
33
import fsSync from "node:fs";
4-
import { readWindowsProcessStartTimeSync } from "../infra/windows-port-pids.js";
4+
import { readWindowsProcessStartTimeSync } from "../infra/windows-process-start.js";
55

66
const PROCESS_START_TIMEOUT_MS = 1000;
77
// Cron reads its own identity on every tick. Cache only a successful Windows

0 commit comments

Comments
 (0)