Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 0bb0f53822 Format Windows process diagnostics parser
Co-authored-by: Julius Marminge <[email protected]>
2026-06-29 16:13:09 +00:00
Cursor AgentandJulius Marminge f3da91a0d7 Use Effect Schema for Windows process diagnostics
Co-authored-by: Julius Marminge <[email protected]>
2026-06-29 16:07:02 +00:00
3 changed files with 224 additions and 247 deletions

No files matched your search

@@ -67,6 +67,98 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("parses Windows CIM JSON process rows", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(`[
{
"ProcessId": 10,
"ParentProcessId": 1,
"Name": "node.exe",
"CommandLine": "node server.js",
"Status": "Running",
"WorkingSetSize": 4096,
"PercentProcessorTime": 12.5
},
{
"ProcessId": "invalid",
"ParentProcessId": 10,
"Name": "ignored.exe"
},
{
"ProcessId": 11,
"ParentProcessId": 10,
"Name": "agent.exe",
"CommandLine": null,
"Status": null,
"WorkingSetSize": -128,
"PercentProcessorTime": -1
}
]`);
assert.deepStrictEqual(rows, [
{
pid: 10,
ppid: 1,
pgid: null,
status: "Running",
cpuPercent: 12.5,
rssBytes: 4096,
elapsed: "",
command: "node server.js",
},
{
pid: 11,
ppid: 10,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "agent.exe",
},
]);
}),
);
it.effect("parses single Windows CIM JSON process objects", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(`{
"ProcessId": 42,
"ParentProcessId": 10,
"Name": "agent.exe",
"CommandLine": "",
"WorkingSetSize": 2048,
"PercentProcessorTime": 5
}`);
assert.deepStrictEqual(rows, [
{
pid: 42,
ppid: 10,
pgid: null,
status: "Live",
cpuPercent: 5,
rssBytes: 2048,
elapsed: "",
command: "agent.exe",
},
]);
}),
);
it.effect("ignores malformed Windows CIM JSON output", () =>
Effect.sync(() => {
assert.deepStrictEqual(ProcessDiagnostics.parseWindowsProcessRows("{not json"), []);
assert.deepStrictEqual(
ProcessDiagnostics.parseWindowsProcessRows(`{
"ProcessId": 42,
"Name": "missing-parent.exe"
}`),
[],
);
}),
);
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
@@ -220,84 +312,6 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("queries Windows processes through schema-decoded PowerShell JSON", () =>
Effect.gen(function* () {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
[];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((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: JSON.stringify([
{
ProcessId: process.pid,
ParentProcessId: 1,
Name: "node.exe",
CommandLine: "t3 server",
Status: "Running",
WorkingSetSize: 1024,
PercentProcessorTime: 0,
},
{
ProcessId: 4242,
ParentProcessId: process.pid,
Name: "agent.exe",
CommandLine: "agent.exe --work",
Status: "Running",
WorkingSetSize: 4096.4,
PercentProcessorTime: 12.25,
},
{
ProcessId: "invalid",
ParentProcessId: process.pid,
Name: "ignored.exe",
},
]),
}),
);
}),
);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
Effect.flatMap((pd) => pd.read),
Effect.provide(layer),
Effect.provideService(HostProcessPlatform, "win32"),
);
assert.deepStrictEqual(
diagnostics.processes.map((process) => ({
pid: process.pid,
ppid: process.ppid,
command: process.command,
rssBytes: process.rssBytes,
cpuPercent: process.cpuPercent,
})),
[
{
pid: 4242,
ppid: process.pid,
command: "agent.exe --work",
rssBytes: 4096,
cpuPercent: 12.25,
},
],
);
assert.equal(commands[0]?.command, "powershell.exe");
assert.deepStrictEqual(commands[0]?.args.slice(0, 3), [
"-NoProfile",
"-NonInteractive",
"-Command",
]);
}),
);
it.effect("keeps bounded command diagnostics when the process query exits unsuccessfully", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
@@ -28,23 +28,10 @@ export interface ProcessRow {
readonly command: string;
}
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const PROCESS_QUERY_TIMEOUT = Duration.seconds(1);
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
const WindowsProcessRecord = Schema.Struct({
ProcessId: Schema.Number.check(Schema.isFinite()),
ParentProcessId: Schema.Number.check(Schema.isFinite()),
CommandLine: Schema.optional(Schema.Unknown),
Name: Schema.optional(Schema.Unknown),
Status: Schema.optional(Schema.Unknown),
WorkingSetSize: Schema.optional(Schema.Unknown),
PercentProcessorTime: Schema.optional(Schema.Unknown),
});
const WindowsProcessDocument = Schema.fromJsonString(Schema.Unknown);
const decodeWindowsProcessDocument = Schema.decodeUnknownOption(WindowsProcessDocument);
const decodeWindowsProcessRecord = Schema.decodeUnknownOption(WindowsProcessRecord);
export class ProcessDiagnostics extends Context.Service<
ProcessDiagnostics,
{
@@ -134,6 +121,19 @@ const ProcessDiagnosticsError = Schema.Union([
type ProcessDiagnosticsError = typeof ProcessDiagnosticsError.Type;
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
const WindowsCimProcessRecord = Schema.Struct({
ProcessId: Schema.Number,
ParentProcessId: Schema.Number,
Name: Schema.optional(Schema.NullOr(Schema.String)),
CommandLine: Schema.optional(Schema.NullOr(Schema.String)),
Status: Schema.optional(Schema.NullOr(Schema.String)),
WorkingSetSize: Schema.optional(Schema.Number),
PercentProcessorTime: Schema.optional(Schema.Number),
});
type WindowsCimProcessRecord = typeof WindowsCimProcessRecord.Type;
const decodeWindowsProcessJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));
const decodeWindowsProcessRecord = Schema.decodeUnknownOption(WindowsCimProcessRecord);
function parsePositiveInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
@@ -149,14 +149,6 @@ function parseNumber(value: string): number | null {
return Number.isFinite(parsed) ? parsed : null;
}
function finiteNumber(value: unknown): Option.Option<number> {
return typeof value === "number" && Number.isFinite(value) ? Option.some(value) : Option.none();
}
function nonBlankString(value: unknown): Option.Option<string> {
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
}
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
const rows: ProcessRow[] = [];
const rowPattern =
@@ -222,52 +214,48 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function nonEmptyStringOption(value: string | null | undefined): Option.Option<string> {
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
}
function normalizeWindowsProcessRow(value: unknown): Option.Option<ProcessRow> {
const recordOption = decodeWindowsProcessRecord(value);
if (Option.isNone(recordOption)) return Option.none();
const record = recordOption.value;
const pid = record.ProcessId;
const ppid = record.ParentProcessId;
const commandLineOption = nonBlankString(record.CommandLine).pipe(
Option.orElse(() => nonBlankString(record.Name)),
);
return Option.flatMap(decodeWindowsProcessRecord(value), (record: WindowsCimProcessRecord) => {
const pid = record.ProcessId;
const ppid = record.ParentProcessId;
if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(ppid) || ppid < 0) {
return Option.none();
}
if (
!Number.isInteger(pid) ||
pid <= 0 ||
!Number.isInteger(ppid) ||
ppid < 0 ||
Option.isNone(commandLineOption)
) {
return Option.none();
}
const workingSet = Option.getOrElse(
finiteNumber(record.WorkingSetSize).pipe(Option.map((bytes) => Math.max(0, Math.round(bytes)))),
() => 0,
);
const cpuPercent = Option.getOrElse(
finiteNumber(record.PercentProcessorTime).pipe(Option.map((percent) => Math.max(0, percent))),
() => 0,
);
return Option.some({
pid,
ppid,
pgid: null,
status: Option.getOrElse(nonBlankString(record.Status), () => "Live"),
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLineOption.value,
const commandLine = nonEmptyStringOption(record.CommandLine).pipe(
Option.orElse(() => nonEmptyStringOption(record.Name)),
);
return Option.map(commandLine, (command) => ({
pid,
ppid,
pgid: null,
status: Option.getOrElse(nonEmptyStringOption(record.Status), () => "Live"),
cpuPercent:
typeof record.PercentProcessorTime === "number" &&
Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0,
rssBytes:
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0,
elapsed: "",
command,
}));
});
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
export function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
const document = decodeWindowsProcessDocument(output);
if (Option.isNone(document)) return [];
const records = Array.isArray(document.value) ? document.value : [document.value];
const parsed = decodeWindowsProcessJson(output);
if (Option.isNone(parsed)) {
return [];
}
const records = Array.isArray(parsed.value) ? parsed.value : [parsed.value];
return records.flatMap((record) =>
Option.match(normalizeWindowsProcessRow(record), {
onNone: () => [],
@@ -409,7 +397,7 @@ const runProcess = Effect.fn("runProcess")(function* (input: {
} satisfies ProcessOutput;
}).pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
Effect.timeoutOption(PROCESS_QUERY_TIMEOUT),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
@@ -418,7 +406,7 @@ const runProcess = Effect.fn("runProcess")(function* (input: {
command: input.command,
argCount: input.args.length,
cwd,
timeoutMillis: PROCESS_QUERY_TIMEOUT_MS,
timeoutMillis: Duration.toMillis(PROCESS_QUERY_TIMEOUT),
}),
),
onSome: Effect.succeed,
+80 -105
View File
@@ -17,31 +17,22 @@ import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
const TraceRecordLine = Schema.Struct({
name: Schema.String,
traceId: Schema.String,
spanId: Schema.String,
startTimeUnixNano: Schema.optional(Schema.Unknown),
endTimeUnixNano: Schema.String,
durationMs: Schema.Number.check(Schema.isFinite()),
exit: Schema.optional(Schema.Unknown),
events: Schema.optional(Schema.Array(Schema.Unknown)),
});
const decodeTraceRecordLine = Schema.decodeUnknownOption(Schema.fromJsonString(TraceRecordLine));
interface TraceRecordLike {
readonly name?: unknown;
readonly traceId?: unknown;
readonly spanId?: unknown;
readonly startTimeUnixNano?: unknown;
readonly endTimeUnixNano?: unknown;
readonly durationMs?: unknown;
readonly exit?: unknown;
readonly events?: unknown;
}
const TraceExit = Schema.Struct({
_tag: Schema.String,
cause: Schema.optional(Schema.Unknown),
});
const decodeTraceExit = Schema.decodeUnknownOption(TraceExit);
const TraceEvent = Schema.Struct({
name: Schema.optional(Schema.Unknown),
timeUnixNano: Schema.optional(Schema.Unknown),
attributes: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
});
type TraceEvent = typeof TraceEvent.Type;
const decodeTraceEvent = Schema.decodeUnknownOption(TraceEvent);
interface TraceEventLike {
readonly name?: unknown;
readonly timeUnixNano?: unknown;
readonly attributes?: unknown;
}
export interface TraceDiagnosticsOptions {
readonly traceFilePath: string;
@@ -99,38 +90,47 @@ function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyA
return [...backups, traceFilePath];
}
function nonBlankString(value: string): Option.Option<string> {
return value.trim().length > 0 ? Option.some(value) : Option.none();
function isRecordObject(value: unknown): value is TraceRecordLike {
return typeof value === "object" && value !== null;
}
function unixNanoToDateTime(value: unknown): Option.Option<DateTime.Utc> {
if (typeof value !== "string" || value.trim().length === 0) return Option.none();
function toStringValue(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value : null;
}
function toNumberValue(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function unixNanoToDateTime(value: unknown): DateTime.Utc | null {
const text = toStringValue(value);
if (!text) return null;
try {
const millis = Number(BigInt(value) / 1_000_000n);
return DateTime.make(millis);
const millis = Number(BigInt(text) / 1_000_000n);
return Option.getOrNull(DateTime.make(millis));
} catch {
return Option.none();
return null;
}
}
function readExitTag(exit: unknown): Option.Option<string> {
return decodeTraceExit(exit).pipe(Option.flatMap((decoded) => nonBlankString(decoded._tag)));
function readExitTag(exit: unknown): string | null {
if (!isRecordObject(exit) || !("_tag" in exit)) return null;
return toStringValue(exit._tag);
}
function readExitCause(exit: unknown): string {
return Option.getOrElse(
decodeTraceExit(exit).pipe(
Option.flatMap((decoded) => Option.fromNullishOr(decoded.cause)),
Option.filter((cause): cause is string => typeof cause === "string"),
Option.map((cause) => cause.trim()),
Option.filter((cause) => cause.length > 0),
),
() => "Failure",
);
if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
return toStringValue(exit.cause)?.trim() ?? "Failure";
}
function readEventAttributes(event: TraceEvent): Readonly<Record<string, unknown>> {
return event.attributes ?? {};
function isTraceEvent(value: unknown): value is TraceEventLike {
return typeof value === "object" && value !== null;
}
function readEventAttributes(event: TraceEventLike): Readonly<Record<string, unknown>> {
return typeof event.attributes === "object" && event.attributes !== null
? (event.attributes as Readonly<Record<string, unknown>>)
: {};
}
function makeEmptyDiagnostics(input: {
@@ -211,8 +211,8 @@ export function aggregateTraceDiagnostics(
let failureCount = 0;
let interruptionCount = 0;
let slowSpanCount = 0;
let firstSpanAt = Option.none<DateTime.Utc>();
let lastSpanAt = Option.none<DateTime.Utc>();
let firstSpanAt: DateTime.Utc | null = null;
let lastSpanAt: DateTime.Utc | null = null;
const spansByName = new Map<
string,
@@ -229,52 +229,40 @@ export function aggregateTraceDiagnostics(
for (const line of lines) {
if (line.trim().length === 0) continue;
const parsedOption = decodeTraceRecordLine(line);
if (Option.isNone(parsedOption)) {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
parseErrorCount += 1;
continue;
}
const parsed = parsedOption.value;
const nameOption = nonBlankString(parsed.name);
const traceIdOption = nonBlankString(parsed.traceId);
const spanIdOption = nonBlankString(parsed.spanId);
const endedAtOption = unixNanoToDateTime(parsed.endTimeUnixNano);
const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);
if (
Option.isNone(nameOption) ||
Option.isNone(traceIdOption) ||
Option.isNone(spanIdOption) ||
Option.isNone(endedAtOption)
) {
if (!isRecordObject(parsed)) {
parseErrorCount += 1;
continue;
}
const name = toStringValue(parsed.name);
const traceId = toStringValue(parsed.traceId);
const spanId = toStringValue(parsed.spanId);
const durationMs = toNumberValue(parsed.durationMs);
const endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);
const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);
if (!name || !traceId || !spanId || durationMs === null || !endedAt) {
parseErrorCount += 1;
continue;
}
const name = nameOption.value;
const traceId = traceIdOption.value;
const spanId = spanIdOption.value;
const endedAt = endedAtOption.value;
const durationMs = parsed.durationMs;
recordCount += 1;
firstSpanAt = Option.match(startedAt, {
onNone: () => firstSpanAt,
onSome: (spanStartedAt) =>
Option.match(firstSpanAt, {
onNone: () => Option.some(spanStartedAt),
onSome: (currentFirstSpanAt) =>
DateTime.isLessThan(spanStartedAt, currentFirstSpanAt)
? Option.some(spanStartedAt)
: firstSpanAt,
}),
});
lastSpanAt = Option.match(lastSpanAt, {
onNone: () => Option.some(endedAt),
onSome: (currentLastSpanAt) =>
DateTime.isGreaterThan(endedAt, currentLastSpanAt) ? Option.some(endedAt) : lastSpanAt,
});
firstSpanAt =
startedAt && (firstSpanAt === null || DateTime.isLessThan(startedAt, firstSpanAt))
? startedAt
: firstSpanAt;
lastSpanAt =
lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
const exitTag = Option.getOrNull(readExitTag(parsed.exit));
const exitTag = readExitTag(parsed.exit);
const isFailure = exitTag === "Failure";
const isInterrupted = exitTag === "Interrupted";
if (isFailure) failureCount += 1;
@@ -315,18 +303,12 @@ export function aggregateTraceDiagnostics(
});
}
if (parsed.events) {
for (const encodedEvent of parsed.events) {
const eventOption = decodeTraceEvent(encodedEvent);
if (Option.isNone(eventOption)) continue;
const event = eventOption.value;
const attributes = readEventAttributes(event);
const levelOption =
typeof attributes["effect.logLevel"] === "string"
? nonBlankString(attributes["effect.logLevel"])
: Option.none<string>();
if (Option.isNone(levelOption)) continue;
const level = levelOption.value;
if (Array.isArray(parsed.events)) {
for (const rawEvent of parsed.events) {
if (!isTraceEvent(rawEvent)) continue;
const attributes = readEventAttributes(rawEvent);
const level = toStringValue(attributes["effect.logLevel"]);
if (!level) continue;
logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
const normalizedLevel = level.toLowerCase();
@@ -339,15 +321,8 @@ export function aggregateTraceDiagnostics(
continue;
}
const seenAt = Option.getOrElse(unixNanoToDateTime(event.timeUnixNano), () => endedAt);
const message = Option.getOrElse(
Option.fromNullishOr(event.name).pipe(
Option.filter((name): name is string => typeof name === "string"),
Option.map((name) => name.trim()),
Option.filter((name) => name.length > 0),
),
() => "Log event",
);
const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
latestWarningAndErrorLogs.push({
spanName: name,
level,
@@ -379,8 +354,8 @@ export function aggregateTraceDiagnostics(
readAt,
recordCount,
parseErrorCount,
firstSpanAt,
lastSpanAt,
firstSpanAt: Option.fromNullishOr(firstSpanAt),
lastSpanAt: Option.fromNullishOr(lastSpanAt),
failureCount,
interruptionCount,
slowSpanThresholdMs,