Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge 048e0fb9ac Tighten Windows process number guards
Co-authored-by: Julius Marminge <[email protected]>
2026-07-09 16:09:48 +00:00
Cursor AgentandJulius Marminge f179a675e3 Format process diagnostics parser
Co-authored-by: Julius Marminge <[email protected]>
2026-07-09 16:09:10 +00:00
Cursor AgentandJulius Marminge 3b6702eb1e Use schema parsing for Windows process diagnostics
Co-authored-by: Julius Marminge <[email protected]>
2026-07-09 16:07:46 +00:00
2 changed files with 202 additions and 41 deletions

No files matched your search

@@ -1,4 +1,4 @@
import { describe, expect, it } from "@effect/vitest";
import { assert, describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -32,6 +32,26 @@ function mockHandle(result: {
});
}
function readWindowsRows(stdout: string) {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> = [];
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner)({
spawn: (command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
commands.push({ command: childProcess.command, args: childProcess.args });
return Effect.succeed(mockHandle({ stdout }));
},
});
return ProcessDiagnostics.readProcessRows.pipe(
Effect.map((rows) => ({ rows, commands })),
Effect.provide(spawnerLayer),
Effect.provideService(HostProcessPlatform, "win32"),
);
}
describe("ProcessDiagnostics", () => {
it.effect("parses POSIX ps rows with full commands", () =>
Effect.sync(() => {
@@ -67,6 +87,110 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("parses Windows PowerShell JSON rows through the child process layer", () =>
Effect.gen(function* () {
const { rows, commands } = yield* readWindowsRows(`[
{
"ProcessId": 100,
"ParentProcessId": 1,
"Name": "node.exe",
"CommandLine": "node server.js",
"Status": "Running",
"WorkingSetSize": 4096.4,
"PercentProcessorTime": 1.5
},
{
"ProcessId": 101,
"ParentProcessId": 100,
"Name": "agent.exe",
"CommandLine": null,
"Status": null,
"WorkingSetSize": -128,
"PercentProcessorTime": -2
},
{
"ProcessId": 0,
"ParentProcessId": 100,
"Name": "skip-zero-pid.exe"
},
{
"ProcessId": 102,
"Name": "skip-missing-parent.exe"
},
{
"ProcessId": "bad",
"ParentProcessId": 100,
"Name": "skip-schema-invalid.exe"
}
]`);
assert.deepStrictEqual(rows, [
{
pid: 100,
ppid: 1,
pgid: null,
status: "Running",
cpuPercent: 1.5,
rssBytes: 4096,
elapsed: "",
command: "node server.js",
},
{
pid: 101,
ppid: 100,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "agent.exe",
},
]);
assert.strictEqual(commands[0]?.command, "powershell.exe");
assert.deepStrictEqual(commands[0]?.args.slice(0, 3), [
"-NoProfile",
"-NonInteractive",
"-Command",
]);
assert.isTrue(commands[0]?.args[3]?.includes("Get-CimInstance Win32_Process") === true);
}),
);
it.effect("parses a single Windows PowerShell JSON object", () =>
Effect.gen(function* () {
const { rows } = yield* readWindowsRows(`{
"ProcessId": 200,
"ParentProcessId": 100,
"Name": "single.exe",
"CommandLine": null,
"Status": "",
"WorkingSetSize": 2048,
"PercentProcessorTime": 3
}`);
assert.deepStrictEqual(rows, [
{
pid: 200,
ppid: 100,
pgid: null,
status: "Live",
cpuPercent: 3,
rssBytes: 2048,
elapsed: "",
command: "single.exe",
},
]);
}),
);
it.effect("returns no Windows rows for invalid JSON", () =>
Effect.gen(function* () {
const { rows } = yield* readWindowsRows("not-json");
assert.deepStrictEqual(rows, []);
}),
);
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
@@ -136,6 +136,35 @@ function parseNumber(value: string): number | null {
return Number.isFinite(parsed) ? parsed : null;
}
const WindowsProcessRowJson = Schema.Struct({
ProcessId: Schema.optional(Schema.Number),
ParentProcessId: Schema.optional(Schema.Number),
CommandLine: Schema.optional(Schema.NullOr(Schema.String)),
Name: Schema.optional(Schema.NullOr(Schema.String)),
Status: Schema.optional(Schema.NullOr(Schema.String)),
WorkingSetSize: Schema.optional(Schema.Number),
PercentProcessorTime: Schema.optional(Schema.Number),
});
type WindowsProcessRowJson = typeof WindowsProcessRowJson.Type;
const WindowsProcessRowsJson = Schema.fromJsonString(
Schema.Union([Schema.Array(Schema.Unknown), Schema.Unknown]),
);
const decodeWindowsProcessRowsJson = Schema.decodeUnknownOption(WindowsProcessRowsJson);
const decodeWindowsProcessRowJson = Schema.decodeUnknownOption(WindowsProcessRowJson);
function positiveIntegerOption(value: number | undefined): Option.Option<number> {
return typeof value === "number" && Number.isInteger(value) && value > 0
? Option.some(value)
: Option.none();
}
function nonNegativeIntegerOption(value: number | undefined): Option.Option<number> {
return typeof value === "number" && Number.isInteger(value) && value >= 0
? Option.some(value)
: Option.none();
}
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
const rows: ProcessRow[] = [];
const rowPattern =
@@ -201,51 +230,59 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
const commandLine =
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
? record.CommandLine
: typeof record.Name === "string"
? record.Name
: null;
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
function nonEmptyStringOption(value: string | null | undefined): Option.Option<string> {
return Option.fromNullishOr(value).pipe(Option.filter((text) => text.trim().length > 0));
}
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
pid,
ppid,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
function normalizeWindowsProcessRow(record: WindowsProcessRowJson): Option.Option<ProcessRow> {
return Option.gen(function* () {
const pid = yield* positiveIntegerOption(record.ProcessId);
const ppid = yield* nonNegativeIntegerOption(record.ParentProcessId);
const commandLine = yield* Option.firstSomeOf([
nonEmptyStringOption(record.CommandLine),
nonEmptyStringOption(record.Name),
]);
const workingSet =
record.WorkingSetSize === undefined || !Number.isFinite(record.WorkingSetSize)
? 0
: Math.max(0, Math.round(record.WorkingSetSize));
const cpuPercent =
record.PercentProcessorTime === undefined || !Number.isFinite(record.PercentProcessorTime)
? 0
: Math.max(0, record.PercentProcessorTime);
return {
pid,
ppid,
pgid: null,
status: Option.getOrElse(nonEmptyStringOption(record.Status), () => "Live"),
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
});
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
return [];
}
return Option.match(decodeWindowsProcessRowsJson(output), {
onNone: () => [],
onSome: (payload) => {
const records = Array.isArray(payload) ? payload : [payload];
return records.flatMap((record) =>
Option.match(
Option.flatMap(decodeWindowsProcessRowJson(record), normalizeWindowsProcessRow),
{
onNone: () => [],
onSome: (row) => [row],
},
),
);
},
});
}
export function buildDescendantEntries(