Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(daemon): support diagnostics on Windows

Gus1f9ae0703f84
diff --git a/src/daemon/src/diagnostics/coordinator.test.ts b/src/daemon/src/diagnostics/coordinator.test.ts
index 4ed1580d8..19436fe5e 100644
--- a/src/daemon/src/diagnostics/coordinator.test.ts
+++ b/src/daemon/src/diagnostics/coordinator.test.ts
@@ -16,7 +16,7 @@ import {
writeSync,
} from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import type { Readable } from "node:stream";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { DiagnosticCollectCommand, DiagnosticReportFailureCode } from "@alook/shared";
@@ -71,7 +71,7 @@ interface CoordinatorModule {
checkpoint?: (point: CrashPoint) => void;
fsOps?: {
randomSuffix(): string;
- open(path: string, flags: "wx" | "r", mode?: number): number;
+ open(path: string, flags: "wx" | "r" | "r+", mode?: number): number;
write(fd: number, bytes: Uint8Array): void;
fsync(fd: number): void;
close(fd: number): void;
@@ -289,7 +289,7 @@ describe("B2c durable diagnostic coordinator", () => {
let suffix = 0;
const fsOps = {
randomSuffix: vi.fn(() => `nonce-${++suffix}`),
- open: vi.fn((path: string, flags: "wx" | "r", mode?: number) => {
+ open: vi.fn((path: string, flags: "wx" | "r" | "r+", mode?: number) => {
operations.push({ op: "open", path, flags, mode });
return openSync(path, flags, mode);
}),
@@ -331,9 +331,26 @@ describe("B2c durable diagnostic coordinator", () => {
const exclusiveOpens = operations.filter((operation) => operation.op === "open" && operation.flags === "wx");
expect(exclusiveOpens).toHaveLength(2);
expect(exclusiveOpens.every((operation) => operation.mode === 0o600)).toBe(true);
+ const archiveOpen = operations.find((operation) => operation.op === "open" && operation.flags === "r+");
+ expect(archiveOpen?.path).toBe(bundleTemps[0]);
+ const archiveOpenIndex = operations.indexOf(archiveOpen!);
+ expect(operations.slice(archiveOpenIndex, archiveOpenIndex + 4).map(({ op }) => op)).toEqual([
+ "open",
+ "fsync",
+ "close",
+ "rename",
+ ]);
+ expect(harness.uploaded).toEqual([{
+ meta: {
+ reportId: "dbr_report_1",
+ sizeBytes: bytes.length,
+ sha256: createHash("sha256").update(bytes).digest("hex"),
+ },
+ bytes,
+ }]);
const tempPaths = [...exclusiveOpens.map((operation) => operation.path!), ...bundleTemps];
expect(new Set(tempPaths).size).toBe(tempPaths.length);
- expect(tempPaths.every((path) => join(path, "..") !== path && path.startsWith(`${diagnosticsDir(harness.machineDir)}/`))).toBe(true);
+ expect(tempPaths.every((path) => dirname(path) === diagnosticsDir(harness.machineDir))).toBe(true);
const names = operations.map((operation) => operation.op);
let cursor = 0;
@@ -356,7 +373,7 @@ describe("B2c durable diagnostic coordinator", () => {
let firstExclusivePath: string | null = null;
const fsOps = {
randomSuffix: vi.fn(() => suffixes.shift() ?? `fresh-${Date.now()}`),
- open: vi.fn((path: string, flags: "wx" | "r", mode?: number) => {
+ open: vi.fn((path: string, flags: "wx" | "r" | "r+", mode?: number) => {
if (flags === "wx" && firstExclusivePath === null) {
firstExclusivePath = path;
symlinkSync(outside, path);
diff --git a/src/daemon/src/diagnostics/coordinator.ts b/src/daemon/src/diagnostics/coordinator.ts
index 4662b2bff..825088100 100644
--- a/src/daemon/src/diagnostics/coordinator.ts
+++ b/src/daemon/src/diagnostics/coordinator.ts
@@ -60,7 +60,7 @@ type Sidecar = CollectingSidecar | ReadySidecar;
interface FsOps {
randomSuffix(): string;
- open(path: string, flags: "wx" | "r", mode?: number): number;
+ open(path: string, flags: "wx" | "r" | "r+", mode?: number): number;
write(fd: number, bytes: Uint8Array): void;
fsync(fd: number): void;
close(fd: number): void;
@@ -304,7 +304,7 @@ export function createDiagnosticReportCoordinator(args: {
const temp = join(dir, `.${command.reportId}.archive.${fsOps.randomSuffix()}.tmp`);
const artifact = await args.buildBundle({ command, outputPath: temp });
checkpoint("archive_temp_written");
- const fd = fsOps.open(artifact.path, "r");
+ const fd = fsOps.open(artifact.path, "r+");
try { fsOps.fsync(fd); checkpoint("archive_temp_fsynced"); } finally { fsOps.close(fd); }
fsOps.rename(artifact.path, archivePath(command.reportId));
if (process.platform !== "win32") chmodSync(archivePath(command.reportId), 0o600);
diff --git a/src/daemon/src/diagnostics/snapshotReader.test.ts b/src/daemon/src/diagnostics/snapshotReader.test.ts
index 65b94c9a4..e99d42a2b 100644
--- a/src/daemon/src/diagnostics/snapshotReader.test.ts
+++ b/src/daemon/src/diagnostics/snapshotReader.test.ts
@@ -2,6 +2,7 @@ import { execFileSync } from "node:child_process";
import {
appendFileSync,
closeSync,
+ constants,
existsSync,
mkdtempSync,
openSync,
@@ -19,6 +20,18 @@ import {
type RotatingFileSink,
} from "../util/rotatingFileSink.js";
+const fsMocks = vi.hoisted(() => ({
+ lstatSync: vi.fn(),
+ actualLstatSync: null as null | typeof import("node:fs").lstatSync,
+}));
+
+vi.mock("node:fs", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:fs")>();
+ fsMocks.actualLstatSync = actual.lstatSync;
+ fsMocks.lstatSync.mockImplementation(actual.lstatSync);
+ return { ...actual, lstatSync: fsMocks.lstatSync };
+});
+
type SnapshotSourceName = "daemon_log" | "fsm_trace";
type SnapshotWarningCode =
| "source_unavailable"
@@ -78,6 +91,9 @@ function tempDir(): string {
afterEach(() => {
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
dirs.clear();
+ fsMocks.lstatSync.mockReset();
+ fsMocks.lstatSync.mockImplementation(fsMocks.actualLstatSync!);
+ vi.restoreAllMocks();
});
describe("B2c snapshot reader", () => {
@@ -315,4 +331,42 @@ describe("B2c snapshot reader", () => {
warnings: ["line_too_long"],
});
});
+
+ it("prechecks and rejects a symlink on Windows without reading its target", async () => {
+ vi.spyOn(process, "platform", "get").mockReturnValue("win32");
+ const api = await loadSubject();
+ const dir = tempDir();
+ const targetPath = join(dir, "target.json");
+ const linkPath = join(dir, "status-link.json");
+ writeFileSync(targetPath, JSON.stringify({ secret: "must-not-be-read" }));
+ symlinkSync(targetPath, linkPath);
+
+ await expect(api.readPinnedJsonFile({ path: linkPath, maxBytes: 1024 })).resolves.toEqual({
+ value: null,
+ warnings: ["source_unavailable"],
+ });
+ expect(fsMocks.lstatSync).toHaveBeenCalledWith(linkPath);
+ });
+
+ it.runIf("O_NOFOLLOW" in constants && constants.O_NOFOLLOW !== 0)(
+ "uses reliable non-Windows O_NOFOLLOW without fallback lstat",
+ async () => {
+ vi.spyOn(process, "platform", "get").mockReturnValue("linux");
+ fsMocks.lstatSync.mockImplementation(() => {
+ throw new Error("fallback lstat must not run");
+ });
+ const api = await loadSubject();
+ const dir = tempDir();
+ const targetPath = join(dir, "target.json");
+ const linkPath = join(dir, "status-link.json");
+ writeFileSync(targetPath, JSON.stringify({ secret: "must-not-be-read" }));
+ symlinkSync(targetPath, linkPath);
+
+ await expect(api.readPinnedJsonFile({ path: linkPath, maxBytes: 1024 })).resolves.toEqual({
+ value: null,
+ warnings: ["source_unavailable"],
+ });
+ expect(fsMocks.lstatSync).not.toHaveBeenCalled();
+ },
+ );
});
diff --git a/src/daemon/src/diagnostics/snapshotReader.ts b/src/daemon/src/diagnostics/snapshotReader.ts
index 5371a37ed..e772a0c3f 100644
--- a/src/daemon/src/diagnostics/snapshotReader.ts
+++ b/src/daemon/src/diagnostics/snapshotReader.ts
@@ -1,4 +1,4 @@
-import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
+import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "node:fs";
import type { RotatingFileSink } from "../util/rotatingFileSink.js";
import type {
SnapshotReadResult,
@@ -185,6 +185,12 @@ export async function readPinnedJsonFile(args: {
let fd: number | null = null;
try {
const noFollow = "O_NOFOLLOW" in constants ? constants.O_NOFOLLOW : 0;
+ if (process.platform === "win32" || noFollow === 0) {
+ const preopenStat = lstatSync(args.path);
+ if (!preopenStat.isFile() || preopenStat.isSymbolicLink()) {
+ return { value: null, warnings: ["source_unavailable"] };
+ }
+ }
fd = openSync(args.path, constants.O_RDONLY | noFollow);
const stat = fstatSync(fd);
if (!stat.isFile()) return { value: null, warnings: ["source_unavailable"] };
diff --git a/src/daemon/src/timeline/timeline.test.ts b/src/daemon/src/timeline/timeline.test.ts
index 199c444b8..aa2dcfe1a 100644
--- a/src/daemon/src/timeline/timeline.test.ts
+++ b/src/daemon/src/timeline/timeline.test.ts
@@ -290,7 +290,7 @@ describe("daily timeline hard cap", () => {
expect(Buffer.byteLength(JSON.stringify(overflow), "utf8") + 1).toBe(TIMELINE_MAX_BYTES + 3);
expect(appendEntry(dir, overflow, NOW)).toBe(false);
expect(fs.readFileSync(file)).toEqual(before);
- });
+ }, 30_000);
it("rejects a newest row that fits alone but cannot coexist with the required barrier sentinel", () => {
const dir = mkDir();