Skip to content

Runtime and Toolchain

Wijanarko Putra Rajeb edited this page Nov 14, 2026 · 5 revisions

Runtime and toolchain

Runtime: Bun Only

This application runs exclusively on Bun. Do not introduce Node-only APIs, and do not assume node <entry> works.

  • Server (src/server/**) imports bun:sqlite and resolves the @/ path alias — Node fails on both with ERR_MODULE_NOT_FOUND. Run it with bun run src/server/index.ts (dev, watched) or NODE_ENV=production bun run src/server/index.ts (prod). bun run start does the latter, and kabmo serve is production by default (--dev selects the source entry).
  • Tests run under bun test; do not add a Node test runner.
  • A suite that touches the database must isolate it (isolateDb/releaseDb, src/test-support/isolated-db.ts). The handle is a PROCESS-wide singleton (globalThis.__kabmoDb) and KABMO_DB_PATH is read only while that handle is being opened, so setting the path inside a test — after another file already opened the handle — reads the developer's real ~/.kabmo/db.sqlite and WRITES to it. Verified: bun test src/server/lib/panels/registry.server.test.ts bumped the real database's mtime and left a test plugin id in its omp_panel_plugins row, and the panel scan is what reaches getDb() (it reads the disabled set), so a scan-only suite is not exempt. A full bun test under a tracer preload (mock.module('bun:sqlite', …) wrapping Database and logging every open of $HOME/.kabmo/db.sqlite) found 13 more suites doing it — four lib/panels/*.server.test.ts scans, frame-fold{,-signals}, rpc/lifecycle, session/{auto-title,goal-driver,goal-settings}, routes/sessions/delete, and routes/fs/{grant,scope} — now all call isolateDb/releaseDb. A suite that runs alone in a fresh process can hide the leak — it sets the path before anyone opens the handle — so audit in a full run, not one file at a time, and re-run the tracer whenever a newly added suite reaches a store. getDb() now snapshots the configured override at CALL time: a fire-and-forget write (void clearStreamStatus(...), a debounced roots-watch reconcile) that is still resolving when its suite deletes KABMO_DB_PATH used to open the default ~/.kabmo/db.sqlite instead — the last two opens a full-run tracer found. Because such a continuation can also call getDb() only after releaseDb deleted KABMO_DB_PATH, bunfig.toml's [test] preload (src/test-support/preload.ts) assigns the LOWEST-precedence DB_PATH to a run-wide temp file: isolation still wins, and late work lands there instead of ~/.kabmo. isolateDb() closes and clears the cached handle BEFORE pointing the path at a temp file, because the order is the whole point; releaseDb() closes it again and drops the directory.
  • A suite must not write into the developer's real $HOME either — ~/.kabmo and ~/.omp are only the two trees that matter most. Audited by running the full suite under sandbox-exec with (deny file-write* (subpath "/Users/rajebdev")) (the checkout and temp roots allowed): SQLite reports attempt to write a readonly database and fs reports EPERM, so a leak names its own path. The only two EPERM paths were ~/.kabmo-e2e-probe (db.server.test.ts's ~ expansion case created a FIXED directory in the real home and then rmSync-ed it — deleting a directory it did not create if one existed) and ~/.omp-browser-test-* (browser/runtime.test.ts created a unique config dir inside the real home, left behind whenever the run died before afterAll). Both are fixed: the ~ case now expands ~/db.sqlite (the parent exists, so getDatabasePath creates nothing), and the runtime suite points PI_CONFIG_DIR at a name that does not exist and puts the daemon tree under a temp XDG_STATE_HOME. os.homedir() is snapshotted at process start, so HOME cannot relocate getConfigRoot() mid-run — XDG is the only seam. The same sandboxed full run produced ZERO EPERM paths under ~/.kabmo/** or ~/.omp/**, which is the evidence that no suite opens the real database or rewrites a real omp session tree.
  • Process-wide state that owns a handle, a timer or a SUBSCRIBER LIST lives on globalThis, because bun --hot re-evaluates a module while the handle lives on. Measured: signals.server.ts kept its listener Set in module scope while initRealtimeTopics's one-shot guard sat on globalThis, so the first hot reload that re-evaluated the module left an EMPTY set behind and no subscriber was ever re-registered — every signal-based publish stopped dead (no sidebar spinner, no terminal badge, no activity stamp, no workspace or schedule refresh) while topics published by a DIRECT call kept moving, which is why it survived a bun test run and only showed up on a dev server that had been reloading for hours. Fixed by moving the set to globalThis; pinned by signals.server.test.ts, which imports the module a second time under a query-string specifier and asserts the two instances share one list.
  • CLI (src/cli/**) is Bun too: #!/usr/bin/env bun shebang and @/cli/... imports, so it needs Bun on PATH. It resolves the Bun binary via resolveBunBin() and spawns the server with it. Nothing in the toolchain runs under Node any more — the client build is Bun.build (see Build & Dev Loop).
  • The database runs WAL + synchronous=NORMAL, and bulk writes go through writeMany. bun:sqlite leaves SQLite's default at FULL, which fsyncs every commit: measured on this machine, 79 µs per single-row INSERT at FULL against 8 µs at NORMAL (12.6k/s → 124k/s), and 0.20 µs inside a transaction. NORMAL in WAL cannot corrupt the file; the exposure is losing the last commits if the OPERATING SYSTEM crashes, and every write here is UI state that a restart re-reads from omp's own files. DbClient.writeMany(sql, rows, chunkSize = 200) is the only batched writer — chunked rather than one transaction because bun:sqlite is synchronous and a 173 MB overlay rewrite in one transaction would freeze every request, stream and terminal frame for its duration. The two loops that used to autocommit per row (compact-chat-overlay.ts, workspace-sync.ts) now collect and batch.
  • Practical rules: never swap bun:sqlite for a Node driver; never add a node: import to src/client/** or src/shared/lib/**; keep .ts/.tsx execution in Bun's hands (no tsx/ts-node).

Bun-Native APIs vs node:* Imports

Bun implements node:* builtins natively — they do not shell out to a Node binary. Verified: node:child_process runs with node off PATH and process.execPath stays bun. So a node: import is not a correctness bug; it is only a preference when Bun ships a first-class equivalent. Do not "convert" a node: import to a Bun.* call when no equivalent exists — the conversion is either impossible or silently changes behavior.

Prefer Instead of Why
Bun.env.X process.env.X Same object in Bun (Bun.env === process.env), but the Bun name states the runtime. Server/CLI only — Bun.env does not exist in the browser, so src/client/** and src/shared/** must never use it.
crypto.randomUUID() (global) import { randomUUID } from 'crypto' Global is available; no import needed.
Bun.gzipSync / Bun.gunzipSync zlib.gzipSync / gunzipSync Byte-identical output, verified.
Bun.YAML.parse / Bun.YAML.stringify(obj, null, 2) yaml package Rust parser, zero-dependency. The third stringify argument (space) produces block-style multi-line YAML; without it output is flow-style single-line. Caveat: round-trip drops comments — files that must preserve user comments still need a document-model parser (the yaml package was removed because no remaining call site needs comment preservation).
Bun.which('bin') which via spawnSync Direct PATH lookup.
Bun.spawnSync / Bun.spawn child_process.exec/execFile/spawn Native timeout, maxBuffer, windowsHide, detached (process group), and signal: AbortSignal options. Unlike promisified exec, non-zero exits do not throw — check exitCode; timeout/kill detection uses signalCode (Bun sets killed: true even for normal non-zero exits). Server-wide: lib/fs/shell.ts wraps sh -c for shell strings; lib/omp/rpc/lines.ts reads NDJSON from Bun ReadableStream stdout (replaces readline).
Bun.file(p).stream() fs.createReadStream Returns a real Web ReadableStream for new Response(...) — no node-stream adapter or type cast.
Bun.Glob.scanSync({ cwd, onlyFiles: true }) readdirSync + regex filter loops Rust-native globbing; supports *.{a,b,c} alternation. Returns relative paths; size guards still need statSync.
await Bun.file(p).text() / .json() fs.readFileSync(p, 'utf8') / fs.promises.readFile Only where the call site is already async. Bun.file() is async; do not force a sync caller to become async just to use it. Also: .slice(a, b).text() for partial reads (log follow), .stat(), .exists().
await Bun.write(p, data) fs.writeFileSync / fs.promises.writeFile Bun.write ignores mode when creating a new file (verified on Bun 1.4.0 and 1.4.2 despite the docs signature) — it cannot create a 0o600 file; it is honored when overwriting an existing file. Keep fs.writeFileSync(..., { mode: 0o600 }) for the CLI registry (src/cli/lib/runtime.js).

These stay node:* — Bun has no equivalent, so do not attempt a conversion:

  • node:path — Bun.path is undefined. No replacement exists. (The CLI uses its own minimal src/cli/lib/path-utils.js for join/resolve/dirname/home instead of importing node:path.)
  • node:fs directory + metadata ops — mkdir/readdir/stat/exists/rm/rename/Dirent. Bun's own docs point at node:fs for directories; Bun.file() is for file contents (stat()/exists() are async BunFile methods where the chain is already async). Bun.Glob.scanSync covers readdir+filter scans.
  • node:fs sync reads in sync functions — Bun.file() is async; the omp session/config layers are now fully async (2026-09), so sync reads survive only in genuinely sync contexts (module-level path setup, lockfile exclusive-create in config/mcp.ts, and the title-slot in-place 256-byte r+ write where an offset write is required — Bun's FileSink cannot seek). Convert a read only when the enclosing call chain is already async; CLI bootstrap stays sync deliberately: sequential dependencies (mkdir → open fd → spawn → write registry), no concurrency to exploit, and signal-handler paths must not depend on pending promises.
  • node:os — Bun.os is undefined. Never replace os.homedir()/os.tmpdir() with Bun.env.HOME/TMPDIR/TEMP anywhere — the env vars are absent when a process runs without a shell (cron, launchd, systemd, GUI launcher), and they yield undefined, not a fallback: path.join(undefined, x) throws, and in the CLI it produced '' so the data directory silently became a cwd-relative .kabmo (split-brain: kabmo stop/status looked in the wrong directory and could not find a live server). os.homedir() falls back to getpwuid() on POSIX and USERPROFILE on Windows; os.tmpdir() walks TMPDIR → TMP → TEMP then /tmp (and strips macOS's trailing slash). This applies to src/cli/** too — src/cli/lib/path-utils.js uses os.homedir() for exactly this reason. Signal numbers use the local table in src/cli/lib/process-lifecycle.js instead of os.constants.signals.
  • node:readline — no Bun equivalent for generic streams; src/server/lib/omp/rpc/lines.ts is the in-repo NDJSON reader for Bun spawn stdout.
  • node:zlib brotli — Bun.brotliCompressSync is undefined; Bun ships gzip only (src/server/plugins/compress.ts keeps brotli here).
  • node:child_process — fully migrated (2026-09): every exec/execFile/spawn call site now uses Bun.spawn/Bun.spawnSync, and readline usage is gone. Do not reintroduce child_process; new code goes through Bun.spawn (or lib/fs/shell.ts for shell strings).

Toolchain Commands: Bun Only (no npm, npx, yarn, pnpm)

bun.lock is the only lockfile. npm, npx, yarn, and pnpm are never used in this repo — not to install, not to run scripts, not to execute a binary. Every tool that would otherwise be reached through npx is reached through bunx, which resolves the same local node_modules/.bin binary.

Never Always
npm install / npm i <pkg> / npm uninstall <pkg> bun install / bun add <pkg> / bun remove <pkg> (add -d for dev deps)
npm run <script> bun run <script> (or bare bun <script> when it is unambiguous)
npx <bin> / npx -y <pkg> bunx <bin> — e.g. bunx tsc --noEmit
node <entry> / tsx / ts-node bun run <entry.ts> — Bun executes TypeScript directly
npx jest / npx vitest / npx mocha bun test
  • Never commit package-lock.json, yarn.lock, or pnpm-lock.yaml; if one appears, delete it and re-run bun install.
  • bunx is preferred over ./node_modules/.bin/... for readability; both hit the identical local binary.

Clone this wiki locally