Skip to content

feat(sessions): createdAt tracking, date-range filtering & PostgreSQL persistence plugin - #15424

Closed
supmo668 wants to merge 3 commits into
openclaw:mainfrom
Syntropy-Health:feature/session-timestamp-filtering
Closed

supmo668 wants to merge 3 commits into
openclaw:mainfrom
Syntropy-Health:feature/session-timestamp-filtering

Conversation

@supmo668

@supmo668 supmo668 commented Feb 13, 2026 •

Copy link
Copy Markdown

Summary

  • Adds createdAt field to SessionEntry for tracking session creation timestamps
  • Adds date-range filter parameters (updatedAfter, updatedBefore, createdAfter, createdBefore) to the sessions.list gateway API
  • Introduces persist-postgres plugin that persists sessions and messages to PostgreSQL via lifecycle hooks (before_agent_start, agent_end, message_received, message_sent)
  • Fixes SQL parameter numbering bug in queryConversations (hardcoded $1 → dynamic $${values.length + 1})

Changes

Core (src/)

  • src/config/sessions/types.ts — createdAt?: number on SessionEntry, preserved in mergeSessionEntry()
  • src/gateway/session-utils.ts — Date-range filter parsing + application in listSessionsFromStore()
  • src/gateway/session-utils.test.ts — 10 new tests for date-range filtering
  • src/gateway/session-utils.types.ts — createdAt on GatewaySessionRow
  • src/gateway/protocol/schema/sessions.ts — 4 new TypeBox schema fields

Plugin (extensions/persist-postgres/)

  • src/db.ts — PostgreSQL schema, CRUD ops (ensureSchema, upsertConversation, insertMessage, queryConversations, pgRowToSessionEntry)
  • src/index.ts — Plugin registration with 4 lifecycle hooks
  • src/integration.test.ts — 16 integration tests (CRUD, date-range SQL, listSessionsFromStore round-trip)
  • package.json, openclaw.plugin.json

Test plan

  • 16 integration tests pass against live PostgreSQL (bun test extensions/persist-postgres/src/integration.test.ts)
  • 39 session-utils unit tests pass (pnpm vitest run src/gateway/session-utils.test.ts)
  • E2E verified: gateway → /hooks/chat → messages persisted to lp_conversations + lp_messages
  • SQL parameter numbering fix validated (all filter combinations work)

🤖 Generated with Claude Code

Greptile Overview

Greptile Summary

Adds createdAt timestamp tracking to sessions and introduces a PostgreSQL persistence plugin that stores session and message data to a PostgreSQL database via lifecycle hooks.

Core changes:

  • SessionEntry now includes optional createdAt field (timestamp in ms) tracked by mergeSessionEntry()
  • Gateway API (sessions.list) adds 4 date-range filter parameters: updatedAfter, updatedBefore, createdAfter, createdBefore
  • Date filtering implemented in listSessionsFromStore() with proper validation

PostgreSQL plugin (persist-postgres):

  • Hooks into before_agent_start (user prompts) and agent_end (assistant responses)
  • Creates lp_conversations table (tracks sessions) and lp_messages table (stores message history)
  • Includes queryConversations() function with date-range SQL filtering
  • Fixed SQL parameter numbering bug (was hardcoded $1, now dynamic $${values.length + 1})
  • Properly increments message_count only when messages are actually inserted

Testing:

  • 180 new lines of unit tests in session-utils.test.ts cover all date-range filter combinations
  • 349 lines of e2e integration tests verify PostgreSQL CRUD operations, date filtering, and round-trip with listSessionsFromStore()
  • Tests renamed to *.e2e.test.ts to exclude from default test runs

Previous review feedback has been addressed (plugin config precedence, duplicate persistence paths, inflated message counts, PostgreSQL version requirement, e2e test exclusion).

Confidence Score: 4/5

  • This PR is safe to merge with one minor fix needed for createdAt immutability
  • The implementation is well-structured with comprehensive test coverage (39 unit tests + 16 e2e tests). Previous review issues have been properly addressed. The SQL implementation uses parameterized queries correctly to prevent injection. The one logical issue with createdAt fallback logic needs correction to match the stated invariant, but is not critical since patches typically don't include createdAt. Schema changes are backward-compatible (optional field). Plugin properly validates config and gracefully degrades if DB unavailable.
  • Only src/config/sessions/types.ts (line 117) requires attention to fix the createdAt fallback logic

Last reviewed commit: cb578d8

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime size: L labels Feb 13, 2026
@supmo668
supmo668 marked this pull request as draft February 13, 2026 12:37

@greptile-apps greptile-apps 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.

11 files reviewed, 5 comments

Edit Code Review Agent Settings | Greptile

Comment on lines +10 to +14
const databaseUrl = process.env.DATABASE_URL ?? "";
if (!databaseUrl) {
api.logger.warn("persist-postgres: DATABASE_URL not set, plugin disabled");
return;
}

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.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed. Plugin now reads api.pluginConfig?.databaseUrl with DATABASE_URL env var as fallback.

Comment on lines +28 to +47
// 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}`);
}

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.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed. Removed message_received and message_sent hooks. Only before_agent_start (user prompt) and agent_end (assistant response) remain — no more duplicate persistence.

Comment on lines +87 to +90
ON CONFLICT (session_key) DO UPDATE SET
last_message_at = EXCLUDED.last_message_at,
message_count = lp_conversations.message_count + 1
RETURNING *

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.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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.

Comment on lines +31 to +33
CREATE TABLE IF NOT EXISTS lp_conversations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
channel VARCHAR(50) NOT NULL,

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.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Added a doc comment noting PostgreSQL 13+ requirement. gen_random_uuid() is a built-in function since PG 13 and does not require pgcrypto.

Comment on lines +22 to +25
const DATABASE_URL =
process.env.DATABASE_URL ?? "postgresql://postgres:postgres@localhost:5432/openclaw_e2e_test";

const sql = postgres(DATABASE_URL, { max: 5 });

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.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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.

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)
@supmo668
supmo668 force-pushed the feature/session-timestamp-filtering branch from 9558d21 to 3ffecf3 Compare February 14, 2026 08:38
- 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]>
@supmo668
supmo668 marked this pull request as ready for review February 14, 2026 09:27
@supmo668 supmo668 closed this Feb 14, 2026
@supmo668 supmo668 reopened this Feb 14, 2026

@greptile-apps greptile-apps 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.

12 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment on lines +117 to +118
const createdAt = existing.createdAt ?? patch.createdAt;
return { ...existing, ...patch, sessionId, createdAt, updatedAt };

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.

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:

Suggested change
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.

@supmo668

Copy link
Copy Markdown
Author

Closing in favor of a new PR from fork:main with rebased commits on latest origin/main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui gateway Gateway runtime size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant