Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: resolve Git Bash (not WSL) for db.sh on Windows + dedupe schema-upgrade log

[._.]/ Adam Eivyda6a6c16cde4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9c0ae88b33..8fd4920ee4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -11,6 +11,7 @@
## Fixed
- **Database page works on Windows** — the Database page's Start/Fix/Status actions invoke the `db.sh` manager through bash; on Windows the script's native path (`H:\…\db.sh`) was passed with backslashes, which bash collapsed into a bogus path (exit 127, "No such file or directory"), so the page reported the Docker database as stopped even while it was running. The path is now normalized to forward slashes, which Git Bash accepts on Windows. A second Windows-only failure in the per-backend export path (spawning `mkdir -p`, which isn't a real executable on Windows) was also fixed by using Node's filesystem API instead. Mac/Linux behavior is unchanged.
+- **Database page works on Windows (follow-up: use Git Bash, not WSL)** — even after the path was forward-slashed, Start/Fix/Status still failed with exit 127 on machines that have **both** Git Bash and WSL installed: the server (launched by PM2) resolved a bare `bash` to WSL's `C:\Windows\System32\bash.exe`, which mounts drives at `/mnt/h/…` and genuinely cannot see a `H:/…` drive path — and would run `db.sh` against Linux tools even if it could. PortOS now resolves the interpreter explicitly, preferring **Git Bash** (the correct Windows interpreter), with a `PORTOS_BASH` override for non-standard installs. Mac/Linux behavior is unchanged (bare `bash`).
## Changed
diff --git a/scripts/setup-db.js b/scripts/setup-db.js
index 9b64e1b5a7..ea5614928a 100644
--- a/scripts/setup-db.js
+++ b/scripts/setup-db.js
@@ -14,6 +14,7 @@ import { createInterface } from 'readline';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { parseEnvFile, upsertEnvKey } from './lib/envFile.js';
+import { resolveBashBinary } from '../server/lib/bashResolver.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = join(__dirname, '..');
@@ -268,7 +269,7 @@ function setupNativePostgres() {
// Pass resolved PG_* settings via env so db.sh provisions the same
// role/db/port that isPortOSDbReady() probes. db.sh itself doesn't
// source .env — without this, customized creds in .env would mismatch.
- execFileSync('bash', [dbScript, 'setup-native'], {
+ execFileSync(resolveBashBinary(), [dbScript, 'setup-native'], {
stdio: 'inherit',
cwd: rootDir,
env: PG_CHILD_ENV
diff --git a/server/lib/README.md b/server/lib/README.md
index 286a02a9ef..1ed751142d 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -112,6 +112,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
+| `bashResolver.js` | `resolveBashBinary()` — resolves the POSIX `bash` for running bundled `*.sh` scripts (e.g. `scripts/db.sh`). On Windows a bare `bash` often resolves (via PM2's PATH) to WSL, which mounts drives at `/mnt/h` and can't see a `H:/...` drive path (exit 127); this prefers Git Bash (PORTOS_BASH override → standard install dirs → derived from `git` on PATH → bare `bash`). No-op (`bash`) on non-Windows. |
| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, and Windows `taskkill /T /F` tree-kill. Used by `appBuilder.js` and `appUpdater.js`. |
| `commandSecurity.js` | Allowlist of safe shell commands. |
| `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. |
diff --git a/server/lib/bashResolver.js b/server/lib/bashResolver.js
new file mode 100644
index 0000000000..e4fd9e4f5f
--- /dev/null
+++ b/server/lib/bashResolver.js
@@ -0,0 +1,104 @@
+/**
+ * POSIX `bash` resolution for running bundled `*.sh` scripts (notably
+ * `scripts/db.sh`) on Windows.
+ *
+ * THE PROBLEM. On a typical Windows dev box `bash` resolves, in PATH order, to
+ * one of several interpreters:
+ * - C:\Program Files\Git\...\bash.exe — Git Bash (MSYS2)
+ * - C:\Windows\System32\bash.exe — WSL
+ * - %LOCALAPPDATA%\Microsoft\WindowsApps\bash.exe — WSL launcher
+ * PM2 (which launches the PortOS server) frequently resolves the WSL one first.
+ * WSL mounts drives at `/mnt/h/...`, so it CANNOT see a Windows drive path like
+ * `H:/.../db.sh` and exits 127 ("No such file or directory"). Even if the path
+ * were translated, WSL would run db.sh against Linux `docker`/`psql`, not the
+ * Windows toolchain the script expects. Git Bash is the correct interpreter:
+ * it accepts `H:/...` drive paths and shells out to the Windows tools.
+ *
+ * Path-format normalization alone can't fix this — no single drive-path string
+ * works in BOTH Git Bash and WSL — so we resolve the Git Bash binary explicitly.
+ *
+ * Resolution order (Windows):
+ * 1. PORTOS_BASH override — explicit escape hatch, always wins.
+ * 2. Git Bash at the standard install locations.
+ * 3. Git Bash derived from `git` on PATH (…\Git\cmd\git.exe → …\Git\bin\bash.exe).
+ * 4. bare `bash` — last resort (preserves prior behavior).
+ * On non-Windows there is only one bash; always return bare `bash`.
+ *
+ * Self-contained: no imports out to other PortOS modules.
+ */
+
+import { existsSync } from 'fs';
+import { join, dirname } from 'path';
+import { execFileSync } from 'child_process';
+
+const IS_WIN32 = process.platform === 'win32';
+
+// Standard Git-for-Windows install locations. `\bin\bash.exe` is the MSYS2
+// wrapper (preferred over `\usr\bin\bash.exe`, which skips the launcher env).
+function standardGitBashPaths() {
+ const candidates = [];
+ const programFiles = process.env.ProgramFiles || 'C:\\Program Files';
+ const programFilesX86 = process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';
+ const localAppData = process.env.LOCALAPPDATA;
+ candidates.push(join(programFiles, 'Git', 'bin', 'bash.exe'));
+ candidates.push(join(programFilesX86, 'Git', 'bin', 'bash.exe'));
+ if (localAppData) {
+ // Per-user Git install (winget/scoop "Git.Git" user scope).
+ candidates.push(join(localAppData, 'Programs', 'Git', 'bin', 'bash.exe'));
+ }
+ return candidates;
+}
+
+// Derive Git Bash from wherever `git` resolves on PATH:
+// C:\Program Files\Git\cmd\git.exe → C:\Program Files\Git\bin\bash.exe
+function gitBashFromPath() {
+ let gitExe = '';
+ try {
+ gitExe = execFileSync('where', ['git'], { encoding: 'utf8' }).split(/\r?\n/)[0].trim();
+ } catch {
+ return null;
+ }
+ if (!gitExe) return null;
+ // …\Git\cmd\git.exe → …\Git → …\Git\bin\bash.exe
+ const gitRoot = dirname(dirname(gitExe));
+ const bash = join(gitRoot, 'bin', 'bash.exe');
+ return existsSync(bash) ? bash : null;
+}
+
+let cached;
+
+/**
+ * Resolve the bash binary to use for `*.sh` scripts. Memoized after first call.
+ *
+ * @returns {string} an absolute path to Git Bash on Windows (when found), or
+ * the bare command `bash` (non-Windows, or Windows fallback).
+ */
+export function resolveBashBinary() {
+ if (cached !== undefined) return cached;
+ if (!IS_WIN32) {
+ cached = 'bash';
+ return cached;
+ }
+ if (process.env.PORTOS_BASH && existsSync(process.env.PORTOS_BASH)) {
+ cached = process.env.PORTOS_BASH;
+ return cached;
+ }
+ const found = standardGitBashPaths().find(existsSync) || gitBashFromPath();
+ if (found) {
+ console.log(`🐚 Using Git Bash for shell scripts: ${found}`);
+ cached = found;
+ return cached;
+ }
+ // Nothing found — fall back to bare `bash` and warn, since this is the path
+ // that produces the WSL drive-path failure if PATH resolves WSL first.
+ console.warn('🐚 Git Bash not found; falling back to bare `bash` (set PORTOS_BASH to override). On Windows this may resolve to WSL and fail to see drive paths.');
+ cached = 'bash';
+ return cached;
+}
+
+/**
+ * Reset the memoized resolution. Test-only.
+ */
+export function _resetBashResolverCache() {
+ cached = undefined;
+}
diff --git a/server/lib/bashResolver.test.js b/server/lib/bashResolver.test.js
new file mode 100644
index 0000000000..e0160c3e22
--- /dev/null
+++ b/server/lib/bashResolver.test.js
@@ -0,0 +1,46 @@
+import { describe, it, expect, afterEach, vi } from 'vitest';
+import { resolveBashBinary, _resetBashResolverCache } from './bashResolver.js';
+
+// IS_WIN32 is captured at module-eval time, so these tests exercise whichever
+// branch the host platform selects (Linux/macOS CI: the non-Windows path).
+// Platform-specific assertions are gated on process.platform so the suite is
+// correct on every runner.
+const IS_WIN32 = process.platform === 'win32';
+
+afterEach(() => {
+ _resetBashResolverCache();
+ delete process.env.PORTOS_BASH;
+ vi.restoreAllMocks();
+});
+
+describe('resolveBashBinary', () => {
+ it('returns a non-empty string', () => {
+ expect(typeof resolveBashBinary()).toBe('string');
+ expect(resolveBashBinary().length).toBeGreaterThan(0);
+ });
+
+ it('memoizes — repeated calls return the same value', () => {
+ const first = resolveBashBinary();
+ expect(resolveBashBinary()).toBe(first);
+ });
+
+ it('on non-Windows resolves to bare `bash` and ignores PORTOS_BASH', () => {
+ if (IS_WIN32) return; // branch not taken on Windows
+ process.env.PORTOS_BASH = '/nonexistent/custom/bash';
+ expect(resolveBashBinary()).toBe('bash');
+ });
+
+ it('on Windows honors an existing PORTOS_BASH override', () => {
+ if (!IS_WIN32) return; // branch not taken off Windows
+ // Any real existing executable proves the override path is taken; the
+ // resolver only checks existsSync, not that it's really bash.
+ process.env.PORTOS_BASH = process.execPath; // node.exe — guaranteed to exist
+ expect(resolveBashBinary()).toBe(process.execPath);
+ });
+
+ it('ignores a PORTOS_BASH override that does not exist', () => {
+ process.env.PORTOS_BASH = '/definitely/not/here/bash.exe';
+ // Falls through to Git Bash / bare bash — never the bogus override.
+ expect(resolveBashBinary()).not.toBe('/definitely/not/here/bash.exe');
+ });
+});
diff --git a/server/lib/db.js b/server/lib/db.js
index a54db70e87..994576e032 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -114,6 +114,13 @@ export async function checkHealth() {
// cleared on settle so a deliberate later call (the gate runs it twice) still
// re-applies (cheap — ~30 no-op parses on an up-to-date DB).
let ensureSchemaInFlight = null;
+// Every DB-backed store self-runs ensureSchema() when it warms its backend at
+// boot (memory, creative-director, media index, catalog, universe/story/writers
+// stores, pipeline series/issues, plus the boot DB gate). Those warm
+// sequentially, so the in-flight dedup above can't collapse them — each re-runs
+// the idempotent DDL (cheap no-ops) and would otherwise re-log the same line.
+// Log it once per process so the boot output isn't a wall of identical lines.
+let schemaUpgradeLogged = false;
/**
* Apply idempotent schema upgrades to an existing database.
@@ -834,7 +841,10 @@ async function ensureSchemaImpl() {
for (const sql of catalogDDL) {
await pool.query(sql);
}
- console.log('🗄️ Database schema upgrades applied');
+ if (!schemaUpgradeLogged) {
+ console.log('🗄️ Database schema upgrades applied');
+ schemaUpgradeLogged = true;
+ }
}
/**
diff --git a/server/lib/index.js b/server/lib/index.js
index a230bd4200..0f0cc4a9db 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -100,6 +100,7 @@ export * from './pdfImageEmbed.js';
export * from './zipStream.js';
// === Process execution ===
+export * from './bashResolver.js';
export * from './bufferedSpawn.js';
export * from './commandSecurity.js';
export * from './execGit.js';
diff --git a/server/routes/database.js b/server/routes/database.js
index b96d3f9ca0..f9f4c4a245 100644
--- a/server/routes/database.js
+++ b/server/routes/database.js
@@ -6,6 +6,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { checkHealth, query } from '../lib/db.js';
import { PATHS } from '../lib/fileUtils.js';
import { resolvePgDumpBinary } from '../lib/pgTools.js';
+import { resolveBashBinary } from '../lib/bashResolver.js';
const rootDir = PATHS.root;
// Pass the script path to bash with forward slashes. On Windows the native
@@ -14,6 +15,11 @@ const rootDir = PATHS.root;
// Git Bash accepts drive paths with forward slashes (`H:/.../db.sh`), so
// normalize separators here. POSIX paths are unaffected (no backslashes).
const dbScript = join(rootDir, 'scripts', 'db.sh').replace(/\\/g, '/');
+// Resolve the interpreter explicitly. A bare `bash` on Windows often resolves
+// (via PM2's PATH) to WSL, which mounts drives at /mnt/h and can't see the
+// `H:/...` drive path above — exit 127. resolveBashBinary() prefers Git Bash,
+// which both accepts drive paths and runs db.sh against the Windows toolchain.
+const bashBinary = resolveBashBinary();
const router = Router();
@@ -39,7 +45,7 @@ function runCmd(cmd, args, timeout = 120_000, env = process.env) {
});
}
-const runDbScript = (args) => runCmd('bash', [dbScript, ...args]);
+const runDbScript = (args) => runCmd(bashBinary, [dbScript, ...args]);
function parseDbMode(stdout) {
const match = stdout.match(/Current mode:\s*(\w+)/);
@@ -100,7 +106,7 @@ async function getDockerDiskUsage() {
* Get native PostgreSQL process stats via ps.
*/
async function getNativeStats() {
- const result = await runCmd('bash', ['-c',
+ const result = await runCmd(bashBinary, ['-c',
'ps aux | grep "[p]ostgres.*-D" | head -1'
], 5_000);
if (result.exitCode !== 0 || !result.stdout.trim()) return null;
@@ -111,7 +117,7 @@ async function getNativeStats() {
if (!Number.isInteger(pidRaw) || pidRaw <= 0) return null;
const pid = String(pidRaw);
// Get all postgres child processes
- const childResult = await runCmd('bash', ['-c',
+ const childResult = await runCmd(bashBinary, ['-c',
`ps -o pid=,pcpu=,pmem=,rss= -p $(pgrep -P ${pid} | tr '\\n' ',')${pid} 2>/dev/null`
], 5_000);
let totalCpu = 0, totalMem = 0, totalRss = 0, pids = 0;
@@ -372,7 +378,7 @@ router.post('/sync', asyncHandler(async (req, res) => {
// Step 3: Import into target (active backend untouched — different port)
// Strip pg17-only features for compat with older psql: \restrict/\unrestrict, transaction_timeout
emit('start', { message: `Importing into ${targetMode} (port ${targetPort})...` });
- const importResult = await runCmd('bash', ['-c',
+ const importResult = await runCmd(bashBinary, ['-c',
`sed -e '/^\\\\restrict /d' -e '/^\\\\unrestrict /d' -e '/^SET transaction_timeout/d' "${dumpFile}" | psql -h localhost -p ${targetPort} -U ${pgUser} -d ${pgDb} -v ON_ERROR_STOP=1 --single-transaction`
], 120_000, pgEnv(targetPort));
@@ -398,7 +404,7 @@ router.post('/start', asyncHandler(async (req, res) => {
}
// Native: use db.sh which handles brew services / pg_ctl
- const result = await runCmd('bash', [dbScript, 'start'], 30_000);
+ const result = await runCmd(bashBinary, [dbScript, 'start'], 30_000);
res.json({ success: result.exitCode === 0, output: result.stdout });
}));
@@ -415,7 +421,7 @@ router.post('/stop', asyncHandler(async (req, res) => {
}
// Native stop
- const result = await runCmd('bash', [dbScript, 'stop'], 15_000);
+ const result = await runCmd(bashBinary, [dbScript, 'stop'], 15_000);
res.json({ success: result.exitCode === 0, output: result.stdout });
}));