forked from Atomlaunch/engram
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdispatch_context.py
More file actions
284 lines (257 loc) · 9.91 KB
/
dispatch_context.py
File metadata and controls
284 lines (257 loc) · 9.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#!/usr/bin/env python3
"""
Engram Pre-Dispatch Context Builder.
Builds a compact markdown context block for agent dispatch prompts.
"""
import os
import sys
from datetime import datetime
from typing import Optional
try:
import kuzu
except ImportError:
kuzu = None
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from engram.backend import get_db, get_conn
def _fetch_agent_entity(conn: kuzu.Connection, agent_name: str) -> Optional[dict]:
try:
result = conn.execute(
"MATCH (e:Entity) "
"WHERE lower(e.name) = lower($p_name) "
"RETURN e.id, e.name, e.entity_type, e.description LIMIT 1",
{"p_name": agent_name}
)
if result.has_next():
row = result.get_next()
return {
"id": row[0], "name": row[1], "type": row[2], "description": row[3]
}
except Exception:
pass
return None
def _fetch_project_entity(conn: kuzu.Connection, project_name: str) -> Optional[dict]:
try:
result = conn.execute(
"MATCH (e:Entity) "
"WHERE lower(e.name) CONTAINS lower($p_name) "
"RETURN e.id, e.name, e.entity_type, e.description LIMIT 1",
{"p_name": project_name}
)
if result.has_next():
row = result.get_next()
return {
"id": row[0], "name": row[1], "type": row[2], "description": row[3]
}
except Exception:
pass
return None
def get_dispatch_context(conn: kuzu.Connection, agent_name: str, project_name: Optional[str] = None) -> str:
"""Return formatted markdown context for agent dispatch."""
agent_entity = _fetch_agent_entity(conn, agent_name)
project_entity = _fetch_project_entity(conn, project_name) if project_name else None
agent_facts = []
project_facts = []
recent_episodes = []
key_decisions = []
# Agent history: facts about agent or by agent_id
try:
combined = []
params = {"p_agent": agent_name, "p_limit": 12}
result = conn.execute(
"MATCH (f:Fact) "
"WHERE f.agent_id = $p_agent "
"RETURN f.content, f.category, f.created_at "
"ORDER BY f.created_at DESC LIMIT $p_limit",
params
)
while result.has_next():
row = result.get_next()
combined.append({
"content": row[0], "category": row[1], "_created_at": row[2]
})
if agent_entity:
result = conn.execute(
"MATCH (f:Fact)-[:ABOUT]->(e:Entity {id: $p_eid}) "
"RETURN f.content, f.category, f.created_at "
"ORDER BY f.created_at DESC LIMIT $p_limit",
{"p_eid": agent_entity["id"], "p_limit": params["p_limit"]}
)
while result.has_next():
row = result.get_next()
combined.append({
"content": row[0], "category": row[1], "_created_at": row[2]
})
if combined:
combined.sort(
key=lambda x: (x.get("_created_at") is None, x.get("_created_at") or datetime.min),
reverse=True
)
for item in combined[:params["p_limit"]]:
agent_facts.append({
"content": item.get("content", ""),
"category": item.get("category", ""),
"created_at": str(item.get("_created_at")),
})
except Exception:
pass
# Project context: facts about the project entity
if project_entity:
try:
result = conn.execute(
"MATCH (f:Fact)-[:ABOUT]->(e:Entity {id: $p_eid}) "
"RETURN f.content, f.category, f.created_at "
"ORDER BY f.created_at DESC LIMIT $p_limit",
{"p_eid": project_entity["id"], "p_limit": 12}
)
while result.has_next():
row = result.get_next()
project_facts.append({
"content": row[0], "category": row[1], "created_at": str(row[2])
})
except Exception:
pass
# Recent activity: episodes mentioning agent (+ project if provided)
try:
if project_entity:
result = conn.execute(
"MATCH (agent:Entity {id: $p_agent_id})-[:MENTIONED_IN]->(ep:Episode)"
"<-[:MENTIONED_IN]-(project:Entity {id: $p_project_id}) "
"RETURN ep.summary, ep.source_file, ep.occurred_at "
"ORDER BY ep.occurred_at DESC LIMIT $p_limit",
{"p_agent_id": agent_entity["id"] if agent_entity else "", "p_project_id": project_entity["id"], "p_limit": 10}
)
elif agent_entity:
result = conn.execute(
"MATCH (agent:Entity {id: $p_agent_id})-[:MENTIONED_IN]->(ep:Episode) "
"RETURN ep.summary, ep.source_file, ep.occurred_at "
"ORDER BY ep.occurred_at DESC LIMIT $p_limit",
{"p_agent_id": agent_entity["id"], "p_limit": 10}
)
else:
result = None
if result:
while result.has_next():
row = result.get_next()
recent_episodes.append({
"summary": row[0], "source_file": row[1], "occurred_at": str(row[2])
})
except Exception:
pass
# Key decisions: decision facts about agent or project
try:
combined = []
params = {"p_limit": 8, "p_agent_name": agent_name}
result = conn.execute(
"MATCH (f:Fact) "
"WHERE lower(f.category) = 'decision' AND f.agent_id = $p_agent_name "
"RETURN f.content, f.created_at "
"ORDER BY f.created_at DESC LIMIT $p_limit",
params
)
while result.has_next():
row = result.get_next()
combined.append({"content": row[0], "_created_at": row[1]})
if agent_entity:
result = conn.execute(
"MATCH (f:Fact)-[:ABOUT]->(e:Entity {id: $p_agent_eid}) "
"WHERE lower(f.category) = 'decision' "
"RETURN f.content, f.created_at "
"ORDER BY f.created_at DESC LIMIT $p_limit",
{"p_agent_eid": agent_entity["id"], "p_limit": params["p_limit"]}
)
while result.has_next():
row = result.get_next()
combined.append({"content": row[0], "_created_at": row[1]})
if project_entity:
result = conn.execute(
"MATCH (f:Fact)-[:ABOUT]->(e:Entity {id: $p_project_eid}) "
"WHERE lower(f.category) = 'decision' "
"RETURN f.content, f.created_at "
"ORDER BY f.created_at DESC LIMIT $p_limit",
{"p_project_eid": project_entity["id"], "p_limit": params["p_limit"]}
)
while result.has_next():
row = result.get_next()
combined.append({"content": row[0], "_created_at": row[1]})
if combined:
combined.sort(
key=lambda x: (x.get("_created_at") is None, x.get("_created_at") or datetime.min),
reverse=True
)
for item in combined[:params["p_limit"]]:
key_decisions.append({
"content": item.get("content", ""),
"created_at": str(item.get("_created_at")),
})
except Exception:
pass
lines = []
lines.append(f"# Dispatch Context - {agent_name}")
lines.append(f"*Generated: {datetime.now().strftime('%Y-%m-%d %H:%M PST')}*")
lines.append("")
lines.append("## Agent History")
if agent_facts:
seen = set()
for fact in agent_facts:
content = fact.get("content", "")
if not content or content in seen:
continue
seen.add(content)
cat = fact.get("category", "")
lines.append(f"- [{cat}] {content}")
else:
lines.append("- None")
lines.append("")
lines.append("## Project Context")
if project_facts:
seen = set()
for fact in project_facts:
content = fact.get("content", "")
if not content or content in seen:
continue
seen.add(content)
cat = fact.get("category", "")
lines.append(f"- [{cat}] {content}")
else:
lines.append("- None")
lines.append("")
lines.append("## Recent Activity")
if recent_episodes:
seen = set()
for ep in recent_episodes:
summary = ep.get("summary", "")
if not summary or summary in seen:
continue
seen.add(summary)
date = ep.get("occurred_at", "")[:10]
lines.append(f"- **[{date}]** {summary}")
else:
lines.append("- None")
lines.append("")
lines.append("## Key Decisions")
if key_decisions:
seen = set()
for item in key_decisions:
content = item.get("content", "")
if not content or content in seen:
continue
seen.add(content)
lines.append(f"- {content}")
else:
lines.append("- None")
return "\n".join(lines)
if __name__ == "__main__":
import argparse
import json
parser = argparse.ArgumentParser(description="Engram Dispatch Context")
parser.add_argument("agent", help="Agent name")
parser.add_argument("--project", "-p", default=None, help="Optional project name")
parser.add_argument("--json", "-j", action="store_true", help="JSON output")
args = parser.parse_args()
db = get_db(read_only=True)
conn = get_conn(db)
context = get_dispatch_context(conn, args.agent, args.project)
if args.json:
print(json.dumps({"context": context, "generated_at": datetime.now().isoformat()}, default=str))
else:
print(context)