Skip to content

feat(db): embed pgserve as genie's persistent brain - #673

Merged
namastex888 merged 6 commits into
devfrom
pgserve-embed
Mar 20, 2026
Merged

namastex888 merged 6 commits into
devfrom
pgserve-embed

Conversation

@namastex888

Copy link
Copy Markdown
Contributor

Summary

  • Embed pgserve (embedded PostgreSQL) as a genie dependency with lazy auto-start on port 19642
  • Create connection management layer (src/lib/db.ts) with ensurePgserve(), getConnection(), isAvailable(), and shutdown()
  • Add schema versioning and migration system (src/lib/db-migrations.ts) with initial schema including scheduler tables (schedules, triggers, runs, heartbeats, audit_events) and agent_checkpoints
  • Add genie db CLI commands: status, migrate, query

Test plan

  • genie db status auto-starts pgserve, runs migrations, reports health
  • genie db migrate runs pending migrations
  • genie db query "SELECT 1" returns result
  • pgserve data persists in ~/.genie/data/pgserve/
  • bun run check passes (verified: 786 tests, 0 failures)

Wish: pgserve-embed

Genie added 5 commits March 20, 2026 01:47
Embed pgserve as genie's persistent brain with lazy initialization.
Adds postgres.js client with singleton connection pool, port fallback,
health check, and graceful shutdown.
Create db-migrations.ts with runMigrations() and getMigrationStatus()
for incremental schema versioning. Add 001_initial.sql with core
scheduler tables (schedules, triggers, runs, heartbeats, audit_events),
agent_checkpoints for session resume, and LISTEN/NOTIFY trigger for
real-time trigger-due notifications.
Call runMigrations() from getConnection() so the schema is
automatically applied when any command first touches the database.
Wire up database management commands to the CLI router:
- `genie db status` shows pgserve health, port, data dir, table counts
- `genie db migrate` runs pending migrations manually
- `genie db query "<sql>"` executes ad-hoc SQL with tabular output
- Clean up knip config now that db modules are consumed by CLI
@gitguardian

gitguardian Bot commented Mar 20, 2026 •

Copy link
Copy Markdown

⚠️ GitGuardian has uncovered 1 secret following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

🔎 Detected hardcoded secret in your pull request
GitGuardian id GitGuardian status Secret Commit Filename
18760271 Triggered Generic Password faf11f4 src/lib/db.ts View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secret safely. Learn here the best practices.
  3. Revoke and rotate this secret.
  4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

@coderabbitai

coderabbitai Bot commented Mar 20, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: afa6235a-53c5-44cd-85bd-3433f62109de

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch pgserve-embed
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances Genie's capabilities by embedding a persistent PostgreSQL database (pgserve) directly within the application. This foundational change provides Genie with a reliable mechanism for state management, enabling features like scheduling, event tracking, and agent checkpointing. The integration includes a comprehensive migration system for schema evolution and new CLI tools for easy database interaction and diagnostics, transforming Genie into a more robust and stateful application.

Highlights

  • Embedded PostgreSQL Integration: Integrated pgserve (embedded PostgreSQL) as a core dependency for Genie, providing a persistent data store. It features lazy auto-start on port 19642 (or a fallback port) and stores data in ~/.genie/data/pgserve/.
  • Database Connection Management: Introduced a new connection management layer (src/lib/db.ts) that handles pgserve lifecycle, provides a postgres.js client, and includes utility functions for connection availability and graceful shutdown.
  • Schema Versioning and Migrations: Implemented a robust schema versioning and migration system (src/lib/db-migrations.ts) to manage database schema changes. This includes an initial schema for scheduler tables (schedules, triggers, runs, heartbeats, audit_events) and agent checkpoints.
  • New CLI Commands for Database Management: Added a suite of genie db CLI commands: status to check database health and migration status, migrate to apply pending schema changes, and query to execute arbitrary SQL statements.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e7287961f1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/db-migrations.ts
* Falls back to the project root if the relative path doesn't work (bundled builds).
*/
async function loadMigrationFiles(): Promise<MigrationFile[]> {
const candidates = [getMigrationsDir(), join(process.cwd(), 'src', 'db', 'migrations')];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve migrations from package root, not caller cwd

The migration loader only checks ../db/migrations relative to import.meta.dir and process.cwd()/src/db/migrations, so in the packaged CLI (dist/genie.js) invoked from a normal project directory it can fail to find src/db/migrations entirely and return no migrations. In that case _genie_migrations is created but the actual schema (e.g., schedules, triggers, etc.) is never applied, causing runtime failures or empty behavior in DB-backed commands outside the repo root.

Useful? React with 👍 / 👎.

Comment thread src/lib/db.ts
Comment on lines +83 to +84
if (await isPortListening(port, DEFAULT_HOST)) {
activePort = port;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Verify Postgres readiness before reusing an occupied port

This branch treats any TCP listener on the configured port as a valid pgserve instance, but isPortListening only performs a socket connect and does not confirm PostgreSQL protocol/auth readiness. If another local service is bound to 127.0.0.1:19642, ensurePgserve() returns success here and getConnection() later fails instead of starting pgserve on a fallback port, breaking all genie db commands on machines with a port conflict.

Useful? React with 👍 / 👎.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces pgserve as a persistent brain for genie, along with connection management, schema versioning, migration system, and a genie db CLI. The changes include adding dependencies, creating database management files, modifying the genie.ts file, and adding a pgserve type definition file. I have provided feedback to address potential issues and improve the code.

Comment thread src/lib/db.ts
Comment on lines +137 to +138
console.warn(`Warning: pgserve failed to start: ${message}`);
throw new Error(`pgserve failed to start on port ${port} (and fallbacks ${port + 1}-${port + 3}): ${message}`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The console.warn call here is duplicated in the catch block below. Consider refactoring this to a single place to avoid duplication.

    const message = err instanceof Error ? err.message : String(err);
    console.warn(`Warning: pgserve failed to start: ${message}`);
    throw new Error(`pgserve failed to start on port ${port} (and fallbacks ${port + 1}-${port + 3}): ${message}`);

pgserve depends on the bun npm package, whose postinstall script
must run to set up the binary. Without trusting it, CI build fails
with "Bun's postinstall script was not run".
@namastex888
namastex888 merged commit 45153d5 into dev Mar 20, 2026
5 of 6 checks passed
@namastex888
namastex888 deleted the pgserve-embed branch March 29, 2026 22:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant