Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge cb6fa9c8ea Use schema decoding for Effect parsing paths
Co-authored-by: Julius Marminge <[email protected]>
2026-05-21 16:07:18 +00:00
5 changed files with 162 additions and 173 deletions

No files matched your search

@@ -1,4 +1,4 @@
import { assert, describe, 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";
@@ -41,7 +41,7 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
);
assert.deepEqual(rows, [
expect(rows).toEqual([
{
pid: 10,
ppid: 1,
@@ -66,6 +66,56 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("parses Windows process JSON through schemas", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(`
[
{
"ProcessId": 4242,
"ParentProcessId": 100,
"CommandLine": "node server.js",
"WorkingSetSize": 4096.7,
"PercentProcessorTime": 2.5,
"Status": "Running"
},
{
"ProcessId": 0,
"ParentProcessId": 100,
"Name": "invalid.exe"
},
{
"ProcessId": 4243,
"ParentProcessId": 4242,
"Name": "child.exe"
}
]
`);
assert.deepEqual(rows, [
{
pid: 4242,
ppid: 100,
pgid: null,
status: "Running",
cpuPercent: 2.5,
rssBytes: 4097,
elapsed: "",
command: "node server.js",
},
{
pid: 4243,
ppid: 4242,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "child.exe",
},
]);
}),
);
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
@@ -125,21 +175,15 @@ describe("ProcessDiagnostics", () => {
],
});
assert.equal(diagnostics.serverPid, 100);
assert.equal(DateTime.formatIso(diagnostics.readAt), "2026-05-05T10:00:00.000Z");
assert.equal(diagnostics.processCount, 2);
assert.equal(diagnostics.totalRssBytes, 6_000);
assert.equal(diagnostics.totalCpuPercent, 4.75);
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[101, 102],
);
assert.deepEqual(
diagnostics.processes.map((process) => process.depth),
[0, 1],
);
assert.equal(Option.getOrNull(diagnostics.processes[0]!.pgid), 100);
assert.deepEqual(diagnostics.processes[0]?.childPids, [102]);
expect(diagnostics.serverPid).toBe(100);
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
expect(diagnostics.processCount).toBe(2);
expect(diagnostics.totalRssBytes).toBe(6_000);
expect(diagnostics.totalCpuPercent).toBe(4.75);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
}),
);
@@ -182,10 +226,7 @@ describe("ProcessDiagnostics", () => {
],
});
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[101, 102, 103],
);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
}),
);
@@ -218,11 +259,8 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[4242],
);
assert.deepEqual(commands, [
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
expect(commands).toEqual([
{
command: "ps",
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
@@ -231,63 +269,6 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("decodes Windows process rows from schema-backed 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: [
"[",
'{"ProcessId":4242,"ParentProcessId":1,"Name":"node.exe","CommandLine":"node server.js","Status":"Running","WorkingSetSize":2048,"PercentProcessorTime":12.5},',
'{"ProcessId":4243,"ParentProcessId":4242,"Name":"fallback.exe","CommandLine":"","Status":"","WorkingSetSize":-5,"PercentProcessorTime":-1},',
'{"ProcessId":0,"ParentProcessId":4242,"Name":"ignored.exe"}',
"]",
].join(""),
}),
);
}),
);
const rows = yield* ProcessDiagnostics.readProcessRows("win32").pipe(
Effect.provide(spawnerLayer),
);
assert.deepEqual(rows, [
{
pid: 4242,
ppid: 1,
pgid: null,
status: "Running",
cpuPercent: 12.5,
rssBytes: 2048,
elapsed: "",
command: "node server.js",
},
{
pid: 4243,
ppid: 4242,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "fallback.exe",
},
]);
assert.equal(commands[0]?.command, "powershell.exe");
assert.match(commands[0]?.args.join(" ") ?? "", /Get-CimInstance Win32_Process/);
}),
);
it.effect("does not allow signaling the diagnostics query process", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
@@ -310,7 +291,7 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
assert.deepEqual(result, {
expect(result).toEqual({
pid: 4242,
signal: "SIGINT",
signaled: false,
@@ -26,9 +26,23 @@ export interface ProcessRow {
readonly command: string;
}
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 PROCESS_QUERY_TIMEOUT = Duration.seconds(1);
const WindowsProcessRecord = Schema.Struct({
ProcessId: Schema.Number,
ParentProcessId: Schema.Number,
CommandLine: Schema.optional(Schema.String),
Name: Schema.optional(Schema.String),
WorkingSetSize: Schema.optional(Schema.Number),
PercentProcessorTime: Schema.optional(Schema.Number),
Status: Schema.optional(Schema.String),
});
type WindowsProcessRecord = typeof WindowsProcessRecord.Type;
const WindowsProcessJson = Schema.fromJsonString(Schema.Unknown);
const decodeWindowsProcessRecord = Schema.decodeUnknownOption(WindowsProcessRecord);
const decodeWindowsProcessJson = Schema.decodeUnknownOption(WindowsProcessJson);
export interface ProcessDiagnosticsShape {
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
@@ -52,24 +66,6 @@ class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnostics
) {}
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
const WindowsProcessRecordJson = Schema.Struct({
ProcessId: Schema.optional(Schema.Number),
ParentProcessId: Schema.optional(Schema.Number),
Name: Schema.optional(Schema.String),
CommandLine: Schema.optional(Schema.String),
Status: Schema.optional(Schema.String),
WorkingSetSize: Schema.optional(Schema.Number),
PercentProcessorTime: Schema.optional(Schema.Number),
});
type WindowsProcessRecordJson = typeof WindowsProcessRecordJson.Type;
const WindowsProcessJson = Schema.Union([
WindowsProcessRecordJson,
Schema.Array(WindowsProcessRecordJson),
]);
const decodeWindowsProcessJson = Schema.decodeUnknownOption(
Schema.fromJsonString(WindowsProcessJson),
);
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
return new ProcessDiagnosticsError({
message,
@@ -92,13 +88,8 @@ function parseNumber(value: string): number | null {
return Number.isFinite(parsed) ? parsed : null;
}
function finiteNumberOption(value: number | undefined): Option.Option<number> {
return typeof value === "number" && Number.isFinite(value) ? Option.some(value) : Option.none();
}
function nonEmptyStringOption(value: string | undefined): Option.Option<string> {
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
}
const nonEmptyWindowsString = (value: string | undefined): Option.Option<string> =>
Option.fromUndefinedOr(value).pipe(Option.filter((text) => text.trim().length > 0));
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
const rows: ProcessRow[] = [];
@@ -165,34 +156,37 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function normalizeWindowsProcessRow(record: WindowsProcessRecordJson): Option.Option<ProcessRow> {
const pid = finiteNumberOption(record.ProcessId).pipe(Option.filter((value) => value > 0));
const ppid = finiteNumberOption(record.ParentProcessId).pipe(
Option.filter((value) => value >= 0),
);
const commandLine = nonEmptyStringOption(record.CommandLine).pipe(
Option.orElse(() => nonEmptyStringOption(record.Name)),
function normalizeWindowsProcessRow(record: WindowsProcessRecord): Option.Option<ProcessRow> {
const pid = Number.isInteger(record.ProcessId) ? Option.some(record.ProcessId) : Option.none();
const ppid = Number.isInteger(record.ParentProcessId)
? Option.some(record.ParentProcessId)
: Option.none();
const commandLine = nonEmptyWindowsString(record.CommandLine).pipe(
Option.orElse(() => nonEmptyWindowsString(record.Name)),
);
const workingSet =
record.WorkingSetSize !== undefined && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
record.PercentProcessorTime !== undefined && Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
if (Option.isNone(pid) || Option.isNone(ppid) || Option.isNone(commandLine)) {
return Option.none();
if (
Option.isNone(pid) ||
pid.value <= 0 ||
Option.isNone(ppid) ||
ppid.value < 0 ||
Option.isNone(commandLine)
) {
return Option.none<ProcessRow>();
}
const workingSet = finiteNumberOption(record.WorkingSetSize).pipe(
Option.map((value) => Math.max(0, Math.round(value))),
Option.getOrElse(() => 0),
);
const cpuPercent = finiteNumberOption(record.PercentProcessorTime).pipe(
Option.map((value) => Math.max(0, value)),
Option.getOrElse(() => 0),
);
const status = nonEmptyStringOption(record.Status).pipe(Option.getOrElse(() => "Live"));
return Option.some({
pid: pid.value,
ppid: ppid.value,
pgid: null,
status,
status: record.Status !== undefined && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
@@ -200,16 +194,22 @@ function normalizeWindowsProcessRow(record: WindowsProcessRecordJson): Option.Op
});
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
export function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
const decoded = decodeWindowsProcessJson(output);
if (Option.isNone(decoded)) {
return [];
}
const records = Array.isArray(decoded.value) ? decoded.value : [decoded.value];
const parsed = decodeWindowsProcessJson(output);
if (Option.isNone(parsed)) return [];
const records = Array.isArray(parsed.value) ? parsed.value : [parsed.value];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return Option.isSome(row) ? [row.value] : [];
const decoded = decodeWindowsProcessRecord(record);
return Option.match(decoded, {
onNone: () => [],
onSome: (windowsRecord) =>
Option.match(normalizeWindowsProcessRow(windowsRecord), {
onNone: () => [],
onSome: (row) => [row],
}),
});
});
}
@@ -14,7 +14,6 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
interface TraceRecordLike {
readonly name?: unknown;
@@ -66,8 +65,6 @@ interface TraceDiagnosticsErrorSummary {
const DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000;
const TOP_LIMIT = 10;
const RECENT_LIMIT = 20;
const decodeTraceRecordJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyArray<string> {
const backupCount = Math.max(0, Math.floor(maxFiles));
const backups = Array.from(
@@ -220,13 +217,14 @@ export function aggregateTraceDiagnostics(
for (const line of lines) {
if (line.trim().length === 0) continue;
const decoded = decodeTraceRecordJson(line);
if (Option.isNone(decoded)) {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
parseErrorCount += 1;
continue;
}
const parsed = decoded.value;
if (!isRecordObject(parsed)) {
parseErrorCount += 1;
continue;
@@ -67,4 +67,24 @@ describe("VcsProjectConfig", () => {
}),
);
});
it.layer(TestLayer)("falls back to auto when config is invalid JSON", (it) => {
it.effect("returns auto", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-config-test-",
});
const configDir = path.join(root, ".t3code");
yield* fileSystem.makeDirectory(configDir, { recursive: true });
yield* fileSystem.writeFileString(path.join(configDir, "vcs.json"), "{ nope");
const config = yield* VcsProjectConfig.VcsProjectConfig;
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
}),
);
});
});
+18 -28
View File
@@ -2,6 +2,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -15,16 +16,10 @@ const ProjectVcsConfig = Schema.Struct({
),
vcsKind: Schema.optional(VcsDriverKind),
});
const isProjectVcsConfig = Schema.is(ProjectVcsConfig);
const ProjectVcsConfigJson = Schema.fromJsonString(ProjectVcsConfig);
const decodeProjectVcsConfigJson = Schema.decodeUnknownOption(ProjectVcsConfigJson);
interface ProjectVcsConfigFile {
readonly vcs?:
| {
readonly kind?: VcsDriverKindType | undefined;
}
| undefined;
readonly vcsKind?: VcsDriverKindType | undefined;
}
type ProjectVcsConfigFile = typeof ProjectVcsConfig.Type;
export interface VcsProjectConfigResolveInput {
readonly cwd: string;
@@ -45,13 +40,8 @@ function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto
return config.vcs?.kind ?? config.vcsKind ?? "auto";
}
function parseConfig(raw: string): ProjectVcsConfigFile | null {
try {
const parsed = JSON.parse(raw) as unknown;
return isProjectVcsConfig(parsed) ? parsed : null;
} catch {
return null;
}
function parseConfig(raw: string): Option.Option<ProjectVcsConfigFile> {
return decodeProjectVcsConfigJson(raw);
}
export const make = Effect.fn("makeVcsProjectConfig")(function* () {
@@ -63,12 +53,12 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
while (true) {
const candidate = path.join(current, ".t3code", "vcs.json");
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
return candidate;
return Option.some(candidate);
}
const parent = path.dirname(current);
if (parent === current) {
return null;
return Option.none<string>();
}
current = parent;
}
@@ -78,26 +68,27 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
configPath: string,
) {
const raw = yield* fileSystem.readFileString(configPath).pipe(
Effect.map(Option.some),
Effect.catch((error) =>
Effect.logWarning("failed to read VCS project config", {
configPath,
error,
}).pipe(Effect.as(null)),
}).pipe(Effect.as(Option.none<string>())),
),
);
if (raw === null) {
if (Option.isNone(raw)) {
return "auto" as const;
}
const parsed = parseConfig(raw);
if (parsed === null) {
const parsed = parseConfig(raw.value);
if (Option.isNone(parsed)) {
yield* Effect.logWarning("invalid VCS project config", {
configPath,
});
return "auto" as const;
}
return configuredKind(parsed);
return configuredKind(parsed.value);
});
const resolveKind: VcsProjectConfigShape["resolveKind"] = Effect.fn(
@@ -108,11 +99,10 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
}
const configPath = yield* findConfigPath(input.cwd);
if (configPath === null) {
return "auto";
}
return yield* readConfiguredKind(configPath);
return yield* Option.match(configPath, {
onNone: () => Effect.succeed("auto" as const),
onSome: readConfiguredKind,
});
});
return VcsProjectConfig.of({