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

feat(database): native mode reuses system PostgreSQL on port 5432

Adam Eivyd40cb941e6c8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4300a9c7d2..08e6d84028 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -19,6 +19,8 @@
## Changed
+- **Native PostgreSQL uses system pg** — Native mode now reuses the existing system PostgreSQL on port 5432 (e.g., Homebrew service) instead of running a separate instance on port 5561. `setup-native` detects an already-running pg, creates the portos user/database, and applies the schema. No dedicated data directory or manual startup needed. Docker mode unchanged on port 5561. Sync between backends is zero-downtime since they run on different ports simultaneously.
+
- **CoS feature-ideas task** — Agents now implement the next unchecked PLAN.md item instead of inventing features. When user clarification is needed, agents create a `.plan-questions.md` marker and a `plan_question` notification linking to the Documents tab. Added `{appId}` template variable for prompt linking.
- **CoS task prompt enhancement** — Enhance prompt now instructs the LLM to research the codebase (find relevant files, patterns, conventions), plan the approach, and produce a codebase-grounded prompt with specific file paths and implementation steps instead of generic advice
diff --git a/.env.example b/.env.example
index d451dc8472..ad09fbbabe 100644
--- a/.env.example
+++ b/.env.example
@@ -1,14 +1,16 @@
# PortOS Environment Variables
# Copy to .env and customize for your deployment.
-# Default values match docker-compose.yml for zero-config local development.
-# PostgreSQL (must match docker-compose.yml POSTGRES_PASSWORD)
+# Database mode: "native" uses system PostgreSQL (port 5432), "docker" uses containerized pg (port 5561)
+# PGMODE=native
+
+# PostgreSQL password (must match docker-compose.yml POSTGRES_PASSWORD in Docker mode)
# Note: Changing this after initial setup requires manually updating the PostgreSQL user password (or recreating the DB volume).
PGPASSWORD=portos
-# Optional overrides (defaults match docker-compose.yml)
+# Optional overrides (defaults auto-detect from PGMODE)
# PGHOST=localhost
-# PGPORT=5561
+# PGPORT=5432
# PGDATABASE=portos
# PGUSER=portos
diff --git a/CLAUDE.md b/CLAUDE.md
index 6ff0ee7541..e4ed1295f3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -36,7 +36,7 @@ PortOS is a monorepo with Express.js server (port 5555) and React/Vite client (p
### Port Allocation
-PortOS uses ports 5554-5560. Define all ports in `ecosystem.config.cjs` using the `ports` object:
+PortOS uses ports 5554-5561. In native mode, PostgreSQL uses the system pg on port 5432; in Docker mode, port 5561. Define all ports in `ecosystem.config.cjs` using the `ports` object:
```javascript
ports: { api: 5555, health: 5554 } // labeled ports for documentation
diff --git a/docker-compose.yml b/docker-compose.yml
index 63de9acfd5..b53736b1ae 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -12,7 +12,7 @@ services:
container_name: portos-db
restart: unless-stopped
ports:
- - "5561:5432"
+ - "${PGPORT_DOCKER:-5561}:5432"
environment:
POSTGRES_DB: portos
POSTGRES_USER: portos
diff --git a/docs/PORTS.md b/docs/PORTS.md
index bb8e88067e..6f7e13fe47 100644
--- a/docs/PORTS.md
+++ b/docs/PORTS.md
@@ -30,7 +30,7 @@ Common port labels:
| 5558 | portos-cos | api | CoS Agent Runner (isolated process) |
| 5559 | portos-autofixer | api | Autofixer daemon API |
| 5560 | portos-autofixer-ui | ui | Autofixer web UI |
-| 5561 | portos-db | db | PostgreSQL + pgvector (Docker, memory system) |
+| 5561 | portos-db | db | PostgreSQL Docker container (native mode uses system pg on 5432) |
## Defining Ports in ecosystem.config.cjs
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index 42ae858e96..c42dc7dc4c 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -11,6 +11,16 @@ const BASE_ENV = {
TZ: 'UTC' // All log timestamps and Date operations in UTC
};
+// Read PGMODE from .env to determine PostgreSQL port
+const fs = require('fs');
+const envFile = path.join(__dirname, '.env');
+let pgMode = 'docker';
+try {
+ const envContent = fs.readFileSync(envFile, 'utf8');
+ const modeMatch = envContent.match(/^PGMODE=(\w+)/m);
+ if (modeMatch) pgMode = modeMatch[1];
+} catch { /* no .env file — default to docker */ }
+
const PORTS = {
API: 5555, // Express API server
UI: 5554, // Vite dev server (client)
@@ -19,7 +29,8 @@ const PORTS = {
COS: 5558, // Chief of Staff agent runner
AUTOFIXER: 5559, // Autofixer API
AUTOFIXER_UI: 5560, // Autofixer UI
- POSTGRES: 5561 // PostgreSQL + pgvector (Docker, memory system)
+ POSTGRES_DOCKER: 5561, // PostgreSQL Docker container (host port mapping)
+ POSTGRES: pgMode === 'native' ? 5432 : 5561 // Active PostgreSQL port
};
module.exports = {
diff --git a/scripts/db.sh b/scripts/db.sh
index e80d809dc0..45d03bec99 100755
--- a/scripts/db.sh
+++ b/scripts/db.sh
@@ -2,8 +2,9 @@
#
# PortOS Database Manager
#
-# Manage PostgreSQL via Docker or native Homebrew installation.
-# Supports switching between modes and migrating data safely.
+# Manage PostgreSQL via Docker or native (system) installation.
+# Native mode reuses an existing system PostgreSQL (e.g., Homebrew) on port 5432
+# rather than running a separate instance. Docker mode runs a container on port 5561.
#
# Usage:
# scripts/db.sh <command>
@@ -25,8 +26,6 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
-# Note: In Docker mode, PGPORT must match the published port in docker-compose.yml (default 5561)
-PGPORT="${PGPORT:-5561}"
PGUSER="${PGUSER:-portos}"
PGDATABASE="${PGDATABASE:-portos}"
PGPASSWORD="${PGPASSWORD:-portos}"
@@ -67,6 +66,19 @@ get_mode() {
fi
}
+# Derive port from mode: native=5432 (system pg), docker=5561 (container)
+get_port() {
+ if [ -n "${PGPORT:-}" ]; then
+ echo "$PGPORT"
+ elif [ "$(get_mode)" = "native" ]; then
+ echo "5432"
+ else
+ echo "5561"
+ fi
+}
+
+PGPORT=$(get_port)
+
# Set mode in .env
set_mode() {
local mode="$1"
@@ -79,7 +91,9 @@ set_mode() {
else
echo "PGMODE=$mode" > "$ENV_FILE"
fi
- log "Mode set to: $mode"
+ # Update PGPORT to match mode
+ PGPORT=$([ "$mode" = "native" ] && echo "5432" || echo "5561")
+ log "Mode set to: $mode (port $PGPORT)"
}
# Check if Docker PostgreSQL is running
@@ -103,16 +117,11 @@ require_docker_compose() {
fi
}
-# Check if native PostgreSQL is running on our port
+# Check if native PostgreSQL is accepting connections on the expected port
native_running() {
PGPASSWORD="$PGPASSWORD" pg_isready -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" >/dev/null 2>&1
}
-# Get native PostgreSQL data directory
-native_data_dir() {
- echo "$ROOT_DIR/data/pgdata"
-}
-
# Auto-detect Homebrew PostgreSQL on macOS and add to PATH
if [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
_pg_bin="$(brew --prefix postgresql@17 2>/dev/null)/bin"
@@ -123,7 +132,35 @@ fi
# Check if native PostgreSQL is installed
has_native_pg() {
- command -v pg_ctl >/dev/null 2>&1
+ command -v psql >/dev/null 2>&1
+}
+
+# Detect an already-running system PostgreSQL and its port
+detect_system_pg() {
+ # Check standard port 5432 first
+ if pg_isready -h localhost -p 5432 >/dev/null 2>&1; then
+ echo "5432"
+ return 0
+ fi
+ # Check if pg_ctl reports a running server
+ if command -v pg_ctl >/dev/null 2>&1; then
+ local datadir=""
+ # Try Homebrew default data dir
+ if [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
+ datadir="$(brew --prefix)/var/postgresql@17"
+ if [ ! -d "$datadir" ]; then
+ datadir="$(brew --prefix)/var/postgres"
+ fi
+ fi
+ if [ -n "$datadir" ] && [ -d "$datadir" ] && pg_ctl -D "$datadir" status >/dev/null 2>&1; then
+ # Parse port from postgresql.conf
+ local port
+ port=$(grep -E '^port\s*=' "$datadir/postgresql.conf" 2>/dev/null | sed 's/.*=\s*//' | tr -d '[:space:]' || echo "5432")
+ echo "${port:-5432}"
+ return 0
+ fi
+ fi
+ return 1
}
# Status command
@@ -148,14 +185,17 @@ cmd_status() {
echo ""
echo "Native:"
if has_native_pg; then
- local datadir
- datadir=$(native_data_dir)
- if [ -f "$datadir/postmaster.pid" ] && PGPASSWORD="$PGPASSWORD" pg_isready -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" >/dev/null 2>&1; then
- log " Native PostgreSQL is running (data: $datadir)"
- elif [ -d "$datadir" ]; then
- warn " Native PostgreSQL configured but not running (data: $datadir)"
+ local sys_port
+ if sys_port=$(detect_system_pg); then
+ log " System PostgreSQL is running on port $sys_port"
+ # Check if portos database exists
+ if PGPASSWORD="$PGPASSWORD" psql -h "$PGHOST" -p "$sys_port" -U "$PGUSER" -d "$PGDATABASE" -c "SELECT 1" >/dev/null 2>&1; then
+ log " PortOS database exists"
+ else
+ warn " PortOS database/user not configured (run: scripts/db.sh setup-native)"
+ fi
else
- warn " Native PostgreSQL installed but not configured for PortOS"
+ warn " Native PostgreSQL installed but not running"
fi
else
warn " Native PostgreSQL not installed"
@@ -229,45 +269,49 @@ start_native() {
exit 1
fi
- local datadir
- datadir=$(native_data_dir)
-
- if [ ! -d "$datadir" ] || [ ! -f "$datadir/PG_VERSION" ]; then
- err "Database not initialized. Run: scripts/db.sh setup-native"
- exit 1
+ # Check if system PostgreSQL is already running and accepting connections
+ if PGPASSWORD="$PGPASSWORD" pg_isready -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" >/dev/null 2>&1; then
+ log "Native PostgreSQL already running on port $PGPORT"
+ return
fi
- # If already running and accepting connections, nothing to do
- if [ -f "$datadir/postmaster.pid" ] && pg_ctl -D "$datadir" status >/dev/null 2>&1; then
- if PGPASSWORD="$PGPASSWORD" pg_isready -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" >/dev/null 2>&1; then
- log "Native PostgreSQL already running on port $PGPORT"
- return
+ # Try to start via Homebrew services (macOS)
+ if [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
+ if brew services list 2>/dev/null | grep -q "postgresql@17"; then
+ info "Starting PostgreSQL via Homebrew services..."
+ brew services start postgresql@17 2>/dev/null || true
+ for i in $(seq 1 15); do
+ if pg_isready -h "$PGHOST" -p "$PGPORT" >/dev/null 2>&1; then
+ log "Native PostgreSQL ready on port $PGPORT"
+ return
+ fi
+ sleep 1
+ done
fi
- # Running but not accepting connections on our port — stop and restart
- warn "Native PostgreSQL running but not accepting connections — restarting..."
- pg_ctl -D "$datadir" stop -m fast 2>/dev/null || true
- rm -f "$datadir/postmaster.pid"
fi
- # Clean stale pid if process is gone
- if [ -f "$datadir/postmaster.pid" ]; then
- if ! pg_ctl -D "$datadir" status >/dev/null 2>&1; then
- warn "Removing stale postmaster.pid..."
- rm -f "$datadir/postmaster.pid"
+ # Try pg_ctl with Homebrew data directory
+ if command -v pg_ctl >/dev/null 2>&1; then
+ local datadir=""
+ if [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
+ datadir="$(brew --prefix)/var/postgresql@17"
+ if [ ! -d "$datadir" ]; then
+ datadir="$(brew --prefix)/var/postgres"
+ fi
fi
- fi
-
- pg_ctl -D "$datadir" -l "$datadir/server.log" -o "-p $PGPORT" start
-
- for i in $(seq 1 15); do
- if PGPASSWORD="$PGPASSWORD" pg_isready -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" >/dev/null 2>&1; then
- log "Native PostgreSQL ready on port $PGPORT"
- return
+ if [ -n "$datadir" ] && [ -d "$datadir" ]; then
+ pg_ctl -D "$datadir" -l "$datadir/server.log" start 2>/dev/null || true
+ for i in $(seq 1 15); do
+ if pg_isready -h "$PGHOST" -p "$PGPORT" >/dev/null 2>&1; then
+ log "Native PostgreSQL ready on port $PGPORT"
+ return
+ fi
+ sleep 1
+ done
fi
- sleep 1
- done
+ fi
- err "PostgreSQL did not start in 15s. Check: $datadir/server.log"
+ err "Could not start PostgreSQL. Try: brew services start postgresql@17"
exit 1
}
@@ -292,16 +336,23 @@ stop_docker() {
}
stop_native() {
- local datadir
- datadir=$(native_data_dir)
-
- if [ ! -d "$datadir" ]; then
- warn "No native database found"
+ info "Stopping native PostgreSQL..."
+ # Stop via Homebrew services (macOS)
+ if [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
+ brew services stop postgresql@17 2>/dev/null || true
+ log "Stopped"
return
fi
-
- info "Stopping native PostgreSQL..."
- pg_ctl -D "$datadir" stop -m fast 2>/dev/null || true
+ # Fallback: pg_ctl
+ if command -v pg_ctl >/dev/null 2>&1; then
+ local datadir=""
+ if [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
+ datadir="$(brew --prefix)/var/postgresql@17"
+ fi
+ if [ -n "$datadir" ] && [ -d "$datadir" ]; then
+ pg_ctl -D "$datadir" stop -m fast 2>/dev/null || true
+ fi
+ fi
log "Stopped"
}
@@ -348,34 +399,21 @@ fix_docker() {
}
fix_native() {
- local datadir
- datadir=$(native_data_dir)
-
- if [ ! -d "$datadir" ]; then
- warn "No native database found"
+ info "Fixing native PostgreSQL..."
+ # Restart via Homebrew services
+ if [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
+ brew services restart postgresql@17 2>/dev/null || true
+ log "PostgreSQL restarted via Homebrew"
return
fi
-
- info "Fixing native PostgreSQL..."
-
- # Try graceful shutdown first
- pg_ctl -D "$datadir" stop -m fast 2>/dev/null || true
-
- # Remove stale pid
- rm -f "$datadir/postmaster.pid"
-
- log "Stale lock files cleaned"
- info "Run 'scripts/db.sh start' to restart"
+ warn "Manual fix may be needed — check PostgreSQL logs"
}
-# Setup native PostgreSQL
+# Setup native PostgreSQL — detects and reuses existing system installation
cmd_setup_native() {
- info "Setting up native PostgreSQL + pgvector..."
-
- local datadir
- datadir=$(native_data_dir)
+ info "Setting up native PostgreSQL for PortOS..."
- # Install PostgreSQL 17 and pgvector via Homebrew
+ # Step 1: Ensure PostgreSQL is installed
if [ "$(uname)" = "Darwin" ]; then
if ! command -v brew >/dev/null 2>&1; then
err "Homebrew not installed. Install from https://brew.sh"
@@ -400,76 +438,75 @@ cmd_setup_native() {
PG_BIN="$(brew --prefix postgresql@17)/bin"
export PATH="$PG_BIN:$PATH"
info "Using PostgreSQL from: $PG_BIN"
- if ! echo "$PATH" | tr ':' '\n' | grep -qx "$PG_BIN"; then
- warn "PostgreSQL bin dir is not on your default PATH"
- echo " Add this to your shell profile (~/.zshrc or ~/.bashrc):"
- echo " export PATH=\"$PG_BIN:\\\$PATH\""
- echo " Then restart your terminal or run: source ~/.zshrc"
- fi
else
- if ! command -v pg_ctl >/dev/null 2>&1; then
+ if ! command -v psql >/dev/null 2>&1; then
err "Please install PostgreSQL 17 and pgvector for your platform"
exit 1
fi
fi
- # Initialize the data directory
- if [ -d "$datadir" ]; then
- warn "Data directory already exists: $datadir"
- echo " To reinitialize, remove it first: rm -rf $datadir"
+ # Step 2: Ensure PostgreSQL is running
+ local pg_port=""
+ if pg_port=$(detect_system_pg); then
+ log "System PostgreSQL already running on port $pg_port"
else
- info "Initializing database cluster..."
- mkdir -p "$datadir"
- local pwfile
- pwfile="$(mktemp)"
- chmod 600 "$pwfile"
- printf '%s\n' "$PGPASSWORD" > "$pwfile"
- # Ensure the temp password file is cleared and removed on any exit/error path
- trap 'if [ -n "${pwfile-}" ] && [ -f "$pwfile" ]; then : > "$pwfile"; rm -f "$pwfile"; fi' RETURN ERR
- initdb -D "$datadir" --username="$PGUSER" --auth=scram-sha-256 --pwfile="$pwfile" --no-locale --encoding=UTF8
- : > "$pwfile"
- rm -f "$pwfile"
- log "Database cluster initialized"
-
- # Configure to use our port
- echo "port = $PGPORT" >> "$datadir/postgresql.conf"
- echo "listen_addresses = 'localhost'" >> "$datadir/postgresql.conf"
- info "Configured to listen on port $PGPORT"
- fi
-
- # Start the server
- start_native
-
- # Create the database and run init SQL
- if ! PGPASSWORD="$PGPASSWORD" psql -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -lqt 2>/dev/null | cut -d\| -f1 | grep -qw "$PGDATABASE"; then
- info "Creating database: $PGDATABASE"
- PGPASSWORD="$PGPASSWORD" createdb -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" "$PGDATABASE"
+ info "Starting PostgreSQL..."
+ if [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
+ brew services start postgresql@17
+ sleep 2
+ if pg_port=$(detect_system_pg); then
+ log "PostgreSQL started on port $pg_port"
+ else
+ err "PostgreSQL failed to start. Check: brew services list"
+ exit 1
+ fi
+ else
+ err "PostgreSQL is not running. Start it and try again."
+ exit 1
+ fi
fi
- # Set user password (using psql variables to avoid shell injection)
- PGPASSWORD="$PGPASSWORD" psql -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDATABASE" \
- -v pw="$PGPASSWORD" -v user="$PGUSER" -c "ALTER USER :\"user\" WITH PASSWORD :'pw';" 2>/dev/null
+ PGPORT="$pg_port"
- # Run init SQL
+ # Step 3: Create portos user if it doesn't exist
+ # Connect as the current system user (default Homebrew superuser) to create the role
+ local sys_user
+ sys_user="$(whoami)"
+ if ! psql -h "$PGHOST" -p "$PGPORT" -U "$sys_user" -d postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname='$PGUSER'" 2>/dev/null | grep -q 1; then
+ info "Creating database user: $PGUSER"
+ psql -h "$PGHOST" -p "$PGPORT" -U "$sys_user" -d postgres -c "CREATE ROLE $PGUSER WITH LOGIN PASSWORD '$PGPASSWORD' CREATEDB;"
+ log "User $PGUSER created"
+ else
+ log "User $PGUSER already exists"
+ # Ensure password is set correctly
+ psql -h "$PGHOST" -p "$PGPORT" -U "$sys_user" -d postgres \
+ -v pw="$PGPASSWORD" -v user="$PGUSER" -c "ALTER USER :\"user\" WITH PASSWORD :'pw';" 2>/dev/null || true
+ fi
+
+ # Step 4: Create portos database if it doesn't exist
+ if ! psql -h "$PGHOST" -p "$PGPORT" -U "$sys_user" -d postgres -lqt 2>/dev/null | cut -d\| -f1 | grep -qw "$PGDATABASE"; then
+ info "Creating database: $PGDATABASE"
+ psql -h "$PGHOST" -p "$PGPORT" -U "$sys_user" -d postgres -c "CREATE DATABASE $PGDATABASE OWNER $PGUSER;"
+ log "Database $PGDATABASE created"
+ else
+ log "Database $PGDATABASE already exists"
+ fi
+
+ # Step 5: Enable pgvector extension and apply schema
info "Applying schema..."
+ # pgvector extension requires superuser — create as system user, then run schema as portos
+ psql -h "$PGHOST" -p "$PGPORT" -U "$sys_user" -d "$PGDATABASE" -c "CREATE EXTENSION IF NOT EXISTS vector;" 2>/dev/null || true
+ psql -h "$PGHOST" -p "$PGPORT" -U "$sys_user" -d "$PGDATABASE" -c "CREATE EXTENSION IF NOT EXISTS pgcrypto;" 2>/dev/null || true
PGPASSWORD="$PGPASSWORD" psql -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDATABASE" -v ON_ERROR_STOP=1 --single-transaction -f "$ROOT_DIR/server/scripts/init-db.sql"
log "Schema applied"
- # Switch mode
+ # Step 6: Switch mode to native
set_mode native
- # Update PGPORT in .env if not already correct
- if [ -f "$ENV_FILE" ] && ! grep -q "^PGPORT=$PGPORT" "$ENV_FILE"; then
- if grep -q "^PGPORT=" "$ENV_FILE"; then
- inplace_sed "s/^PGPORT=.*/PGPORT=$PGPORT/" "$ENV_FILE"
- else
- printf '\nPGPORT=%s\n' "$PGPORT" >> "$ENV_FILE"
- fi
- fi
-
echo ""
log "Native PostgreSQL is ready!"
- info "Data directory: $datadir"
+ info "Using system PostgreSQL on port $PGPORT"
+ info "Database: $PGDATABASE (user: $PGUSER)"
info "To migrate data from Docker: scripts/db.sh migrate"
}
@@ -579,6 +616,8 @@ cmd_migrate() {
# Switch mode and start target — restore mode on failure or interruption
set_mode "$target_mode"
+ # Recalculate port for the new mode
+ PGPORT=$(get_port)
_migrate_cleanup() {
warn "Migration aborted — restoring mode to $current_mode"
set_mode "$current_mode"
@@ -586,12 +625,6 @@ cmd_migrate() {
trap '_migrate_cleanup' ERR INT TERM
if [ "$target_mode" = "native" ]; then
- if [ ! -d "$(native_data_dir)" ]; then
- err "Native PostgreSQL not set up. Run: scripts/db.sh setup-native"
- set_mode "$current_mode"
- trap - ERR
- exit 1
- fi
start_native
else
start_docker
@@ -616,9 +649,8 @@ cmd_migrate() {
# Use Docker mode
cmd_use_docker() {
- stop_native 2>/dev/null || true
set_mode docker
- info "Switched to Docker mode. Run 'scripts/db.sh start' to start."
+ info "Switched to Docker mode (port 5561). Run 'scripts/db.sh start' to start."
}
# Use native mode
@@ -627,11 +659,12 @@ cmd_use_native() {
err "Native PostgreSQL not installed. Run: scripts/db.sh setup-native"
exit 1
fi
- if [ ! -d "$(native_data_dir)" ]; then
- err "Native database not initialized. Run: scripts/db.sh setup-native"
- exit 1
+ # Verify system pg is reachable
+ if ! pg_isready -h "$PGHOST" -p 5432 >/dev/null 2>&1; then
+ warn "System PostgreSQL not running on port 5432"
+ echo " Start it: brew services start postgresql@17"
fi
- # Best-effort stop of Docker DB container without requiring Docker to be installed/running
+ # Best-effort stop of Docker DB container
if command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
(
cd "$ROOT_DIR"
@@ -639,7 +672,7 @@ cmd_use_native() {
)
fi
set_mode native
- info "Switched to native mode. Run 'scripts/db.sh start' to start."
+ info "Switched to native mode (port 5432). Run 'scripts/db.sh start' to start."
}
# Show logs
@@ -652,12 +685,15 @@ cmd_logs() {
cd "$ROOT_DIR"
docker compose logs -f db
else
- local datadir
- datadir=$(native_data_dir)
- if [ -f "$datadir/server.log" ]; then
- tail -f "$datadir/server.log"
+ # Homebrew pg logs
+ local logfile=""
+ if [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
+ logfile="$(brew --prefix)/var/log/[email protected]"
+ fi
+ if [ -n "$logfile" ] && [ -f "$logfile" ]; then
+ tail -f "$logfile"
else
- warn "No log file found at $datadir/server.log"
+ warn "No log file found. Check: brew services info postgresql@17"
fi
fi
}
@@ -676,9 +712,9 @@ Commands:
fix Fix stale postmaster.pid and other issues
logs Tail database logs
- setup-native Install PostgreSQL 17 + pgvector via Homebrew
- use-docker Switch to Docker mode
- use-native Switch to native mode
+ setup-native Detect/install PostgreSQL, create portos database
+ use-docker Switch to Docker mode (port 5561)
+ use-native Switch to native/system mode (port 5432)
migrate Export from current mode, import to the other
export [label] Export database to data/db-dumps/
@@ -686,7 +722,7 @@ Commands:
Environment:
PGMODE=docker|native Set in .env to control default mode
- PGPORT=5561 PostgreSQL port (default: 5561)
+ PGPORT=5432 PostgreSQL port (native=5432, docker=5561)
PGPASSWORD=portos Database password
HELP
}
diff --git a/scripts/setup-db.js b/scripts/setup-db.js
index 14f1afdb8a..89d8d40233 100644
--- a/scripts/setup-db.js
+++ b/scripts/setup-db.js
@@ -3,9 +3,8 @@
/**
* Database Setup Script
*
- * Ensures PostgreSQL + pgvector is running via Docker Compose.
- * Gracefully skips if Docker is not available — the memory system
- * falls back to file-based JSON storage automatically.
+ * Ensures PostgreSQL is available — either via Docker Compose (docker mode)
+ * or the system PostgreSQL (native mode).
*
* Called by: npm run setup, npm run update, npm start, npm run dev
*/
@@ -14,10 +13,22 @@ import { execFileSync } from 'child_process';
import { createInterface } from 'readline';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
+import { readFileSync } from 'fs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = join(__dirname, '..');
+// Read PGMODE from .env
+function getMode() {
+ try {
+ const env = readFileSync(join(rootDir, '.env'), 'utf8');
+ const match = env.match(/^PGMODE=(\w+)/m);
+ return match?.[1] || 'docker';
+ } catch {
+ return 'docker';
+ }
+}
+
// Check if Docker is available
function hasDocker() {
try {
@@ -61,6 +72,16 @@ function isContainerRunning() {
}
}
+// Check if native PostgreSQL is accepting connections
+function isNativeReady(port = 5432) {
+ try {
+ execFileSync('pg_isready', ['-h', 'localhost', '-p', String(port)], { stdio: 'pipe' });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
// Wait for PostgreSQL to accept connections
function waitForHealth(maxAttempts = 30) {
for (let i = 0; i < maxAttempts; i++) {
@@ -134,8 +155,34 @@ async function handleDockerUnavailable(message, issue) {
}
}
-console.log('🗄️ Setting up PostgreSQL + pgvector...');
+const mode = getMode();
+console.log(`🗄️ Setting up PostgreSQL (mode: ${mode})...`);
+
+if (mode === 'native') {
+ // Native mode: check if system PostgreSQL is running
+ if (isNativeReady()) {
+ console.log('✅ System PostgreSQL ready on port 5432');
+ process.exit(0);
+ }
+
+ // Try to start via Homebrew
+ if (process.platform === 'darwin') {
+ try {
+ console.log('🍺 Starting PostgreSQL via Homebrew...');
+ execFileSync('brew', ['services', 'start', 'postgresql@17'], { stdio: 'pipe' });
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 2000);
+ if (isNativeReady()) {
+ console.log('✅ System PostgreSQL ready on port 5432');
+ process.exit(0);
+ }
+ } catch { /* fall through */ }
+ }
+
+ console.warn('⚠️ Native PostgreSQL not running — run: scripts/db.sh setup-native');
+ process.exit(0);
+}
+// Docker mode
if (!hasDocker()) {
await handleDockerUnavailable('Docker not found — skipping database setup', 'not_installed');
}
diff --git a/server/lib/db.js b/server/lib/db.js
index a19b88d9b0..c1ffd2d637 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -13,10 +13,10 @@ if (!process.env.PGPASSWORD) {
console.warn('⚠️ PGPASSWORD not set — using default. Set PGPASSWORD env var for production.');
}
-// Connection config from environment or defaults matching docker-compose.yml
+// Connection config from environment or defaults
const pool = new Pool({
host: process.env.PGHOST || 'localhost',
- port: parseInt(process.env.PGPORT || '5561', 10),
+ port: parseInt(process.env.PGPORT || '5432', 10),
database: process.env.PGDATABASE || 'portos',
user: process.env.PGUSER || 'portos',
password: process.env.PGPASSWORD || 'portos',
diff --git a/server/routes/database.js b/server/routes/database.js
index d3faa8382b..d19af025d2 100644
--- a/server/routes/database.js
+++ b/server/routes/database.js
@@ -8,7 +8,6 @@ import { checkHealth, query } from '../lib/db.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = join(__dirname, '..', '..');
const dbScript = join(rootDir, 'scripts', 'db.sh');
-const nativeDataDir = join(rootDir, 'data', 'pgdata');
const router = Router();
@@ -128,12 +127,15 @@ async function getNativeStats() {
}
/**
- * Get native data directory disk usage.
+ * Get native PostgreSQL database size via SQL query.
*/
async function getNativeDiskUsage() {
- const result = await runCmd('du', ['-sh', nativeDataDir], 5_000);
+ const nativePort = process.env.PGPORT || '5432';
+ const result = await runCmd('bash', ['-c',
+ `PGPASSWORD=${pgPassword} psql -h localhost -p ${nativePort} -U ${pgUser} -d ${pgDb} -tAc "SELECT pg_size_pretty(pg_database_size(current_database()))"`
+ ], 5_000);
if (result.exitCode !== 0) return null;
- return result.stdout.trim().split('\t')[0] || null;
+ return result.stdout.trim() || null;
}
// GET /api/database/status — current mode, connectivity, row counts, resource stats
@@ -158,8 +160,8 @@ router.get('/status', asyncHandler(async (req, res) => {
// Parse native status
const nativeInstalled = !/Native PostgreSQL not installed/.test(scriptResult.stdout);
- const nativeRunning = /Native PostgreSQL is running/.test(scriptResult.stdout);
- const nativeConfigured = nativeInstalled && !/not configured for PortOS/.test(scriptResult.stdout);
+ const nativeRunning = /System PostgreSQL is running/.test(scriptResult.stdout);
+ const nativeConfigured = nativeInstalled && /PortOS database exists/.test(scriptResult.stdout);
// Parse row count
const rowMatch = scriptResult.stdout.match(/Memories table has (\d+|N\/A) rows/);
@@ -246,64 +248,17 @@ router.post('/switch', asyncHandler(async (req, res) => {
res.json({ success: true, output: switchResult.stdout + '\n' + startResult.stdout });
}));
-const SYNC_PORT = '5562';
-const pgPort = process.env.PGPORT || '5561';
const pgUser = process.env.PGUSER || 'portos';
const pgDb = process.env.PGDATABASE || 'portos';
const pgPassword = process.env.PGPASSWORD || 'portos';
-/**
- * Start the target backend on a temporary port for sync import.
- * Returns a cleanup function to stop the temporary backend.
- * The active backend stays running on the main port untouched.
- */
-async function startTargetOnTempPort(targetMode) {
- if (targetMode === 'native') {
- // Start native pg on temp port — won't conflict with active backend on main port
- const pgCtl = process.env.PG_BIN ? join(process.env.PG_BIN, 'pg_ctl') : 'pg_ctl';
- const result = await runCmd(pgCtl, [
- '-D', nativeDataDir, '-l', join(nativeDataDir, 'server.log'),
- '-o', `-p ${SYNC_PORT}`, 'start'
- ], 30_000);
- if (result.exitCode !== 0) return { ok: false, details: result.stderr || result.stdout };
- // Wait for ready
- for (let i = 0; i < 15; i++) {
- const ready = await runCmd('bash', ['-c',
- `PGPASSWORD=${pgPassword} pg_isready -h localhost -p ${SYNC_PORT} -U ${pgUser}`
- ], 3_000);
- if (ready.exitCode === 0) break;
- await new Promise(r => setTimeout(r, 1000));
- }
- return {
- ok: true,
- cleanup: () => runCmd(pgCtl, ['-D', nativeDataDir, 'stop', '-m', 'fast'], 15_000)
- };
- }
-
- // Docker: start a temporary container on the temp port using the same volume
- const syncContainer = 'portos-db-sync';
- await runCmd('docker', ['rm', '-f', syncContainer], 5_000);
- const result = await runCmd('docker', [
- 'compose', 'run', '-d', '--no-deps', '--name', syncContainer,
- '-p', `${SYNC_PORT}:5432`, 'db'
- ], 60_000);
- if (result.exitCode !== 0) return { ok: false, details: result.stderr || result.stdout };
- // Wait for ready
- for (let i = 0; i < 30; i++) {
- const ready = await runCmd('bash', ['-c',
- `PGPASSWORD=${pgPassword} pg_isready -h localhost -p ${SYNC_PORT} -U ${pgUser}`
- ], 3_000);
- if (ready.exitCode === 0) break;
- await new Promise(r => setTimeout(r, 1000));
- }
- return {
- ok: true,
- cleanup: () => runCmd('docker', ['rm', '-f', syncContainer], 15_000)
- };
-}
+// Native (5432) and Docker (5561) use different ports, so both can run simultaneously.
+const NATIVE_PORT = '5432';
+const DOCKER_PORT = '5561';
// POST /api/database/sync — copy data from active to non-active backend
-// Uses a temporary port for the target so the active backend never goes down.
+// Since native (5432) and Docker (5561) use different ports, both can be
+// running simultaneously. No need to stop the active backend.
router.post('/sync', asyncHandler(async (req, res) => {
const io = req.app.get('io');
const emit = (event, data) => io?.emit('database:progress', { event, ...data });
@@ -311,6 +266,8 @@ router.post('/sync', asyncHandler(async (req, res) => {
const statusResult = await runDbScript(['status']);
const currentMode = parseDbMode(statusResult.stdout);
const targetMode = currentMode === 'docker' ? 'native' : 'docker';
+ const sourcePort = currentMode === 'docker' ? DOCKER_PORT : NATIVE_PORT;
+ const targetPort = targetMode === 'docker' ? DOCKER_PORT : NATIVE_PORT;
// Step 1: Export from active database (stays running)
emit('start', { message: 'Exporting from active database...' });
@@ -323,23 +280,22 @@ router.post('/sync', asyncHandler(async (req, res) => {
const dumpFile = exportLines[exportLines.length - 1]?.trim();
console.log(`🗄️ Sync: exported to ${dumpFile}`);
- // Step 2: Start target on temporary port (active backend untouched)
- emit('start', { message: `Starting ${targetMode} for import...` });
- const target = await startTargetOnTempPort(targetMode);
- if (!target.ok) {
- emit('error', { message: `Failed to start ${targetMode}` });
- return res.status(500).json({ error: `Failed to start ${targetMode}`, details: target.details });
+ // Step 2: Ensure target is running
+ emit('start', { message: `Checking ${targetMode} is running...` });
+ const readyResult = await runCmd('bash', ['-c',
+ `PGPASSWORD=${pgPassword} pg_isready -h localhost -p ${targetPort} -U ${pgUser}`
+ ], 5_000);
+ if (readyResult.exitCode !== 0) {
+ emit('error', { message: `${targetMode} database not running on port ${targetPort}. Start it first.` });
+ return res.status(400).json({ error: `${targetMode} database not running on port ${targetPort}. Start it first.` });
}
- // Step 3: Import into target via temp port
- emit('start', { message: `Importing into ${targetMode}...` });
+ // Step 3: Import into target (active backend untouched — different port)
+ emit('start', { message: `Importing into ${targetMode} (port ${targetPort})...` });
const importResult = await runCmd('bash', ['-c',
- `PGPASSWORD=${pgPassword} psql -h localhost -p ${SYNC_PORT} -U ${pgUser} -d ${pgDb} -v ON_ERROR_STOP=1 --single-transaction < "${dumpFile}"`
+ `PGPASSWORD=${pgPassword} psql -h localhost -p ${targetPort} -U ${pgUser} -d ${pgDb} -v ON_ERROR_STOP=1 --single-transaction < "${dumpFile}"`
], 120_000);
- // Step 4: Stop temp target regardless of import result
- await target.cleanup();
-
if (importResult.exitCode !== 0) {
emit('error', { message: `Import into ${targetMode} failed` });
return res.status(500).json({ error: `Import into ${targetMode} failed`, details: importResult.stderr || importResult.stdout });
@@ -361,14 +317,8 @@ router.post('/start', asyncHandler(async (req, res) => {
return res.json({ success: result.exitCode === 0, output: result.stdout });
}
- // Native: use pg_ctl directly
- const pgBin = process.env.PG_BIN || '';
- const pgCtl = pgBin ? join(pgBin, 'pg_ctl') : 'pg_ctl';
- const pgPort = process.env.PGPORT || '5561';
- const result = await runCmd(pgCtl, [
- '-D', nativeDataDir, '-l', join(nativeDataDir, 'server.log'),
- '-o', `-p ${pgPort}`, 'start'
- ], 30_000);
+ // Native: use db.sh which handles brew services / pg_ctl
+ const result = await runCmd('bash', [dbScript, 'start'], 30_000);
res.json({ success: result.exitCode === 0, output: result.stdout });
}));
@@ -413,10 +363,13 @@ router.post('/destroy', asyncHandler(async (req, res) => {
return res.json({ success: true, output: result.stdout });
}
- // Native: stop and remove data directory
- await runCmd('bash', [dbScript, 'stop'], 15_000);
- const result = await runCmd('rm', ['-rf', nativeDataDir], 10_000);
- res.json({ success: result.exitCode === 0 });
+ // Native: drop the portos database (system pg stays running)
+ const sysUser = process.env.USER || 'portos';
+ const nativePort = process.env.PGPORT || '5432';
+ const result = await runCmd('bash', ['-c',
+ `psql -h localhost -p ${nativePort} -U ${sysUser} -d postgres -c "DROP DATABASE IF EXISTS ${pgDb}"`
+ ], 15_000);
+ res.json({ success: result.exitCode === 0, output: result.stdout });
}));
// POST /api/database/setup-native — install and configure native PostgreSQL
diff --git a/server/services/backup.js b/server/services/backup.js
index 1be27a1993..425aac283e 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -155,7 +155,7 @@ export async function dumpPostgres(outputPath) {
}
const pgHost = process.env.PGHOST || 'localhost';
- const pgPort = process.env.PGPORT || '5561';
+ const pgPort = process.env.PGPORT || '5432';
const pgDb = process.env.PGDATABASE || 'portos';
const pgUser = process.env.PGUSER || 'portos';