chronos-mem 0.1.0__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,32 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+ build/
7
+ dist/
8
+ .venv/
9
+ venv/
10
+ env/
11
+ .python-version
12
+
13
+ # Test / coverage
14
+ .pytest_cache/
15
+ .coverage
16
+ htmlcov/
17
+ .mypy_cache/
18
+ .ruff_cache/
19
+
20
+ # Environment / secrets
21
+ .env
22
+ .env.*
23
+ !.env.example
24
+
25
+ # Postgres / Docker local volumes
26
+ db/data/
27
+ pgdata/
28
+
29
+ # Editor / OS
30
+ .idea/
31
+ .vscode/
32
+ .DS_Store
@@ -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,75 @@
1
+ Metadata-Version: 2.4
2
+ Name: chronos-mem
3
+ Version: 0.1.0
4
+ Summary: PostgreSQL-backed structured memory and causal debugging engine for autonomous AI agents.
5
+ Project-URL: Homepage, https://github.com/JCHETAN26/Chronos-mem
6
+ Project-URL: Repository, https://github.com/JCHETAN26/Chronos-mem
7
+ Project-URL: Issues, https://github.com/JCHETAN26/Chronos-mem/issues
8
+ Author: chronos-mem
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: agents,ai-agents,llm,memory,observability,pgvector,postgres
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Database
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: psycopg[binary,pool]>=3.2
24
+ Requires-Dist: pydantic>=2.6
25
+ Provides-Extra: dev
26
+ Requires-Dist: mypy>=1.10; extra == 'dev'
27
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
28
+ Requires-Dist: pytest>=8.0; extra == 'dev'
29
+ Requires-Dist: ruff>=0.4; extra == 'dev'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # chronos-mem (Python SDK)
33
+
34
+ Async, typed client for the chronos-mem agent memory engine.
35
+
36
+ ```python
37
+ import asyncio
38
+ from chronos_mem import ChronosClient
39
+
40
+ async def main():
41
+ async with ChronosClient(dsn="postgresql://chronos:chronos@localhost:5432/chronos_mem") as db:
42
+ plan = await db.create_plan(agent_id="agent-1", goal="Book a vacation to Tokyo")
43
+
44
+ action = await db.log_action(
45
+ plan_id=plan.id,
46
+ tool_name="flights.search",
47
+ payload={"from": "SFO", "to": "HND"},
48
+ )
49
+
50
+ await db.log_outcome(
51
+ action_id=action.id,
52
+ status="success",
53
+ result={"cheapest_usd": 812},
54
+ )
55
+
56
+ asyncio.run(main())
57
+ ```
58
+
59
+ ## Install (dev)
60
+
61
+ ```bash
62
+ pip install -e ".[dev]"
63
+ ```
64
+
65
+ The DSN can also be supplied via the `CHRONOS_DSN` environment variable instead
66
+ of the `dsn=` argument.
67
+
68
+ ## Design
69
+
70
+ - **`client.py`** — `ChronosClient` owns one async `psycopg_pool` connection pool;
71
+ open once per process and share it across concurrent agent calls.
72
+ - **`tracking.py`** — `create_plan` / `log_action` / `log_outcome`, the three core
73
+ write verbs, each a single `INSERT ... RETURNING *`.
74
+ - **`models.py`** — Pydantic v2 models (`Plan`, `Action`, `Outcome`, `Memory`)
75
+ mirroring the SQL schema in `db/migrations/001_init_chronos_schema.sql`.
@@ -0,0 +1,44 @@
1
+ # chronos-mem (Python SDK)
2
+
3
+ Async, typed client for the chronos-mem agent memory engine.
4
+
5
+ ```python
6
+ import asyncio
7
+ from chronos_mem import ChronosClient
8
+
9
+ async def main():
10
+ async with ChronosClient(dsn="postgresql://chronos:chronos@localhost:5432/chronos_mem") as db:
11
+ plan = await db.create_plan(agent_id="agent-1", goal="Book a vacation to Tokyo")
12
+
13
+ action = await db.log_action(
14
+ plan_id=plan.id,
15
+ tool_name="flights.search",
16
+ payload={"from": "SFO", "to": "HND"},
17
+ )
18
+
19
+ await db.log_outcome(
20
+ action_id=action.id,
21
+ status="success",
22
+ result={"cheapest_usd": 812},
23
+ )
24
+
25
+ asyncio.run(main())
26
+ ```
27
+
28
+ ## Install (dev)
29
+
30
+ ```bash
31
+ pip install -e ".[dev]"
32
+ ```
33
+
34
+ The DSN can also be supplied via the `CHRONOS_DSN` environment variable instead
35
+ of the `dsn=` argument.
36
+
37
+ ## Design
38
+
39
+ - **`client.py`** — `ChronosClient` owns one async `psycopg_pool` connection pool;
40
+ open once per process and share it across concurrent agent calls.
41
+ - **`tracking.py`** — `create_plan` / `log_action` / `log_outcome`, the three core
42
+ write verbs, each a single `INSERT ... RETURNING *`.
43
+ - **`models.py`** — Pydantic v2 models (`Plan`, `Action`, `Outcome`, `Memory`)
44
+ mirroring the SQL schema in `db/migrations/001_init_chronos_schema.sql`.
@@ -0,0 +1,47 @@
1
+ """chronos-mem — structured memory & causal debugging engine for AI agents.
2
+
3
+ Public surface:
4
+
5
+ from chronos_mem import ChronosClient
6
+
7
+ async with ChronosClient(dsn="postgresql://...") as db:
8
+ plan = await db.create_plan(agent_id="agent-1", goal="Book a vacation")
9
+ action = await db.log_action(plan_id=plan.id, tool_name="flights.search")
10
+ await db.log_outcome(action_id=action.id, status="success")
11
+ """
12
+
13
+ from .client import ChronosClient
14
+ from .models import (
15
+ Action,
16
+ ActionTrace,
17
+ BestIntervention,
18
+ CausalNode,
19
+ CausalTrace,
20
+ Intervention,
21
+ InterventionStrategy,
22
+ Memory,
23
+ Outcome,
24
+ OutcomeStatus,
25
+ Plan,
26
+ PlanStatus,
27
+ ToolBrittleness,
28
+ )
29
+
30
+ __all__ = [
31
+ "ChronosClient",
32
+ "Memory",
33
+ "Plan",
34
+ "Action",
35
+ "Outcome",
36
+ "Intervention",
37
+ "BestIntervention",
38
+ "ToolBrittleness",
39
+ "PlanStatus",
40
+ "OutcomeStatus",
41
+ "InterventionStrategy",
42
+ "ActionTrace",
43
+ "CausalNode",
44
+ "CausalTrace",
45
+ ]
46
+
47
+ __version__ = "0.1.0"
@@ -0,0 +1,37 @@
1
+ """Analytics — read accessors over chronos-mem's analytical views.
2
+
3
+ ``tool_brittleness()`` surfaces the tool_brittleness view (db/migrations/
4
+ 002_tool_brittleness_view.sql): which tools fail most, ranked. Useful for the
5
+ dashboard and for an operator deciding which integrations to harden.
6
+
7
+ Implemented as a mixin; ChronosClient supplies ``_fetch``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any, Protocol
13
+
14
+ from .models import ToolBrittleness
15
+
16
+ # Order most-brittle first; the view itself does not guarantee row order.
17
+ _TOOL_BRITTLENESS_SQL = """
18
+ SELECT tool_name, total_calls, successes, failures, partials, failure_rate, last_seen
19
+ FROM view_tool_brittleness_analysis
20
+ ORDER BY failure_rate DESC, total_calls DESC
21
+ LIMIT %(limit)s;
22
+ """
23
+
24
+
25
+ class _Fetcher(Protocol):
26
+ async def _fetch(self, query: str, params: Any) -> list[dict[str, Any]]: ...
27
+
28
+
29
+ class AnalyticsMixin:
30
+ """tool_brittleness — rank tools by how often they fail."""
31
+
32
+ async def tool_brittleness(
33
+ self: _Fetcher, limit: int = 50
34
+ ) -> list[ToolBrittleness]:
35
+ """Return per-tool failure profiles, most brittle first."""
36
+ rows = await self._fetch(_TOOL_BRITTLENESS_SQL, {"limit": limit})
37
+ return [ToolBrittleness.model_validate(r) for r in rows]
@@ -0,0 +1,177 @@
1
+ """Causal tracing — the debugging read layer of chronos-mem.
2
+
3
+ ``query_causality(plan_id)`` explains a point in an agent's execution by walking
4
+ the plan DAG in both directions with two recursive CTEs (one round trip each):
5
+
6
+ * DOWN — the subtree of descendant plans, each with its actions + outcomes,
7
+ so you can see everything that happened under a goal and where it
8
+ broke.
9
+ * UP — the ancestor path back to the root goal, so a failure can be read
10
+ backwards through the decomposition that produced it.
11
+
12
+ The canonical SQL lives in db/queries/causality.sql; the embedded copies below
13
+ are kept byte-for-byte equivalent. Both walks are index-backed
14
+ (idx_plans_parent_plan_id downward, the primary key upward), keeping a trace to
15
+ a single statement per direction and well inside the sub-5ms target.
16
+
17
+ Implemented as a mixin; ChronosClient supplies ``_fetch``.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from contextlib import AbstractAsyncContextManager
23
+ from typing import Any, Protocol
24
+ from uuid import UUID
25
+
26
+ from .models import (
27
+ Action,
28
+ ActionTrace,
29
+ CausalNode,
30
+ CausalTrace,
31
+ Outcome,
32
+ Plan,
33
+ )
34
+
35
+ # --- Embedded queries (see db/queries/causality.sql) -----------------------
36
+
37
+ _SUBTREE_SQL = """
38
+ WITH RECURSIVE subtree AS (
39
+ SELECT p.id, p.parent_plan_id, p.agent_id, p.goal, p.status, p.metadata,
40
+ p.created_at, 0 AS depth
41
+ FROM plans p
42
+ WHERE p.id = %(plan_id)s
43
+ UNION ALL
44
+ SELECT c.id, c.parent_plan_id, c.agent_id, c.goal, c.status, c.metadata,
45
+ c.created_at, s.depth + 1
46
+ FROM plans c
47
+ JOIN subtree s ON c.parent_plan_id = s.id
48
+ )
49
+ SELECT
50
+ s.id AS plan_id,
51
+ s.parent_plan_id,
52
+ s.agent_id,
53
+ s.goal,
54
+ s.status AS plan_status,
55
+ s.metadata AS plan_metadata,
56
+ s.created_at AS plan_created_at,
57
+ s.depth,
58
+ a.id AS action_id,
59
+ a.tool_name,
60
+ a.payload AS action_payload,
61
+ a.created_at AS action_created_at,
62
+ o.id AS outcome_id,
63
+ o.status AS outcome_status,
64
+ o.result AS outcome_result,
65
+ o.error AS outcome_error,
66
+ o.created_at AS outcome_created_at
67
+ FROM subtree s
68
+ LEFT JOIN actions a ON a.plan_id = s.id
69
+ LEFT JOIN outcomes o ON o.action_id = a.id
70
+ ORDER BY s.depth ASC, s.created_at ASC, a.created_at ASC NULLS FIRST;
71
+ """
72
+
73
+ _ANCESTORS_SQL = """
74
+ WITH RECURSIVE ancestors AS (
75
+ SELECT p.id, p.parent_plan_id, p.agent_id, p.goal, p.status, p.metadata,
76
+ p.created_at, 0 AS height
77
+ FROM plans p
78
+ WHERE p.id = %(plan_id)s
79
+ UNION ALL
80
+ SELECT p.id, p.parent_plan_id, p.agent_id, p.goal, p.status, p.metadata,
81
+ p.created_at, a.height + 1
82
+ FROM plans p
83
+ JOIN ancestors a ON p.id = a.parent_plan_id
84
+ )
85
+ SELECT id AS plan_id, parent_plan_id, agent_id, goal, status AS plan_status,
86
+ metadata AS plan_metadata, created_at AS plan_created_at, height
87
+ FROM ancestors
88
+ WHERE id <> %(plan_id)s
89
+ ORDER BY height DESC;
90
+ """
91
+
92
+
93
+ class _Fetcher(Protocol):
94
+ def _cursor(self) -> AbstractAsyncContextManager[Any]: ...
95
+
96
+
97
+ def _plan_from_row(row: dict[str, Any]) -> Plan:
98
+ """Rebuild a Plan from a CTE row's aliased plan_* columns."""
99
+ return Plan.model_validate(
100
+ {
101
+ "id": row["plan_id"],
102
+ "agent_id": row["agent_id"],
103
+ "parent_plan_id": row["parent_plan_id"],
104
+ "goal": row["goal"],
105
+ "status": row["plan_status"],
106
+ "metadata": row["plan_metadata"],
107
+ "created_at": row["plan_created_at"],
108
+ # updated_at isn't needed for a trace view; mirror created_at so the
109
+ # required field validates without a second column in the CTE.
110
+ "updated_at": row["plan_created_at"],
111
+ }
112
+ )
113
+
114
+
115
+ class CausalityMixin:
116
+ """query_causality — backwards/forwards causal trace over the plan DAG."""
117
+
118
+ async def query_causality(self: _Fetcher, plan_id: UUID | str) -> CausalTrace:
119
+ """Return the full causal context of ``plan_id``.
120
+
121
+ Runs the subtree (downward) and ancestor (upward) CTEs on a single
122
+ pooled connection — one checkout, one consistent snapshot — and
123
+ assembles a typed :class:`CausalTrace`. Raises ``LookupError`` if the
124
+ plan is absent.
125
+ """
126
+ params = {"plan_id": str(plan_id)}
127
+ async with self._cursor() as cur:
128
+ await cur.execute(_SUBTREE_SQL, params)
129
+ subtree_rows = await cur.fetchall()
130
+ if not subtree_rows:
131
+ raise LookupError(f"No plan found with id {plan_id!r}")
132
+ await cur.execute(_ANCESTORS_SQL, params)
133
+ ancestor_rows = await cur.fetchall()
134
+
135
+ # Group the flat (plan x action) rows into one CausalNode per plan,
136
+ # preserving the SQL ordering (depth, then chronological).
137
+ nodes: dict[Any, CausalNode] = {}
138
+ for row in subtree_rows:
139
+ pid = row["plan_id"]
140
+ node = nodes.get(pid)
141
+ if node is None:
142
+ node = CausalNode(plan=_plan_from_row(row), depth=row["depth"], actions=[])
143
+ nodes[pid] = node
144
+
145
+ if row["action_id"] is None:
146
+ continue # plan node with no actions (LEFT JOIN null row)
147
+
148
+ action = Action.model_validate(
149
+ {
150
+ "id": row["action_id"],
151
+ "plan_id": pid,
152
+ "tool_name": row["tool_name"],
153
+ "payload": row["action_payload"],
154
+ "created_at": row["action_created_at"],
155
+ }
156
+ )
157
+ outcome = None
158
+ if row["outcome_id"] is not None:
159
+ outcome = Outcome.model_validate(
160
+ {
161
+ "id": row["outcome_id"],
162
+ "action_id": row["action_id"],
163
+ "status": row["outcome_status"],
164
+ "result": row["outcome_result"],
165
+ "error": row["outcome_error"],
166
+ "created_at": row["outcome_created_at"],
167
+ }
168
+ )
169
+ node.actions.append(ActionTrace(action=action, outcome=outcome))
170
+
171
+ ancestors = [_plan_from_row(r) for r in ancestor_rows]
172
+
173
+ return CausalTrace(
174
+ plan_id=UUID(str(plan_id)),
175
+ ancestors=ancestors,
176
+ subtree=list(nodes.values()),
177
+ )