From 2ff81eabfd7bc565b9851f3345eabb6830c42fd4 Mon Sep 17 00:00:00 2001 From: "opencode-agent[bot]" <219766164+opencode-agent[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:58:39 +0000 Subject: [PATCH] fix(core): keep opencode tmp files on disk and sweep them after 7 days --- packages/core/src/file-retention.ts | 3 +- packages/core/src/instructions/builtins.ts | 5 +- packages/core/src/tmp-retention.ts | 68 +++++++++++++++++++ .../core/test/instructions/builtins.test.ts | 7 +- packages/core/test/tmp-retention.test.ts | 57 ++++++++++++++++ packages/util/src/global-roots.ts | 3 +- packages/util/test/global-roots.test.ts | 4 +- packages/util/test/global.test.ts | 14 ++-- 8 files changed, 143 insertions(+), 18 deletions(-) create mode 100644 packages/core/src/tmp-retention.ts create mode 100644 packages/core/test/tmp-retention.test.ts diff --git a/packages/core/src/file-retention.ts b/packages/core/src/file-retention.ts index a325f2165fc..46245f5e895 100644 --- a/packages/core/src/file-retention.ts +++ b/packages/core/src/file-retention.ts @@ -15,7 +15,8 @@ export const cleanup = Effect.fn("FileRetention.cleanup")(function* ( Effect.gen(function* () { const info = yield* fs.stat(file).pipe(Effect.orElseSucceed(() => undefined)) const mtime = info && Option.getOrUndefined(info.mtime) - if (!mtime || mtime.getTime() >= cutoff) return + // Runtimes without real timestamps (workerd) report the epoch; keep those files. + if (!mtime || mtime.getTime() <= 0 || mtime.getTime() >= cutoff) return yield* fs.remove(file).pipe(Effect.ignore) }), { concurrency: 8, discard: true }, diff --git a/packages/core/src/instructions/builtins.ts b/packages/core/src/instructions/builtins.ts index fab4b8dd8cb..d0fb11a0bfd 100644 --- a/packages/core/src/instructions/builtins.ts +++ b/packages/core/src/instructions/builtins.ts @@ -5,6 +5,7 @@ import { Context, DateTime, Effect, Layer, Schema } from "effect" import { Global } from "@opencode/util/global" import { Location } from "../location.js" import { Instructions } from "./index.js" +import { TmpRetention } from "../tmp-retention.js" export interface Interface { readonly load: () => Effect.Effect @@ -40,7 +41,7 @@ const layer = Layer.effect( ` Workspace root folder: ${location.project.directory}`, ` Is directory a git repo: ${location.vcs?.type === "git" ? "yes" : "no"}`, ` Platform: ${process.platform}`, - ` Prefer ${global.tmp} over generic system temporary directories such as /tmp; it is pre-created and approved for external access.`, + ` Prefer ${global.tmp} over generic system temporary directories such as /tmp; it is pre-created and approved for external access. Files there untouched for 7 days are deleted automatically.`, "", ].join("\n"), ), @@ -57,4 +58,4 @@ const layer = Layer.effect( }), ) -export const node = makeLocationNode({ service: Service, layer, deps: [Global.node, Location.node] }) +export const node = makeLocationNode({ service: Service, layer, deps: [Global.node, Location.node, TmpRetention.node] }) diff --git a/packages/core/src/tmp-retention.ts b/packages/core/src/tmp-retention.ts new file mode 100644 index 00000000000..42f8f932b55 --- /dev/null +++ b/packages/core/src/tmp-retention.ts @@ -0,0 +1,68 @@ +export * as TmpRetention from "./tmp-retention.js" + +import path from "path" +import { Duration, Effect, Layer, Option, Schedule } from "effect" +import { makeGlobalNode } from "@opencode/util/effect/app-node" +import { FSUtil } from "@opencode/util/fs-util" +import { Global } from "@opencode/util/global" +import { FileRetention } from "./file-retention.js" + +export const RETENTION = Duration.days(7) + +/** Deletes files under `directory` untouched for `RETENTION`, then the directories that leaves empty. */ +export const cleanup = Effect.fn("TmpRetention.cleanup")(function* (fs: FSUtil.Interface, directory: string) { + const cutoff = Date.now() - Duration.toMillis(RETENTION) + const files: string[] = [] + // Directories with no entry added or removed within the retention, judged before this sweep + // removes anything (which would touch them). A newer one may be about to receive a file. + const stale: string[] = [] + const walk = (current: string): Effect.Effect => + fs.readDirectoryEntries(current).pipe( + Effect.orElseSucceed(() => []), + Effect.flatMap((entries) => + Effect.forEach( + entries, + (entry) => { + const target = path.join(current, entry.name) + if (entry.type !== "Directory") return Effect.sync(() => void files.push(target)) + return fs.stat(target).pipe( + Effect.map((info) => Option.getOrUndefined(info.mtime)), + Effect.orElseSucceed(() => undefined), + Effect.flatMap((mtime) => { + if (mtime && mtime.getTime() > 0 && mtime.getTime() < cutoff) stale.push(target) + return walk(target) + }), + ) + }, + { discard: true }, + ), + ), + ) + yield* walk(directory) + yield* FileRetention.cleanup(fs, files, RETENTION) + // Children are listed after their parents; remove deepest first so a parent can empty out. + yield* Effect.forEach( + stale.reverse(), + (target) => + Effect.gen(function* () { + const entries = yield* fs.readDirectory(target).pipe(Effect.orElseSucceed(() => [""])) + // Node's rm needs `recursive` for any directory; it is empty here. + if (entries.length === 0) yield* fs.remove(target, { recursive: true }).pipe(Effect.ignore) + }), + { discard: true }, + ) +}) + +const layer = Layer.effectDiscard( + Effect.gen(function* () { + const fs = yield* FSUtil.Service + const global = yield* Global.Service + yield* cleanup(fs, global.tmp).pipe(Effect.repeat(Schedule.spaced(Duration.hours(1))), Effect.forkScoped) + }), +) + +export const node = makeGlobalNode({ + name: "tmp-retention", + layer, + deps: [FSUtil.node, Global.node], +}) diff --git a/packages/core/test/instructions/builtins.test.ts b/packages/core/test/instructions/builtins.test.ts index 005abe45dc6..f7315df5fd6 100644 --- a/packages/core/test/instructions/builtins.test.ts +++ b/packages/core/test/instructions/builtins.test.ts @@ -1,5 +1,7 @@ import { describe, expect } from "bun:test" +import fs from "fs" import os from "os" +import path from "path" import { Effect, Layer } from "effect" import { TestClock } from "effect/testing" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" @@ -15,7 +17,8 @@ import { readInitial, readUpdate } from "../lib/instructions" const directory = AbsolutePath.make(FSUtil.resolve("/repo/packages/core")) const projectDirectory = AbsolutePath.make(FSUtil.resolve("/repo")) const timestamp = Date.parse("2026-06-03T12:00:00.000Z") -const temporary = os.tmpdir() +// Its own directory: building the node starts the tmp retention sweep there. +const temporary = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "opencode-builtins-"))) const localDate = (time: number) => new Date(time).toDateString() const locationLayer = Layer.succeed( Location.Service, @@ -50,7 +53,7 @@ describe("InstructionBuiltIns", () => { ` Workspace root folder: ${projectDirectory}`, " Is directory a git repo: yes", ` Platform: ${process.platform}`, - ` Prefer ${temporary} over generic system temporary directories such as /tmp; it is pre-created and approved for external access.`, + ` Prefer ${temporary} over generic system temporary directories such as /tmp; it is pre-created and approved for external access. Files there untouched for 7 days are deleted automatically.`, "", ].join("\n"), ) diff --git a/packages/core/test/tmp-retention.test.ts b/packages/core/test/tmp-retention.test.ts new file mode 100644 index 00000000000..504423fba42 --- /dev/null +++ b/packages/core/test/tmp-retention.test.ts @@ -0,0 +1,57 @@ +import { describe, expect } from "bun:test" +import path from "path" +import { Effect } from "effect" +import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { FSUtil } from "@opencode/util/fs-util" +import { TmpRetention } from "@opencode/core/tmp-retention" +import { withTempDir } from "./fixture/tmpdir" +import { it } from "./lib/effect" + +const fsLayer = AppNodeBuilder.build(FSUtil.node, []) +const old = new Date(Date.now() - 8 * 24 * 60 * 60 * 1_000) + +describe("TmpRetention", () => { + it.live("deletes stale files at any depth and the directories they leave empty", () => + withTempDir((tmp) => + Effect.gen(function* () { + const fs = yield* FSUtil.Service + const upload = path.join(tmp.path, "uploads", "a", "photo.png") + const image = path.join(tmp.path, "images", "ses_1", "image_1.png") + const fresh = path.join(tmp.path, "images", "ses_1", "image_2.png") + const scratch = path.join(tmp.path, "notes.txt") + for (const file of [upload, image, fresh, scratch]) yield* fs.writeWithDirs(file, "x") + for (const file of [upload, image, scratch]) yield* fs.utimes(file, old, old) + for (const directory of ["uploads", "uploads/a", "images", "images/ses_1"]) + yield* fs.utimes(path.join(tmp.path, directory), old, old) + + yield* TmpRetention.cleanup(fs, tmp.path) + + expect(yield* fs.exists(upload)).toBe(false) + expect(yield* fs.exists(image)).toBe(false) + expect(yield* fs.exists(scratch)).toBe(false) + expect(yield* fs.exists(fresh)).toBe(true) + expect(yield* fs.exists(path.join(tmp.path, "uploads"))).toBe(false) + expect(yield* fs.exists(path.join(tmp.path, "images", "ses_1"))).toBe(true) + expect(yield* fs.exists(tmp.path)).toBe(true) + }), + ).pipe(Effect.provide(fsLayer)), + ) + + it.live("keeps a recently created empty directory and files without a real timestamp", () => + withTempDir((tmp) => + Effect.gen(function* () { + const fs = yield* FSUtil.Service + const directory = path.join(tmp.path, "uploads", "b") + const epoch = path.join(tmp.path, "epoch.txt") + yield* fs.ensureDir(directory) + yield* fs.writeFileString(epoch, "x") + yield* fs.utimes(epoch, new Date(0), new Date(0)) + + yield* TmpRetention.cleanup(fs, tmp.path) + + expect(yield* fs.exists(directory)).toBe(true) + expect(yield* fs.exists(epoch)).toBe(true) + }), + ).pipe(Effect.provide(fsLayer)), + ) +}) diff --git a/packages/util/src/global-roots.ts b/packages/util/src/global-roots.ts index a9324e4987d..62262ccd3c2 100644 --- a/packages/util/src/global-roots.ts +++ b/packages/util/src/global-roots.ts @@ -14,6 +14,7 @@ export function roots(app: string) { cache: path.join(cache!, app), config: path.join(config!, app), state: path.join(state!, app), - tmp: path.join(os.tmpdir(), app), + // On disk rather than os.tmpdir(), which is often RAM-backed (tmpfs). + tmp: path.join(data!, app, "tmp"), } } diff --git a/packages/util/test/global-roots.test.ts b/packages/util/test/global-roots.test.ts index a5ce4032bb5..deb096a86c7 100644 --- a/packages/util/test/global-roots.test.ts +++ b/packages/util/test/global-roots.test.ts @@ -20,7 +20,7 @@ describe("global roots", () => { cache: path.join(env.XDG_CACHE_HOME, "opencode"), config: path.join(env.XDG_CONFIG_HOME, "opencode"), state: path.join(env.XDG_STATE_HOME, "opencode"), - tmp: path.join(os.tmpdir(), "opencode"), + tmp: path.join(env.XDG_DATA_HOME, "opencode", "tmp"), }) }) @@ -40,7 +40,7 @@ describe("global roots", () => { cache: path.join(home, ".cache", "opencode"), config: path.join(home, ".config", "opencode"), state: path.join(home, ".local", "state", "opencode"), - tmp: path.join(os.tmpdir(), "opencode"), + tmp: path.join(home, ".local", "share", "opencode", "tmp"), }) }) }) diff --git a/packages/util/test/global.test.ts b/packages/util/test/global.test.ts index ed7787f8b6e..11b78aaf6e9 100644 --- a/packages/util/test/global.test.ts +++ b/packages/util/test/global.test.ts @@ -9,7 +9,7 @@ import { Global } from "../src/global.js" describe("global", () => { test("importing the module does not create directories", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-global-import-")) - const directories = ["data", "cache", "config", "state", "tmp"].map((directory) => path.join(root, directory)) + const directories = ["data", "cache", "config", "state"].map((directory) => path.join(root, directory)) const module = pathToFileURL(path.join(import.meta.dir, "../src/global.ts")).href const result = Bun.spawnSync({ cmd: [process.execPath, "-e", `const { Global } = await import(${JSON.stringify(module)}); void Global.Path.tmp`], @@ -19,9 +19,6 @@ describe("global", () => { XDG_CACHE_HOME: directories[1], XDG_CONFIG_HOME: directories[2], XDG_STATE_HOME: directories[3], - // os.tmpdir() reads TMPDIR on POSIX and TEMP on Windows. - TMPDIR: directories[4], - TEMP: directories[4], }, stderr: "pipe", }) @@ -52,7 +49,7 @@ describe("global", () => { test("building a layer with default tmp creates and canonicalizes it", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-global-layer-")) - const directories = ["data", "cache", "config", "state", "tmp"].map((directory) => path.join(root, directory)) + const directories = ["data", "cache", "config", "state"].map((directory) => path.join(root, directory)) const module = pathToFileURL(path.join(import.meta.dir, "../src/global.ts")).href const result = Bun.spawnSync({ cmd: [ @@ -72,9 +69,6 @@ describe("global", () => { XDG_CACHE_HOME: directories[1], XDG_CONFIG_HOME: directories[2], XDG_STATE_HOME: directories[3], - // os.tmpdir() reads TMPDIR on POSIX and TEMP on Windows. - TMPDIR: directories[4], - TEMP: directories[4], }, stdout: "pipe", stderr: "pipe", @@ -83,7 +77,7 @@ describe("global", () => { expect(result.exitCode, result.stderr.toString()).toBe(0) // The layer canonicalizes through the native realpath, which on Windows also expands 8.3 short // names such as RUNNER~1 that the JavaScript realpathSync leaves in place. - expect(result.stdout.toString()).toBe(fs.realpathSync.native(path.join(directories[4], "opencode"))) + expect(result.stdout.toString()).toBe(fs.realpathSync.native(path.join(directories[0], "opencode", "tmp"))) const created = [ path.join(directories[0], "opencode"), path.join(directories[1], "opencode", "bin"), @@ -91,7 +85,7 @@ describe("global", () => { path.join(directories[3], "opencode"), path.join(directories[0], "opencode", "log"), path.join(directories[0], "opencode", "repos"), - path.join(directories[4], "opencode"), + path.join(directories[0], "opencode", "tmp"), ] created.forEach((directory) => expect(fs.statSync(directory).isDirectory()).toBe(true)) fs.rmSync(root, { recursive: true, force: true })