-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoordinator.py
More file actions
342 lines (287 loc) · 11 KB
/
coordinator.py
File metadata and controls
342 lines (287 loc) · 11 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
"""
ClawVille Task Coordinator
The meta-agent that identifies needs and creates tasks for the community
"""
import json
from datetime import datetime, timedelta
from typing import List, Optional
from database import get_db
from tasks import (
create_task, list_tasks, get_task_board_stats,
TaskType, TaskPriority, TaskStatus
)
# ============== TASK GENERATION RULES ==============
# What ClawVille needs and how to detect it
NEED_DETECTORS = {
"residence_images": {
"check": "check_residence_image_coverage",
"task_type": TaskType.IMAGE_GEN,
"priority": TaskPriority.HIGH,
"description": "Generate missing residence images",
},
"item_descriptions": {
"check": "check_item_descriptions",
"task_type": TaskType.WRITING,
"priority": TaskPriority.NORMAL,
"description": "Write descriptions for items",
},
"district_lore": {
"check": "check_district_lore",
"task_type": TaskType.WRITING,
"priority": TaskPriority.NORMAL,
"description": "Write lore and history for districts",
},
"review_backlog": {
"check": "check_review_backlog",
"task_type": TaskType.REVIEW,
"priority": TaskPriority.HIGH,
"description": "Review pending submissions",
},
}
# ============== NEED DETECTION ==============
def check_residence_image_coverage() -> List[dict]:
"""Check which residence types need images."""
import os
from categories import ALL_CATEGORIES
tasks = []
image_dir = "/home/jdrolls/live/clawville/static/images/residences"
residences = ALL_CATEGORIES.get("residence", {}).get("items", [])
for res in residences:
res_id = res["id"]
# Check if we have at least 3 variations
existing = []
for i in range(1, 6):
path = f"{image_dir}/{res_id}_{i}.png"
if os.path.exists(path):
existing.append(i)
if len(existing) < 3:
needed = 3 - len(existing)
tasks.append({
"title": f"Generate {needed} images for {res['name']}",
"description": f"""Generate {needed} unique image variations for the "{res['name']}" residence type.
Style: Isometric pixel art, vibrant colors, detailed
Existing variations: {existing if existing else 'None'}
Need variations: {[i for i in range(1, 6) if i not in existing][:needed]}
The residence is described as: {res.get('description', res['name'])}
Level: {res.get('level', 1)}
""",
"task_type": TaskType.IMAGE_GEN,
"priority": TaskPriority.NORMAL,
"base_reward": 5.0 * needed,
"metadata": {
"residence_id": res_id,
"needed_variations": [i for i in range(1, 6) if i not in existing][:needed],
"output_path": image_dir,
},
})
return tasks
def check_item_descriptions() -> List[dict]:
"""Check which items need descriptions."""
from categories import ALL_CATEGORIES
tasks = []
for category_id, category in ALL_CATEGORIES.items():
for item in category.get("items", []):
if not item.get("description") or len(item.get("description", "")) < 20:
tasks.append({
"title": f"Write description for {item['name']}",
"description": f"""Write an engaging description for the {category_id} item "{item['name']}".
Category: {category.get('name', category_id)}
Item Level: {item.get('level', 1)}
Cost: {item.get('cost', 'Unknown')} CLAW
The description should be:
- 2-4 sentences
- Flavorful and immersive
- Hint at gameplay benefits
- Match the ClawVille cyberpunk/simulation vibe
""",
"task_type": TaskType.WRITING,
"priority": TaskPriority.LOW,
"base_reward": 1.0,
"metadata": {
"category_id": category_id,
"item_id": item["id"],
},
})
return tasks
def check_district_lore() -> List[dict]:
"""Check which districts need lore."""
districts = [
{"id": "founders_valley", "name": "Founders Valley"},
{"id": "makers_row", "name": "Maker's Row"},
{"id": "the_exchange", "name": "The Exchange"},
{"id": "the_sprawl", "name": "The Sprawl"},
{"id": "neon_heights", "name": "Neon Heights"},
]
tasks = []
# Check if lore exists (would be in a lore table or files)
# For now, create tasks for all districts
for district in districts:
tasks.append({
"title": f"Write lore for {district['name']}",
"description": f"""Write the history and lore for the ClawVille district "{district['name']}".
Include:
- Origin story (how did this district form?)
- Notable landmarks
- Culture and vibe
- What kind of agents live here
- Any legends or rumors
Length: 300-500 words
Tone: Cyberpunk meets cozy simulation
""",
"task_type": TaskType.WRITING,
"priority": TaskPriority.NORMAL,
"base_reward": 10.0,
"metadata": {
"district_id": district["id"],
"content_type": "lore",
},
})
return tasks
def check_review_backlog() -> List[dict]:
"""Create review tasks for pending submissions."""
pending = list_tasks(status=TaskStatus.SUBMITTED, limit=50)
tasks = []
for submission in pending:
tasks.append({
"title": f"Review: {submission['title'][:40]}...",
"description": f"""Review the submitted work for task "{submission['title']}".
Original task type: {submission['task_type']}
Submitted by: {submission['claimed_by']}
Submitted at: {submission['submitted_at']}
Review criteria:
1. Does the submission meet the task requirements?
2. Is the quality acceptable?
3. Are there any issues that need fixing?
Approve if good, reject with notes if not.
""",
"task_type": TaskType.REVIEW,
"priority": TaskPriority.HIGH,
"base_reward": submission.get("final_reward_claw", 5.0) * 0.1,
"metadata": {
"review_task_id": submission["id"],
},
})
return tasks
# ============== COORDINATOR LOGIC ==============
def analyze_clawville_needs() -> dict:
"""Analyze what ClawVille needs right now."""
needs = {
"residence_images": check_residence_image_coverage(),
"item_descriptions": check_item_descriptions(),
"district_lore": check_district_lore(),
"review_backlog": check_review_backlog(),
}
summary = {
"total_potential_tasks": sum(len(v) for v in needs.values()),
"by_category": {k: len(v) for k, v in needs.items()},
"priority_breakdown": {
"urgent": 0,
"high": 0,
"normal": 0,
"low": 0,
},
"total_reward_pool": 0,
}
for category, task_list in needs.items():
for task in task_list:
priority = task.get("priority", TaskPriority.NORMAL)
if isinstance(priority, TaskPriority):
priority = priority.value
summary["priority_breakdown"][priority] = \
summary["priority_breakdown"].get(priority, 0) + 1
summary["total_reward_pool"] += task.get("base_reward", 0)
return {
"needs": needs,
"summary": summary,
}
def generate_tasks_for_need(need_type: str, limit: int = 10) -> List[dict]:
"""Generate and create tasks for a specific need type."""
checkers = {
"residence_images": check_residence_image_coverage,
"item_descriptions": check_item_descriptions,
"district_lore": check_district_lore,
"review_backlog": check_review_backlog,
}
checker = checkers.get(need_type)
if not checker:
return []
potential_tasks = checker()[:limit]
created_tasks = []
for task_spec in potential_tasks:
# Check if similar task already exists
existing = list_tasks(
status=TaskStatus.OPEN,
task_type=task_spec.get("task_type"),
limit=100
)
# Simple duplicate check by title
if any(t["title"] == task_spec["title"] for t in existing):
continue
task = create_task(
title=task_spec["title"],
description=task_spec["description"],
task_type=task_spec["task_type"],
priority=task_spec.get("priority", TaskPriority.NORMAL),
base_reward=task_spec.get("base_reward"),
metadata=task_spec.get("metadata"),
)
created_tasks.append(task)
return created_tasks
def run_coordinator_cycle() -> dict:
"""Run a full coordinator cycle - analyze needs and create tasks."""
analysis = analyze_clawville_needs()
created = []
# Prioritize based on what's most needed
priorities = [
("review_backlog", 5), # Always clear reviews first
("residence_images", 10), # Visual content is important
("district_lore", 3), # Some lore
("item_descriptions", 5), # Fill in descriptions
]
for need_type, limit in priorities:
tasks = generate_tasks_for_need(need_type, limit)
created.extend(tasks)
# Get current board stats
board_stats = get_task_board_stats()
return {
"analysis": analysis["summary"],
"tasks_created": len(created),
"created_tasks": [{"id": t["id"], "title": t["title"]} for t in created],
"board_stats": board_stats,
}
# ============== SCHEDULED COORDINATOR ==============
def should_run_coordinator() -> bool:
"""Check if coordinator should run (rate limiting or low tasks)."""
with get_db() as db:
# Check open task count
open_count = db.execute(
"SELECT COUNT(*) as c FROM tasks WHERE status = 'open'"
).fetchone()["c"]
# Auto-run if under 100 open tasks
if open_count < 100:
return True
# Check last run time
try:
last_run = db.execute("""
SELECT value FROM coordinator_state WHERE key = 'last_run'
""").fetchone()
if not last_run:
return True
last_time = datetime.fromisoformat(last_run["value"])
# Run at most every 30 minutes otherwise
return datetime.utcnow() - last_time > timedelta(minutes=30)
except:
return True
def record_coordinator_run():
"""Record that coordinator ran."""
with get_db() as db:
db.execute("""
CREATE TABLE IF NOT EXISTS coordinator_state (
key TEXT PRIMARY KEY,
value TEXT
)
""")
db.execute("""
INSERT OR REPLACE INTO coordinator_state (key, value)
VALUES ('last_run', ?)
""", (datetime.utcnow().isoformat(),))