From f16295bc1ed6bc4cad8be14294c2fe5c2dfd5f98 Mon Sep 17 00:00:00 2001 From: Vincent Koc Date: Sat, 14 Nov 2026 09:16:49 +0800 Subject: [PATCH] refactor: share script test directory cleanup --- scripts/dev-workers.test.ts | 26 ++--- .../skill-evaluation-runtime.test.ts | 17 +-- scripts/generate-llms-txt.test.ts | 20 +--- scripts/lib/testTempDirectories.ts | 22 ++++ .../bundled-skillspector-diagnostic.test.ts | 16 +-- scripts/security/clawscan-decisions.test.ts | 11 +- .../security/clawscan-diagnostic-pair.test.ts | 13 +-- .../security/clawscan-docker-cleanup.test.ts | 13 +-- .../security/clawscan-plugin-runtime.test.ts | 11 +- scripts/security/clawscan-receipt.test.ts | 13 +-- .../prepublication-report-retention.test.ts | 11 +- .../run-codex-scan-worker-clawscan.test.ts | 106 +++++++++--------- ...run-codex-scan-worker-skillspector.test.ts | 11 +- .../security/run-codex-scan-worker.test.ts | 42 +++---- .../security/run-endor-plugin-scan.test.ts | 13 +-- .../run-prepublication-worker.test.ts | 32 +++--- .../skillspector-exception-diagnostic.test.ts | 13 +-- ...solaris-bundled-diagnostic-runtime.test.ts | 11 +- .../skill-cards/run-skill-card-worker.test.ts | 30 ++--- 19 files changed, 191 insertions(+), 240 deletions(-) create mode 100644 scripts/lib/testTempDirectories.ts diff --git a/scripts/dev-workers.test.ts b/scripts/dev-workers.test.ts index 5c83e28451..09b33ef59e 100644 --- a/scripts/dev-workers.test.ts +++ b/scripts/dev-workers.test.ts @@ -1,7 +1,6 @@ /* @vitest-environment node */ -import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { @@ -13,18 +12,11 @@ import { validateWorkerEnv, WORKERS, } from "./dev-workers"; +import { createTestTempDirectories } from "./lib/testTempDirectories"; -const tempDirs: string[] = []; +const tempDirs = createTestTempDirectories("clawhub-dev-workers-test-"); -afterEach(async () => { - await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); -}); - -async function tempDir() { - const dir = await mkdtemp(join(tmpdir(), "clawhub-dev-workers-test-")); - tempDirs.push(dir); - return dir; -} +afterEach(tempDirs.cleanup); describe("dev-workers", () => { it("parses worker selection and polling options", () => { @@ -58,7 +50,7 @@ describe("dev-workers", () => { }); it("loads .env.local without overriding shell env and aliases VITE_CONVEX_URL", async () => { - const root = await tempDir(); + const root = await tempDirs.create(); await writeFile( join(root, ".env.local"), ["VITE_CONVEX_URL=https://dev.example", "SECURITY_SCAN_WORKER_TOKEN=from-file"].join("\n"), @@ -76,7 +68,7 @@ describe("dev-workers", () => { }); it("aliases VITE_CONVEX_URL from shell env when .env.local is absent", async () => { - const root = await tempDir(); + const root = await tempDirs.create(); const env: NodeJS.ProcessEnv = { VITE_CONVEX_URL: "https://dev.example", SECURITY_SCAN_WORKER_TOKEN: "from-shell", @@ -99,7 +91,7 @@ describe("dev-workers", () => { }); it("skips the default Skill Card worker when NVIDIA tooling is absent", async () => { - const root = await tempDir(); + const root = await tempDirs.create(); const selected = resolveEnabledWorkers({ workers: [], skip: [], @@ -124,7 +116,7 @@ describe("dev-workers", () => { }); it("keeps Codex workers with explicit local opt-in", async () => { - const root = await tempDir(); + const root = await tempDirs.create(); const toolDir = join(root, "nvidia-tooling"); await mkdir(join(toolDir, "AI Transparency Card Automation", "scripts"), { recursive: true }); await writeFile( @@ -147,7 +139,7 @@ describe("dev-workers", () => { }); it("keeps the Skill Card worker when an explicit NVIDIA tool checkout exists", async () => { - const root = await tempDir(); + const root = await tempDirs.create(); const toolDir = join(root, "nvidia-tooling"); await mkdir(join(toolDir, "AI Transparency Card Automation", "scripts"), { recursive: true }); await writeFile( diff --git a/scripts/evaluations/skill-evaluation-runtime.test.ts b/scripts/evaluations/skill-evaluation-runtime.test.ts index 6b99ea91b6..580a8a8cb3 100644 --- a/scripts/evaluations/skill-evaluation-runtime.test.ts +++ b/scripts/evaluations/skill-evaluation-runtime.test.ts @@ -1,31 +1,24 @@ /* @vitest-environment node */ -import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { buildTier3Commands, discoverSkillEvals, resolveRepositoryPath, } from "./skill-evaluation-runtime"; -const temporaryDirectories: string[] = []; +const temporaryDirectories = createTestTempDirectories("clawhub-skill-evals-test-"); async function makeSkill() { - const directory = await mkdtemp(join(tmpdir(), "clawhub-skill-evals-test-")); - temporaryDirectories.push(directory); + const directory = await temporaryDirectories.create(); await writeFile(join(directory, "SKILL.md"), "---\nname: demo\n---\n"); return directory; } -afterEach(async () => { - await Promise.all( - temporaryDirectories - .splice(0) - .map((directory) => rm(directory, { recursive: true, force: true })), - ); -}); +afterEach(temporaryDirectories.cleanup); describe("SkillEvaluator eval discovery", () => { it("discovers the canonical evals/evals.json contract", async () => { diff --git a/scripts/generate-llms-txt.test.ts b/scripts/generate-llms-txt.test.ts index 3f902f956a..fdf983bdc5 100644 --- a/scripts/generate-llms-txt.test.ts +++ b/scripts/generate-llms-txt.test.ts @@ -1,15 +1,14 @@ /* @vitest-environment node */ -import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { readLlmsDocs, renderLlmsTxt, writeLlmsTxt } from "./generate-llms-txt"; +import { createTestTempDirectories } from "./lib/testTempDirectories"; -const temporaryDirectories: string[] = []; +const temporaryDirectories = createTestTempDirectories("clawhub-llms-"); async function temporaryDocs() { - const root = await mkdtemp(join(tmpdir(), "clawhub-llms-")); - temporaryDirectories.push(root); + const root = await temporaryDirectories.create(); const docsDir = join(root, "docs"); await mkdir(docsDir); return docsDir; @@ -19,13 +18,7 @@ async function writeDoc(docsDir: string, filename: string, content: string) { await writeFile(join(docsDir, filename), content, "utf8"); } -afterEach(async () => { - await Promise.all( - temporaryDirectories - .splice(0) - .map((directory) => rm(directory, { recursive: true, force: true })), - ); -}); +afterEach(temporaryDirectories.cleanup); describe("llms.txt generation", () => { it("discovers publishable docs from frontmatter without maintaining a second index", async () => { @@ -89,8 +82,7 @@ describe("llms.txt generation", () => { }); it("writes the static asset once and leaves an identical file untouched", async () => { - const root = await mkdtemp(join(tmpdir(), "clawhub-llms-output-")); - temporaryDirectories.push(root); + const root = await temporaryDirectories.create("clawhub-llms-output-"); const outputFile = join(root, "llms.txt"); await expect(writeLlmsTxt(outputFile)).resolves.toBe(true); diff --git a/scripts/lib/testTempDirectories.ts b/scripts/lib/testTempDirectories.ts new file mode 100644 index 0000000000..9509b78730 --- /dev/null +++ b/scripts/lib/testTempDirectories.ts @@ -0,0 +1,22 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +export function createTestTempDirectories(defaultPrefix: string) { + const directories: string[] = []; + return { + async create(prefix = defaultPrefix) { + const directory = await mkdtemp(join(tmpdir(), prefix)); + directories.push(directory); + return directory; + }, + track(directory: string) { + directories.push(directory); + }, + async cleanup() { + await Promise.all( + directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })), + ); + }, + }; +} diff --git a/scripts/security/bundled-skillspector-diagnostic.test.ts b/scripts/security/bundled-skillspector-diagnostic.test.ts index 0fafbc49a5..2b3bd6b298 100644 --- a/scripts/security/bundled-skillspector-diagnostic.test.ts +++ b/scripts/security/bundled-skillspector-diagnostic.test.ts @@ -1,20 +1,17 @@ /* @vitest-environment node */ -import { chmod, mkdtemp, rm, symlink, truncate, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, rm, symlink, truncate, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, expect, it } from "vitest"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { bundledSkillSpectorTerminalContext } from "./bundled-skillspector-diagnostic"; -const roots: string[] = []; -afterEach(async () => { - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); -}); +const roots = createTestTempDirectories("bundled-terminal-"); +afterEach(roots.cleanup); it.each(["missing", "invalid", "symlink", "world-readable", "oversized"])( "fails closed on %s terminal evidence without echoing labels or raw errors", async (mode) => { - const root = await mkdtemp(join(tmpdir(), "bundled-terminal-")); - roots.push(root); + const root = await roots.create(); const file = join(root, "report.json"); const canary = "private-source-and-credential-canary"; if (mode !== "missing") { @@ -42,8 +39,7 @@ it.each(["missing", "invalid", "symlink", "world-readable", "oversized"])( ); it("retains known failure categories while counting malformed and unknown metadata", async () => { - const root = await mkdtemp(join(tmpdir(), "bundled-terminal-")); - roots.push(root); + const root = await roots.create(); const file = join(root, "report.json"); const canary = "private-arbitrary-analyzer-and-reason"; await writeFile( diff --git a/scripts/security/clawscan-decisions.test.ts b/scripts/security/clawscan-decisions.test.ts index 255d41a544..74fae3edec 100644 --- a/scripts/security/clawscan-decisions.test.ts +++ b/scripts/security/clawscan-decisions.test.ts @@ -1,9 +1,9 @@ /* @vitest-environment node */ import { createHash } from "node:crypto"; -import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { validateDecisionsRun } from "./clawscan-decisions"; import * as dockerCleanup from "./clawscan-docker-cleanup"; import { clawScanExposure, type ClawScanExposure } from "./clawscan-exposure"; @@ -118,14 +118,14 @@ function fixture(verdict = "benign") { }, }; } -const dirs: string[] = []; +const dirs = createTestTempDirectories("decisions-consumer-"); afterEach(async () => { vi.restoreAllMocks(); runtimeFixture.qualified = false; runtimeFixture.templateQualified = false; runtimeFixture.command = ""; vi.unstubAllEnvs(); - await Promise.all(dirs.splice(0).map((path) => rm(path, { recursive: true, force: true }))); + await dirs.cleanup(); }); async function runFixture( artifact: unknown, @@ -143,8 +143,7 @@ async function runFixture( } = {}, ) { let exposure: ClawScanExposure | undefined; - const workspace = await mkdtemp(join(tmpdir(), "decisions-consumer-")); - dirs.push(workspace); + const workspace = await dirs.create(); await mkdir(join(workspace, "artifact")); await writeFile(join(workspace, "artifact", "openclaw.plugin.json"), '{"id":"fixture"}'); await writeFile(join(workspace, "artifact", "SKILL.md"), "# Embedded skill at plugin root\n"); diff --git a/scripts/security/clawscan-diagnostic-pair.test.ts b/scripts/security/clawscan-diagnostic-pair.test.ts index 5cf018a7d8..5ad1f6ad85 100644 --- a/scripts/security/clawscan-diagnostic-pair.test.ts +++ b/scripts/security/clawscan-diagnostic-pair.test.ts @@ -1,15 +1,13 @@ /* @vitest-environment node */ -import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, expect, it } from "vitest"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { type DiagnosticEventContext, runPairedDiagnostic } from "./clawscan-diagnostic-pair"; import { runDiagnosticProcess } from "./run-clawscan-diagnostic"; -const roots: string[] = []; -afterEach(async () => { - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); -}); +const roots = createTestTempDirectories("paired-diagnostic-test-"); +afterEach(roots.cleanup); function artifact(verdict = "benign", retry = false) { const result = { @@ -93,8 +91,7 @@ type Mode = | "judge_failed"; async function harness(mode: (context: DiagnosticEventContext) => Mode = () => "benign") { - const root = await mkdtemp(join(tmpdir(), "paired-diagnostic-test-")); - roots.push(root); + const root = await roots.create(); const home = join(root, "home"); const codexHome = join(root, "codex-home"); await mkdir(home); diff --git a/scripts/security/clawscan-docker-cleanup.test.ts b/scripts/security/clawscan-docker-cleanup.test.ts index c0a611bf12..342a301013 100644 --- a/scripts/security/clawscan-docker-cleanup.test.ts +++ b/scripts/security/clawscan-docker-cleanup.test.ts @@ -1,6 +1,5 @@ /* @vitest-environment node */ -import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { performance } from "node:perf_hooks"; import { afterEach, describe, expect, it } from "vitest"; @@ -9,6 +8,7 @@ import { runWorkerCommand, type WorkerCommandTermination, } from "../lib/runWorkerCommand"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { ClawScanContainerCleanupError, hasKnownClawScanChildFinality, @@ -16,7 +16,7 @@ import { clawScanDockerEnvironment, } from "./clawscan-docker-cleanup"; -const dirs: string[] = []; +const dirs = createTestTempDirectories("clawscan-cleanup-test-"); const a = "a".repeat(64); const b = "b".repeat(64); const c = "c".repeat(64); @@ -30,9 +30,7 @@ const normal: WorkerCommandTermination = { outputLimitExceeded: null, }; -afterEach(async () => { - await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); -}); +afterEach(dirs.cleanup); type Container = { id: string; @@ -59,8 +57,7 @@ type State = { type Log = { args: string[]; env: Record }; async function fixture(initial: State = {}) { - const workspace = await mkdtemp(join(tmpdir(), "clawscan-cleanup-test-")); - dirs.push(workspace); + const workspace = await dirs.create(); const bin = join(workspace, "bin"); await mkdir(bin); const path = join(workspace, "state.json"); diff --git a/scripts/security/clawscan-plugin-runtime.test.ts b/scripts/security/clawscan-plugin-runtime.test.ts index ed4e1898dd..7e595ec761 100644 --- a/scripts/security/clawscan-plugin-runtime.test.ts +++ b/scripts/security/clawscan-plugin-runtime.test.ts @@ -1,8 +1,8 @@ /* @vitest-environment node */ -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { assertQualifiedPluginArtifact, qualifiedPluginCommand, @@ -18,14 +18,13 @@ vi.mock("./prepublicationScannerSource", async (importOriginal) => ({ ...(await importOriginal()), verifyInstalledClawScanSource: vi.fn(async () => ({ command: "/qualified/clawscan" })), })); -const dirs: string[] = []; +const dirs = createTestTempDirectories("plugin-runtime-"); afterEach(async () => { vi.clearAllMocks(); - await Promise.all(dirs.splice(0).map((path) => rm(path, { recursive: true, force: true }))); + await dirs.cleanup(); }); async function source(profile: string) { - const root = await mkdtemp(join(tmpdir(), "plugin-runtime-")); - dirs.push(root); + const root = await dirs.create(); await mkdir(join(root, "internal/profiles/clawhub"), { recursive: true }); await writeFile(join(root, "internal/profiles/clawhub/clawscan.yml"), profile); return { CLAWSCAN_SOURCE_DIR: root }; diff --git a/scripts/security/clawscan-receipt.test.ts b/scripts/security/clawscan-receipt.test.ts index f048d93063..2fc853fcec 100644 --- a/scripts/security/clawscan-receipt.test.ts +++ b/scripts/security/clawscan-receipt.test.ts @@ -1,8 +1,8 @@ /* @vitest-environment node */ -import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { clawScanExposure, summarizeClawScanExposure } from "./clawscan-exposure"; import completeReport from "./fixtures/skillspector-completed.json"; import partialReport from "./fixtures/skillspector-usable-partial.json"; @@ -12,12 +12,10 @@ import { } from "./run-codex-scan-worker"; import { runNativeClawScan } from "./run-prepublication-worker"; -const tempDirectories: string[] = []; +const tempDirectories = createTestTempDirectories("clawhub-receipt-boundary-"); afterEach(async () => { vi.unstubAllEnvs(); - await Promise.all( - tempDirectories.splice(0).map((path) => rm(path, { recursive: true, force: true })), - ); + await tempDirectories.cleanup(); }); function artifactFixture(verdict = "benign", additional: unknown[] = []) { @@ -495,8 +493,7 @@ describe("versioned ClawScan receipt consumer", () => { )( "uses the shared mapper at prepublication for $targetKind $mode", async ({ targetKind, mode }) => { - const workspace = await mkdtemp(join(tmpdir(), "clawhub-receipt-boundary-")); - tempDirectories.push(workspace); + const workspace = await tempDirectories.create(); await mkdir(join(workspace, "artifact")); await writeFile(join(workspace, "artifact/SKILL.md"), "# Inert\n"); await writeFile( diff --git a/scripts/security/prepublication-report-retention.test.ts b/scripts/security/prepublication-report-retention.test.ts index 96c71f3354..52cdfa5c4d 100644 --- a/scripts/security/prepublication-report-retention.test.ts +++ b/scripts/security/prepublication-report-retention.test.ts @@ -1,19 +1,19 @@ /* @vitest-environment node */ -import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, expect, it, vi } from "vitest"; import type { Id } from "../../convex/_generated/dataModel"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { processPrePublicationAttempt, runNativeClawScan } from "./run-prepublication-worker"; const logs = vi.hoisted(() => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() })); vi.mock("../lib/workerLogger", () => ({ createWorkerLogger: () => logs })); -const workspaces: string[] = []; +const workspaces = createTestTempDirectories("prepublication-report-retention-"); afterEach(async () => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); vi.clearAllMocks(); - await Promise.all(workspaces.splice(0).map((path) => rm(path, { recursive: true, force: true }))); + await workspaces.cleanup(); }); it("stores private execution evidence before normal completion without changing its verdict", async () => { @@ -161,8 +161,7 @@ it.each(["upload", "receipt", "old-backend"])( ); it("retains the complete failed native execution before the workspace is removed", async () => { - const workspace = await mkdtemp(join(tmpdir(), "prepublication-report-retention-")); - workspaces.push(workspace); + const workspace = await workspaces.create(); await mkdir(join(workspace, "artifact")); await writeFile(join(workspace, "artifact/SKILL.md"), "# Controlled fixture\n"); const artifact = JSON.stringify({ diff --git a/scripts/security/run-codex-scan-worker-clawscan.test.ts b/scripts/security/run-codex-scan-worker-clawscan.test.ts index ba66d373d3..22052f615e 100644 --- a/scripts/security/run-codex-scan-worker-clawscan.test.ts +++ b/scripts/security/run-codex-scan-worker-clawscan.test.ts @@ -2,11 +2,11 @@ import { execFile, execFileSync } from "node:child_process"; import { createHash } from "node:crypto"; import { existsSync } from "node:fs"; -import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, mkdir, readFile, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { promisify } from "node:util"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import * as dockerCleanup from "./clawscan-docker-cleanup"; import * as pluginRuntime from "./clawscan-plugin-runtime"; import completeReport from "./fixtures/skillspector-completed.json"; @@ -29,12 +29,12 @@ import { type SecurityScanJobHealth, } from "./security-scan-worker-summary"; -const tempDirs: string[] = []; +const tempDirs = createTestTempDirectories("clawhub-codex-worker-test-"); const execFileAsync = promisify(execFile); const sha256 = (content: string) => createHash("sha256").update(content).digest("hex"); it("selects the claimed bundle manifest without narrowing the artifact", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await mkdir(join(workspace, "artifact/.claude-plugin"), { recursive: true }); await writeFile(join(workspace, "artifact/.claude-plugin/plugin.json"), '{"name":"bundle"}'); await writeFile(join(workspace, "artifact/openclaw.plugin.json"), "{}"); @@ -49,7 +49,7 @@ it("selects the claimed bundle manifest without narrowing the artifact", async ( }); it("does not let a nested package.json relocate a legacy bundle root", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await mkdir(join(workspace, "artifact/.claude-plugin"), { recursive: true }); await mkdir(join(workspace, "artifact/package"), { recursive: true }); await writeFile(join(workspace, "artifact/.claude-plugin/plugin.json"), '{"name":"bundle"}'); @@ -68,7 +68,7 @@ it.each([ { family: "unknown", paths: ["openclaw.plugin.json"] }, { family: "bundle-plugin", paths: ["SKILL.md"] }, ])("fails closed for mismatched or ambiguous family $family", async ({ family, paths }) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); for (const path of paths) { await mkdir(dirname(join(workspace, "artifact", path)), { recursive: true }); await writeFile(join(workspace, "artifact", path), "{}"); @@ -98,7 +98,7 @@ it.each([ selected: ".codex-plugin/plugin.json", }, ])("preserves already-admitted legacy $family selection", async ({ family, paths, selected }) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); for (const path of paths) { await mkdir(dirname(join(workspace, "artifact", path)), { recursive: true }); await writeFile(join(workspace, "artifact", path), '{"name":"legacy","id":"legacy"}'); @@ -113,15 +113,9 @@ it.each([ afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); - await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true }))); + await tempDirs.cleanup(); }); -async function tempDir() { - const dir = await mkdtemp(join(tmpdir(), "clawhub-codex-worker-test-")); - tempDirs.push(dir); - return dir; -} - async function readStartedPid(path: string) { while (true) { const contents = await readFile(path, "utf8").catch((error: NodeJS.ErrnoException) => { @@ -221,7 +215,7 @@ function fileTarget(path: string, content: string): ClaimedJob["target"] { } async function clawPackTarget(): Promise { - const sourceDir = await tempDir(); + const sourceDir = await tempDirs.create(); const packageDir = join(sourceDir, "package"); const archivePath = join(sourceDir, "artifact.tgz"); await mkdir(packageDir, { recursive: true }); @@ -539,7 +533,7 @@ describe("run-codex-scan-worker clawscan authority", () => { retryableFailed: false, }); expect(preserved).toBeTruthy(); - tempDirs.push(preserved!); + tempDirs.track(preserved!); expect( await readFile(join(preserved!, "artifact/package/openclaw.plugin.json"), "utf8"), ).toContain("fixture-plugin"); @@ -586,7 +580,7 @@ describe("run-codex-scan-worker clawscan authority", () => { }); it("saves a failed Endor-only scan on the release instead of failing the job", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await configureEndorFakeCommands({ clawScan: "/missing/must-not-launch-clawscan", dockerBody: fakeEndorDockerBody({ @@ -653,7 +647,7 @@ describe("run-codex-scan-worker clawscan authority", () => { ] as const)( "reports %s without inventing exposure or a verdict", async (scenario, invocations, failures, accepted) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const artifact = JSON.parse(clawScanArtifactJson()); const receiptError = "Judge did not provide the required artifact inspection receipt."; const first = { @@ -766,8 +760,8 @@ describe("run-codex-scan-worker clawscan authority", () => { ); it("retains a failed receipt invocation after a successful second receipt through worker summaries", async () => { - const workspace = await tempDir(); - const diagnostics = await tempDir(); + const workspace = await tempDirs.create(); + const diagnostics = await tempDirs.create(); const artifact = JSON.parse(clawScanArtifactJson({ verdict: "malicious" })); artifact.judge.result.artifact_inspection.challenge = "b".repeat(64); artifact.judge.result.artifact_inspection.required_file_sha256 = "c".repeat(64); @@ -883,7 +877,7 @@ describe("run-codex-scan-worker clawscan authority", () => { it.each([false, true])( "passes default/overridden scanner settings to the real subprocess (override=%s)", async (overrides) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await mkdir(join(workspace, "artifact"), { recursive: true }); await writeFile(join(workspace, "artifact", "SKILL.md"), "# Safe skill\n"); const fakeClawScan = join(workspace, "fake-clawscan"); @@ -981,7 +975,7 @@ JSON`, expected: [{ rootPath: "skills/safe", scanPath: "artifact/package/skills/safe" }], }, ])("selects $name only from the package manifest", async ({ name, roots, expected }) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await mkdir(join(workspace, "artifact", "package"), { recursive: true }); await writeFile(join(workspace, "artifact", "package", "package.json"), "{}\n"); const job = claimedJob({ @@ -1068,7 +1062,7 @@ JSON`, it.each([0, 1])( "retains original partial bundled reports for adjudication on exit %s without findings", async (exitCode) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const partial = { ...structuredClone(partialReport), issues: [] }; const complete = structuredClone(completeReport); const command = join(workspace, "skillspector"); @@ -1104,7 +1098,7 @@ esac`, ); it("retains partial bundled reports in declared-root order when roots finish out of order", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const partial = { ...structuredClone(partialReport), issues: [] }; const complete = structuredClone(completeReport); // Two roots run together; the first declared root cannot finish until the @@ -1141,7 +1135,7 @@ esac`, it.each(["no-partial", "partial"])( "requires explicit complete-child controls only in a partial bundle (%s)", async (mode) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const command = join(workspace, "skillspector"); const alpha = mode === "partial" ? partialReport : { status: "clean", issues: [] }; await writeFakeClawScanCommand( @@ -1170,7 +1164,7 @@ esac`, it.each(["crashed", "malformed", "duplicate-keys", "unsuccessful"])( "rejects %s bundled evidence before the judge", async (mode) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); let raw = JSON.stringify(partialReport); if (mode === "malformed") raw = "[]"; if (mode === "duplicate-keys") @@ -1200,7 +1194,7 @@ exit ${mode === "crashed" ? 2 : 0}`, it.each([0, 1])( "never passes a package root to SkillSpector (findings exit %s)", async (exitCode) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const packageRoot = join(workspace, "artifact", "package"); await mkdir(join(packageRoot, "skills", "alpha"), { recursive: true }); await mkdir(join(packageRoot, "skills", "beta"), { recursive: true }); @@ -1314,7 +1308,7 @@ JSON`, ); it("uses ClawScan as the only skillVersion scan implementation", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const clawscanMarker = join(workspace, "clawscan-called.log"); await writeFakeClawScanCommand( @@ -1378,7 +1372,7 @@ JSON`, }>)( "persists %s ClawScan verdicts through the existing completion shape", async ({ verdict, expectedStatus, reportsSupported }) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const argsLog = join(workspace, "clawscan-args.log"); const artifactJson = clawScanArtifactJson({ @@ -1545,7 +1539,7 @@ JSON`, ])( "routes $name through the same artifact-only ClawScan persistence adapter", async ({ source, targetKind, expectedTarget, expectedFile, target }) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const argsLog = join(workspace, "clawscan-args.log"); const filesLog = join(workspace, "clawscan-files.log"); @@ -1663,7 +1657,7 @@ JSON`, ])( "uses the existing retry lifecycle when $targetKind/$source ClawScan execution fails", async ({ source, targetKind, target }) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); await writeFakeClawScanCommand(fakeClawScan, 'echo "matrix failure" >&2\nexit 17'); @@ -1710,7 +1704,7 @@ JSON`, ])( "saves $status community code-plugin Endor analysis without passing it to the judge", async (scan) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const endorDoneMarker = join(workspace, "endor-done"); const metadataLog = join(workspace, "judge-metadata.json"); @@ -1778,7 +1772,7 @@ JSON`, family: "code-plugin", }, ])("does not launch Endor for $excluded", async (cohort) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const dockerLog = join(workspace, "unexpected-docker-call"); await writeFakeClawScanCommand( @@ -1813,7 +1807,7 @@ JSON`, }); it("prepares bundled SkillSpector while Endor is active, then judges after both finish", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const callLog = join(workspace, "clawscan-calls.log"); const endorStarted = join(workspace, "endor-started"); @@ -1869,8 +1863,8 @@ touch ${JSON.stringify(skillReady)}`, }); it("waits for Endor cleanup when bundled SkillSpector preparation fails early", async () => { - const workspace = await tempDir(); - const diagnosticsRoot = await tempDir(); + const workspace = await tempDirs.create(); + const diagnosticsRoot = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const callLog = join(workspace, "clawscan-calls.log"); const skillFailed = join(workspace, "skill-failed"); @@ -1960,8 +1954,8 @@ exit 7`, it.each(["child failure", "shared deadline"])( "retains bounded context after an earlier bundled root succeeds: %s", async (failure) => { - const workspace = await tempDir(); - const diagnosticsRoot = await tempDir(); + const workspace = await tempDirs.create(); + const diagnosticsRoot = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const callLog = join(workspace, "clawscan-called"); const firstRootCompleted = join(workspace, "first-root-completed"); @@ -2100,8 +2094,8 @@ exit 2`, it.each([true, false])( "classifies bundled SkillSpector timeouts without changing retry=%s", async (retry) => { - const workspace = await tempDir(); - const diagnosticsRoot = await tempDir(); + const workspace = await tempDirs.create(); + const diagnosticsRoot = await tempDirs.create(); const callLog = join(workspace, "clawscan-called"); const started = join(workspace, "skillspector-started"); const timeoutMs = 2_000; @@ -2168,8 +2162,8 @@ exec sleep 10`, ); it("retries a primary ClawScan failure while retaining bounded diagnostics for both failures", async () => { - const workspace = await tempDir(); - const diagnosticsRoot = await tempDir(); + const workspace = await tempDirs.create(); + const diagnosticsRoot = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const endorDoneMarker = join(workspace, "endor-done"); await writeFakeClawScanCommand( @@ -2229,8 +2223,8 @@ exit 19`, }); it("records an Endor timeout as scanner health while completing moderation", async () => { - const workspace = await tempDir(); - const diagnosticsRoot = await tempDir(); + const workspace = await tempDirs.create(); + const diagnosticsRoot = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const callLog = join(workspace, "clawscan-calls.log"); const endorDoneMarker = join(workspace, "endor-done"); @@ -2283,7 +2277,7 @@ exit 19`, }); it("fails the job when SkillSpector scanner status is skipped", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const artifactJson = clawScanArtifactJson({ scannerStatuses: { skillspector: "skipped" }, @@ -2340,7 +2334,7 @@ JSON`, }); it("fails the job when the ClawScan artifact is malformed", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); await writeFakeClawScanCommand( fakeClawScan, @@ -2395,7 +2389,7 @@ echo "not json" > "$out"`, }); it("fails the job when completed A.I.G output has no SARIF run", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const artifactJson = clawScanArtifactJson({ aigRaw: { version: "2.1.0", runs: [] }, @@ -2452,7 +2446,7 @@ JSON`, }); it("fails the job when the ClawScan judge omits artifact inspection proof", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const { artifact_inspection: _inspection, ...judgeResult } = completeJudgeResult("benign"); const artifactJson = clawScanArtifactJson({ judgeResult }); @@ -2508,7 +2502,7 @@ JSON`, }); it("fails the job when the ClawScan judge result is missing required dimensions", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const artifactJson = clawScanArtifactJson({ judgeResult: { @@ -2605,7 +2599,7 @@ JSON`, ])( "fails the job when ClawScan artifact completedAt is $name", async ({ artifactJson, expectedError, name }) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); await writeFakeClawScanCommand( fakeClawScan, @@ -2661,7 +2655,7 @@ JSON`, ); it("fails the job when a required ClawScan scanner reports failed", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); const artifactJson = clawScanArtifactJson({ scannerStatuses: { skillspector: "failed" }, @@ -2728,7 +2722,7 @@ JSON`, }); it("uses the existing timeout/failure retry path for ClawScan timeouts", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const fakeClawScan = join(workspace, "fake-clawscan"); await writeFakeClawScanCommand( fakeClawScan, @@ -2781,8 +2775,8 @@ echo "this should never complete"`, }); it("retains opt-in phase evidence through the outer timeout diagnostic path", async () => { - const workspace = await tempDir(); - const diagnosticsRoot = await tempDir(); + const workspace = await tempDirs.create(); + const diagnosticsRoot = await tempDirs.create(); await mkdir(join(workspace, "artifact"), { recursive: true }); const fakeClawScan = join(workspace, "fake-clawscan"); const event = @@ -2838,7 +2832,7 @@ exec sleep 10`, }); it("never accepts a progress checkpoint as a completed scan artifact", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await mkdir(join(workspace, "artifact"), { recursive: true }); const fakeClawScan = join(workspace, "fake-clawscan"); await writeFakeClawScanCommand( @@ -2858,7 +2852,7 @@ done`, }); it("terminates the full ClawScan process tree on timeout", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await mkdir(join(workspace, "artifact"), { recursive: true }); const fakeClawScan = join(workspace, "fake-clawscan"); await writeFakeClawScanCommand( diff --git a/scripts/security/run-codex-scan-worker-skillspector.test.ts b/scripts/security/run-codex-scan-worker-skillspector.test.ts index da37e6919b..06d81c197f 100644 --- a/scripts/security/run-codex-scan-worker-skillspector.test.ts +++ b/scripts/security/run-codex-scan-worker-skillspector.test.ts @@ -1,18 +1,18 @@ /* @vitest-environment node */ import { existsSync, readFileSync } from "node:fs"; -import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, mkdir, readFile, stat, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, expect, it, vi } from "vitest"; import * as workerCommand from "../lib/runWorkerCommand"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { type ClaimedJob, runBundledSkillSpector, runClawScan } from "./run-codex-scan-worker"; -const workspaces: string[] = []; +const workspaces = createTestTempDirectories("clawhub-bundled-skillspector-"); afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); - await Promise.all(workspaces.splice(0).map((path) => rm(path, { recursive: true, force: true }))); + await workspaces.cleanup(); }); async function command(path: string, body: string) { @@ -21,8 +21,7 @@ async function command(path: string, body: string) { } async function fixture(scannerBody: string, roots = ["skills/example"]) { - const workspace = await mkdtemp(join(tmpdir(), "clawhub-bundled-skillspector-")); - workspaces.push(workspace); + const workspace = await workspaces.create(); for (const root of roots) { await mkdir(join(workspace, "artifact", root), { recursive: true }); await writeFile(join(workspace, "artifact", root, "SKILL.md"), "# Example"); diff --git a/scripts/security/run-codex-scan-worker.test.ts b/scripts/security/run-codex-scan-worker.test.ts index f3dc751cdf..56a809b414 100644 --- a/scripts/security/run-codex-scan-worker.test.ts +++ b/scripts/security/run-codex-scan-worker.test.ts @@ -1,9 +1,9 @@ /* @vitest-environment node */ import { createHash } from "node:crypto"; -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { summarizeClawScanExposure } from "./clawscan-exposure"; import { assertAigFilePathsHaveNoCompiledPython, @@ -16,19 +16,13 @@ import { writeJobDiagnostic, } from "./run-codex-scan-worker"; -const tempDirs: string[] = []; +const tempDirs = createTestTempDirectories("clawhub-codex-worker-test-"); afterEach(async () => { vi.restoreAllMocks(); - await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true }))); + await tempDirs.cleanup(); }); -async function tempDir() { - const dir = await mkdtemp(join(tmpdir(), "clawhub-codex-worker-test-")); - tempDirs.push(dir); - return dir; -} - function unsafeFixtureLabels() { return { label: ["API", "key"].join(" "), @@ -40,8 +34,8 @@ function unsafeFixtureLabels() { describe("run-codex-scan-worker diagnostics", () => { it("publishes the worker report to the Actions summary and diagnostics artifact", async () => { - const diagnosticsRoot = await tempDir(); - const stepSummaryPath = join(await tempDir(), "step-summary.md"); + const diagnosticsRoot = await tempDirs.create(); + const stepSummaryPath = join(await tempDirs.create(), "step-summary.md"); await writeFile(stepSummaryPath, ""); const previousStepSummary = process.env.GITHUB_STEP_SUMMARY; process.env.GITHUB_STEP_SUMMARY = stepSummaryPath; @@ -680,7 +674,7 @@ describe("run-codex-scan-worker diagnostics", () => { }); it("writes scanner metadata without lease tokens or signed file URLs", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await writeArtifactWorkspace( { @@ -729,7 +723,7 @@ describe("run-codex-scan-worker diagnostics", () => { }); it("rejects downloaded bytes that do not match the stored file hash", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await expect( writeArtifactWorkspace( { @@ -757,7 +751,7 @@ describe("run-codex-scan-worker diagnostics", () => { }); it("materializes zero-byte directory markers with descendant files", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await writeArtifactWorkspace( { @@ -801,7 +795,7 @@ describe("run-codex-scan-worker diagnostics", () => { }); it("does not extract legacy ZIP archives after materializing verified files", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const manifest = '{"id":"demo-plugin"}\n'; await writeArtifactWorkspace( @@ -841,7 +835,7 @@ describe("run-codex-scan-worker diagnostics", () => { const fetchMock = vi .spyOn(globalThis, "fetch") .mockResolvedValue(new Response("forbidden", { status: 403 })); - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await expect( writeArtifactWorkspace( @@ -888,7 +882,7 @@ describe("run-codex-scan-worker diagnostics", () => { ], }, }, - await tempDir(), + await tempDirs.create(), ).catch((caught: unknown) => caught); const message = error instanceof Error ? error.message : String(error); @@ -921,7 +915,7 @@ describe("run-codex-scan-worker diagnostics", () => { ], }, }, - await tempDir(), + await tempDirs.create(), ).catch((caught: unknown) => caught); const unsafePathMessage = unsafePathError instanceof Error ? unsafePathError.message : String(unsafePathError); @@ -959,7 +953,7 @@ describe("run-codex-scan-worker diagnostics", () => { ], }, }, - await tempDir(), + await tempDirs.create(), ).catch((caught: unknown) => caught); const networkMessage = networkError instanceof Error ? networkError.message : String(networkError); @@ -1003,7 +997,7 @@ describe("run-codex-scan-worker diagnostics", () => { "https://signed.example.invalid/package.tgz?token=secret&X-Amz-Signature=abc123", }, }, - await tempDir(), + await tempDirs.create(), ).catch((caught: unknown) => caught); const clawpackMessage = clawpackError instanceof Error ? clawpackError.message : String(clawpackError); @@ -1142,8 +1136,8 @@ describe("run-codex-scan-worker diagnostics", () => { }); it("retains full ClawScan artifact and scanner outputs with secret-safe redaction", async () => { - const diagnosticsRoot = await tempDir(); - const workspace = await tempDir(); + const diagnosticsRoot = await tempDirs.create(); + const workspace = await tempDirs.create(); const scannerOutputRoot = join(workspace, "clawscan-artifact", "scanner-results"); await mkdir(scannerOutputRoot, { recursive: true }); @@ -1327,7 +1321,7 @@ describe("run-codex-scan-worker diagnostics", () => { }); it("writes bounded Endor failure diagnostics with secrets redacted", async () => { - const diagnosticsRoot = await tempDir(); + const diagnosticsRoot = await tempDirs.create(); await writeJobDiagnostic({ completedAt: 2000, diagnosticsRoot, diff --git a/scripts/security/run-endor-plugin-scan.test.ts b/scripts/security/run-endor-plugin-scan.test.ts index 196f5a84f2..f7739f2a0c 100644 --- a/scripts/security/run-endor-plugin-scan.test.ts +++ b/scripts/security/run-endor-plugin-scan.test.ts @@ -1,23 +1,20 @@ /* @vitest-environment node */ -import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, mkdir, readFile, stat, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { runEndorPluginScan, type EndorCommandDiagnostic } from "./run-endor-plugin-scan"; -const tempDirs: string[] = []; +const tempDirs = createTestTempDirectories("clawhub-endor-plugin-test-"); const claimedRelease = { package: { name: "@openclaw/fixture-plugin" }, release: { version: "1.0.0" }, }; -afterEach(async () => { - await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true }))); -}); +afterEach(tempDirs.cleanup); async function tempDir() { - const workspace = await mkdtemp(join(tmpdir(), "clawhub-endor-plugin-test-")); - tempDirs.push(workspace); + const workspace = await tempDirs.create(); const bin = join(workspace, "bin"); await mkdir(bin); const docker = join(bin, "docker"); diff --git a/scripts/security/run-prepublication-worker.test.ts b/scripts/security/run-prepublication-worker.test.ts index 51a58e17ef..fabe78c63d 100644 --- a/scripts/security/run-prepublication-worker.test.ts +++ b/scripts/security/run-prepublication-worker.test.ts @@ -1,10 +1,10 @@ /* @vitest-environment node */ import { execFileSync } from "node:child_process"; -import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { Id } from "../../convex/_generated/dataModel"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { ClawScanContainerCleanupError } from "./clawscan-docker-cleanup"; import { summarizeClawScanExposure } from "./clawscan-exposure"; import partialReport from "./fixtures/skillspector-usable-partial.json"; @@ -26,7 +26,7 @@ import { isAdjudicableSkillSpectorResult } from "./skillSpectorReportPolicy"; const diagnosticLogs = vi.hoisted(() => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() })); vi.mock("../lib/workerLogger", () => ({ createWorkerLogger: () => diagnosticLogs })); -const tempDirs: string[] = []; +const tempDirs = createTestTempDirectories("clawhub-prepublication-worker-test-"); const noNewExposure = { scanExecution: "not_started", eligibleScanAttempt: false, @@ -83,17 +83,11 @@ function legacyArtifact( afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); - await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true }))); + await tempDirs.cleanup(); }); -async function tempDir() { - const dir = await mkdtemp(join(tmpdir(), "clawhub-prepublication-worker-test-")); - tempDirs.push(dir); - return dir; -} - async function nativeDiagnosticCase(artifactText: string | null, exitCode = 1) { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await mkdir(join(workspace, "artifact")); await writeFile(join(workspace, "artifact", "SKILL.md"), "# Synthetic diagnostic control\n"); const fakeClawScan = join(workspace, "fake-clawscan"); @@ -181,7 +175,7 @@ describe("pre-publication worker", () => { }); expect(result).toEqual({ completed: false, result: undefined, workerMustStop: true }); expect(client.action).not.toHaveBeenCalled(); - tempDirs.push(preserved!); + tempDirs.track(preserved!); expect(await readFile(join(preserved!, "artifact/SKILL.md"), "utf8")).toBe( "retained mounted fixture", ); @@ -381,7 +375,7 @@ describe("pre-publication worker", () => { it.each(["recovered receipt", "repeated failure", "malformed metadata", "missing artifact"])( "reports native %s exposure without publishing metadata", async (scenario) => { - const root = await tempDir(); + const root = await tempDirs.create(); const command = join(root, "fake-clawscan"); const result = legacyJudgeResult("malicious", "Security block, not clean."); const first = { @@ -1056,7 +1050,7 @@ describe("pre-publication worker", () => { it.each([false, true])( "runs the real native subprocess with independent defaults/overrides (override=%s)", async (overrides) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await mkdir(join(workspace, "artifact"), { recursive: true }); await writeFile(join(workspace, "artifact", "SKILL.md"), "# Demo\n"); await writeFile(join(workspace, "artifact", "openclaw.plugin.json"), '{"id":"demo"}\n'); @@ -1178,7 +1172,7 @@ JSON it.each(["./artifact", "./artifact/package"])( "scans the plugin manifest in dual-layout package %s", async (packageRoot) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await mkdir(join(workspace, packageRoot), { recursive: true }); await writeFile(join(workspace, packageRoot, "package.json"), '{"name":"demo-plugin"}\n'); await writeFile( @@ -1483,7 +1477,7 @@ JSON }); it("logs allowlisted completeness evidence for a failed scanner without artifact text", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await mkdir(join(workspace, "artifact"), { recursive: true }); await writeFile(join(workspace, "artifact", "SKILL.md"), "# Demo\n"); const report = { @@ -1593,7 +1587,7 @@ process.exit(1); summary: "ClawScan judge status was failed: Codex request was rate limited.", }, ])("$name", async (fixture) => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await mkdir(join(workspace, "artifact"), { recursive: true }); await writeFile(join(workspace, "artifact", "SKILL.md"), "# Demo\n"); const fakeClawScan = join(workspace, "fake-clawscan"); @@ -1647,7 +1641,7 @@ JSON }); it("terminates the full ClawScan process tree on timeout", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await mkdir(join(workspace, "artifact"), { recursive: true }); await writeFile(join(workspace, "artifact", "SKILL.md"), "# Demo\n"); const fakeClawScan = join(workspace, "fake-clawscan"); @@ -1717,7 +1711,7 @@ wait "$child_pid" }); it("maps TruffleHog verified-secret exit code to a blocked result", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await mkdir(join(workspace, "artifact"), { recursive: true }); const fakeTruffleHog = join(workspace, "fake-trufflehog"); await writeFile( diff --git a/scripts/security/skillspector-exception-diagnostic.test.ts b/scripts/security/skillspector-exception-diagnostic.test.ts index 62ca07ff85..be36c10568 100644 --- a/scripts/security/skillspector-exception-diagnostic.test.ts +++ b/scripts/security/skillspector-exception-diagnostic.test.ts @@ -1,11 +1,11 @@ /* @vitest-environment node */ import { execFile } from "node:child_process"; -import { chmod, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { chmod, mkdir, readFile, symlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { promisify } from "node:util"; import { afterEach, expect, it } from "vitest"; import { parse } from "yaml"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { selectSolarisExceptionCase } from "./run-solaris-exception-diagnostic"; import { installSkillSpectorExceptionObserver, @@ -13,10 +13,8 @@ import { readSkillSpectorExceptionEvents, } from "./skillspector-exception-diagnostic"; -const roots: string[] = []; -afterEach(async () => { - await Promise.all(roots.splice(0).map((p) => rm(p, { recursive: true, force: true }))); -}); +const roots = createTestTempDirectories("exception-observer-"); +afterEach(roots.cleanup); it("projects actual Python exceptions without their messages and preserves classifier behavior", async () => { const code = ` @@ -239,8 +237,7 @@ print(json.dumps({"trusted":projected,"forged":forged,"other":other,"oversize":o }); it("installs only over the qualified venv entrypoint and reads private regular files only", async () => { - const root = await mkdtemp(join(tmpdir(), "exception-observer-")); - roots.push(root); + const root = await roots.create(); const venv = join(root, "skillspector-source.control/.venv/bin"); await mkdir(venv, { recursive: true }); await writeFile(join(venv, "skillspector"), `#!${venv}/python3\n`); diff --git a/scripts/security/solaris-bundled-diagnostic-runtime.test.ts b/scripts/security/solaris-bundled-diagnostic-runtime.test.ts index 3c6ed6916b..b711fb951c 100644 --- a/scripts/security/solaris-bundled-diagnostic-runtime.test.ts +++ b/scripts/security/solaris-bundled-diagnostic-runtime.test.ts @@ -1,8 +1,8 @@ /* @vitest-environment node */ -import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, expect, it, vi } from "vitest"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; const probe = vi.hoisted(() => ({ calls: 0, @@ -112,13 +112,13 @@ vi.mock("../lib/runWorkerCommand", async (original) => { }); import { main } from "./solaris-bundled-diagnostic"; -const roots: string[] = []; +const roots = createTestTempDirectories("solaris-diagnostic-test-"); const platform = Object.getOwnPropertyDescriptor(process, "platform")!; afterEach(async () => { Object.defineProperty(process, "platform", platform); vi.unstubAllEnvs(); process.exitCode = undefined; - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); + await roots.cleanup(); }); async function setup(corrupt = false) { @@ -128,8 +128,7 @@ async function setup(corrupt = false) { // A later production rollout must not silently rewrite that diagnostic scope. probe.adoptedCommitOverride = "c3cfaf1515a47685786d72f031c714b1e5d9b34e"; probe.scannerCommit = probe.adoptedCommitOverride; - const root = await mkdtemp(join(tmpdir(), "solaris-diagnostic-test-")); - roots.push(root); + const root = await roots.create(); const source = join(root, "solaris-source/harnesses/openclaw/skills/control"); await mkdir(source, { recursive: true }); await writeFile(join(source, "SKILL.md"), corrupt ? "changed" : "control"); diff --git a/scripts/skill-cards/run-skill-card-worker.test.ts b/scripts/skill-cards/run-skill-card-worker.test.ts index 85c6020446..762ab8e4ae 100644 --- a/scripts/skill-cards/run-skill-card-worker.test.ts +++ b/scripts/skill-cards/run-skill-card-worker.test.ts @@ -1,12 +1,12 @@ /* @vitest-environment node */ import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; import { createServer } from "node:http"; -import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { isDeepStrictEqual, promisify } from "node:util"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { createTestTempDirectories } from "../lib/testTempDirectories"; import { applyServerPublisherToContext, assertPublicSkillCardMarkdown, @@ -24,19 +24,13 @@ import { writeWorkspace, } from "./run-skill-card-worker"; -const tempDirs: string[] = []; +const tempDirs = createTestTempDirectories("clawhub-skill-card-worker-test-"); afterEach(async () => { vi.restoreAllMocks(); - await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true }))); + await tempDirs.cleanup(); }); -async function tempDir() { - const dir = await mkdtemp(join(tmpdir(), "clawhub-skill-card-worker-test-")); - tempDirs.push(dir); - return dir; -} - describe("run-skill-card-worker Codex skill setup", () => { it("uses the same batch, runtime, and lease defaults as the security worker", () => { expect(DEFAULT_BATCH_LIMIT).toBe(4); @@ -114,7 +108,7 @@ describe("run-skill-card-worker Codex skill setup", () => { SKILL_CARD_CODEX_SERVICE_TIER: "fast", }), ).toEqual({ model: "custom-model", reasoningEffort: "high", serviceTier: "fast" }); - const tool = await tempDir(); + const tool = await tempDirs.create(); const automation = join(tool, "AI Transparency Card Automation"); await mkdir(automation); await writeFile(join(automation, "Skill Card Generator.md"), "trusted workflow"); @@ -171,8 +165,8 @@ describe("run-skill-card-worker Codex skill setup", () => { }); it("wraps NVIDIA's automation folder as a project-local Codex skill", async () => { - const workspace = await tempDir(); - const toolDir = await tempDir(); + const workspace = await tempDirs.create(); + const toolDir = await tempDirs.create(); const automationDir = join(toolDir, "AI Transparency Card Automation"); await mkdir(join(automationDir, "scripts"), { recursive: true }); await mkdir(join(automationDir, "references"), { recursive: true }); @@ -329,7 +323,7 @@ describe("run-skill-card-worker Codex skill setup", () => { const fetchMock = vi .spyOn(globalThis, "fetch") .mockResolvedValue(new Response("forbidden", { status: 403 })); - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const error = await writeWorkspace( { @@ -365,7 +359,7 @@ describe("run-skill-card-worker Codex skill setup", () => { }); it("materializes directory markers, descendants, and real empty files", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); const openAiConfig = "provider: openai\n"; const emptySha256 = createHash("sha256").update("").digest("hex"); @@ -412,7 +406,7 @@ describe("run-skill-card-worker Codex skill setup", () => { }); it("rejects downloaded artifact bytes that do not match the stored hash", async () => { - const workspace = await tempDir(); + const workspace = await tempDirs.create(); await expect( writeWorkspace( @@ -477,7 +471,7 @@ describe("run-skill-card-worker Codex skill setup", () => { version: { version: "1.2.3" }, }, }, - await tempDir(), + await tempDirs.create(), ), ).resolves.toBe(false); @@ -543,7 +537,7 @@ describe("run-skill-card-worker Codex skill setup", () => { version: { version: "1.2.3" }, }, }, - await tempDir(), + await tempDirs.create(), ), ).resolves.toBe(false);