agentforge-chat-history-postgres 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,49 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+
7
+ # Distribution / packaging
8
+ .Python
9
+ build/
10
+ dist/
11
+ *.egg-info/
12
+ *.egg
13
+ wheels/
14
+ sdist/
15
+ share/python-wheels/
16
+
17
+ # uv
18
+ .venv/
19
+ uv-cache/
20
+
21
+ # Testing
22
+ .pytest_cache/
23
+ .coverage
24
+ .coverage.*
25
+ htmlcov/
26
+ coverage.xml
27
+ .tox/
28
+ .mypy_cache/
29
+ .ruff_cache/
30
+ .hypothesis/
31
+
32
+ # Environment
33
+ .env
34
+ .envrc
35
+
36
+ # Editors
37
+ .vscode/
38
+ .idea/
39
+ *.swp
40
+ *.swo
41
+ *~
42
+
43
+ # OS
44
+ .DS_Store
45
+ Thumbs.db
46
+
47
+ # Project-local
48
+ *.local
49
+ .agentforge-state/.session-cache
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentforge-chat-history-postgres
3
+ Version: 0.2.3
4
+ Summary: Postgres-backed ChatHistoryStore for AgentForge
5
+ Project-URL: Homepage, https://github.com/Scaffoldic/agentforge-py
6
+ Project-URL: Repository, https://github.com/Scaffoldic/agentforge-py
7
+ Project-URL: Changelog, https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md
8
+ Project-URL: Issues, https://github.com/Scaffoldic/agentforge-py/issues
9
+ Author: The AgentForge Authors
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agent,ai,chat,history,postgres
13
+ Classifier: Development Status :: 2 - Pre-Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Database
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.13
22
+ Requires-Dist: agentforge-core~=0.2.3
23
+ Requires-Dist: asyncpg>=0.30
24
+ Description-Content-Type: text/markdown
25
+
26
+ # agentforge-chat-history-postgres
27
+
28
+ Postgres-backed `ChatHistoryStore` for AgentForge (feat-020 v0.2).
29
+
30
+ Sister package to [`agentforge-memory-postgres`](../agentforge-memory-postgres).
31
+ Drop-in replacement for `SqliteChatHistory` when chat sessions
32
+ need multi-writer concurrency or managed-database guarantees
33
+ (Neon / Supabase / RDS / Cloud SQL).
34
+
35
+ ```python
36
+ from agentforge_chat_history_postgres import PostgresChatHistory
37
+
38
+ history = await PostgresChatHistory.from_dsn(
39
+ "postgresql://user:pw@host:5432/agentforge"
40
+ )
41
+ ```
42
+
43
+ Implements the locked `ChatHistoryStore` contract from
44
+ `agentforge-core` plus `init_schema()` that creates the
45
+ `chat_sessions` + `chat_turns` tables idempotently
46
+ (`CREATE TABLE IF NOT EXISTS`).
47
+
48
+ Run live integration tests with:
49
+
50
+ ```bash
51
+ RUN_LIVE_POSTGRES_DSN=postgresql://postgres:test@localhost:5432/postgres \
52
+ uv run pytest -m live packages/agentforge-chat-history-postgres/
53
+ ```
@@ -0,0 +1,28 @@
1
+ # agentforge-chat-history-postgres
2
+
3
+ Postgres-backed `ChatHistoryStore` for AgentForge (feat-020 v0.2).
4
+
5
+ Sister package to [`agentforge-memory-postgres`](../agentforge-memory-postgres).
6
+ Drop-in replacement for `SqliteChatHistory` when chat sessions
7
+ need multi-writer concurrency or managed-database guarantees
8
+ (Neon / Supabase / RDS / Cloud SQL).
9
+
10
+ ```python
11
+ from agentforge_chat_history_postgres import PostgresChatHistory
12
+
13
+ history = await PostgresChatHistory.from_dsn(
14
+ "postgresql://user:pw@host:5432/agentforge"
15
+ )
16
+ ```
17
+
18
+ Implements the locked `ChatHistoryStore` contract from
19
+ `agentforge-core` plus `init_schema()` that creates the
20
+ `chat_sessions` + `chat_turns` tables idempotently
21
+ (`CREATE TABLE IF NOT EXISTS`).
22
+
23
+ Run live integration tests with:
24
+
25
+ ```bash
26
+ RUN_LIVE_POSTGRES_DSN=postgresql://postgres:test@localhost:5432/postgres \
27
+ uv run pytest -m live packages/agentforge-chat-history-postgres/
28
+ ```
@@ -0,0 +1,59 @@
1
+ # agentforge-chat-history-postgres — Postgres-backed ChatHistoryStore.
2
+ #
3
+ # Sister package to agentforge-memory-postgres. Implements
4
+ # `ChatHistoryStore` from agentforge-core over an asyncpg connection
5
+ # pool. Drop-in for SqliteChatHistory when chat-http needs to scale
6
+ # beyond a single SQLite file (multi-writer concurrency, managed DB
7
+ # guarantees, point-in-time recovery — Neon / Supabase / RDS).
8
+
9
+ [project]
10
+ name = "agentforge-chat-history-postgres"
11
+ version = "0.2.3"
12
+ description = "Postgres-backed ChatHistoryStore for AgentForge"
13
+ readme = "README.md"
14
+ requires-python = ">=3.13"
15
+ license = "Apache-2.0"
16
+ license-files = ["LICENSE"]
17
+ authors = [
18
+ {name = "The AgentForge Authors"},
19
+ ]
20
+ keywords = ["ai", "agent", "chat", "postgres", "history"]
21
+ classifiers = [
22
+ "Development Status :: 2 - Pre-Alpha",
23
+ "Intended Audience :: Developers",
24
+ "License :: OSI Approved :: Apache Software License",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Topic :: Database",
28
+ "Topic :: Software Development :: Libraries :: Python Modules",
29
+ "Typing :: Typed",
30
+ ]
31
+
32
+ dependencies = [
33
+ "agentforge-core ~= 0.2.3",
34
+ "asyncpg>=0.30",
35
+ ]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/Scaffoldic/agentforge-py"
39
+ Repository = "https://github.com/Scaffoldic/agentforge-py"
40
+ Changelog = "https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md"
41
+ Issues = "https://github.com/Scaffoldic/agentforge-py/issues"
42
+
43
+ [project.entry-points."agentforge.chat.history"]
44
+ postgres = "agentforge_chat_history_postgres:PostgresChatHistory"
45
+
46
+ [build-system]
47
+ requires = ["hatchling>=1.27"]
48
+ build-backend = "hatchling.build"
49
+
50
+ [tool.hatch.build.targets.wheel]
51
+ packages = ["src/agentforge_chat_history_postgres"]
52
+
53
+ [tool.hatch.build.targets.sdist]
54
+ include = [
55
+ "src/agentforge_chat_history_postgres",
56
+ "tests",
57
+ "README.md",
58
+ "LICENSE",
59
+ ]
@@ -0,0 +1,8 @@
1
+ """`agentforge-chat-history-postgres` — Postgres-backed
2
+ `ChatHistoryStore` for AgentForge (feat-020 v0.2)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from agentforge_chat_history_postgres.history import PostgresChatHistory
7
+
8
+ __all__ = ["PostgresChatHistory"]
@@ -0,0 +1,215 @@
1
+ """In-memory `PostgresFakeRunner` for unit tests (feat-020 v0.2).
2
+
3
+ Interprets the narrow SQL vocabulary `PostgresChatHistory` emits and
4
+ routes operations to in-memory backings. Mirrors the pattern used by
5
+ `agentforge-memory-postgres`. Lets the conformance suite run without
6
+ a real Postgres instance — live tests in `tests/integration/` cover
7
+ the real driver.
8
+
9
+ The fake handles enough SQL to exercise every code path in
10
+ `history.py`:
11
+
12
+ - `INSERT INTO chat_turns ... ON CONFLICT` / `INSERT INTO chat_sessions`
13
+ - `SELECT * FROM chat_turns WHERE session_id = $1 [AND ...] ORDER BY timestamp [LIMIT $N]`
14
+ - `SELECT COUNT(*) AS n FROM chat_turns WHERE session_id = $1`
15
+ - `SELECT * FROM chat_sessions [WHERE ...] ORDER BY last_active_at DESC LIMIT $N`
16
+ - `SELECT owner, metadata FROM chat_sessions WHERE id = $1`
17
+ - `SELECT COUNT(*), COALESCE(SUM(cost_usd), 0.0) FROM chat_turns WHERE session_id = $1`
18
+ - `UPDATE chat_sessions SET metadata = $1::jsonb, owner = $2 WHERE id = $3`
19
+ - `DELETE FROM chat_turns WHERE session_id = $1`
20
+ - `DELETE FROM chat_sessions WHERE id = $1`
21
+ - `DELETE FROM chat_turns WHERE session_id IN (... last_active_at < $1)`
22
+ - `DELETE FROM chat_sessions WHERE last_active_at < $1`
23
+ - `CREATE TABLE IF NOT EXISTS ...` / `CREATE INDEX IF NOT EXISTS ...` (no-op).
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from datetime import datetime
29
+ from typing import Any
30
+
31
+
32
+ class _FakeRecord(dict[str, Any]):
33
+ """Dict that supports asyncpg-style `record["col"]` access."""
34
+
35
+
36
+ class PostgresFakeRunner:
37
+ """In-memory emulation of the SQL the driver emits."""
38
+
39
+ def __init__(self) -> None:
40
+ self._sessions: dict[str, dict[str, Any]] = {}
41
+ self._turns: dict[str, dict[str, Any]] = {}
42
+ self.closed = False
43
+
44
+ async def fetch(self, sql: str, *params: Any) -> list[Any]:
45
+ sql_n = _norm(sql)
46
+ if sql_n.startswith("select * from chat_turns where session_id = $1"):
47
+ return self._select_turns(sql_n, params)
48
+ if sql_n.startswith("select * from chat_sessions"):
49
+ return self._select_sessions(sql_n, params)
50
+ msg = f"PostgresFakeRunner: unsupported fetch sql: {sql_n!r}"
51
+ raise NotImplementedError(msg)
52
+
53
+ async def fetchrow(self, sql: str, *params: Any) -> Any | None:
54
+ sql_n = _norm(sql)
55
+ if sql_n.startswith("select count(*) as n from chat_turns where session_id = $1"):
56
+ session_id = params[0]
57
+ count = sum(1 for t in self._turns.values() if t["session_id"] == session_id)
58
+ return _FakeRecord(n=count)
59
+ if sql_n.startswith("select owner, metadata from chat_sessions where id = $1"):
60
+ session = self._sessions.get(params[0])
61
+ if session is None:
62
+ return None
63
+ return _FakeRecord(owner=session["owner"], metadata=dict(session["metadata"]))
64
+ if sql_n.startswith("select count(*) as n, coalesce(sum(cost_usd), 0.0) as total"):
65
+ session_id = params[0]
66
+ matched = [t for t in self._turns.values() if t["session_id"] == session_id]
67
+ return _FakeRecord(
68
+ n=len(matched),
69
+ total=sum(float(t["cost_usd"]) for t in matched),
70
+ )
71
+ msg = f"PostgresFakeRunner: unsupported fetchrow sql: {sql_n!r}"
72
+ raise NotImplementedError(msg)
73
+
74
+ async def execute(self, sql: str, *params: Any) -> None:
75
+ sql_n = _norm(sql)
76
+ if sql_n.startswith("create"):
77
+ return
78
+ if sql_n.startswith("insert into chat_turns"):
79
+ self._insert_turn(params)
80
+ return
81
+ if sql_n.startswith("insert into chat_sessions"):
82
+ self._upsert_session(params[0], params[1])
83
+ return
84
+ if sql_n.startswith("update chat_sessions set metadata"):
85
+ metadata_json, owner, session_id = params
86
+ import json # noqa: PLC0415
87
+
88
+ self._sessions[session_id]["metadata"] = json.loads(metadata_json)
89
+ self._sessions[session_id]["owner"] = owner
90
+ return
91
+ if sql_n.startswith("delete from chat_turns where session_id in"):
92
+ cutoff = params[0]
93
+ kill = {sid for sid, s in self._sessions.items() if s["last_active_at"] < cutoff}
94
+ self._turns = {tid: t for tid, t in self._turns.items() if t["session_id"] not in kill}
95
+ return
96
+ if sql_n.startswith("delete from chat_sessions where id = $1"):
97
+ session_id = params[0]
98
+ self._sessions.pop(session_id, None)
99
+ return
100
+ msg = f"PostgresFakeRunner: unsupported execute sql: {sql_n!r}"
101
+ raise NotImplementedError(msg)
102
+
103
+ async def execute_returning_count(self, sql: str, *params: Any) -> int:
104
+ sql_n = _norm(sql)
105
+ if sql_n.startswith("delete from chat_turns where session_id = $1"):
106
+ session_id = params[0]
107
+ before = len(self._turns)
108
+ self._turns = {
109
+ tid: t for tid, t in self._turns.items() if t["session_id"] != session_id
110
+ }
111
+ return before - len(self._turns)
112
+ if sql_n.startswith("delete from chat_sessions where last_active_at < $1"):
113
+ cutoff = params[0]
114
+ before = len(self._sessions)
115
+ self._sessions = {
116
+ sid: s for sid, s in self._sessions.items() if s["last_active_at"] >= cutoff
117
+ }
118
+ return before - len(self._sessions)
119
+ msg = f"PostgresFakeRunner: unsupported execute_returning_count sql: {sql_n!r}"
120
+ raise NotImplementedError(msg)
121
+
122
+ async def close(self) -> None:
123
+ self.closed = True
124
+
125
+ # ------------------------------------------------------------------
126
+ # Helpers
127
+ # ------------------------------------------------------------------
128
+
129
+ def _insert_turn(self, params: tuple[Any, ...]) -> None:
130
+ import json # noqa: PLC0415
131
+
132
+ (
133
+ turn_id,
134
+ session_id,
135
+ role,
136
+ content,
137
+ timestamp,
138
+ run_id,
139
+ tool_calls,
140
+ tool_call_id,
141
+ tokens_in,
142
+ tokens_out,
143
+ cost_usd,
144
+ metadata,
145
+ ) = params
146
+ self._turns[turn_id] = {
147
+ "id": turn_id,
148
+ "session_id": session_id,
149
+ "role": role,
150
+ "content": content,
151
+ "timestamp": timestamp,
152
+ "run_id": run_id,
153
+ "tool_calls": json.loads(tool_calls),
154
+ "tool_call_id": tool_call_id,
155
+ "tokens_in": int(tokens_in),
156
+ "tokens_out": int(tokens_out),
157
+ "cost_usd": float(cost_usd),
158
+ "metadata": json.loads(metadata),
159
+ }
160
+
161
+ def _upsert_session(self, session_id: str, ts: datetime) -> None:
162
+ existing = self._sessions.get(session_id)
163
+ if existing is None:
164
+ self._sessions[session_id] = {
165
+ "id": session_id,
166
+ "owner": None,
167
+ "created_at": ts,
168
+ "last_active_at": ts,
169
+ "metadata": {},
170
+ }
171
+ else:
172
+ existing["last_active_at"] = ts
173
+
174
+ def _select_turns(self, sql_n: str, params: tuple[Any, ...]) -> list[Any]:
175
+ session_id = params[0]
176
+ matched = [t for t in self._turns.values() if t["session_id"] == session_id]
177
+ # Apply optional filters by inspecting param count + sql snippets.
178
+ idx = 1
179
+ if "timestamp < $" in sql_n:
180
+ before = params[idx]
181
+ matched = [t for t in matched if t["timestamp"] < before]
182
+ idx += 1
183
+ if "timestamp > $" in sql_n:
184
+ after = params[idx]
185
+ matched = [t for t in matched if t["timestamp"] > after]
186
+ idx += 1
187
+ if "role = any(" in sql_n:
188
+ roles = params[idx]
189
+ matched = [t for t in matched if t["role"] in roles]
190
+ idx += 1
191
+ matched.sort(key=lambda t: t["timestamp"])
192
+ if "limit $" in sql_n:
193
+ limit = int(params[idx])
194
+ matched = matched[:limit]
195
+ return [_FakeRecord(t) for t in matched]
196
+
197
+ def _select_sessions(self, sql_n: str, params: tuple[Any, ...]) -> list[Any]:
198
+ matched = list(self._sessions.values())
199
+ idx = 0
200
+ if "where owner = $" in sql_n:
201
+ owner = params[idx]
202
+ matched = [s for s in matched if s["owner"] == owner]
203
+ idx += 1
204
+ if "last_active_at < $" in sql_n:
205
+ before = params[idx]
206
+ matched = [s for s in matched if s["last_active_at"] < before]
207
+ idx += 1
208
+ matched.sort(key=lambda s: s["last_active_at"], reverse=True)
209
+ limit = int(params[idx])
210
+ return [_FakeRecord(s) for s in matched[:limit]]
211
+
212
+
213
+ def _norm(sql: str) -> str:
214
+ """Normalise whitespace + lowercase for prefix matching."""
215
+ return " ".join(sql.lower().split()).strip()
@@ -0,0 +1,68 @@
1
+ """Internal asyncpg-runner abstraction for the postgres chat history.
2
+
3
+ `PostgresChatHistory` always goes through one of these — never the
4
+ pool directly — so unit tests inject a `PostgresFakeRunner` that
5
+ interprets the SQL vocabulary the driver emits and routes operations
6
+ to in-memory backings. Mirrors the pattern in
7
+ `agentforge-memory-postgres/_runner.py`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any, Protocol
13
+
14
+
15
+ class PostgresRunner(Protocol): # pragma: no cover — Protocol method stubs
16
+ """Thin slice of `asyncpg.Pool` we depend on."""
17
+
18
+ async def fetch(self, sql: str, *params: Any) -> list[Any]: ...
19
+
20
+ async def fetchrow(self, sql: str, *params: Any) -> Any | None: ...
21
+
22
+ async def execute(self, sql: str, *params: Any) -> None: ...
23
+
24
+ async def execute_returning_count(self, sql: str, *params: Any) -> int: ...
25
+
26
+ async def close(self) -> None: ...
27
+
28
+
29
+ class _AsyncpgPoolRunner: # pragma: no cover — exercised only with `-m live`
30
+ """Production runner wrapping `asyncpg.Pool`."""
31
+
32
+ def __init__(self, pool: Any) -> None:
33
+ self._pool = pool
34
+
35
+ async def fetch(self, sql: str, *params: Any) -> list[Any]:
36
+ async with self._pool.acquire() as conn:
37
+ return list(await conn.fetch(sql, *params))
38
+
39
+ async def fetchrow(self, sql: str, *params: Any) -> Any | None:
40
+ async with self._pool.acquire() as conn:
41
+ return await conn.fetchrow(sql, *params)
42
+
43
+ async def execute(self, sql: str, *params: Any) -> None:
44
+ async with self._pool.acquire() as conn, conn.transaction():
45
+ await conn.execute(sql, *params)
46
+
47
+ async def execute_returning_count(self, sql: str, *params: Any) -> int:
48
+ async with self._pool.acquire() as conn, conn.transaction():
49
+ tag = await conn.execute(sql, *params)
50
+ return _parse_count(tag)
51
+
52
+ async def close(self) -> None:
53
+ await self._pool.close()
54
+
55
+
56
+ def _parse_count(tag: Any) -> int: # pragma: no cover — exercised via live
57
+ if not isinstance(tag, str):
58
+ return 0
59
+ parts = tag.rsplit(maxsplit=1)
60
+ if not parts:
61
+ return 0
62
+ try:
63
+ return int(parts[-1])
64
+ except ValueError:
65
+ return 0
66
+
67
+
68
+ __all__ = ["PostgresRunner"]
@@ -0,0 +1,319 @@
1
+ """`PostgresChatHistory` — `ChatHistoryStore` over Postgres via asyncpg.
2
+
3
+ Two tables (mirrors `SqliteChatHistory`): `chat_sessions`
4
+ (one row per session) and `chat_turns` (one row per turn, with
5
+ composite index on `(session_id, timestamp)` so `load()` stays
6
+ sub-linear w.r.t. total turn count).
7
+
8
+ Schema is created via `init_schema()` / `from_dsn()` using
9
+ `CREATE TABLE IF NOT EXISTS` — no migration framework in v0.2.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from collections.abc import Mapping
16
+ from datetime import datetime
17
+ from typing import Any
18
+
19
+ from agentforge_core.contracts.chat import ChatHistoryStore
20
+ from agentforge_core.production.exceptions import ModuleError
21
+ from agentforge_core.values.chat import ChatTurn, SessionInfo
22
+ from agentforge_core.values.messages import ToolCall
23
+
24
+ from agentforge_chat_history_postgres._runner import PostgresRunner
25
+
26
+ _SCHEMA_SQL = """
27
+ CREATE TABLE IF NOT EXISTS chat_sessions (
28
+ id TEXT PRIMARY KEY,
29
+ owner TEXT,
30
+ created_at TIMESTAMPTZ NOT NULL,
31
+ last_active_at TIMESTAMPTZ NOT NULL,
32
+ metadata JSONB NOT NULL
33
+ );
34
+ CREATE INDEX IF NOT EXISTS idx_chat_sessions_owner
35
+ ON chat_sessions(owner);
36
+ CREATE INDEX IF NOT EXISTS idx_chat_sessions_last_active
37
+ ON chat_sessions(last_active_at);
38
+ CREATE TABLE IF NOT EXISTS chat_turns (
39
+ id TEXT PRIMARY KEY,
40
+ session_id TEXT NOT NULL,
41
+ role TEXT NOT NULL,
42
+ content TEXT NOT NULL,
43
+ timestamp TIMESTAMPTZ NOT NULL,
44
+ run_id TEXT,
45
+ tool_calls JSONB NOT NULL,
46
+ tool_call_id TEXT,
47
+ tokens_in INTEGER NOT NULL,
48
+ tokens_out INTEGER NOT NULL,
49
+ cost_usd DOUBLE PRECISION NOT NULL,
50
+ metadata JSONB NOT NULL
51
+ );
52
+ CREATE INDEX IF NOT EXISTS idx_chat_turns_session_ts
53
+ ON chat_turns(session_id, timestamp);
54
+ """
55
+
56
+
57
+ class PostgresChatHistory(ChatHistoryStore):
58
+ """`ChatHistoryStore` backed by a Postgres database."""
59
+
60
+ def __init__(self, *, runner: PostgresRunner) -> None:
61
+ self._r = runner
62
+
63
+ @classmethod
64
+ async def from_dsn(
65
+ cls,
66
+ dsn: str,
67
+ *,
68
+ min_size: int = 1,
69
+ max_size: int = 10,
70
+ runner: PostgresRunner | None = None,
71
+ ) -> PostgresChatHistory:
72
+ """Open a connection pool against ``dsn`` and bootstrap the schema."""
73
+ if runner is None: # pragma: no cover — production path; exercised via `-m live`
74
+ runner = await _build_pool_runner(dsn, min_size=min_size, max_size=max_size)
75
+ store = cls(runner=runner)
76
+ await store.init_schema()
77
+ return store
78
+
79
+ async def init_schema(self) -> None:
80
+ for stmt in _split_statements(_SCHEMA_SQL):
81
+ await self._r.execute(stmt)
82
+
83
+ async def close(self) -> None:
84
+ await self._r.close()
85
+
86
+ async def append(self, turn: ChatTurn) -> None:
87
+ await self._r.execute(
88
+ """INSERT INTO chat_turns
89
+ (id, session_id, role, content, timestamp, run_id,
90
+ tool_calls, tool_call_id, tokens_in, tokens_out,
91
+ cost_usd, metadata)
92
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
93
+ ON CONFLICT (id) DO UPDATE SET
94
+ content = EXCLUDED.content,
95
+ timestamp = EXCLUDED.timestamp,
96
+ run_id = EXCLUDED.run_id,
97
+ tool_calls = EXCLUDED.tool_calls,
98
+ tool_call_id = EXCLUDED.tool_call_id,
99
+ tokens_in = EXCLUDED.tokens_in,
100
+ tokens_out = EXCLUDED.tokens_out,
101
+ cost_usd = EXCLUDED.cost_usd,
102
+ metadata = EXCLUDED.metadata""",
103
+ turn.id,
104
+ turn.session_id,
105
+ turn.role,
106
+ turn.content,
107
+ turn.timestamp,
108
+ turn.run_id,
109
+ json.dumps([tc.model_dump(mode="json") for tc in turn.tool_calls]),
110
+ turn.tool_call_id,
111
+ turn.tokens_in,
112
+ turn.tokens_out,
113
+ turn.cost_usd,
114
+ json.dumps(dict(turn.metadata)),
115
+ )
116
+ await self._upsert_session(turn.session_id, turn.timestamp)
117
+
118
+ async def _upsert_session(self, session_id: str, ts: datetime) -> None:
119
+ await self._r.execute(
120
+ """INSERT INTO chat_sessions
121
+ (id, owner, created_at, last_active_at, metadata)
122
+ VALUES ($1, NULL, $2, $2, '{}'::jsonb)
123
+ ON CONFLICT (id) DO UPDATE
124
+ SET last_active_at = EXCLUDED.last_active_at""",
125
+ session_id,
126
+ ts,
127
+ )
128
+
129
+ async def load(
130
+ self,
131
+ session_id: str,
132
+ *,
133
+ limit: int | None = None,
134
+ before: datetime | None = None,
135
+ after: datetime | None = None,
136
+ roles: list[str] | None = None,
137
+ ) -> list[ChatTurn]:
138
+ clauses = ["session_id = $1"]
139
+ params: list[Any] = [session_id]
140
+ if before is not None:
141
+ clauses.append(f"timestamp < ${len(params) + 1}")
142
+ params.append(before)
143
+ if after is not None:
144
+ clauses.append(f"timestamp > ${len(params) + 1}")
145
+ params.append(after)
146
+ if roles is not None:
147
+ clauses.append(f"role = ANY(${len(params) + 1}::text[])")
148
+ params.append(list(roles))
149
+ sql = (
150
+ "SELECT * FROM chat_turns WHERE " # noqa: S608 # nosec B608 — placeholders only
151
+ + " AND ".join(clauses)
152
+ + " ORDER BY timestamp"
153
+ )
154
+ if limit is not None:
155
+ sql += f" LIMIT ${len(params) + 1}"
156
+ params.append(limit)
157
+ rows = await self._r.fetch(sql, *params)
158
+ return [_row_to_turn(row) for row in rows]
159
+
160
+ async def count(self, session_id: str) -> int:
161
+ row = await self._r.fetchrow(
162
+ "SELECT COUNT(*) AS n FROM chat_turns WHERE session_id = $1",
163
+ session_id,
164
+ )
165
+ return int(row["n"]) if row is not None else 0
166
+
167
+ async def delete_session(self, session_id: str) -> int:
168
+ removed = await self._r.execute_returning_count(
169
+ "DELETE FROM chat_turns WHERE session_id = $1",
170
+ session_id,
171
+ )
172
+ await self._r.execute(
173
+ "DELETE FROM chat_sessions WHERE id = $1",
174
+ session_id,
175
+ )
176
+ return removed
177
+
178
+ async def list_sessions(
179
+ self,
180
+ *,
181
+ owner: str | None = None,
182
+ limit: int = 100,
183
+ before: datetime | None = None,
184
+ ) -> list[SessionInfo]:
185
+ clauses: list[str] = []
186
+ params: list[Any] = []
187
+ if owner is not None:
188
+ clauses.append(f"owner = ${len(params) + 1}")
189
+ params.append(owner)
190
+ if before is not None:
191
+ clauses.append(f"last_active_at < ${len(params) + 1}")
192
+ params.append(before)
193
+ sql = "SELECT * FROM chat_sessions"
194
+ if clauses:
195
+ sql += " WHERE " + " AND ".join(clauses)
196
+ sql += f" ORDER BY last_active_at DESC LIMIT ${len(params) + 1}" # nosec B608
197
+ params.append(limit)
198
+ rows = await self._r.fetch(sql, *params)
199
+ return [await self._row_to_info(row) for row in rows]
200
+
201
+ async def update_session_metadata(self, session_id: str, metadata: Mapping[str, Any]) -> None:
202
+ row = await self._r.fetchrow(
203
+ "SELECT owner, metadata FROM chat_sessions WHERE id = $1",
204
+ session_id,
205
+ )
206
+ if row is None:
207
+ raise ModuleError(f"Cannot update metadata for unknown session {session_id!r}")
208
+ existing: dict[str, Any] = dict(_coerce_jsonb(row["metadata"]))
209
+ existing.update(dict(metadata))
210
+ owner = metadata.get("owner", row["owner"])
211
+ await self._r.execute(
212
+ "UPDATE chat_sessions SET metadata = $1::jsonb, owner = $2 WHERE id = $3",
213
+ json.dumps(existing),
214
+ owner,
215
+ session_id,
216
+ )
217
+
218
+ async def expire_before(self, cutoff: datetime) -> int:
219
+ await self._r.execute(
220
+ """DELETE FROM chat_turns
221
+ WHERE session_id IN (
222
+ SELECT id FROM chat_sessions WHERE last_active_at < $1
223
+ )""",
224
+ cutoff,
225
+ )
226
+ return await self._r.execute_returning_count(
227
+ "DELETE FROM chat_sessions WHERE last_active_at < $1",
228
+ cutoff,
229
+ )
230
+
231
+ def capabilities(self) -> set[str]:
232
+ return {"ttl", "encryption_at_rest", "full_text_search"}
233
+
234
+ async def _row_to_info(self, row: Any) -> SessionInfo:
235
+ agg = await self._r.fetchrow(
236
+ """SELECT COUNT(*) AS n,
237
+ COALESCE(SUM(cost_usd), 0.0) AS total
238
+ FROM chat_turns WHERE session_id = $1""",
239
+ row["id"],
240
+ )
241
+ count = int(agg["n"]) if agg is not None else 0
242
+ total = float(agg["total"]) if agg is not None else 0.0
243
+ return SessionInfo(
244
+ id=row["id"],
245
+ owner=row["owner"],
246
+ created_at=row["created_at"],
247
+ last_active_at=row["last_active_at"],
248
+ turn_count=count,
249
+ total_cost_usd=total,
250
+ metadata=dict(_coerce_jsonb(row["metadata"])),
251
+ )
252
+
253
+
254
+ async def _build_pool_runner( # pragma: no cover — exercised only with `-m live`
255
+ dsn: str,
256
+ *,
257
+ min_size: int,
258
+ max_size: int,
259
+ ) -> PostgresRunner:
260
+ try:
261
+ import asyncpg # noqa: PLC0415
262
+ except ImportError as exc:
263
+ msg = (
264
+ "asyncpg is not installed. Install via `pip install asyncpg` "
265
+ "to use PostgresChatHistory."
266
+ )
267
+ raise ModuleError(msg) from exc
268
+ from agentforge_chat_history_postgres._runner import _AsyncpgPoolRunner # noqa: PLC0415
269
+
270
+ pool = await asyncpg.create_pool(dsn=dsn, min_size=min_size, max_size=max_size)
271
+ return _AsyncpgPoolRunner(pool)
272
+
273
+
274
+ def _coerce_jsonb(value: Any) -> dict[str, Any]:
275
+ if value is None: # pragma: no cover — defensive for asyncpg JSON variants
276
+ return {}
277
+ if isinstance(value, dict):
278
+ return value
279
+ if isinstance(value, str): # pragma: no cover — asyncpg returns str when JSONB codec absent
280
+ parsed: Any = json.loads(value)
281
+ return parsed if isinstance(parsed, dict) else {}
282
+ return {} # pragma: no cover — defensive fallback
283
+
284
+
285
+ def _row_to_turn(row: Any) -> ChatTurn:
286
+ raw_calls = _coerce_jsonb_list(row["tool_calls"])
287
+ tool_calls = tuple(ToolCall.model_validate(tc) for tc in raw_calls)
288
+ return ChatTurn(
289
+ id=row["id"],
290
+ session_id=row["session_id"],
291
+ role=row["role"],
292
+ content=row["content"],
293
+ timestamp=row["timestamp"],
294
+ run_id=row["run_id"],
295
+ tool_calls=tool_calls,
296
+ tool_call_id=row["tool_call_id"],
297
+ tokens_in=int(row["tokens_in"]),
298
+ tokens_out=int(row["tokens_out"]),
299
+ cost_usd=float(row["cost_usd"]),
300
+ metadata=dict(_coerce_jsonb(row["metadata"])),
301
+ )
302
+
303
+
304
+ def _coerce_jsonb_list(value: Any) -> list[Any]:
305
+ if value is None: # pragma: no cover — defensive for asyncpg JSON variants
306
+ return []
307
+ if isinstance(value, list):
308
+ return value
309
+ if isinstance(value, str): # pragma: no cover — asyncpg returns str when JSONB codec absent
310
+ parsed: Any = json.loads(value)
311
+ return parsed if isinstance(parsed, list) else []
312
+ return [] # pragma: no cover — defensive fallback
313
+
314
+
315
+ def _split_statements(sql: str) -> list[str]:
316
+ return [s.strip() for s in sql.split(";") if s.strip()]
317
+
318
+
319
+ __all__ = ["PostgresChatHistory"]
@@ -0,0 +1,33 @@
1
+ """Live integration test for `PostgresChatHistory` (feat-020 v0.2).
2
+
3
+ Gated by `@pytest.mark.live` and the `RUN_LIVE_POSTGRES_DSN` env var.
4
+ Default unit gate skips this; the CI `live` job runs it against a
5
+ Postgres `services:` container.
6
+
7
+ Boot up:
8
+
9
+ docker run --rm -d -p 5432:5432 -e POSTGRES_PASSWORD=test postgres:16
10
+ RUN_LIVE_POSTGRES_DSN=postgresql://postgres:test@localhost:5432/postgres \
11
+ uv run pytest -m live packages/agentforge-chat-history-postgres/
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+
18
+ import pytest
19
+ from agentforge_chat_history_postgres import PostgresChatHistory
20
+ from agentforge_core.testing import run_chat_history_conformance
21
+
22
+
23
+ @pytest.mark.live
24
+ @pytest.mark.asyncio
25
+ async def test_postgres_chat_history_live_conformance() -> None:
26
+ dsn = os.environ.get("RUN_LIVE_POSTGRES_DSN")
27
+ if not dsn:
28
+ pytest.skip("RUN_LIVE_POSTGRES_DSN env var unset; skipping live test")
29
+ store = await PostgresChatHistory.from_dsn(dsn)
30
+ try:
31
+ await run_chat_history_conformance(store)
32
+ finally:
33
+ await store.close()
@@ -0,0 +1,28 @@
1
+ """Unit tests for `PostgresChatHistory` against the fake runner."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+ from agentforge_chat_history_postgres import PostgresChatHistory
7
+ from agentforge_chat_history_postgres._inmem_runner import PostgresFakeRunner
8
+ from agentforge_core.testing import run_chat_history_conformance
9
+
10
+
11
+ @pytest.mark.asyncio
12
+ async def test_postgres_chat_history_satisfies_conformance() -> None:
13
+ runner = PostgresFakeRunner()
14
+ store = await PostgresChatHistory.from_dsn("postgres://fake", runner=runner)
15
+ await run_chat_history_conformance(store)
16
+ await store.close()
17
+ assert runner.closed is True
18
+
19
+
20
+ @pytest.mark.asyncio
21
+ async def test_postgres_chat_history_capabilities() -> None:
22
+ runner = PostgresFakeRunner()
23
+ store = await PostgresChatHistory.from_dsn("postgres://fake", runner=runner)
24
+ caps = store.capabilities()
25
+ assert "ttl" in caps
26
+ assert "encryption_at_rest" in caps
27
+ assert "full_text_search" in caps
28
+ await store.close()
@@ -0,0 +1,89 @@
1
+ """Additional unit tests covering `PostgresChatHistory` branches not
2
+ exercised by the ABC conformance suite (load filters, list_sessions
3
+ without owner, metadata coercion, tool-call round-trip)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from datetime import UTC, datetime, timedelta
8
+
9
+ import pytest
10
+ from agentforge_chat_history_postgres import PostgresChatHistory
11
+ from agentforge_chat_history_postgres._inmem_runner import PostgresFakeRunner
12
+ from agentforge_core.production.exceptions import ModuleError
13
+ from agentforge_core.values.chat import ChatTurn
14
+ from agentforge_core.values.messages import ToolCall
15
+
16
+
17
+ def _turn(turn_id: str, session_id: str, ts: datetime, role: str = "user") -> ChatTurn:
18
+ return ChatTurn(
19
+ id=turn_id,
20
+ session_id=session_id,
21
+ role=role,
22
+ content=f"msg-{turn_id}",
23
+ timestamp=ts,
24
+ )
25
+
26
+
27
+ @pytest.mark.asyncio
28
+ async def test_load_filters_before_after_and_roles() -> None:
29
+ runner = PostgresFakeRunner()
30
+ store = await PostgresChatHistory.from_dsn("p", runner=runner)
31
+ now = datetime.now(UTC)
32
+ await store.append(_turn("a", "s", now - timedelta(minutes=2), role="user"))
33
+ await store.append(_turn("b", "s", now - timedelta(minutes=1), role="assistant"))
34
+ await store.append(_turn("c", "s", now, role="user"))
35
+
36
+ before = await store.load("s", before=now - timedelta(seconds=30))
37
+ assert {t.id for t in before} == {"a", "b"}
38
+ after = await store.load("s", after=now - timedelta(seconds=30))
39
+ assert {t.id for t in after} == {"c"}
40
+ roles_only = await store.load("s", roles=["assistant"])
41
+ assert {t.id for t in roles_only} == {"b"}
42
+
43
+
44
+ @pytest.mark.asyncio
45
+ async def test_list_sessions_without_owner_returns_all() -> None:
46
+ runner = PostgresFakeRunner()
47
+ store = await PostgresChatHistory.from_dsn("p", runner=runner)
48
+ now = datetime.now(UTC)
49
+ await store.append(_turn("t", "s", now))
50
+ sessions = await store.list_sessions()
51
+ assert {s.id for s in sessions} == {"s"}
52
+
53
+
54
+ @pytest.mark.asyncio
55
+ async def test_list_sessions_with_before_filter() -> None:
56
+ runner = PostgresFakeRunner()
57
+ store = await PostgresChatHistory.from_dsn("p", runner=runner)
58
+ now = datetime.now(UTC)
59
+ await store.append(_turn("a", "old", now - timedelta(hours=1)))
60
+ await store.append(_turn("b", "new", now))
61
+ sessions = await store.list_sessions(before=now - timedelta(minutes=30))
62
+ assert {s.id for s in sessions} == {"old"}
63
+
64
+
65
+ @pytest.mark.asyncio
66
+ async def test_update_metadata_unknown_session_raises() -> None:
67
+ runner = PostgresFakeRunner()
68
+ store = await PostgresChatHistory.from_dsn("p", runner=runner)
69
+ with pytest.raises(ModuleError, match="unknown session"):
70
+ await store.update_session_metadata("nope", {"k": "v"})
71
+
72
+
73
+ @pytest.mark.asyncio
74
+ async def test_turn_with_tool_call_round_trips() -> None:
75
+ runner = PostgresFakeRunner()
76
+ store = await PostgresChatHistory.from_dsn("p", runner=runner)
77
+ now = datetime.now(UTC)
78
+ tc = ToolCall(id="call_1", name="search", arguments={"q": "x"})
79
+ turn = ChatTurn(
80
+ id="t1",
81
+ session_id="s",
82
+ role="assistant",
83
+ content="ran",
84
+ timestamp=now,
85
+ tool_calls=(tc,),
86
+ )
87
+ await store.append(turn)
88
+ loaded = await store.load("s")
89
+ assert loaded[0].tool_calls[0].name == "search"