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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(setup): finish native-pg path and run full workspace install
Adam Eivyaa9e6aedfb61
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7bb6264934..31acfaa6e8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -59,6 +59,8 @@- **Dashboard layout picker dropdown no longer clips off-screen on mobile** — the layout selector menu uses `absolute right-0` to anchor its right edge to the trigger button. On a narrow viewport where the picker sits mid-row (after Server status, before Arrange/Ambient), the 224px-wide menu would extend past the left edge of the screen and cut off layout names ("ything", "us", "ning Review"). `LayoutPicker` now measures the trigger's bounding rect on open: when right-aligning would clip, it switches to `position: fixed` anchored to the viewport's right edge with an 8px margin instead. Added `max-w-[calc(100vw-1rem)]` so the menu can never exceed the viewport regardless of placement, `min-h-[40px]` on every row for the project's 40px touch-target standard, and `shrink-0` on the leading icon + trailing "Built-in" badge so they never collapse when the layout name is long. The dashboard header button row also wraps now (`flex-wrap items-center justify-end gap-2 sm:gap-3`) so on very narrow screens the controls re-flow instead of crowding into a single overflowing row. Files: `client/src/components/dashboard/LayoutPicker.jsx`, `client/src/pages/Dashboard.jsx`.+- **`./setup.sh` no longer leaves a fresh checkout half-installed when native PostgreSQL is chosen.** Two bugs combined to make the script exit "successfully" on a clean machine while the resulting app couldn't boot: (1) `scripts/setup-db.js` treated `pg_isready` as proof that the PortOS database was set up, so when a user already had Homebrew Postgres listening on 5432 and picked **2) Native PostgreSQL** at the prompt (or had `PGMODE=native` in `.env`), the script printed "✅ System PostgreSQL ready on port 5432" and exited 0 — never running `db.sh setup-native`, which is what creates the `portos` role, `portos` database, `vector`/`pgcrypto` extensions, and applies `init-db.sql`. The next `npm start` would then fail to connect with `portos`/`portos`. (2) `setup.sh` ran only the root `npm install` and never installed `client/`, `server/`, or `autofixer/` workspace deps, ran the esbuild postinstall, or rebuilt `node-pty`. The fix replaces those two calls with a single `npm run install:all` (which already does the full install + `npm run setup`) and adds a domain-level readiness probe (`isPortOSDbReady` — tries to authenticate as `portos@portos` and probe the `memories` table) to both native-mode branches in `setup-db.js`: when the probe passes the script exits fast (no startup-time hit on `npm start`/`npm run dev`, no recurring `ALTER USER ... PASSWORD` side effect against the `portos` role); when the probe fails — fresh checkout, missing role, missing schema, wrong password — the script falls through to `db.sh setup-native` to bootstrap. `setup.sh` also gains a final `Start PortOS now via pm2? (Y/n)` prompt (with reprompt on unrecognized input) so a fresh `git clone && ./setup.sh` can take the user from zero to a running pm2 stack on `http://localhost:5555` in one invocation. Files: `scripts/setup-db.js`, `setup.sh`.+## Changed- **Command palette cleanup pass** — post-review simplify: `normalizeLabel` is exported once from `navManifest.js` and imported by `voice/tools.js` (was duplicated verbatim); `getToolMetadata(id)` added to `voice/tools.js` so `routes/palette.js` no longer reaches through the OpenAI-shaped function spec; palette manifest frozen at module load (`buildActionManifest` no longer runs per request) with `Cache-Control: private, max-age=300`. Client scorer precomputes lowercased `_label`/`_aliases`/`_keywords`/`_section` so per-keystroke fuzzy matching does zero re-lowercasing over the 117-entry manifest. `CmdKSearch.jsx` trimmed ~80 lines: collapsed the triple `useMemo` chain, merged `renderCommandRow` + inline search-result row into a single `renderRow`/`renderGroup` pair, flattened `dispatchCommand` into a `DISPATCH` lookup table, dropped the dead `running` state, removed two `.catch()` error-swallows (errors now propagate to the central toast handler per CLAUDE.md), cleared `resultRefs` on close. `ALIAS_KEYS` cached once in `resolveNavCommand`. Decorative section-banner comments and narration comments removed across the new files.diff --git a/scripts/setup-db.js b/scripts/setup-db.jsindex 45ce2796b5..cdbed5af6f 100644--- a/scripts/setup-db.js+++ b/scripts/setup-db.js@@ -18,15 +18,62 @@ import { readFileSync, writeFileSync } 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';+// Parse .env into a key/value map. Tolerates blank lines, # comments, and+// optional surrounding single/double quotes around values. Returns {} when+// the file is missing.+function parseEnvFile() {+ const result = {};+ let content = '';+ try { content = readFileSync(join(rootDir, '.env'), 'utf8'); } catch { return result; }+ for (const line of content.split('\n')) {+ const trimmed = line.trim();+ if (!trimmed || trimmed.startsWith('#')) continue;+ const idx = trimmed.indexOf('=');+ if (idx === -1) continue;+ const key = trimmed.slice(0, idx).trim();+ let value = trimmed.slice(idx + 1).trim();+ if ((value.startsWith('"') && value.endsWith('"')) ||+ (value.startsWith("'") && value.endsWith("'"))) {+ value = value.slice(1, -1);+ }+ result[key] = value;}+ return result;+}++const envFile = parseEnvFile();+// Resolve PG config from process.env first, then .env, then defaults — so a+// user who sets PGPASSWORD in .env (without exporting it into the shell) is+// respected the same way getMode() respects PGMODE in .env.+const envVar = (key, fallback) => process.env[key] ?? envFile[key] ?? fallback;+// Tolerate accidental whitespace / inline comments / non-numeric junk in+// .env values — fall back to the canonical native port (5432) on anything+// that doesn't parse to a finite integer, instead of letting NaN flow into+// `psql -p` and the success log.+const parsePgPort = (value) => {+ const parsed = Number.parseInt(String(value).trim(), 10);+ return Number.isFinite(parsed) ? parsed : 5432;+};+const PG_USER = envVar('PGUSER', 'portos');+const PG_DATABASE = envVar('PGDATABASE', 'portos');+const PG_PASSWORD = envVar('PGPASSWORD', 'portos');+const PG_PORT_NATIVE = parsePgPort(envVar('PGPORT', 5432));++// Environment to pass to `db.sh` and other psql-wrapping subprocesses, so+// values configured in .env (but not exported into the shell) reach the+// child process. Without this, db.sh setup-native would provision the+// default `portos`/`portos` while isPortOSDbReady() probes with the+// customized creds — leaving setup looping forever.+const PG_CHILD_ENV = {+ ...process.env,+ PGUSER: PG_USER,+ PGDATABASE: PG_DATABASE,+ PGPASSWORD: PG_PASSWORD,+ PGPORT: String(PG_PORT_NATIVE)+};++function getMode() {+ return envVar('PGMODE', 'docker');}// Check if Docker is available@@ -72,11 +119,35 @@ function isContainerRunning() {}}-// Check if native PostgreSQL is accepting connections-function isNativeReady(port = 5432) {+// Domain-level readiness check: the configured PG_USER role can authenticate+// to PG_DATABASE AND the `memories` table from init-db.sql exists in the+// public schema. This is what `db.sh setup-native` produces. The probe+// itself is a single cheap psql round-trip; passing it lets us skip the+// full setup-native path (brew checks, ALTER USER, schema reapply) on+// every `npm start`/`npm run dev`, which would otherwise reset the role's+// password+SUPERUSER privileges on every invocation.+//+// `psql -tAc` exits 0 even when the SELECT returns no rows, so we capture+// stdout and require the literal "1" — without this, an empty result (db+// exists but schema not yet applied) would falsely report "ready" and the+// app would boot against an unmigrated database. `-X` skips the user's+// .psqlrc so a custom prompt or echo setting can't pollute stdout.+function isPortOSDbReady(port = PG_PORT_NATIVE) {try {- execFileSync('pg_isready', ['-h', 'localhost', '-p', String(port)], { stdio: 'pipe' });- return true;+ const output = execFileSync(+ 'psql',+ [+ '-X',+ '-h', 'localhost',+ '-p', String(port),+ '-U', PG_USER,+ '-d', PG_DATABASE,+ '-tAc',+ "SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'memories' LIMIT 1"+ ],+ { stdio: 'pipe', env: PG_CHILD_ENV }+ ).toString();+ return output.trim() === '1';} catch {return false;}@@ -165,14 +236,25 @@ function promptStorageChoice(message, hint) {});}-// Attempt full native PostgreSQL setup via db.sh setup-native+// Attempt full native PostgreSQL setup via db.sh setup-native. Idempotent:+// db.sh setup-native re-checks each step (brew install, role, db, extensions,+// schema). Verifies success at the *domain* level — the role can auth and the+// schema is in place — not just that the port is listening, since the whole+// point of this PR is that port-listening isn't proof of usable PortOS state.function setupNativePostgres() {const dbScript = join(rootDir, 'scripts', 'db.sh');try {console.log('🍺 Running native PostgreSQL setup...');- execFileSync('bash', [dbScript, 'setup-native'], { stdio: 'inherit', cwd: rootDir });- if (isNativeReady()) {- console.log('✅ System PostgreSQL ready on port 5432');+ // 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'], {+ stdio: 'inherit',+ cwd: rootDir,+ env: PG_CHILD_ENV+ });+ if (isPortOSDbReady()) {+ console.log(`✅ PortOS database ready on port ${PG_PORT_NATIVE}`);return true;}} catch (err) {@@ -199,11 +281,15 @@ async function handleDockerUnavailable(message, issue) {if (choice === 'native') {console.log(' Switching to native PostgreSQL mode...');setPgMode('native');- if (isNativeReady()) {- console.log('✅ System PostgreSQL ready on port 5432');+ // Fast path: portos role can already authenticate to portos db and the+ // schema is in place. Skip setup-native to avoid re-ALTERing credentials+ // and the brew/psql startup-time hit on every `npm start`.+ if (isPortOSDbReady()) {+ console.log(`✅ PortOS database ready on port ${PG_PORT_NATIVE}`);process.exit(0);}- // Attempt automatic setup via db.sh setup-native (installs + configures)+ // Otherwise (fresh checkout, missing role, missing schema, wrong password)+ // run the full bootstrap.if (setupNativePostgres()) {process.exit(0);}@@ -233,13 +319,15 @@ if (mode === 'file') {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');+ // Fast path: portos role can already authenticate to portos db and the+ // schema is in place. Skip setup-native to avoid re-ALTERing credentials+ // and the brew/psql startup-time hit on every `npm start`.+ if (isPortOSDbReady()) {+ console.log(`✅ PortOS database ready on port ${PG_PORT_NATIVE}`);process.exit(0);}-- // Attempt automatic setup via db.sh (installs + starts + configures)+ // Otherwise (fresh checkout, missing role, missing schema, wrong password)+ // run the full bootstrap.if (setupNativePostgres()) {process.exit(0);}diff --git a/setup.sh b/setup.shindex 98425d03f9..cd5a46e24c 100755--- a/setup.sh+++ b/setup.sh@@ -19,12 +19,13 @@ if [ "$NODE_VERSION" -lt 18 ]; thenexit 1fi-echo "Installing dependencies..."-npm install--echo ""-echo "Setting up data directory..."-if ! npm run setup; then+# Run the canonical install: submodules + root/client/server/autofixer deps ++# esbuild postinstall + node-pty rebuild + npm run setup (data dir, db, browser).+# install:all ends with `npm run setup` so this single call covers what the old+# split `npm install` + `npm run setup` did, plus the workspace deps the old+# script was missing.+echo "Installing dependencies and running setup..."+if ! npm run install:all; thenecho ""echo "==================================="echo " Setup incomplete"@@ -37,22 +38,72 @@ fiecho ""-# Optional Ghostty setup-read -p "Set up Ghostty terminal themes? (y/N): " setup_ghostty-if [[ $setup_ghostty =~ ^[Yy]$ ]]; then- node scripts/setup-ghostty.js+# Optional Ghostty setup. Skip on non-TTY (CI, piped stdin) so `read` doesn't+# abort the script under `set -e`, and `||` the read itself so a Ctrl-D in an+# interactive shell defaults to "skip" instead of aborting.+if [ -t 0 ]; then+ setup_ghostty=""+ read -p "Set up Ghostty terminal themes? (y/N): " setup_ghostty || true+ if [[ $setup_ghostty =~ ^[Yy]$ ]]; then+ node scripts/setup-ghostty.js+ fifiecho ""-echo "==================================="-echo " Setup Complete!"-echo "==================================="-echo ""-echo "Start PortOS:"-echo " Development: npm run dev"-echo " Production: npm start (or npm run pm2:start)"-echo " Stop: npm run pm2:stop"-echo " Logs: npm run pm2:logs"-echo ""-echo "Access at: http://localhost:5555"-echo ""++# Optional: start PortOS now. Accept y/yes/Y/YES (and Enter) to start, n/no+# to skip, and reprompt on anything else so a stray "asdf" doesn't silently+# launch pm2. On non-TTY (CI, piped stdin) default to "no" so the script+# completes unattended without auto-launching pm2. A Ctrl-D inside the loop+# is treated as "no" so the script can still finish cleanly.+start_now=0+if [ -t 0 ]; then+ while true; do+ answer=""+ if ! read -p "Start PortOS now via pm2? (Y/n): " answer; then+ start_now=0+ break+ fi+ case "$answer" in+ ""|[Yy]|[Yy][Ee][Ss])+ start_now=1+ break+ ;;+ [Nn]|[Nn][Oo])+ start_now=0+ break+ ;;+ *)+ echo "Please answer yes or no (y/n)."+ ;;+ esac+ done+fi++if [ "$start_now" = "1" ]; then+ echo ""+ echo "Starting PortOS..."+ npm start+ echo ""+ echo "==================================="+ echo " PortOS is running"+ echo "==================================="+ echo ""+ echo "Access at: http://localhost:5555"+ echo "Logs: npm run pm2:logs"+ echo "Stop: npm run pm2:stop"+ echo ""+else+ echo "==================================="+ echo " Setup Complete!"+ echo "==================================="+ echo ""+ echo "Start PortOS:"+ echo " Development: npm run dev"+ echo " Production: npm start (or npm run pm2:start)"+ echo " Stop: npm run pm2:stop"+ echo " Logs: npm run pm2:logs"+ echo ""+ echo "Access at: http://localhost:5555"+ echo ""+fi