Repository navigation
Conversation
| const databaseUrl = process.env.DATABASE_URL ?? ""; | ||
| if (!databaseUrl) { | ||
| api.logger.warn("persist-postgres: DATABASE_URL not set, plugin disabled"); | ||
| return; | ||
| } |
There was a problem hiding this comment.
Plugin config ignored
openclaw.plugin.json declares a required databaseUrl config field, but the plugin only reads process.env.DATABASE_URL here and never uses api.pluginConfig. This makes plugin configuration via OpenClaw’s plugin config/UI ineffective (plugin appears broken unless the env var is set).
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/persist-postgres/src/index.ts
Line: 10:14
Comment:
**Plugin config ignored**
`openclaw.plugin.json` declares a required `databaseUrl` config field, but the plugin only reads `process.env.DATABASE_URL` here and never uses `api.pluginConfig`. This makes plugin configuration via OpenClaw’s plugin config/UI ineffective (plugin appears broken unless the env var is set).
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Fixed. Plugin now reads api.pluginConfig?.databaseUrl with DATABASE_URL env var as fallback.
| // Persist the user prompt when an agent run starts | ||
| api.on( | ||
| "before_agent_start", | ||
| async (event, ctx) => { | ||
| try { | ||
| await ensureReady(); | ||
| const sessionKey = ctx?.sessionKey ?? "unknown"; | ||
| const conv = await upsertConversation(sql, { | ||
| sessionKey, | ||
| channel: "gateway", | ||
| lastMessageAt: new Date(), | ||
| }); | ||
| if (event.prompt) { | ||
| await insertMessage(sql, { | ||
| conversationId: conv.id, | ||
| role: "user", | ||
| content: event.prompt, | ||
| }); | ||
| api.logger.info(`persist-postgres: persisted user message for session ${sessionKey}`); | ||
| } |
There was a problem hiding this comment.
Duplicate persistence paths
This plugin persists the same logical user message in multiple hooks: before_agent_start persists event.prompt, and message_received also persists inbound content. In OpenClaw, message_received is emitted for inbound messages (src/auto-reply/reply/dispatch-from-config.ts:150-198) and before_agent_start runs for the embedded agent prompt (src/agents/pi-embedded-runner/run/attempt.ts:736-761), so a single inbound message can be inserted twice into lp_messages (and likewise assistant replies via agent_end + message_sent).
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/persist-postgres/src/index.ts
Line: 28:47
Comment:
**Duplicate persistence paths**
This plugin persists the same logical user message in multiple hooks: `before_agent_start` persists `event.prompt`, and `message_received` also persists inbound content. In OpenClaw, `message_received` is emitted for inbound messages (src/auto-reply/reply/dispatch-from-config.ts:150-198) and `before_agent_start` runs for the embedded agent prompt (src/agents/pi-embedded-runner/run/attempt.ts:736-761), so a single inbound message can be inserted twice into `lp_messages` (and likewise assistant replies via `agent_end` + `message_sent`).
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Fixed. Removed message_received and message_sent hooks. Only before_agent_start (user prompt) and agent_end (assistant response) remain — no more duplicate persistence.
| ON CONFLICT (session_key) DO UPDATE SET | ||
| last_message_at = EXCLUDED.last_message_at, | ||
| message_count = lp_conversations.message_count + 1 | ||
| RETURNING * |
There was a problem hiding this comment.
Inflated message_count
message_count is incremented on every session_key conflict upsert (message_count = ... + 1), but upsertConversation() is called even when no message is inserted (e.g., agent_end when no assistant message found, or before_agent_start if prompt is empty). This will make message_count drift upward and also compounds the double-persistence issue.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/persist-postgres/src/db.ts
Line: 87:90
Comment:
**Inflated message_count**
`message_count` is incremented on every `session_key` conflict upsert (`message_count = ... + 1`), but `upsertConversation()` is called even when no message is inserted (e.g., `agent_end` when no assistant message found, or `before_agent_start` if prompt is empty). This will make `message_count` drift upward and also compounds the double-persistence issue.
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Fixed. upsertConversation no longer increments message_count. The count is now incremented only inside insertMessage when a row is actually inserted. Hooks also skip the upsert entirely when there is no message to persist.
| CREATE TABLE IF NOT EXISTS lp_conversations ( | ||
| id UUID PRIMARY KEY DEFAULT gen_random_uuid(), | ||
| channel VARCHAR(50) NOT NULL, |
There was a problem hiding this comment.
gen_random_uuid dependency
Schema creation uses gen_random_uuid() for primary keys. On Postgres instances without pgcrypto enabled, this function is undefined and ensureSchema() will fail, preventing the plugin from starting up.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/persist-postgres/src/db.ts
Line: 31:33
Comment:
**gen_random_uuid dependency**
Schema creation uses `gen_random_uuid()` for primary keys. On Postgres instances without pgcrypto enabled, this function is undefined and `ensureSchema()` will fail, preventing the plugin from starting up.
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Added a doc comment noting PostgreSQL 13+ requirement. gen_random_uuid() is a built-in function since PG 13 and does not require pgcrypto.
| const DATABASE_URL = | ||
| process.env.DATABASE_URL ?? "postgresql://postgres:postgres@localhost:5432/openclaw_e2e_test"; | ||
|
|
||
| const sql = postgres(DATABASE_URL, { max: 5 }); |
There was a problem hiding this comment.
Integration test hits localhost
This test will run under the repo’s default Vitest include patterns (extensions/**/*.test.ts is included in vitest.config.ts). It creates a Postgres client using DATABASE_URL or a hardcoded localhost fallback, so CI/dev runs without a live Postgres instance will fail/hang unless this test is gated/renamed/excluded by default.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/persist-postgres/src/integration.test.ts
Line: 22:25
Comment:
**Integration test hits localhost**
This test will run under the repo’s default Vitest include patterns (`extensions/**/*.test.ts` is included in vitest.config.ts). It creates a Postgres client using `DATABASE_URL` or a hardcoded localhost fallback, so CI/dev runs without a live Postgres instance will fail/hang unless this test is gated/renamed/excluded by default.
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Fixed. Renamed to integration.e2e.test.ts which is excluded from default pnpm test via the **/*.e2e.test.ts pattern in vitest.config.ts. Must be run explicitly with a live PostgreSQL instance.
a7dbe6b to
3ef2f48
Compare
Add `createdAt` timestamp to SessionEntry, preserve it across merges, and expose four new list-sessions filters (updatedAfter, updatedBefore, createdAfter, createdBefore) for querying sessions by absolute time range. This is foundational for external persistence backends (e.g. PostgreSQL) that need incremental sync by timestamp. Includes 10 new tests covering all filter combinations and edge cases.
…d messages Add persist-postgres extension plugin that persists conversations and messages to PostgreSQL via agent lifecycle hooks (before_agent_start, agent_end) and channel hooks (message_received, message_sent). Plugin boundary: owns lp_conversations and lp_messages tables only. No user table — user identity is outside this plugin's scope. Schema auto-created on first use with proper indexes. Files: - db.ts: connection pooling, schema DDL, upsert/insert/query, row mapping - index.ts: plugin registration with lifecycle and channel hooks - integration.test.ts: 16 tests (CRUD, date-range SQL filtering, listSessionsFromStore round-trip with PG-sourced data)
9558d21 to
3ffecf3
Compare
- Read databaseUrl from api.pluginConfig with env var fallback - Remove duplicate message_received/message_sent hooks (before_agent_start and agent_end already cover user/assistant messages) - Fix message_count inflation: increment only on insertMessage, not upsert - Add PG 13+ requirement note for gen_random_uuid() - Rename integration test to .e2e.test.ts (excluded from default pnpm test) Co-Authored-By: Claude Opus 4.6 <[email protected]>
| const createdAt = existing.createdAt ?? patch.createdAt; | ||
| return { ...existing, ...patch, sessionId, createdAt, updatedAt }; |
There was a problem hiding this comment.
createdAt fallback order allows patch to overwrite existing value
When existing.createdAt is undefined, the code falls back to patch.createdAt, allowing a patch to set createdAt on a session that previously had none. However, comment on line 116 says "Preserve original createdAt; never overwrite from patch." The logic should be:
| const createdAt = existing.createdAt ?? patch.createdAt; | |
| return { ...existing, ...patch, sessionId, createdAt, updatedAt }; | |
| // Preserve original createdAt; never overwrite from patch. | |
| const createdAt = existing.createdAt ?? Date.now(); |
This ensures createdAt is immutable after initial creation and defaults to Date.now() if missing (for backward compat with sessions created before this field existed).
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/config/sessions/types.ts
Line: 117:118
Comment:
`createdAt` fallback order allows patch to overwrite existing value
When `existing.createdAt` is undefined, the code falls back to `patch.createdAt`, allowing a patch to set `createdAt` on a session that previously had none. However, comment on line 116 says "Preserve original createdAt; never overwrite from patch." The logic should be:
```suggestion
// Preserve original createdAt; never overwrite from patch.
const createdAt = existing.createdAt ?? Date.now();
```
This ensures `createdAt` is immutable after initial creation and defaults to `Date.now()` if missing (for backward compat with sessions created before this field existed).
How can I resolve this? If you propose a fix, please make it concise.|
Closing in favor of a new PR from fork:main with rebased commits on latest origin/main. |
Summary
createdAtfield toSessionEntryfor tracking session creation timestampsupdatedAfter,updatedBefore,createdAfter,createdBefore) to thesessions.listgateway APIpersist-postgresplugin that persists sessions and messages to PostgreSQL via lifecycle hooks (before_agent_start,agent_end,message_received,message_sent)queryConversations(hardcoded$1→ dynamic$${values.length + 1})Changes
Core (
src/)src/config/sessions/types.ts—createdAt?: numberonSessionEntry, preserved inmergeSessionEntry()src/gateway/session-utils.ts— Date-range filter parsing + application inlistSessionsFromStore()src/gateway/session-utils.test.ts— 10 new tests for date-range filteringsrc/gateway/session-utils.types.ts—createdAtonGatewaySessionRowsrc/gateway/protocol/schema/sessions.ts— 4 new TypeBox schema fieldsPlugin (
extensions/persist-postgres/)src/db.ts— PostgreSQL schema, CRUD ops (ensureSchema,upsertConversation,insertMessage,queryConversations,pgRowToSessionEntry)src/index.ts— Plugin registration with 4 lifecycle hookssrc/integration.test.ts— 16 integration tests (CRUD, date-range SQL,listSessionsFromStoreround-trip)package.json,openclaw.plugin.jsonTest plan
bun test extensions/persist-postgres/src/integration.test.ts)pnpm vitest run src/gateway/session-utils.test.ts)/hooks/chat→ messages persisted tolp_conversations+lp_messages🤖 Generated with Claude Code
Greptile Overview
Greptile Summary
Adds
createdAttimestamp tracking to sessions and introduces a PostgreSQL persistence plugin that stores session and message data to a PostgreSQL database via lifecycle hooks.Core changes:
SessionEntrynow includes optionalcreatedAtfield (timestamp in ms) tracked bymergeSessionEntry()sessions.list) adds 4 date-range filter parameters:updatedAfter,updatedBefore,createdAfter,createdBeforelistSessionsFromStore()with proper validationPostgreSQL plugin (
persist-postgres):before_agent_start(user prompts) andagent_end(assistant responses)lp_conversationstable (tracks sessions) andlp_messagestable (stores message history)queryConversations()function with date-range SQL filtering$1, now dynamic$${values.length + 1})message_countonly when messages are actually insertedTesting:
session-utils.test.tscover all date-range filter combinationslistSessionsFromStore()*.e2e.test.tsto exclude from default test runsPrevious review feedback has been addressed (plugin config precedence, duplicate persistence paths, inflated message counts, PostgreSQL version requirement, e2e test exclusion).
Confidence Score: 4/5
createdAtfallback logic needs correction to match the stated invariant, but is not critical since patches typically don't includecreatedAt. Schema changes are backward-compatible (optional field). Plugin properly validates config and gracefully degrades if DB unavailable.src/config/sessions/types.ts(line 117) requires attention to fix thecreatedAtfallback logicLast reviewed commit: cb578d8